Python pytest.hookimpl() Examples

The following are 14 code examples of pytest.hookimpl(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pytest , or try the search function .
Example #1
Source File: test_runner.py    From pytest with MIT License 7 votes vote down vote up
def test_unicode_in_longrepr(testdir) -> None:
    testdir.makeconftest(
        """\
        import pytest
        @pytest.hookimpl(hookwrapper=True)
        def pytest_runtest_makereport():
            outcome = yield
            rep = outcome.get_result()
            if rep.when == "call":
                rep.longrepr = 'รค'
        """
    )
    testdir.makepyfile(
        """
        def test_out():
            assert 0
    """
    )
    result = testdir.runpytest()
    assert result.ret == 1
    assert "UnicodeEncodeError" not in result.stderr.str() 
Example #2
Source File: test_collection.py    From pytest with MIT License 6 votes vote down vote up
def test_collect_report_postprocessing(self, testdir):
        p = testdir.makepyfile(
            """
            import not_exists
        """
        )
        testdir.makeconftest(
            """
            import pytest
            @pytest.hookimpl(hookwrapper=True)
            def pytest_make_collect_report():
                outcome = yield
                rep = outcome.get_result()
                rep.headerlines += ["header1"]
                outcome.force_result(rep)
        """
        )
        result = testdir.runpytest(p)
        result.stdout.fnmatch_lines(["*ERROR collecting*", "*header1*"]) 
Example #3
Source File: collect.py    From pytest with MIT License 6 votes vote down vote up
def test_customized_pymakemodule_issue205_subdir(self, testdir):
        b = testdir.mkdir("a").mkdir("b")
        b.join("conftest.py").write(
            textwrap.dedent(
                """\
                import pytest
                @pytest.hookimpl(hookwrapper=True)
                def pytest_pycollect_makemodule():
                    outcome = yield
                    mod = outcome.get_result()
                    mod.obj.hello = "world"
                """
            )
        )
        b.join("test_module.py").write(
            textwrap.dedent(
                """\
                def test_hello():
                    assert hello == "world"
                """
            )
        )
        reprec = testdir.inline_run()
        reprec.assertoutcome(passed=1) 
Example #4
Source File: test_unittest.py    From pytest with MIT License 6 votes vote down vote up
def test_issue333_result_clearing(testdir):
    testdir.makeconftest(
        """
        import pytest
        @pytest.hookimpl(hookwrapper=True)
        def pytest_runtest_call(item):
            yield
            assert 0
    """
    )
    testdir.makepyfile(
        """
        import unittest
        class TestIt(unittest.TestCase):
            def test_func(self):
                0/0
    """
    )

    reprec = testdir.inline_run()
    reprec.assertoutcome(failed=1) 
Example #5
Source File: plugin.py    From python-pytest-cases with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def pytest_runtest_setup(item  # type: Function
                         ):
    """
    Replace the dictionary of function args with our facade able to handle
    `lazy_value`
    """
    # first let all other hooks run, they will do the setup etc.
    yield

    # now item.funcargs exists so we can handle it
    item.funcargs = {argname: handle_lazy_args(argvalue) for argname, argvalue in item.funcargs.items()}


# @hookspec(firstresult=True)
# @pytest.hookimpl(tryfirst=True, hookwrapper=True) 
Example #6
Source File: test_pytest_mypy.py    From pytest-mypy with MIT License 5 votes vote down vote up
def test_mypy_indirect_inject(testdir, xdist_args):
    """
    Verify that uncollected files checked by mypy because of a MypyFileItem
    injected in pytest_collection_modifyitems cause a failure.
    """
    testdir.makepyfile(bad='''
        def pyfunc(x: int) -> str:
            return x * 2
    ''')
    testdir.makepyfile(good='''
        import bad
    ''')
    testdir.makepyfile(conftest='''
        import py
        import pytest

        @pytest.hookimpl(trylast=True)  # Inject as late as possible.
        def pytest_collection_modifyitems(session, config, items):
            plugin = config.pluginmanager.getplugin('mypy')
            items.append(
                plugin.MypyFileItem(py.path.local('good.py'), session),
            )
    ''')
    testdir.mkdir('empty')
    xdist_args.append('empty')  # Nothing may come after xdist_args in py34.
    result = testdir.runpytest_subprocess('--mypy', *xdist_args)
    assert result.ret != 0 
Example #7
Source File: test_runner.py    From pytest with MIT License 5 votes vote down vote up
def test_runtest_in_module_ordering(testdir) -> None:
    p1 = testdir.makepyfile(
        """
        import pytest
        def pytest_runtest_setup(item): # runs after class-level!
            item.function.mylist.append("module")
        class TestClass(object):
            def pytest_runtest_setup(self, item):
                assert not hasattr(item.function, 'mylist')
                item.function.mylist = ['class']
            @pytest.fixture
            def mylist(self, request):
                return request.function.mylist
            @pytest.hookimpl(hookwrapper=True)
            def pytest_runtest_call(self, item):
                try:
                    (yield).get_result()
                except ValueError:
                    pass
            def test_hello1(self, mylist):
                assert mylist == ['class', 'module'], mylist
                raise ValueError()
            def test_hello2(self, mylist):
                assert mylist == ['class', 'module'], mylist
        def pytest_runtest_teardown(item):
            del item.function.mylist
    """
    )
    result = testdir.runpytest(p1)
    result.stdout.fnmatch_lines(["*2 passed*"]) 
Example #8
Source File: test_mark.py    From pytest with MIT License 5 votes vote down vote up
def test_select_extra_keywords(self, testdir, keyword):
        p = testdir.makepyfile(
            test_select="""
            def test_1():
                pass
            class TestClass(object):
                def test_2(self):
                    pass
        """
        )
        testdir.makepyfile(
            conftest="""
            import pytest
            @pytest.hookimpl(hookwrapper=True)
            def pytest_pycollect_makeitem(name):
                outcome = yield
                if name == "TestClass":
                    item = outcome.get_result()
                    item.extra_keyword_matches.add("xxx")
        """
        )
        reprec = testdir.inline_run(p.dirpath(), "-s", "-k", keyword)
        print("keyword", repr(keyword))
        passed, skipped, failed = reprec.listoutcomes()
        assert len(passed) == 1
        assert passed[0].nodeid.endswith("test_2")
        dlist = reprec.getcalls("pytest_deselected")
        assert len(dlist) == 1
        assert dlist[0].items[0].name == "test_1" 
Example #9
Source File: test_terminal.py    From pytest with MIT License 5 votes vote down vote up
def test_deselected_with_hookwrapper(self, testdir):
        testpath = testdir.makeconftest(
            """
            import pytest

            @pytest.hookimpl(hookwrapper=True)
            def pytest_collection_modifyitems(config, items):
                yield
                deselected = items.pop()
                config.hook.pytest_deselected(items=[deselected])
            """
        )
        testpath = testdir.makepyfile(
            """
                def test_one():
                    pass
                def test_two():
                    pass
                def test_three():
                    pass
           """
        )
        result = testdir.runpytest(testpath)
        result.stdout.fnmatch_lines(
            [
                "collected 3 items / 1 deselected / 2 selected",
                "*= 2 passed, 1 deselected in*",
            ]
        )
        assert result.ret == 0 
Example #10
Source File: test_resultlog.py    From pytest with MIT License 5 votes vote down vote up
def test_unknown_teststatus(testdir):
    """Ensure resultlog correctly handles unknown status from pytest_report_teststatus

    Inspired on pytest-rerunfailures.
    """
    testdir.makepyfile(
        """
        def test():
            assert 0
    """
    )
    testdir.makeconftest(
        """
        import pytest

        def pytest_report_teststatus(report):
            if report.outcome == 'rerun':
                return "rerun", "r", "RERUN"

        @pytest.hookimpl(hookwrapper=True)
        def pytest_runtest_makereport():
            res = yield
            report = res.get_result()
            if report.when == "call":
                report.outcome = 'rerun'
    """
    )
    result = testdir.runpytest("--resultlog=result.log")
    result.stdout.fnmatch_lines(
        ["test_unknown_teststatus.py r *[[]100%[]]", "* 1 rerun *"]
    )

    lines = testdir.tmpdir.join("result.log").readlines(cr=0)
    assert lines[0] == "r test_unknown_teststatus.py::test" 
Example #11
Source File: collect.py    From pytest with MIT License 5 votes vote down vote up
def test_customized_pymakeitem(self, testdir):
        b = testdir.mkdir("a").mkdir("b")
        b.join("conftest.py").write(
            textwrap.dedent(
                """\
                import pytest
                @pytest.hookimpl(hookwrapper=True)
                def pytest_pycollect_makeitem():
                    outcome = yield
                    if outcome.excinfo is None:
                        result = outcome.get_result()
                        if result:
                            for func in result:
                                func._some123 = "world"
                """
            )
        )
        b.join("test_module.py").write(
            textwrap.dedent(
                """\
                import pytest

                @pytest.fixture()
                def obj(request):
                    return request.node._some123
                def test_hello(obj):
                    assert obj == "world"
                """
            )
        )
        reprec = testdir.inline_run()
        reprec.assertoutcome(passed=1) 
Example #12
Source File: conftest.py    From ebonite with Apache License 2.0 5 votes vote down vote up
def interface_hook_creator(package_path, common_filename, fixture_name):
    def create_interface_hooks(meta_fixture, name):
        tests_node_id = os.path.join(package_path, '{}.py'.format(name))

        def pytest_runtest_protocol(item, nextitem):
            filename, *test_name = item.nodeid.split('::')

            if filename == tests_node_id and fixture_name in item.fixturenames:
                fixture = _remap_fixture(item, meta_fixture.__name__, fixture_name)

                for dep_fixt_name in chain.from_iterable(e.argnames for e in fixture):
                    _remap_fixture(item, dep_fixt_name, dep_fixt_name)

        def _remap_fixture(item, actual_name, expected_name):
            fixture = tuple(item.session._fixturemanager._arg2fixturedefs[actual_name])
            item._request._arg2fixturedefs[expected_name] = fixture
            return fixture

        @pytest.hookimpl(hookwrapper=True)
        def pytest_collect_file(path, parent):
            outcome = yield
            result = outcome.get_result()

            if parent.parent is None:
                result.append(
                    DoctestModule(os.path.join(parent.fspath, package_path, 'conftest.py'), parent,
                                  nodeid=os.path.join(package_path, '{}_conf.py'.format(name))))

                result.append(Module(os.path.join(parent.fspath, package_path, common_filename), parent,
                                     nodeid=tests_node_id))

        return pytest_runtest_protocol, pytest_collect_file

    return create_interface_hooks 
Example #13
Source File: conftest.py    From python-pytest-cases with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def pytest_ignore_collect(path, config):
    """
    In python 2, equivalent of adding

        --ignore-glob='**/*py35*.py'

    This method works even with old pytest 2 and 3.
    It was copied from recent pytest.main.pytest_ignore_collect

    :param path:
    :param config:
    :return:
    """
    if sys.version_info < (3, 5):
        ignore_globs = ['**/*py35*.py']
        if any(
                fnmatch.fnmatch(six.text_type(path), six.text_type(glob))
                for glob in ignore_globs
        ):
            return True


# @pytest.hookimpl(trylast=True)
# def pytest_configure(config):
#     """
#     In python 2, add
#
#         --ignore-glob='**/*py35*.py'
#
#     Unfortunately this is not supported in old pytests so we do this in pytest-collect
#
#     :param config:
#     :return:
#     """
#     if sys.version_info < (3, 5):
#         print("Python < 3.5: ignoring test files containing 'py35'")
#         OPT = ['**/*py35*.py']
#         if config.option.ignore_glob is None:
#             config.option.ignore_glob = OPT
#         else:
#             config.option.ignore_glob += OPT
#
#         assert config.getoption('--ignore-glob') == OPT 
Example #14
Source File: test_reporting.py    From pytest with MIT License 4 votes vote down vote up
def test_log_set_path(testdir):
    report_dir_base = testdir.tmpdir.strpath

    testdir.makeini(
        """
        [pytest]
        log_file_level = DEBUG
        log_cli=true
        """
    )
    testdir.makeconftest(
        """
            import os
            import pytest
            @pytest.hookimpl(hookwrapper=True, tryfirst=True)
            def pytest_runtest_setup(item):
                config = item.config
                logging_plugin = config.pluginmanager.get_plugin("logging-plugin")
                report_file = os.path.join({}, item._request.node.name)
                logging_plugin.set_log_path(report_file)
                yield
        """.format(
            repr(report_dir_base)
        )
    )
    testdir.makepyfile(
        """
            import logging
            logger = logging.getLogger("testcase-logger")
            def test_first():
                logger.info("message from test 1")
                assert True

            def test_second():
                logger.debug("message from test 2")
                assert True
        """
    )
    testdir.runpytest()
    with open(os.path.join(report_dir_base, "test_first")) as rfh:
        content = rfh.read()
        assert "message from test 1" in content

    with open(os.path.join(report_dir_base, "test_second")) as rfh:
        content = rfh.read()
        assert "message from test 2" in content