def test_run_runs_the_list_command_without_arguments(tester: ApplicationTester):
    tester.execute("", decorated=False)

    assert (
        tester.io.fetch_output()
        == FIXTURES_PATH.joinpath("application_run1.txt").read_text()
    )
Exemple #2
0
def test_publish_with_client_cert(app_tester: ApplicationTester, mocker: MockerFixture):
    publisher_publish = mocker.patch("poetry.publishing.Publisher.publish")

    app_tester.execute("publish --client-cert path/to/client.pem")
    assert [
        (None, None, None, None, Path("path/to/client.pem"), False, False)
    ] == publisher_publish.call_args
def test_silent_help(app: Application):
    app.catch_exceptions(False)

    tester = ApplicationTester(app)
    tester.execute("-h -q", decorated=False)

    assert tester.io.fetch_output() == ""
Exemple #4
0
    def test_set_run_custom_default_command(self):
        """
        Application calls the default command.
        """
        application = Application()
        application.set_auto_exit(False)
        command = FooCommand()
        application.add(command)
        application.set_default_command(command.get_name())

        tester = ApplicationTester(application)
        tester.run([])
        self.assertEqual(
            'interact called\ncalled\n',
            tester.get_display()
        )

        application = CustomDefaultCommandApplication()
        application.set_auto_exit(False)

        tester = ApplicationTester(application)
        tester.run([])
        self.assertEqual(
            'interact called\ncalled\n',
            tester.get_display()
        )
Exemple #5
0
class TestApplicationTester(TestCase):
    def setUp(self):
        self.application = Application()
        self.application.set_auto_exit(False)
        self.application.register('foo')\
            .add_argument('foo')\
            .set_code(lambda c: c.line('foo'))

        self.tester = ApplicationTester(self.application)
        self.tester.run(
            [('command', 'foo'), ('foo', 'bar')], {
                'interactive': False,
                'decorated': False,
                'verbosity': Output.VERBOSITY_VERBOSE
            })

    def tearDown(self):
        self.application = None
        self.tester = None

    def test_run(self):
        """
        ApplicationTester.run() behaves properly
        """
        self.assertFalse(self.tester.get_input().is_interactive(),
                         msg='.run() takes an interactive option.')
        self.assertFalse(self.tester.get_output().is_decorated(),
                         msg='.run() takes a decorated option.')
        self.assertEqual(Output.VERBOSITY_VERBOSE,
                         self.tester.get_output().get_verbosity(),
                         msg='.run() takes an interactive option.')

    def test_get_input(self):
        """
        ApplicationTester.get_input() behaves properly
        """
        self.assertEqual(
            'bar',
            self.tester.get_input().get_argument('foo'),
            msg='.get_input() returns the current input instance.')

    def test_get_output(self):
        """
        ApplicationTester.get_output() behaves properly
        """
        self.tester.get_output().get_stream().seek(0)
        self.assertEqual(
            'foo\n',
            self.tester.get_output().get_stream().read().decode('utf-8'),
            msg='.get_output() returns the current output instance.')

    def test_get_display(self):
        """
        ApplicationTester.get_display() behaves properly
        """
        self.assertEqual(
            'foo\n',
            self.tester.get_display(),
            msg='.get_display() returns the display of the last execution.')
def test_run_removes_all_output_if_quiet(tester: ApplicationTester):
    tester.execute("list --quiet")

    assert tester.io.fetch_output() == ""

    tester.execute("list -q")

    assert tester.io.fetch_output() == ""
Exemple #7
0
def test_run_keeps_options_passed_before_command(app_tester: ApplicationTester,
                                                 env: MockEnv):
    app_tester.execute("-V --no-ansi run python", decorated=True)

    assert not app_tester.io.is_decorated()
    assert app_tester.io.fetch_output() == app_tester.io.remove_format(
        app_tester.application.long_version + "\n")
    assert [] == env.executed
class TestApplicationTester(TestCase):

    def setUp(self):
        self.application = Application()
        self.application.set_auto_exit(False)
        self.application.register('foo')\
            .add_argument('foo')\
            .set_code(lambda input_, output_: output_.writeln('foo'))

        self.tester = ApplicationTester(self.application)
        self.tester.run(
            [
                ('command', 'foo'),
                ('foo', 'bar')
            ],
            {
                'interactive': False,
                'decorated': False,
                'verbosity': Output.VERBOSITY_VERBOSE
            }
        )

    def tearDown(self):
        self.application = None
        self.tester = None

    def test_run(self):
        """
        ApplicationTester.run() behaves properly
        """
        self.assertFalse(self.tester.get_input().is_interactive(),
                         msg='.run() takes an interactive option.')
        self.assertFalse(self.tester.get_output().is_decorated(),
                         msg='.run() takes a decorated option.')
        self.assertEqual(Output.VERBOSITY_VERBOSE, self.tester.get_output().get_verbosity(),
                         msg='.run() takes an interactive option.')

    def test_get_input(self):
        """
        ApplicationTester.get_input() behaves properly
        """
        self.assertEqual('bar', self.tester.get_input().get_argument('foo'),
                         msg='.get_input() returns the current input instance.')

    def test_get_output(self):
        """
        ApplicationTester.get_output() behaves properly
        """
        self.tester.get_output().get_stream().seek(0)
        self.assertEqual('foo\n', self.tester.get_output().get_stream().read().decode('utf-8'),
                         msg='.get_output() returns the current output instance.')

    def test_get_display(self):
        """
        ApplicationTester.get_display() behaves properly
        """
        self.assertEqual('foo\n', self.tester.get_display(),
                         msg='.get_display() returns the display of the last execution.')
    def test_application_accepts_command(self):
        app = application

        tester = ApplicationTester(app)
        tester.execute("")

        self.assertTrue(re.search("Console Tool", tester.io.fetch_output()))
        self.assertTrue(
            re.search("Display the manual of a command",
                      tester.io.fetch_output()))
        self.assertEqual(0, tester.status_code)
Exemple #10
0
    def test_silent_help(self):
        """
        Silent help should return nothing
        """
        application = Application()
        application.set_auto_exit(False)
        application.set_catch_exceptions(False)

        tester = ApplicationTester(application)
        tester.run([('-h', True), ('-q', True)], {'decorated': False})

        self.assertEqual('', tester.get_display())
Exemple #11
0
    def test_silent_help(self):
        """
        Silent help should return nothing
        """
        application = Application()
        application.set_auto_exit(False)
        application.set_catch_exceptions(False)

        tester = ApplicationTester(application)
        tester.run([("-h", True), ("-q", True)], {"decorated": False})

        self.assertEqual("", tester.get_display())
Exemple #12
0
    def test_application_accepts_watch_command(self):
        app = application

        tester = ApplicationTester(app)
        tester.execute("watch --help")

        self.assertTrue(
            re.search(r"<folder>\s+Which folder do you want to watch?",
                      tester.io.fetch_output()))
        self.assertTrue(
            re.search(r"<command>\s+What command to run?",
                      tester.io.fetch_output()))
        self.assertEqual(0, tester.status_code)
Exemple #13
0
    def setUp(self):
        self.application = Application()
        self.application.set_auto_exit(False)
        self.application.register('foo')\
            .add_argument('foo')\
            .set_code(lambda c: c.line('foo'))

        self.tester = ApplicationTester(self.application)
        self.tester.run(
            [('command', 'foo'), ('foo', 'bar')], {
                'interactive': False,
                'decorated': False,
                'verbosity': Output.VERBOSITY_VERBOSE
            })
Exemple #14
0
def test_run_runs_help_command_with_command(tester: ApplicationTester):
    tester.execute("--help list", decorated=False)

    assert (
        tester.io.fetch_output()
        == FIXTURES_PATH.joinpath("application_run3.txt").read_text()
    )

    tester.execute("list -h", decorated=False)

    assert (
        tester.io.fetch_output()
        == FIXTURES_PATH.joinpath("application_run3.txt").read_text()
    )
Exemple #15
0
def test_run_with_version(tester: ApplicationTester):
    tester.execute("--version")

    assert (
        tester.io.fetch_output()
        == FIXTURES_PATH.joinpath("application_run4.txt").read_text()
    )

    tester.execute("-V")

    assert (
        tester.io.fetch_output()
        == FIXTURES_PATH.joinpath("application_run4.txt").read_text()
    )
Exemple #16
0
def test_run_with_help(tester: ApplicationTester):
    tester.execute("help --help")

    assert (
        tester.io.fetch_output()
        == FIXTURES_PATH.joinpath("application_run5.txt").read_text()
    )

    tester.execute("-h help")

    assert (
        tester.io.fetch_output()
        == FIXTURES_PATH.joinpath("application_run5.txt").read_text()
    )
Exemple #17
0
def test_publish_returns_non_zero_code_for_upload_errors(
    app: PoetryTestApplication,
    app_tester: ApplicationTester,
    http: type[httpretty.httpretty],
):
    http.register_uri(http.POST,
                      "https://upload.pypi.org/legacy/",
                      status=400,
                      body="Bad Request")

    exit_code = app_tester.execute("publish --username foo --password bar")

    assert exit_code == 1

    expected_output = """
Publishing simple-project (1.2.3) to PyPI
"""
    expected_error_output = """\
  UploadError

  HTTP Error 400: Bad Request
"""

    assert expected_output in app_tester.io.fetch_output()
    assert expected_error_output in app_tester.io.fetch_error()
def test_application_execute_plugin_command(mocker: MockerFixture):
    mocker.patch(
        "entrypoints.get_group_all",
        return_value=[
            EntryPoint("my-plugin", "tests.console.test_application",
                       "AddCommandPlugin")
        ],
    )

    app = Application()

    tester = ApplicationTester(app)
    tester.execute("foo")

    assert tester.io.fetch_output() == "foo called\n"
    assert tester.status_code == 0
def test_application_with_plugins_disabled(mocker: MockerFixture):
    mocker.patch(
        "entrypoints.get_group_all",
        return_value=[
            EntryPoint("my-plugin", "tests.console.test_application",
                       "AddCommandPlugin")
        ],
    )

    app = Application()

    tester = ApplicationTester(app)
    tester.execute("--no-plugins")

    assert re.search(r"\s+foo\s+Foo Command", tester.io.fetch_output()) is None
    assert tester.status_code == 0
def test_application_execute_plugin_command_with_plugins_disabled(mocker):
    mocker.patch(
        "entrypoints.get_group_all",
        return_value=[
            EntryPoint("my-plugin", "tests.console.test_application",
                       "AddCommandPlugin")
        ],
    )

    app = Application()

    tester = ApplicationTester(app)
    tester.execute("foo --no-plugins")

    assert "" == tester.io.fetch_output()
    assert '\nThe command "foo" does not exist.\n' == tester.io.fetch_error()
    assert 1 == tester.status_code
def test_application_verify_source_cache_flag(disable_cache: bool):
    app = Application()

    tester = ApplicationTester(app)
    command = "debug info"

    if disable_cache:
        command = f"{command} --no-cache"

    assert not app._poetry

    tester.execute(command)

    assert app.poetry.pool.repositories

    for repo in app.poetry.pool.repositories:
        assert repo._disable_cache == disable_cache
Exemple #22
0
def test_cache_clear_pkg_no(
    tester: ApplicationTester,
    repository_one: str,
    cache: CacheManager,
):
    exit_code = tester.execute(f"cache clear {repository_one}:cachy:0.1", inputs="no")

    assert exit_code == 0
    assert tester.io.fetch_output() == ""
    assert cache.has("cachy:0.1")
    assert cache.has("cleo:0.2")
Exemple #23
0
def test_run_has_helpful_error_when_command_not_found(
        app_tester: ApplicationTester, env: MockEnv,
        capfd: pytest.CaptureFixture[str]):
    env._execute = True
    app_tester.execute("run nonexistent-command")

    assert env.executed == [["nonexistent-command"]]
    assert app_tester.status_code == 1
    if WINDOWS:
        # On Windows we use a shell to run commands which provides its own error
        # message when a command is not found that is not captured by the
        # ApplicationTester but is captured by pytest, and we can access it via capfd.
        # The expected string in this assertion assumes Command Prompt (cmd.exe) is the
        # shell used.
        assert capfd.readouterr().err.splitlines() == [
            "'nonexistent-command' is not recognized as an internal or external"
            " command,",
            "operable program or batch file.",
        ]
    else:
        assert app_tester.io.fetch_error(
        ) == "Command not found: nonexistent-command\n"
Exemple #24
0
    def test_set_run_custom_single_command(self):
        command = FooCommand()

        application = Application()
        application.set_auto_exit(False)
        application.add(command)
        application.set_default_command(command.get_name(), True)

        tester = ApplicationTester(application)

        tester.run([])
        self.assertIn('called', tester.get_display())

        tester.run([('--help', True)])
        self.assertIn('The foo:bar command', tester.get_display())
Exemple #25
0
def test_skip_existing_output(app_tester: ApplicationTester,
                              http: type[httpretty.httpretty]):
    http.register_uri(http.POST,
                      "https://upload.pypi.org/legacy/",
                      status=409,
                      body="Conflict")

    exit_code = app_tester.execute(
        "publish --skip-existing --username foo --password bar")

    assert exit_code == 0

    error = app_tester.io.fetch_error()
    assert "- Uploading simple-project-1.2.3.tar.gz File exists. Skipping" in error
Exemple #26
0
def test_run_with_verbosity(tester: ApplicationTester):
    tester.execute("list --verbose")

    assert tester.io.is_verbose()

    tester.execute("list -v")

    assert tester.io.is_verbose()

    tester.execute("list -vv")

    assert tester.io.is_very_verbose()

    tester.execute("list -vvv")

    assert tester.io.is_debug()
Exemple #27
0
def test_cache_clear_all_no(
    tester: ApplicationTester,
    repository_one: str,
    repository_cache_dir: Path,
    cache: CacheManager,
):
    exit_code = tester.execute(f"cache clear {repository_one} --all", inputs="no")

    assert exit_code == 0
    assert tester.io.fetch_output() == ""
    # ensure directory is not empty
    assert any((repository_cache_dir / repository_one).iterdir())
    assert cache.has("cachy:0.1")
    assert cache.has("cleo:0.2")
Exemple #28
0
def test_publish_dry_run_skip_existing(
    app_tester: ApplicationTester, http: type[httpretty.httpretty], options: str
):
    http.register_uri(
        http.POST, "https://upload.pypi.org/legacy/", status=409, body="Conflict"
    )

    exit_code = app_tester.execute(f"publish {options} --username foo --password bar")

    assert exit_code == 0

    output = app_tester.io.fetch_output()
    error = app_tester.io.fetch_error()

    assert "Publishing simple-project (1.2.3) to PyPI" in output
    assert "- Uploading simple-project-1.2.3.tar.gz" in error
    assert "- Uploading simple_project-1.2.3-py2.py3-none-any.whl" in error
Exemple #29
0
    def test_find_alternative_commands_with_question(self):
        application = Application()
        application.set_auto_exit(False)
        os.environ['COLUMNS'] = '120'
        os.environ['SHELL_INTERACTIVE'] = '1'
        application.add(FooCommand())
        application.add(Foo1Command())
        application.add(Foo2Command())

        tester = ApplicationTester(application)
        tester.set_inputs(['1\n'])
        tester.run([('command', 'f:b')], {'interactive': True})

        self.assertEqual(
            self.open_fixture('application_unknown_command_question.txt'),
            tester.get_display(True))
Exemple #30
0
    def test_set_run_custom_default_command(self):
        """
        Application calls the default command.
        """
        application = Application()
        application.set_auto_exit(False)
        command = FooCommand()
        application.add(command)
        application.set_default_command(command.get_name())

        tester = ApplicationTester(application)
        tester.run([])
        self.assertEqual("interact called\ncalled\n", tester.get_display())

        application = CustomDefaultCommandApplication()
        application.set_auto_exit(False)

        tester = ApplicationTester(application)
        tester.run([])
        self.assertEqual("interact called\ncalled\n", tester.get_display())
Exemple #31
0
    def test_set_catch_exceptions(self):
        application = Application()
        application.set_auto_exit(False)
        os.environ['COLUMNS'] = '120'
        tester = ApplicationTester(application)

        application.set_catch_exceptions(True)
        tester.run([('command', 'foo')], {'decorated': False})
        self.assertEqual(self.open_fixture('application_renderexception1.txt'),
                         tester.get_display())

        application.set_catch_exceptions(False)
        try:
            tester.run([('command', 'foo')], {'decorated': False})
            self.fail('.set_catch_exceptions() sets the catch exception flag')
        except Exception as e:
            self.assertEqual('Command "foo" is not defined.', str(e))
Exemple #32
0
def test_publish_returns_non_zero_code_for_connection_errors(
    app: PoetryTestApplication,
    app_tester: ApplicationTester,
    http: type[httpretty.httpretty],
):
    def request_callback(*_: Any, **__: Any) -> None:
        raise requests.ConnectionError()

    http.register_uri(
        http.POST, "https://upload.pypi.org/legacy/", body=request_callback
    )

    exit_code = app_tester.execute("publish --username foo --password bar")

    assert exit_code == 1

    expected = str(UploadError(error=requests.ConnectionError()))

    assert expected in app_tester.io.fetch_error()
Exemple #33
0
    def setUp(self):
        self.application = Application()
        self.application.set_auto_exit(False)
        self.application.register('foo')\
            .add_argument('foo')\
            .set_code(lambda input_, output_: output_.writeln('foo'))

        self.tester = ApplicationTester(self.application)
        self.tester.run(
            [
                ('command', 'foo'),
                ('foo', 'bar')
            ],
            {
                'interactive': False,
                'decorated': False,
                'verbosity': Output.VERBOSITY_VERBOSE
            }
        )
Exemple #34
0
    def test_set_catch_exceptions(self):
        application = Application()
        application.set_auto_exit(False)
        application.get_terminal_width = self.mock().MagicMock(return_value=120)
        tester = ApplicationTester(application)

        application.set_catch_exceptions(True)
        tester.run([('command', 'foo')], {'decorated': False})
        self.assertEqual(
            self.open_fixture('application_renderexception1.txt'),
            tester.get_display()
        )

        application.set_catch_exceptions(False)
        try:
            tester.run([('command', 'foo')], {'decorated': False})
            self.fail('.set_catch_exceptions() sets the catch exception flag')
        except Exception as e:
            self.assertEqual('Command "foo" is not defined.', str(e))
Exemple #35
0
    def test_set_catch_exceptions(self):
        application = Application()
        application.set_auto_exit(False)
        application.get_terminal_width = self.mock().MagicMock(return_value=120)
        tester = ApplicationTester(application)

        application.set_catch_exceptions(True)
        tester.run([("command", "foo")], {"decorated": False})
        self.assertEqual(self.open_fixture("application_renderexception1.txt"), tester.get_display())

        application.set_catch_exceptions(False)
        try:
            tester.run([("command", "foo")], {"decorated": False})
            self.fail(".set_catch_exceptions() sets the catch exception flag")
        except Exception as e:
            self.assertEqual('Command "foo" is not defined.', str(e))
Exemple #36
0
    def test_render_exception(self):
        """
        Application.render_exception() displays formatted exception.
        """
        application = Application()
        application.set_auto_exit(False)

        application.get_terminal_width = self.mock().MagicMock(return_value=120)
        tester = ApplicationTester(application)

        tester.run([("command", "foo")], {"decorated": False})
        self.assertEqual(self.open_fixture("application_renderexception1.txt"), tester.get_display())

        tester.run([("command", "foo")], {"decorated": False, "verbosity": Output.VERBOSITY_VERBOSE})
        self.assertRegex(tester.get_display(), "Exception trace")

        tester.run([("command", "list"), ("--foo", True)], {"decorated": False})
        self.assertEqual(self.open_fixture("application_renderexception2.txt"), tester.get_display())

        application.add(Foo3Command())
        tester = ApplicationTester(application)
        tester.run([("command", "foo3:bar")], {"decorated": False})
        self.assertEqual(self.open_fixture("application_renderexception3.txt"), tester.get_display())
        tester = ApplicationTester(application)
        tester.run([("command", "foo3:bar")], {"decorated": True})
        self.assertEqual(self.open_fixture("application_renderexception3decorated.txt"), tester.get_display())

        application = Application()
        application.set_auto_exit(False)

        application.get_terminal_width = self.mock().MagicMock(return_value=31)
        tester = ApplicationTester(application)

        tester.run([("command", "foo")], {"decorated": False})
        self.assertEqual(self.open_fixture("application_renderexception4.txt"), tester.get_display())
Exemple #37
0
    def test_run(self):
        application = Application()
        application.set_auto_exit(False)
        application.set_catch_exceptions(False)
        command = Foo1Command()
        application.add(command)

        sys.argv = ["cli.py", "foo:bar1"]

        application.run()

        self.assertEqual("ArgvInput", command.input.__class__.__name__)
        self.assertEqual("ConsoleOutput", command.output.__class__.__name__)

        application = Application()
        application.set_auto_exit(False)
        application.set_catch_exceptions(False)

        self.ensure_static_command_help(application)
        tester = ApplicationTester(application)

        tester.run([], {"decorated": False})
        self.assertEqual(self.open_fixture("application_run1.txt"), tester.get_display())

        tester.run([("--help", True)], {"decorated": False})
        self.assertEqual(self.open_fixture("application_run2.txt"), tester.get_display())

        tester.run([("-h", True)], {"decorated": False})
        self.assertEqual(self.open_fixture("application_run2.txt"), tester.get_display())

        tester.run([("command", "list"), ("--help", True)], {"decorated": False})
        self.assertEqual(self.open_fixture("application_run3.txt"), tester.get_display())

        tester.run([("command", "list"), ("-h", True)], {"decorated": False})
        self.assertEqual(self.open_fixture("application_run3.txt"), tester.get_display())

        tester.run([("--ansi", True)])
        self.assertTrue(tester.get_output().is_decorated())

        tester.run([("--no-ansi", True)])
        self.assertFalse(tester.get_output().is_decorated())

        tester.run([("--version", True)], {"decorated": False})
        self.assertEqual(self.open_fixture("application_run4.txt"), tester.get_display())

        tester.run([("-V", True)], {"decorated": False})
        self.assertEqual(self.open_fixture("application_run4.txt"), tester.get_display())

        tester.run([("command", "list"), ("--quiet", True)])
        self.assertEqual("", tester.get_display())

        tester.run([("command", "list"), ("-q", True)])
        self.assertEqual("", tester.get_display())

        tester.run([("command", "list"), ("--verbose", True)])
        self.assertEqual(Output.VERBOSITY_VERBOSE, tester.get_output().get_verbosity())

        tester.run([("command", "list"), ("-v", True)])
        self.assertEqual(Output.VERBOSITY_VERBOSE, tester.get_output().get_verbosity())

        application = Application()
        application.set_auto_exit(False)
        application.set_catch_exceptions(False)
        application.add(FooCommand())
        tester = ApplicationTester(application)

        tester.run([("command", "foo:bar"), ("--no-interaction", True)], {"decorated": False})
        self.assertEqual("called\n", tester.get_display())

        tester.run([("command", "foo:bar"), ("-n", True)], {"decorated": False})
        self.assertEqual("called\n", tester.get_display())