我们从Python开源项目中,提取了以下5个代码示例,用于说明如何使用pytest.hookimpl()。
def pytest_runtest_makereport(self, item, call): print 'pytest_runtest_makereport %s %s' % (item, call) # @pytest.hookimpl(hookwrapper=True) # def pytest_runtest_makereport(self, item, call): # # logger.debug('pytest_runtest_makereport %s %s', item, call) # outcome = yield # # logger.debug('outcome %s', outcome) # result = outcome.get_result() # logger.debug('result %s', result) # logger.debug('result.capstdout %s', result.capstdout) # logger.debug('result.capstderr %s', result.capstderr) # if call.when == 'call': # self.runner.set_test_result(self.runner.get_test_id(item), call) # logger.debug('pytest_runtest_makereport %s %s', item, call)
def test_select_extra_keywords(self, testdir, keyword): p = testdir.makepyfile(test_select=""" def test_1(): pass class TestClass: 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) py.builtin.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'
def testdir_with_map_hookimpl(testdir): testdir.makeconftest(''' import pytest @pytest.hookimpl def pytest_lab_map(config, roles): roles.load({'mock': { 'mocker.example': {'greeting': 'Hello Custom'} }}, {}) ''') return testdir
def test_customized_pymakeitem(self, testdir): b = testdir.mkdir("a").mkdir("b") b.join("conftest.py").write(py.code.Source(""" import pytest @pytest.hookimpl(hookwrapper=True) def pytest_pycollect_makeitem(): outcome = yield if outcome.excinfo is None: result = outcome.result if result: for func in result: func._some123 = "world" """)) b.join("test_module.py").write(py.code.Source(""" 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)
def test_hookvalidation_optional(testdir): testdir.makeconftest(""" import pytest @pytest.hookimpl(optionalhook=True) def pytest_hello(xyz): pass """) result = testdir.runpytest() assert result.ret == EXIT_NOTESTSCOLLECTED