Example #1
0
    def test_custom_reject(self):
        self.inp.send_text("w")
        confirm_prompt = ConfirmPrompt(
            message="hello",
            style=None,
            default=False,
            qmark="?",
            output=DummyOutput(),
            input=self.inp,
            reject_letter="w",
        )
        result = confirm_prompt.execute()
        self.assertEqual(result, False)
        self.assertEqual(confirm_prompt.status["answered"], True)
        self.assertEqual(confirm_prompt.status["result"], False)

        self.inp.send_text("W")
        confirm_prompt = ConfirmPrompt(
            message="hello",
            style=None,
            default=True,
            qmark="?",
            output=DummyOutput(),
            input=self.inp,
            reject_letter="w",
        )
        result = confirm_prompt.execute()
        self.assertEqual(result, False)
Example #2
0
    def test_input_n(self):
        self.inp.send_text("n")
        confirm_prompt = ConfirmPrompt(
            message="hello",
            style=None,
            default=True,
            qmark="?",
            output=DummyOutput(),
            input=self.inp,
        )
        result = confirm_prompt.execute()
        self.assertEqual(result, False)
        self.assertEqual(confirm_prompt.status["answered"], True)
        self.assertEqual(confirm_prompt.status["result"], False)

        self.inp.send_text("N")
        confirm_prompt = ConfirmPrompt(
            message="hello",
            style=None,
            default=True,
            qmark="?",
            output=DummyOutput(),
            input=self.inp,
        )
        result = confirm_prompt.execute()
        self.assertEqual(result, False)
Example #3
0
    def test_input_y_async(self):
        self.inp.send_text("y")
        confirm_prompt = ConfirmPrompt(
            message="hello",
            style=None,
            default=True,
            qmark="?",
            output=DummyOutput(),
            input=self.inp,
        )
        result = asyncio.run(confirm_prompt._run_async())
        self.assertEqual(result, True)
        self.assertEqual(confirm_prompt.status["answered"], True)
        self.assertEqual(confirm_prompt.status["result"], True)

        self.inp.send_text("Y")
        confirm_prompt = ConfirmPrompt(
            message="hello",
            style=None,
            default=True,
            qmark="?",
            output=DummyOutput(),
            input=self.inp,
        )
        result = asyncio.run(confirm_prompt.execute_async())
        self.assertEqual(result, True)
Example #4
0
    def test_custom_confirm(self):
        self.inp.send_text("s")
        confirm_prompt = ConfirmPrompt(
            message="hello",
            style=None,
            default=True,
            qmark="?",
            output=DummyOutput(),
            input=self.inp,
            confirm_letter="s",
        )
        result = confirm_prompt._session.prompt()
        self.assertEqual(result, True)
        self.assertEqual(confirm_prompt.status["answered"], True)
        self.assertEqual(confirm_prompt.status["result"], True)

        self.inp.send_text("S")
        confirm_prompt = ConfirmPrompt(
            message="hello",
            style=None,
            default=True,
            qmark="?",
            output=DummyOutput(),
            input=self.inp,
            confirm_letter="s",
        )
        result = confirm_prompt.execute()
        self.assertEqual(result, True)
Example #5
0
def example_form(inp):
    return form(q1=questionary.confirm("Hello?",
                                       input=inp,
                                       output=DummyOutput()),
                q2=questionary.select("World?",
                                      choices=["foo", "bar"],
                                      input=inp,
                                      output=DummyOutput()))
Example #6
0
def mock_prompt_input():
    # TODO: remove if prompt-toolkit min version gets bumped
    if PIPE_INPUT_CONTEXT_MANAGER:
        with create_pipe_input() as pipe_input:
            with create_app_session(input=pipe_input, output=DummyOutput()):
                yield pipe_input
    else:
        pipe_input = create_pipe_input()
        try:
            with create_app_session(input=pipe_input, output=DummyOutput()):
                yield pipe_input
        finally:
            pipe_input.close()
Example #7
0
def test_cli_argument():
    arguments = ['ws-ui']
    with patch.object(sys, 'argv', arguments):
        with create_app_session(input=create_pipe_input(),
                                output=DummyOutput()):
            app = Application()
            asyncio.run(app.main())
Example #8
0
def feed_app_with_input(type, message, text, **kwargs):
    """
    Create an application, feed it with the given user input and return
    the CLI object.

    This returns a (result, CLI) tuple.
    note: this only works if you import your prompt and then this function!!
    """
    # If the given text doesn't end with a newline, the interface won't finish.
    assert text.endswith('\r')

    inp = PosixPipeInput(text)

    try:
        with create_app_session(input=inp, output=DummyOutput()) as session:
            application = getattr(prompts, type).question(message, **kwargs)
            #print(application.input)
            #breakpoint()

            if isinstance(application, Application):
                result = application.run()
            elif isinstance(application, PromptSession):
                result = application.prompt()
            return result
    finally:
        inp.close()
Example #9
0
def test_print(monkeypatch):
    mock = Mock(return_value=None)
    monkeypatch.setattr(DummyOutput, "write", mock)

    print_formatted_text("Hello World", output=DummyOutput())

    mock.assert_has_calls([call("Hello World"), call("\r\n")])
Example #10
0
    def test_prompt_completion(self):
        input_prompt = InputPrompt(
            message="yes",
            style=None,
            default="",
            qmark="!",
            vi_mode=False,
            input=self.inp,
            output=DummyOutput(),
            multiline=True,
            completer={
                "hello": None,
                "hey": None,
                "what": None
            },
        )

        completer = input_prompt._completer
        doc_text = "he"
        doc = Document(doc_text, len(doc_text))
        event = CompleteEvent()
        completions = [
            completion.text for completion in list(
                completer.get_completions(doc, event))  # type: ignore
        ]
        self.assertEqual(sorted(completions), ["hello", "hey"])
Example #11
0
 def test_prompt_filter(self):
     self.inp.send_text("hello\n")
     input_prompt = InputPrompt(
         message="yes",
         style=None,
         default="world",
         qmark="!",
         vi_mode=False,
         input=self.inp,
         output=DummyOutput(),
         filter=lambda x: x * 2,
         transformer=lambda _: "what",
     )
     result = input_prompt.execute()
     self.assertEqual(result, "worldhelloworldhello")
     self.assertEqual(input_prompt.status["answered"], True)
     self.assertEqual(input_prompt.status["result"], "worldhello")
     self.assertEqual(
         input_prompt._get_prompt_message(),
         [
             ("class:answermark", "?"),
             ("class:answered_question", " yes"),
             ("class:answer", " what"),
         ],
     )
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 #13
0
def feed_app_with_input(type, message, text, **kwargs):
    """
    Create a CommandLineInterface, feed it with the given user input and return
    the CLI object.

    This returns a (result, CLI) tuple.
    note: this only works if you import your prompt and then this function!!
    """
    # If the given text doesn't end with a newline, the interface won't finish.
    assert text.endswith('\n')

    application = getattr(prompts, type).question(message, **kwargs)

    loop = PosixEventLoop()
    try:
        inp = PipeInput()
        inp.send_text(text)
        cli = CommandLineInterface(
            application=application,
            eventloop=loop,
            input=inp,
            output=DummyOutput())
        result = cli.run()
        return result, cli
    finally:
        loop.close()
        inp.close()
Example #14
0
def ask_with_patched_input(q, text):
    inp = create_pipe_input()
    try:
        inp.send_text(text)
        return q(input=inp, output=DummyOutput())
    finally:
        inp.close()
Example #15
0
def _feed_cli_with_input(text,
                         editing_mode=EditingMode.EMACS,
                         clipboard=None,
                         history=None):
    """
    Create a CommandLineInterface, feed it with the given user input and return
    the CLI object.

    This returns a (result, CLI) tuple.
    """
    # If the given text doesn't end with a newline, the interface won't finish.
    assert text.endswith('\n')

    from prompt_toolkit.eventloop.posix import PosixEventLoop as EventLoop
    loop = EventLoop()
    try:
        inp = PipeInput()
        inp.send_text(text)
        cli = CommandLineInterface(application=Application(
            buffer=Buffer(accept_action=AcceptAction.RETURN_DOCUMENT,
                          history=history),
            editing_mode=editing_mode,
            clipboard=clipboard or InMemoryClipboard(),
            key_bindings_registry=KeyBindingManager.for_prompt().registry,
        ),
                                   eventloop=loop,
                                   input=inp,
                                   output=DummyOutput())
        result = cli.run()
        return result, cli
    finally:
        loop.close()
        inp.close()
Example #16
0
 def setUp(self):
     self.input = PipeInput()
     output = DummyOutput()
     self.aws_shell = AWSShell(None,
                               mock.Mock(),
                               mock.Mock(),
                               input=self.input,
                               output=output)
     self.processor = self.aws_shell.cli.input_processor
Example #17
0
def app():
    pipe_input = create_pipe_input()
    try:
        with create_app_session(input=pipe_input, output=DummyOutput()):
            config = Config()
            app = App(config=config)
            yield app
    finally:
        pipe_input.close()
Example #18
0
def test_skipping_of_questions():
    inp = create_pipe_input()
    try:
        question = text("Hello?", input=inp, output=DummyOutput()).skip_if(
            condition=True, default=42
        )
        response = question.ask()
        assert response == 42
    finally:
        inp.close()
Example #19
0
def mock_input():
    pipe_input = create_pipe_input()
    try:
        with create_app_session(
                input=pipe_input,
                output=DummyOutput(),
        ):
            yield pipe_input
    finally:
        pipe_input.close()
Example #20
0
def mock_app(mocker):
    app = Application(
        input=create_pipe_input(),
        output=DummyOutput(),
    )
    mocker.patch('upsies.uis.tui.tui.TUI._make_app', Mock(return_value=app))
    mocker.patch('upsies.uis.tui.tui.TUI._jobs_container',
                 Mock(children=[]),
                 create=True)
    mocker.patch('upsies.uis.tui.tui.TUI._layout', Mock(), create=True)
Example #21
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.
    """
    app = Application(layout=Layout(Window()),
                      output=DummyOutput(),
                      input=create_pipe_input())
    return set_app(app)
Example #22
0
    def test_layout(self):
        input = create_pipe_input()
        with create_app_session(input=input, output=DummyOutput()):
            tui = TerminalUI()
            layout = tui.app.layout
            assert len(list(layout.find_all_windows())) > 1

            children = layout.container.get_children()
            assert len(children) == 2
            assert len(children[0].get_children()) == 2
Example #23
0
def prompt(monkeypatch):
    monkeypatch.setattr('getpass.getpass', lambda _: 'mock_password')
    pipe = create_pipe_input()
    try:
        session = PromptSession(
            input=pipe,
            output=DummyOutput(),
        )
        yield Prompt(session, pipe)
    finally:
        pipe.close()
Example #24
0
def test_async_ask_question():
    loop = asyncio.new_event_loop()

    inp = create_pipe_input()
    try:
        inp.send_text("World" + KeyInputs.ENTER + "\r")
        question = text("Hello?", input=inp, output=DummyOutput())
        response = loop.run_until_complete(question.ask_async())
        assert response == "World"
    finally:
        inp.close()
Example #25
0
def patched_prompt(questions, text, **kwargs):
    """Create a prompt where the input and output are predefined."""

    inp = create_pipe_input()

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

    finally:
        inp.close()
Example #26
0
def ptk_shell(xonsh_execer):
    from prompt_toolkit.input import create_pipe_input
    from prompt_toolkit.output import DummyOutput
    from xonsh.ptk_shell.shell import PromptToolkitShell

    inp = create_pipe_input()
    out = DummyOutput()
    shell = PromptToolkitShell(
        execer=xonsh_execer, ctx={}, ptk_args={"input": inp, "output": out}
    )
    yield inp, out, shell
    inp.close()
Example #27
0
 def test_input(self):
     self.inp.send_text("./file1\n")
     filepath_prompt = FilePathPrompt(
         message="hello",
         style=InquirerPyStyle({"qmark": "bold"}),
         input=self.inp,
         output=DummyOutput(),
     )
     result = filepath_prompt.execute()
     self.assertEqual(result, "./file1")
     self.assertEqual(filepath_prompt.status["answered"], True)
     self.assertEqual(filepath_prompt.status["result"], "./file1")
Example #28
0
def test_ask_should_catch_keyboard_exception():
    inp = create_pipe_input()

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

        result = application.ask()
        assert result is None
    except KeyboardInterrupt:
        fail("Keyboard Interrupt should be caught by `ask()`")
    finally:
        inp.close()
Example #29
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 #30
0
def test_accept_default():
    """
    Test `prompt(accept_default=True)`.
    """
    with create_pipe_input() as inp:
        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"