当前位置: 首页>>代码示例>>Python>>正文


Python pytest.hookimpl方法代码示例

本文整理汇总了Python中pytest.hookimpl方法的典型用法代码示例。如果您正苦于以下问题:Python pytest.hookimpl方法的具体用法?Python pytest.hookimpl怎么用?Python pytest.hookimpl使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pytest的用法示例。


在下文中一共展示了pytest.hookimpl方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_unicode_in_longrepr

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import hookimpl [as 别名]
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() 
开发者ID:pytest-dev,项目名称:pytest,代码行数:23,代码来源:test_runner.py

示例2: test_collect_report_postprocessing

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import hookimpl [as 别名]
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*"]) 
开发者ID:pytest-dev,项目名称:pytest,代码行数:21,代码来源:test_collection.py

示例3: test_customized_pymakemodule_issue205_subdir

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import hookimpl [as 别名]
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) 
开发者ID:pytest-dev,项目名称:pytest,代码行数:26,代码来源:collect.py

示例4: test_issue333_result_clearing

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import hookimpl [as 别名]
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) 
开发者ID:pytest-dev,项目名称:pytest,代码行数:23,代码来源:test_unittest.py

示例5: pytest_runtest_setup

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import hookimpl [as 别名]
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) 
开发者ID:smarie,项目名称:python-pytest-cases,代码行数:17,代码来源:plugin.py

示例6: test_mypy_indirect_inject

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import hookimpl [as 别名]
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 
开发者ID:dbader,项目名称:pytest-mypy,代码行数:29,代码来源:test_pytest_mypy.py

示例7: test_runtest_in_module_ordering

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import hookimpl [as 别名]
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*"]) 
开发者ID:pytest-dev,项目名称:pytest,代码行数:32,代码来源:test_runner.py

示例8: test_select_extra_keywords

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import hookimpl [as 别名]
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" 
开发者ID:pytest-dev,项目名称:pytest,代码行数:31,代码来源:test_mark.py

示例9: test_deselected_with_hookwrapper

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import hookimpl [as 别名]
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 
开发者ID:pytest-dev,项目名称:pytest,代码行数:32,代码来源:test_terminal.py

示例10: test_unknown_teststatus

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import hookimpl [as 别名]
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" 
开发者ID:pytest-dev,项目名称:pytest,代码行数:36,代码来源:test_resultlog.py

示例11: test_customized_pymakeitem

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import hookimpl [as 别名]
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) 
开发者ID:pytest-dev,项目名称:pytest,代码行数:34,代码来源:collect.py

示例12: interface_hook_creator

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import hookimpl [as 别名]
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 
开发者ID:zyfra,项目名称:ebonite,代码行数:36,代码来源:conftest.py

示例13: pytest_ignore_collect

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import hookimpl [as 别名]
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 
开发者ID:smarie,项目名称:python-pytest-cases,代码行数:45,代码来源:conftest.py

示例14: test_log_set_path

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import hookimpl [as 别名]
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 
开发者ID:pytest-dev,项目名称:pytest,代码行数:48,代码来源:test_reporting.py


注:本文中的pytest.hookimpl方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。