prompt-toolkit / prompt-toolkit/python-prompt-toolkit

Prompt test with backspace+validator

Open
#1,613 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
10.6k
Forks
815
PR merge metrics
No merged PRs in 30d

Description

Hi,

I try to setup unit tests on some code based on prompt. But i am not able to write backspace to the input stream with validator. It sounds like after the first \n aborted by the validator, the \b behave like a left arrow key.

I don't have such behaviour outside of the unittest.

from prompt_toolkit.shortcuts import PromptSession
from prompt_toolkit.input import create_pipe_input
from prompt_toolkit.output import DummyOutput
from prompt_toolkit.validation import Validator, ValidationError


def test_prompt_session():
    """Copy paste of the example provided by prompt toolkit + backspace"""
    with create_pipe_input() as inp:
        inp.send_text("hello\b\n")
        session = PromptSession(
            input=inp,
            output=DummyOutput(),
        )

        result = session.prompt()

    assert result == "hell"


def test_prompt_session2():
    class NameValidator(Validator):
        def validate(self, document):
            text = document.text.lower()
            if not text.isidentifier():
                raise ValidationError(
                    message="The input must be an identifier"
                )

    with create_pipe_input() as inp:
        session = PromptSession(
            input=inp,
            output=DummyOutput(),
            validator=NameValidator()
        )
        inp.send_text("1t\n\b\ba\n")

        result = session.prompt()

    assert result == "a"

The result it

>       assert result == "a"
E       AssertionError: assert 'a1t' == 'a'
E         - a
E         + a1t

Do you have any idea what's wrong or how i should check such key sequence?

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the two test cases using PromptSession, create_pipe_input, DummyOutput, and the validator, then trace how the input sequence is handled after validation fails. Reproduce the behavior with 1t\n\b\ba\n and compare it with hello\b\n; done means the validated sequence returns a while the non-validator case still returns hell.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
cli, testing
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.