コード例 #1
0
ファイル: test_deps_cli.py プロジェクト: nicoddemus/deps
def test_execution_on_project_dir(cli_runner, project_tree, monkeypatch):
    """
    :type cli_runner: click.testing.CliRunner
    :type project_tree: py.path.local
    :type monkeypatch: _pytest.monkeypatch
    """
    monkeypatch.chdir(project_tree.join('root_b'))
    command_args = ['-v', '--', 'python', '-c', '"name: {name}"']
    result = cli_runner.invoke(deps_cli.cli, command_args)
    assert result.exit_code == 0, result.output
    matcher = LineMatcher(result.output.splitlines())
    matcher.fnmatch_lines([
        'dep_z (1/4)',
        'deps: executing: python -c "name:\\ dep_z"',
        'deps: from:      *[\\/]test_projects0[\\/]dep_z',
        'deps: return code: 0',

        'dep_b.1.1 (2/4)',
        'deps: executing: python -c "name:\\ dep_b.1.1"',
        'deps: from:      *[\\/]test_projects0[\\/]bs[\\/]dep_b.1.1',
        'deps: return code: 0',

        'dep_b.1 (3/4)',
        'deps: executing: python -c "name:\\ dep_b.1"',
        'deps: from:      *[\\/]test_projects0[\\/]bs[\\/]dep_b.1',
        'deps: return code: 0',

        'root_b (4/4)',
        'deps: executing: python -c "name:\\ root_b"',
        'deps: from:      *[\\/]test_projects0[\\/]root_b',
        'deps: return code: 0',
    ])
コード例 #2
0
def test_exception_repr_extraction_error_on_recursion():
    """
    Ensure we can properly detect a recursion error even
    if some locals raise error on comparision (#2459).
    """
    class numpy_like(object):
        def __eq__(self, other):
            if type(other) is numpy_like:
                raise ValueError('The truth value of an array '
                                 'with more than one element is ambiguous.')

    def a(x):
        return b(numpy_like())

    def b(x):
        return a(numpy_like())

    try:
        a(numpy_like())
    except:
        from _pytest._code.code import ExceptionInfo
        from _pytest.pytester import LineMatcher
        exc_info = ExceptionInfo()

        matcher = LineMatcher(str(exc_info.getrepr()).splitlines())
        matcher.fnmatch_lines([
            '!!! Recursion error detected, but an error occurred locating the origin of recursion.',
            '*The following exception happened*',
            '*ValueError: The truth value of an array*',
        ])
コード例 #3
0
ファイル: test_deps_cli.py プロジェクト: nicoddemus/deps
def test_here_flag(cli_runner, project_tree, monkeypatch):
    """
    :type cli_runner: click.testing.CliRunner
    :type project_tree: py.path.local
    :type monkeypatch: _pytest.monkeypatch
    """
    monkeypatch.chdir(project_tree.join('root_b'))
    command_args = ['-v', '--here', '--', 'python', '-c', '"name: {name}"']
    result = cli_runner.invoke(deps_cli.cli, command_args)
    assert result.exit_code == 0, result.output
    matcher = LineMatcher(result.output.splitlines())
    # Current working directory is not changed.
    matcher.fnmatch_lines([
        'dep_z (1/4)',
        'deps: executing: python -c "name:\\ dep_z"',
        'deps: return code: 0',

        'dep_b.1.1 (2/4)',
        'deps: executing: python -c "name:\\ dep_b.1.1"',
        'deps: return code: 0',

        'dep_b.1 (3/4)',
        'deps: executing: python -c "name:\\ dep_b.1"',
        'deps: return code: 0',

        'root_b (4/4)',
        'deps: executing: python -c "name:\\ root_b"',
        'deps: return code: 0',
    ])
コード例 #4
0
ファイル: test_deps_cli.py プロジェクト: nicoddemus/deps
def test_script_execution(cli_runner, project_tree, piped_shell_execute):
    """
    :type cli_runner: click.testing.CliRunner
    :type project_tree: py.path.local
    :type piped_shell_execute: mocker.patch
    """
    root_b = str(project_tree.join('root_b'))
    task_script = os.path.join('tasks', 'asd')
    command_args = ['-p', root_b, '-v', '-f', 'tasks/asd', task_script, '{name}', '{abs}']
    result = cli_runner.invoke(deps_cli.cli, command_args, catch_exceptions=False)
    assert result.exit_code == 0, result.output
    matcher = LineMatcher(result.output.splitlines())
    matcher.fnmatch_lines([
        'dep_z (1/4)',
        'deps: executing: tasks[\\/]asd dep_z *[\\/]test_projects0[\\/]dep_z',
        'deps: from:      *[\\/]test_projects0[\\/]dep_z',
        'Sample script dep_z *[\\/]test_projects0[\\/]dep_z',
        '',
        'deps: return code: 0',

        'dep_b.1.1: skipping since "*[\\/]tasks[\\/]asd" does not exist',

        'dep_b.1: skipping since "*[\\/]tasks[\\/]asd" does not exist',

        'root_b (4/4)',
        'deps: executing: tasks[\\/]asd root_b *[\\/]test_projects0[\\/]root_b',
        'deps: from:      *[\\/]test_projects0[\\/]root_b',
        'Sample script root_b *[\\/]test_projects0[\\/]root_b',
        '',
        'deps: return code: 0',
    ])
コード例 #5
0
def test_exception_repr_extraction_error_on_recursion():
    """
    Ensure we can properly detect a recursion error even
    if some locals raise error on comparison (#2459).
    """
    from _pytest.pytester import LineMatcher

    class numpy_like(object):
        def __eq__(self, other):
            if type(other) is numpy_like:
                raise ValueError("The truth value of an array "
                                 "with more than one element is ambiguous.")

    def a(x):
        return b(numpy_like())

    def b(x):
        return a(numpy_like())

    with pytest.raises(RuntimeError) as excinfo:
        a(numpy_like())

    matcher = LineMatcher(str(excinfo.getrepr()).splitlines())
    matcher.fnmatch_lines([
        "!!! Recursion error detected, but an error occurred locating the origin of recursion.",
        "*The following exception happened*",
        "*ValueError: The truth value of an array*",
    ])
コード例 #6
0
def test_capsys(testdir_setup, global_cap_method):
    testdir_setup.makepyfile(r"""
        def test_print(capsys):
            import sys
            print("a:out")
            print("a:err", file=sys.stderr)
            assert list(capsys.readouterr()) == ["a:out\n", "a:err\n"]
            assert True                                                # line 6
            print("b:out", flush=True)
            print("b:err", flush=True, file=sys.stderr)
            assert list(capsys.readouterr()) == ["b:out\n", "b:err\n"]
    """)  # raw string \n
    pe = testdir_setup.spawn_pytest("--break=test_capsys.py:6 "
                                    "--capture=%s" % global_cap_method)
    pe.expect(prompt_re)
    befs = unansi(pe.before)
    assert "a:out" not in befs
    lbefs = LineMatcher(befs)
    lbefs.fnmatch_lines(("*>*/test_capsys.py(6)test_print()", "->*# line 6"))
    pe.sendline("c")
    pe.expect(EOF)
    befs = unansi(pe.before)
    assert "b:out" not in befs
    lbefs = LineMatcher(befs)
    lbefs.fnmatch_lines(["*[[]100%[]]*", "*1 passed*"])
コード例 #7
0
async it "cleans up tests properly on interrupt":
    directory = os.path.join(this_dir, "interrupt_test")
    expected_file = os.path.join(directory, "expected")

    assert os.path.isfile(expected_file)

    with open(expected_file, "r") as fle:
        expected = fle.read().strip()

    p = await asyncio.create_subprocess_exec(
        shutil.which("pytest"), cwd=directory, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
    )

    await asyncio.sleep(2)
    p.send_signal(signal.SIGINT)
    await p.wait()

    got = (await p.stdout.read()).decode().strip().split("\n")
    while got and not got[0].startswith("collected"):
        got.pop(0)

    want = expected.strip().split("\n")

    if len(got) != len(want):
        print("\n".join(got))
        assert False, "expected different number of lines in output"

    matcher = LineMatcher(got)
    matcher.fnmatch_lines(want)
コード例 #8
0
ファイル: test_deps_cli.py プロジェクト: nicoddemus/deps
def test_list_repos_conflict_skipped_ignored_project(cli_runner, project_tree, piped_shell_execute):
    """
    :type cli_runner: click.testing.CliRunner
    :type project_tree: py.path.local
    :type piped_shell_execute: mocker.patch
    """
    root = str(project_tree.join('root_c'))
    base_args = ['-p', root, '--repos']

    # Test pretty print.
    command_args = base_args + ['--skip-project=dep_c1.3', '--ignore-project=dep_c1.3', '-pp']
    result = cli_runner.invoke(deps_cli.cli, command_args)
    assert result.exit_code == 0, result.output
    matcher = LineMatcher(result.output.splitlines())
    matcher.fnmatch_lines([
        '*[\\/]test_projects0[\\/]root_c',
        '    *[\\/]test_projects0[\\/]cs1',
        '        (*[\\/]test_projects0[\\/]cs1)',
    ])

    # Test pretty print.
    command_args = base_args + ['--skip-project=dep_c2.1', '--ignore-project=dep_c2.1', '-pp']
    result = cli_runner.invoke(deps_cli.cli, command_args)
    assert result.exit_code == 0, result.output
    matcher = LineMatcher(result.output.splitlines())
    matcher.fnmatch_lines([
        '*[\\/]test_projects0[\\/]root_c',
        '    *[\\/]test_projects0[\\/]cs1',
        '        (*[\\/]test_projects0[\\/]cs1)',
        '        <*[\\/]test_projects0[\\/]cs2>',
    ])
コード例 #9
0
ファイル: test_excinfo.py プロジェクト: ceridwen/pytest
def test_exception_repr_extraction_error_on_recursion():
    """
    Ensure we can properly detect a recursion error even
    if some locals raise error on comparision (#2459).
    """
    class numpy_like(object):

        def __eq__(self, other):
            if type(other) is numpy_like:
                raise ValueError('The truth value of an array '
                                 'with more than one element is ambiguous.')

    def a(x):
        return b(numpy_like())

    def b(x):
        return a(numpy_like())

    try:
        a(numpy_like())
    except:  # noqa
        from _pytest._code.code import ExceptionInfo
        from _pytest.pytester import LineMatcher
        exc_info = ExceptionInfo()

        matcher = LineMatcher(str(exc_info.getrepr()).splitlines())
        matcher.fnmatch_lines([
            '!!! Recursion error detected, but an error occurred locating the origin of recursion.',
            '*The following exception happened*',
            '*ValueError: The truth value of an array*',
        ])
コード例 #10
0
def test_list_repos_precedence(mode, cli_runner, project_tree,
                               piped_shell_execute):
    """
    :type cli_runner: click.testing.CliRunner
    :type project_tree: py.path.local
    :type piped_shell_execute: mocker.patch
    """
    root = str(project_tree.join("root_d"))
    base_args = ["-p", root, "--repos"]

    command_args = base_args + [
        "-pp", "--ignore-project=d1", "--ignore-project=d2"
    ]
    if mode == "skipped":
        command_args.append("--skip-project=d3")
    result = cli_runner.invoke(deps_cli.cli, command_args)
    assert result.exit_code == 0, result.output
    matcher = LineMatcher(result.output.splitlines())
    if mode == "skipped":
        matcher.fnmatch_lines([
            "*[\\/]test_projects0[\\/]root_d",
            "    {*[\\/]test_projects0[\\/]d}",
        ])
    else:
        assert mode == "normal"
        matcher.fnmatch_lines([
            "*[\\/]test_projects0[\\/]root_d",
            "    *[\\/]test_projects0[\\/]d",
        ])
コード例 #11
0
def test_no_expected_env_file(cli_runner, tmpdir_factory, piped_shell_execute):
    test_projects = tmpdir_factory.mktemp("test_projects")
    projects = {
        "expected_env_file": (
            "environment.devenv.yml",
            ["../unexpected_env_file/foo_environment.devenv.yml"],
        ),
        "unexpected_env_file": ("foo_environment.devenv.yml", []),
    }
    for proj, (env_filename, deps) in projects.items():
        proj_path = proj.split("/")
        proj_dir = test_projects.ensure(*proj_path, dir=True)
        env_yml = proj_dir.join(env_filename)
        env_content = ["name: {}".format(proj), ""]
        if len(deps) > 0:
            env_content.append("includes:")
            env_content.extend(
                ["  - {{{{ root }}}}/{}".format(dep) for dep in deps])
            env_content.append("")
        env_yml.write("\n".join(env_content))

    root = str(test_projects.join("expected_env_file"))
    # Prepare the invocation.
    command_args = ["-p", root, "echo", "test", "{name}"]
    result = cli_runner.invoke(deps_cli.cli, command_args)
    assert result.exit_code == 0, result.output

    matcher = LineMatcher(result.output.splitlines())
    matcher.fnmatch_lines([
        "unexpected_env_file (1/2)",
        "test unexpected_env_file",
        "expected_env_file (2/2)",
        "test expected_env_file",
    ])
コード例 #12
0
def test_list_repos_with_skipped_project(cli_runner, project_tree,
                                         piped_shell_execute):
    """
    :type cli_runner: click.testing.CliRunner
    :type project_tree: py.path.local
    :type piped_shell_execute: mocker.patch
    """
    root = str(project_tree.join("root_c"))
    base_args = ["-p", root, "--repos"]

    # Test pretty print.
    command_args = base_args + ["--skip-project=dep_c1.3", "-pp"]
    result = cli_runner.invoke(deps_cli.cli, command_args)
    assert result.exit_code == 0, result.output
    matcher = LineMatcher(result.output.splitlines())
    matcher.fnmatch_lines([
        "*[\\/]test_projects0[\\/]root_c",
        "    *[\\/]test_projects0[\\/]cs1",
        "        (*[\\/]test_projects0[\\/]cs1)",
        "        *[\\/]test_projects0[\\/]cs2",
        "            (*[\\/]test_projects0[\\/]cs1)",
    ])

    # Test pretty print.
    command_args = base_args + ["--skip-project=dep_c2.1", "-pp"]
    result = cli_runner.invoke(deps_cli.cli, command_args)
    assert result.exit_code == 0, result.output
    matcher = LineMatcher(result.output.splitlines())
    matcher.fnmatch_lines([
        "*[\\/]test_projects0[\\/]root_c",
        "    *[\\/]test_projects0[\\/]cs1",
        "        (*[\\/]test_projects0[\\/]cs1)",
        "        {*[\\/]test_projects0[\\/]cs2}",
        "            (*[\\/]test_projects0[\\/]cs1)",
    ])
コード例 #13
0
def test_require_file(cli_runner, project_tree, piped_shell_execute):
    """
    :type cli_runner: click.testing.CliRunner
    :type project_tree: py.path.local
    :type piped_shell_execute: mocker.patch
    """
    root_b = str(project_tree.join("root_b"))
    base_args = ["-p", root_b, "--require-file", "tasks/asd"]

    command_args = base_args + ["-v", "echo", "This", "is", "{name}"]
    result = cli_runner.invoke(deps_cli.cli, command_args)
    assert result.exit_code == 0, result.output
    matcher = LineMatcher(result.output.splitlines())
    matcher.fnmatch_lines([
        "dep_z (1/4)",
        "deps: executing: echo This is dep_z",
        "deps: from:      *[\\/]test_projects0[\\/]dep_z",
        "This is dep_z",
        "deps: return code: 0",
        'dep_b.1.1: skipping since "*[\\/]test_projects0[\\/]bs[\\/]dep_b.1.1[\\/]tasks[\\/]asd" does not exist',
        'dep_b.1: skipping since "*[\\/]test_projects0[\\/]bs[\\/]dep_b.1[\\/]tasks[\\/]asd" does not exist',
        "root_b (4/4)",
        "deps: executing: echo This is root_b",
        "deps: from:      *[\\/]test_projects0[\\/]root_b",
        "This is root_b",
        "deps: return code: 0",
    ])

    command_args = ["-p", root_b, "--require-file", "tasks/asd"]
    result = cli_runner.invoke(deps_cli.cli, command_args)
    assert result.exit_code == 0, result.output
    assert result.output == textwrap.dedent("""\
        dep_z
        root_b
        """)
コード例 #14
0
ファイル: test_deps_cli.py プロジェクト: nicoddemus/deps
def test_list_repos_precedence(mode, cli_runner, project_tree, piped_shell_execute):
    """
    :type cli_runner: click.testing.CliRunner
    :type project_tree: py.path.local
    :type piped_shell_execute: mocker.patch
    """
    root = str(project_tree.join('root_d'))
    base_args = ['-p', root, '--repos']

    command_args = base_args + ['-pp', '--ignore-project=d1', '--ignore-project=d2']
    if mode == 'skipped':
        command_args.append('--skip-project=d3')
    result = cli_runner.invoke(deps_cli.cli, command_args)
    assert result.exit_code == 0, result.output
    matcher = LineMatcher(result.output.splitlines())
    if mode == 'skipped':
        matcher.fnmatch_lines([
            '*[\\/]test_projects0[\\/]root_d',
            '    {*[\\/]test_projects0[\\/]d}',
        ])
    else:
        assert mode == 'normal'
        matcher.fnmatch_lines([
            '*[\\/]test_projects0[\\/]root_d',
            '    *[\\/]test_projects0[\\/]d',
        ])
コード例 #15
0
ファイル: test_deps_cli.py プロジェクト: nicoddemus/deps
def test_cant_find_root(cli_runner, project_tree, piped_shell_execute):
    """
    :type cli_runner: click.testing.CliRunner
    :type project_tree: py.path.local
    :type piped_shell_execute: mocker.patch
    """
    proj_dir = str(project_tree.join('not_a_project'))
    command_args = ['-p', proj_dir, 'echo', 'Hi', '{name}!']
    result = cli_runner.invoke(deps_cli.cli, command_args)
    assert result.exception is None or isinstance(result.exception, SystemExit)
    assert result.exit_code != 0
    matcher = LineMatcher(result.output.splitlines())
    matcher.fnmatch_lines([
        'deps: error: could not find "environment.devenv.yml" for "*[\\/]test_projects0[\\/]not_a_project".',
    ])

    proj_dir = str(project_tree.join('not_a_valid_folder'))
    command_args = ['-p', proj_dir, 'echo', 'Hi', '{name}!']
    result = cli_runner.invoke(deps_cli.cli, command_args)
    assert result.exception is None or isinstance(result.exception, SystemExit)
    assert result.exit_code != 0
    matcher = LineMatcher(result.output.splitlines())
    matcher.fnmatch_lines([
        'deps: error: could not find "environment.devenv.yml" for "*[\\/]test_projects0[\\/]not_a_valid_folder".',
    ])
コード例 #16
0
ファイル: test_excinfo.py プロジェクト: nicoddemus/pytest
def test_exception_repr_extraction_error_on_recursion():
    """
    Ensure we can properly detect a recursion error even
    if some locals raise error on comparison (#2459).
    """
    from _pytest.pytester import LineMatcher

    class numpy_like(object):
        def __eq__(self, other):
            if type(other) is numpy_like:
                raise ValueError(
                    "The truth value of an array "
                    "with more than one element is ambiguous."
                )

    def a(x):
        return b(numpy_like())

    def b(x):
        return a(numpy_like())

    with pytest.raises(RuntimeError) as excinfo:
        a(numpy_like())

    matcher = LineMatcher(str(excinfo.getrepr()).splitlines())
    matcher.fnmatch_lines(
        [
            "!!! Recursion error detected, but an error occurred locating the origin of recursion.",
            "*The following exception happened*",
            "*ValueError: The truth value of an array*",
        ]
    )
コード例 #17
0
ファイル: test_pastebin.py プロジェクト: Stranger6667/pytest
    def test_all(self, testdir, pastebinlist):
        from _pytest.pytester import LineMatcher

        testpath = testdir.makepyfile(
            """
            import pytest
            def test_pass():
                pass
            def test_fail():
                assert 0
            def test_skip():
                pytest.skip("")
        """
        )
        reprec = testdir.inline_run(testpath, "--pastebin=all", "-v")
        assert reprec.countoutcomes() == [1, 1, 1]
        assert len(pastebinlist) == 1
        contents = pastebinlist[0].decode("utf-8")
        matcher = LineMatcher(contents.splitlines())
        matcher.fnmatch_lines(
            [
                "*test_pass PASSED*",
                "*test_fail FAILED*",
                "*test_skip SKIPPED*",
                "*== 1 failed, 1 passed, 1 skipped in *",
            ]
        )
コード例 #18
0
ファイル: test_pastebin.py プロジェクト: eocanha/webkit
    def test_all(self, testdir, pastebinlist):
        from _pytest.pytester import LineMatcher

        testpath = testdir.makepyfile(
            """
            import pytest
            def test_pass():
                pass
            def test_fail():
                assert 0
            def test_skip():
                pytest.skip("")
        """
        )
        reprec = testdir.inline_run(testpath, "--pastebin=all", "-v")
        assert reprec.countoutcomes() == [1, 1, 1]
        assert len(pastebinlist) == 1
        contents = pastebinlist[0].decode("utf-8")
        matcher = LineMatcher(contents.splitlines())
        matcher.fnmatch_lines(
            [
                "*test_pass PASSED*",
                "*test_fail FAILED*",
                "*test_skip SKIPPED*",
                "*== 1 failed, 1 passed, 1 skipped in *",
            ]
        )
コード例 #19
0
ファイル: test_pytester.py プロジェクト: swetaj6/pytest
def test_linematcher_match_failure() -> None:
    lm = LineMatcher(["foo", "foo", "bar"])
    with pytest.raises(Failed) as e:
        lm.fnmatch_lines(["foo", "f*", "baz"])
    assert e.value.msg is not None
    assert e.value.msg.splitlines() == [
        "exact match: 'foo'",
        "fnmatch: 'f*'",
        "   with: 'foo'",
        "nomatch: 'baz'",
        "    and: 'bar'",
        "remains unmatched: 'baz'",
    ]

    lm = LineMatcher(["foo", "foo", "bar"])
    with pytest.raises(Failed) as e:
        lm.re_match_lines(["foo", "^f.*", "baz"])
    assert e.value.msg is not None
    assert e.value.msg.splitlines() == [
        "exact match: 'foo'",
        "re.match: '^f.*'",
        "    with: 'foo'",
        " nomatch: 'baz'",
        "     and: 'bar'",
        "remains unmatched: 'baz'",
    ]
コード例 #20
0
ファイル: test_deps_cli.py プロジェクト: nicoddemus/deps
def test_no_expected_env_file(cli_runner, tmpdir_factory, piped_shell_execute):
    test_projects = tmpdir_factory.mktemp('test_projects')
    projects = {
        'expected_env_file': ('environment.devenv.yml', ['../unexpected_env_file/foo_environment.devenv.yml'],),
        'unexpected_env_file': ('foo_environment.devenv.yml', []),
    }
    for proj, (env_filename, deps) in projects.items():
        proj_path = proj.split('/')
        proj_dir = test_projects.ensure(*proj_path, dir=True)
        env_yml = proj_dir.join(env_filename)
        env_content = ['name: {}'.format(proj), '']
        if len(deps) > 0:
            env_content.append('includes:')
            env_content.extend(
                ['  - {{{{ root }}}}/{}'.format(dep) for dep in deps])
            env_content.append('')
        env_yml.write('\n'.join(env_content))

    root = str(test_projects.join('expected_env_file'))
    # Prepare the invocation.
    command_args = ['-p', root, 'echo', 'test', '{name}']
    result = cli_runner.invoke(deps_cli.cli, command_args)
    assert result.exit_code == 0, result.output

    matcher = LineMatcher(result.output.splitlines())
    matcher.fnmatch_lines([
        'unexpected_env_file (1/2)',
        'test unexpected_env_file',

        'expected_env_file (2/2)',
        'test expected_env_file',
    ])
コード例 #21
0
def test_elsewhere_fixture_with_yield_nested(testdir_setup):
    testdir_setup.makepyfile(test_file="""
        import pytest

        @pytest.fixture
        def fixie():
            class C:
                def __init__(self):
                    print("in init")     # <- line 7
                def ran(self):
                    return True
            c = C()
            yield c
            del c

        def test_foo(fixie):
            assert fixie.ran()
    """)
    pe = testdir_setup.spawn_pytest("--break=test_file.py:7")
    pe.expect(prompt_re)
    befs = LineMatcher(unansi(pe.before))
    befs.fnmatch_lines(["*>*/test_file.py(7)__init__()", "->*# <- line 7"])
    pe.sendline("c")
    pe.expect(EOF)
    befs = LineMatcher(unansi(pe.before))
    befs.fnmatch_lines("*1 passed*")
コード例 #22
0
def test_class_gap_named(testdir_class):
    pe = testdir_class.spawn_pytest(
        "--break=test_class_gap_named.py:10 "
        "test_class_gap_named.py::TestClass::test_two")
    pe.expect(EOF)
    befs = LineMatcher(unansi(pe.before))
    befs.fnmatch_lines(["*unable to determine*", "*no tests ran*"])
コード例 #23
0
def test_class_gap(testdir_class):
    # If a requested line precedes the start of the first test item, an error
    # is raised; same goes for intervals between items, as shown here
    pe = testdir_class.spawn_pytest("--break=test_class_gap.py:10")
    pe.expect(EOF)
    befs = LineMatcher(unansi(pe.before))
    befs.fnmatch_lines(["*unable to determine*", "*no tests ran*"])
コード例 #24
0
def test_class_early(testdir_class):
    # Target docstring
    pe = testdir_class.spawn_pytest("--break=test_class_early.py:5")
    pe.expect(prompt_re)
    befs = LineMatcher(unansi(pe.before))
    befs.fnmatch_lines(["*>*/test_class_early.py(8)test_one()", "->*# line 8"])
    pe.sendline("c")
    pe.expect(EOF)
コード例 #25
0
def test_class_simple(testdir_class):
    pe = testdir_class.spawn_pytest("--break=test_class_simple.py:8")
    pe.expect(prompt_re)
    befs = LineMatcher(unansi(pe.before))
    befs.fnmatch_lines(
        ["*>*/test_class_simple.py(8)test_one()", "->*# line 8"])
    pe.sendline("c")
    pe.expect(EOF)
コード例 #26
0
def test_compat_invoke_same_after_baseline(testdir_setup):
    td = testdir_setup
    td.makepyfile(test_file=t2f4)
    pe = td.spawn_pytest("--pdb")
    pe.expect(prompt_re)
    befs = LineMatcher(unansi(pe.before))
    befs.fnmatch_lines(["*>*/test_file.py(4)test_foo()", "->*assert False*"])
    pe.sendline("c")
コード例 #27
0
 def inner():
     lines = self.logfile.readlines()
     if lines:
         latest = LineMatcher(lines)
         try:
             latest.fnmatch_lines(pattern)
         except Failed:
             return None
         return True
コード例 #28
0
def test_two_funcs_comment(testdir_two_funcs):
    pe = testdir_two_funcs.spawn_pytest("--break=test_two_funcs_comment.py:2")
    pe.expect(prompt_re)
    befs = LineMatcher(unansi(pe.before))
    befs.fnmatch_lines([
        "*>*/test_two_funcs_comment.py(3)test_true_int()", "->*somevar = True"
    ])
    pe.sendline("c")
    pe.expect(EOF)
コード例 #29
0
def test_simple_unknown(testdir):
    filename = testdir.copy_example("asyncio/test_simple.py")
    assert filename.exists()

    pe = testdir.spawn_pytest("--break=test_simple.py:4")
    pe.expect(EOF)
    befs = LineMatcher(unansi(pe.before))
    befs.fnmatch_lines([
        "*unable to determine breakpoint*",
    ])
コード例 #30
0
def test_two_funcs_simple(testdir_two_funcs):
    pe = testdir_two_funcs.spawn_pytest("--break=test_two_funcs_simple.py:4")
    pe.expect(prompt_re)
    befs = LineMatcher(unansi(pe.before))
    befs.fnmatch_lines([
        "*>*/test_two_funcs_simple.py(4)test_true_int()",
        "->*# <- line 4",
    ])
    pe.sendline("c")
    pe.expect(EOF)
コード例 #31
0
def test_skip_projects(
    use_env_var,
    cli_runner,
    project_tree,
    piped_shell_execute,
):
    """
    :type use_env_var: bool
    :type cli_runner: click.testing.CliRunner
    :type project_tree: py.path.local
    :type piped_shell_execute: mocker.patch
    """
    def configure_skipped_projects():
        if use_env_var:
            extra_env["DEPS_SKIP_PROJECT"] = str("dep_a.1{}dep_z".format(
                os.pathsep))
        else:
            command_args.insert(0, "--skip-project=dep_a.1")
            command_args.insert(1, "--skip-project=dep_z")

    root_a = str(project_tree.join("root_a"))
    # Prepare the invocation.
    command_args = ["-p", root_a, "echo", "test", "{name}"]
    extra_env = {}
    configure_skipped_projects()

    result = cli_runner.invoke(deps_cli.cli, command_args, env=extra_env)
    assert result.exit_code == 0, result.output
    matcher = LineMatcher(result.output.splitlines())
    matcher.fnmatch_lines([
        "dep_z skipped",
        "dep_a.1.2 (2/6)",
        "test dep_a.1.2",
        "dep_a.1.1 (3/6)",
        "test dep_a.1.1",
        "dep_a.2 (4/6)",
        "test dep_a.2",
        "dep_a.1 skipped",
        "root_a (6/6)",
        "test root_a",
    ])

    # Prepare the invocation.
    command_args = ["-p", root_a]
    extra_env = {}
    configure_skipped_projects()

    result = cli_runner.invoke(deps_cli.cli, command_args, env=extra_env)
    assert result.exit_code == 0, result.output
    assert result.output == textwrap.dedent("""\
        dep_a.1.2
        dep_a.1.1
        dep_a.2
        root_a
        """)
コード例 #32
0
ファイル: test_deps_cli.py プロジェクト: nicoddemus/deps
def test_conflict_ignore_skip_projects(
    use_env_var,
    cli_runner,
    project_tree,
    piped_shell_execute,
):
    """
    :type use_env_var: bool
    :type cli_runner: click.testing.CliRunner
    :type project_tree: py.path.local
    :type piped_shell_execute: mocker.patch
    """
    def configure_skipped_projects():
        if use_env_var:
            extra_env['DEPS_SKIP_PROJECT'] = 'dep_a.1'
            extra_env['DEPS_IGNORE_PROJECT'] = 'dep_a.1'
        else:
            command_args.insert(0, '--skip-project=dep_a.1')
            command_args.insert(0, '--ignore-project=dep_a.1')
    root_a = str(project_tree.join('root_a'))
    # Prepare the invocation.
    command_args = ['-p', root_a, 'echo', 'test', '{name}']
    extra_env = {}
    configure_skipped_projects()

    result = cli_runner.invoke(deps_cli.cli, command_args, env=extra_env)
    assert result.exit_code == 0, result.output
    matcher = LineMatcher(result.output.splitlines())
    matcher.fnmatch_lines([
        'dep_a.1 ignored',

        'dep_z (2/4)',
        'test dep_z',

        'dep_a.2 (3/4)',
        'test dep_a.2',

        'root_a (4/4)',
        'test root_a',
    ])

    # Prepare the invocation.
    command_args = ['-p', root_a]
    extra_env = {}
    configure_skipped_projects()

    result = cli_runner.invoke(deps_cli.cli, command_args, env=extra_env)
    assert result.exit_code == 0, result.output
    assert result.output == textwrap.dedent(
        '''\
        dep_z
        dep_a.2
        root_a
        '''
    )
コード例 #33
0
def test_two_funcs_on(testdir_two_funcs):
    # On first line (declaration line) of function
    pe = testdir_two_funcs.spawn_pytest("--break=test_two_funcs_on.py:6")
    pe.expect(prompt_re)
    befs = LineMatcher(unansi(pe.before))
    befs.fnmatch_lines([
        "*>*/test_two_funcs_on.py(7)test_false_int()",
        "->*isinstance(False, int)"
    ])
    pe.sendline("c")
    pe.expect(EOF)
コード例 #34
0
ファイル: test_excinfo.py プロジェクト: Coder206/servo
    def test_exc_chain_repr_without_traceback(self, importasmod, reason, description):
        """
        Handle representation of exception chains where one of the exceptions doesn't have a
        real traceback, such as those raised in a subprocess submitted by the multiprocessing
        module (#1984).
        """
        from _pytest.pytester import LineMatcher

        exc_handling_code = " from e" if reason == "cause" else ""
        mod = importasmod(
            """
            def f():
                try:
                    g()
                except Exception as e:
                    raise RuntimeError('runtime problem'){exc_handling_code}
            def g():
                raise ValueError('invalid value')
        """.format(
                exc_handling_code=exc_handling_code
            )
        )

        with pytest.raises(RuntimeError) as excinfo:
            mod.f()

        # emulate the issue described in #1984
        attr = "__%s__" % reason
        getattr(excinfo.value, attr).__traceback__ = None

        r = excinfo.getrepr()
        tw = py.io.TerminalWriter(stringio=True)
        tw.hasmarkup = False
        r.toterminal(tw)

        matcher = LineMatcher(tw.stringio.getvalue().splitlines())
        matcher.fnmatch_lines(
            [
                "ValueError: invalid value",
                description,
                "* except Exception as e:",
                "> * raise RuntimeError('runtime problem')" + exc_handling_code,
                "E *RuntimeError: runtime problem",
            ]
        )
コード例 #35
0
ファイル: test_pytester.py プロジェクト: nicoddemus/pytest
def test_linematcher_with_nonlist():
    """Test LineMatcher with regard to passing in a set (accidentally)."""
    lm = LineMatcher([])

    with pytest.raises(AssertionError):
        lm.fnmatch_lines(set())
    with pytest.raises(AssertionError):
        lm.fnmatch_lines({})
    lm.fnmatch_lines([])
    lm.fnmatch_lines(())

    assert lm._getlines({}) == {}
    assert lm._getlines(set()) == set()