def _feed_cli_with_input(
        text, editing_mode=EditingMode.EMACS, clipboard=None, history=None,
        multiline=False, check_line_ending=True, key_bindings=None):
    """
    Create a Prompt, feed it with the given user input and return the CLI
    object.

    This returns a (result, Application) tuple.
    """
    # If the given text doesn't end with a newline, the interface won't finish.
    if check_line_ending:
        assert text.endswith('\r')

    inp = create_pipe_input()

    try:
        inp.send_text(text)
        session = PromptSession(
            input=inp, output=DummyOutput(), editing_mode=editing_mode,
            history=history, multiline=multiline, clipboard=clipboard,
            key_bindings=key_bindings)

        result = session.prompt()
        return session.default_buffer.document, session.app

    finally:
        inp.close()
def set_dummy_app():
    """
    Return a context manager that makes sure that this dummy application is
    active. This is important, because we need an `Application` with
    `is_done=False` flag, otherwise no keys will be processed.
    """
    app = Application(
        layout=Layout(Window()),
        output=DummyOutput(),
        input=create_pipe_input())
    return set_app(app)
Example #3
0
def test_form_creation():
    inp = create_pipe_input()
    text = "Y" + KeyInputs.ENTER + "\r"

    try:
        inp.send_text(text)
        f = example_form(inp)

        result = f.unsafe_ask()

        assert result == {'q1': True, 'q2': 'foo'}
    finally:
        inp.close()
Example #4
0
def test_ask_should_catch_keyboard_exception():
    inp = create_pipe_input()

    try:
        inp.send_text(KeyInputs.CONTROLC)
        f = example_form(inp)

        result = f.ask()
        assert result == {}
    except KeyboardInterrupt:
        fail("Keyboard Interrupt should be caught by `ask()`")
    finally:
        inp.close()
Example #5
0
def test_ask_should_catch_keyboard_exception():
    inp = create_pipe_input()

    try:
        inp.send_text(KeyInputs.CONTROLC)
        question = text("Hello?", input=inp, output=DummyOutput())

        result = question.ask()
        assert result is None
    except KeyboardInterrupt:
        fail("Keyboard Interrupt should be caught by `ask()`")
    finally:
        inp.close()
Example #6
0
def test_multiline_text():
    inp = create_pipe_input()
    try:
        inp.send_text(
            f"Hello{KeyInputs.ENTER}world{KeyInputs.ESCAPE}{KeyInputs.ENTER}")
        question = text("Hello?",
                        input=inp,
                        output=DummyOutput(),
                        multiline=True)
        response = question.ask()
        assert response == "Hello\nworld"
    finally:
        inp.close()
Example #7
0
def patched_prompt(questions, text, **kwargs):
    """Create a prompt where the input and output are predefined."""

    inp = create_pipe_input()

    try:
        # noinspection PyUnresolvedReferences
        inp.send_text(text)
        result = prompt(questions, input=inp, output=DummyOutput(), **kwargs)
        return result

    finally:
        inp.close()
Example #8
0
def set_dummy_app():
    """
    Return a context manager that makes sure that this dummy application is
    active. This is important, because we need an `Application` with
    `is_done=False` flag, otherwise no keys will be processed.
    """
    with create_pipe_input() as pipe_input:
        app = Application(
            layout=Layout(Window()),
            output=DummyOutput(),
            input=pipe_input,
        )
        with set_app(app):
            yield
Example #9
0
def test_skipping_of_skipping_of_questions():
    inp = create_pipe_input()
    try:
        inp.send_text("World" + KeyInputs.ENTER + "\r")

        question = text("Hello?", input=inp, output=DummyOutput()).skip_if(
            condition=False, default=42
        )

        response = question.ask()

        assert response == "World" and not response == 42
    finally:
        inp.close()
def test_accept_default():
    """
    Test `prompt(accept_default=True)`.
    """
    inp = create_pipe_input()

    session = PromptSession(input=inp, output=DummyOutput())
    result = session.prompt(default='hello', accept_default=True)
    assert result == 'hello'

    # Test calling prompt() for a second time. (We had an issue where the
    # prompt reset between calls happened at the wrong time, breaking this.)
    result = session.prompt(default='world', accept_default=True)
    assert result == 'world'

    inp.close()
def test_accept_default():
    """
    Test `prompt(accept_default=True)`.
    """
    inp = create_pipe_input()

    session = PromptSession(input=inp, output=DummyOutput())
    result = session.prompt(default='hello', accept_default=True)
    assert result == 'hello'

    # Test calling prompt() for a second time. (We had an issue where the
    # prompt reset between calls happened at the wrong time, breaking this.)
    result = session.prompt(default='world', accept_default=True)
    assert result == 'world'

    inp.close()
Example #12
0
    def __init__(self,
                 ctx: click.Context = None,
                 on_finished=None,
                 hist_file=None,
                 before_start=None,
                 readline=None,
                 complete_while_typing=True,
                 fuzzy_completion=True,
                 mouse_support=False,
                 lexer=True,
                 *args,
                 **kwargs):
        self._stdout = kwargs.get('stdout')
        super(ClickCmd, self).__init__(*args, **kwargs)

        # readline overrides
        self.old_completer = None
        self.old_delims = None
        self.readline = readline

        # Prompt Toolkit Settings
        self.complete_while_typing = complete_while_typing
        self.fuzzy_completion = fuzzy_completion
        self.mouse_support = mouse_support
        self.lexer = lexer
        self._pipe_input = create_pipe_input() if not self.readline else None

        # A callback function that will be excuted before loading up the shell.
        # By default this changes the color to 0a on a Windows machine
        self.before_start = before_start

        # Save the click.Context and callback for when the shell completes
        self.ctx = ctx
        self.on_finished = on_finished

        # Define the history file
        hist_file = hist_file or os.path.join(os.path.expanduser('~'),
                                              globs.HISTORY_FILENAME)
        self.hist_file = os.path.abspath(hist_file)
        if not os.path.isdir(os.path.dirname(self.hist_file)):
            os.makedirs(os.path.dirname(self.hist_file))

        self.history = FileHistory(self.hist_file)
        self.history.load_history_strings()
Example #13
0
def feed_cli_with_input(_type, message, text, **kwargs):
    """
    Create a Prompt, feed it with the given user input and return the CLI
    object.
    This returns a (result, Application) tuple.
    """

    inp = create_pipe_input()

    try:
        inp.send_text(text)
        prompter = prompt_by_name(_type)
        application = prompter(message, input=inp, output=DummyOutput(), **kwargs)

        result = application.unsafe_ask()
        return result, application

    finally:
        inp.close()
Example #14
0
def feed_cli_with_input(_type, message, texts, sleep_time=1, **kwargs):
    """
    Create a Prompt, feed it with the given user input and return the CLI
    object.

    You an provide multiple texts, the feeder will async sleep for `sleep_time`

    This returns a (result, Application) tuple.
    """

    if not isinstance(texts, list):
        texts = [texts]

    inp = create_pipe_input()

    try:
        prompter = prompt_by_name(_type)
        application = prompter(message,
                               input=inp,
                               output=DummyOutput(),
                               **kwargs)

        if is_prompt_toolkit_3():
            loop = asyncio.new_event_loop()
            future_result = loop.create_task(application.unsafe_ask_async())

            for i, text in enumerate(texts):
                # noinspection PyUnresolvedReferences
                inp.send_text(text)

                if i != len(texts) - 1:
                    loop.run_until_complete(asyncio.sleep(sleep_time))
            result = loop.run_until_complete(future_result)
        else:
            for text in texts:
                inp.send_text(text)
            result = application.unsafe_ask()

        return result, application
    finally:
        inp.close()
Example #15
0
def test_blank_line_fix():
    def get_prompt_tokens():
        return [("class:question", "What is your favourite letter?")]

    ic = InquirerControl(["a", "b", "c"])

    inp = create_pipe_input()

    try:
        inp.send_text("")
        layout = common.create_inquirer_layout(ic,
                                               get_prompt_tokens,
                                               input=inp,
                                               output=DummyOutput())

        # usually this would be 2000000000000000000000000000000
        # but `common._fix_unecessary_blank_lines` makes sure
        # the main window is not as greedy (avoiding blank lines)
        assert (layout.container.preferred_height(
            100, 200).max == 1000000000000000000000000000001)
    finally:
        inp.close()
Example #16
0
def _feed_cli_with_input(
    text,
    editing_mode=EditingMode.EMACS,
    clipboard=None,
    history=None,
    multiline=False,
    check_line_ending=True,
    key_bindings=None,
):
    """
    Create a Prompt, feed it with the given user input and return the CLI
    object.

    This returns a (result, Application) tuple.
    """
    # If the given text doesn't end with a newline, the interface won't finish.
    if check_line_ending:
        assert text.endswith("\r")

    inp = create_pipe_input()

    try:
        inp.send_text(text)
        session = PromptSession(
            input=inp,
            output=DummyOutput(),
            editing_mode=editing_mode,
            history=history,
            multiline=multiline,
            clipboard=clipboard,
            key_bindings=key_bindings,
        )

        result = session.prompt()
        return session.default_buffer.document, session.app

    finally:
        inp.close()
Example #17
0
 def setUp(self):
     self.inp = create_pipe_input()
Example #18
0
 def setUp(self):
     self.inp = create_pipe_input()
     self.dirs_to_create = ["dir1", "dir2", "dir3", ".dir"]
     self.files_to_create = ["file1", "file2", "file3", ".file"]
     self.test_dir = Path(tempfile.mkdtemp())
     self.create_temp_files()