我们从Python开源项目中,提取了以下35个代码示例,用于说明如何使用pytest.Module()。
def _importtestmodule(self): # we assume we are only called once per module importmode = self.config.getoption("--import-mode", default=True) try: # XXX patch pyimport in pytest._pytest.pythod.Module mod = _patch_pyimport(self.fspath, ensuresyspath=importmode) except SyntaxError: raise self.CollectError( _pytest._code.ExceptionInfo().getrepr(style="short")) except self.fspath.ImportMismatchError: e = sys.exc_info()[1] raise self.CollectError( "import file mismatch:\n" "imported module %r has this __file__ attribute:\n" " %s\n" "which is not the same as the test file we want to collect:\n" " %s\n" "HINT: remove __pycache__ / .pyc files and/or use a " "unique basename for your test file modules" % e.args ) # print "imported test module", mod self.config.pluginmanager.consider_module(mod) return mod
def collect(self): from unittest import TestLoader cls = self.obj if not getattr(cls, "__test__", True): return self.session._fixturemanager.parsefactories(self, unittest=True) loader = TestLoader() module = self.getparent(pytest.Module).obj foundsomething = False for name in loader.getTestCaseNames(self.obj): x = getattr(self.obj, name) if not getattr(x, '__test__', True): continue funcobj = getattr(x, 'im_func', x) transfer_markers(funcobj, cls, module) yield TestCaseFunction(name, parent=self) foundsomething = True if not foundsomething: runtest = getattr(self.obj, 'runTest', None) if runtest is not None: ut = sys.modules.get("twisted.trial.unittest", None) if ut is None or runtest != ut.TestCase.runTest: yield TestCaseFunction('runTest', parent=self)
def test_pytest_pycollect_module(self, testdir): testdir.makeconftest(""" import pytest class MyModule(pytest.Module): pass def pytest_pycollect_makemodule(path, parent): if path.basename == "test_xyz.py": return MyModule(path, parent) """) testdir.makepyfile("def test_some(): pass") testdir.makepyfile(test_xyz="def test_func(): pass") result = testdir.runpytest("--collect-only") result.stdout.fnmatch_lines([ "*<Module*test_pytest*", "*<MyModule*xyz*", ])
def test_collector_attributes(testdir): testdir.makeconftest(""" import pytest def pytest_pycollect_makeitem(collector): assert collector.Function == pytest.Function assert collector.Class == pytest.Class assert collector.Instance == pytest.Instance assert collector.Module == pytest.Module """) testdir.makepyfile(""" def test_hello(): pass """) result = testdir.runpytest() result.stdout.fnmatch_lines([ "*1 passed*", ])
def test_request_addfinalizer(self, testdir): item = testdir.getitem(""" teardownlist = [] def pytest_funcarg__something(request): request.addfinalizer(lambda: teardownlist.append(1)) def test_func(something): pass """) item.session._setupstate.prepare(item) pytest._fillfuncargs(item) # successively check finalization calls teardownlist = item.getparent(pytest.Module).obj.teardownlist ss = item.session._setupstate assert not teardownlist ss.teardown_exact(item, None) print(ss.stack) assert teardownlist == [1]
def test_getparent(self, testdir): modcol = testdir.getmodulecol(""" class TestClass: def test_foo(): pass """) cls = testdir.collect_by_name(modcol, "TestClass") fn = testdir.collect_by_name( testdir.collect_by_name(cls, "()"), "test_foo") parent = fn.getparent(pytest.Module) assert parent is modcol parent = fn.getparent(pytest.Function) assert parent is fn parent = fn.getparent(pytest.Class) assert parent is cls
def test_pytest_fs_collect_hooks_are_seen(self, testdir): testdir.makeconftest(""" import pytest class MyModule(pytest.Module): pass def pytest_collect_file(path, parent): if path.ext == ".py": return MyModule(path, parent) """) testdir.mkdir("sub") testdir.makepyfile("def test_x(): pass") result = testdir.runpytest("--collect-only") result.stdout.fnmatch_lines([ "*MyModule*", "*test_x*" ])
def getmodpath(self, stopatmodule=True, includemodule=False): """ return python path relative to the containing module. """ chain = self.listchain() chain.reverse() parts = [] for node in chain: if isinstance(node, Instance): continue name = node.name if isinstance(node, Module): assert name.endswith(".py") name = name[:-3] if stopatmodule: if includemodule: parts.append(name) break parts.append(name) parts.reverse() s = ".".join(parts) return s.replace(".[", "[")
def collect(self): from unittest import TestLoader cls = self.obj if not getattr(cls, "__test__", True): return self.session._fixturemanager.parsefactories(self, unittest=True) loader = TestLoader() module = self.getparent(pytest.Module).obj foundsomething = False for name in loader.getTestCaseNames(self.obj): x = getattr(self.obj, name) funcobj = getattr(x, 'im_func', x) transfer_markers(funcobj, cls, module) yield TestCaseFunction(name, parent=self) foundsomething = True if not foundsomething: runtest = getattr(self.obj, 'runTest', None) if runtest is not None: ut = sys.modules.get("twisted.trial.unittest", None) if ut is None or runtest != ut.TestCase.runTest: yield TestCaseFunction('runTest', parent=self)
def pytest_namespace(): scopename2class.update({ 'class': pytest.Class, 'module': pytest.Module, 'function': pytest.Item, }) return { 'fixture': fixture, 'yield_fixture': yield_fixture, 'collect': {'_fillfuncargs': fillfixtures} }
def module(self): """ python module object where the test function was collected. """ return self._pyfuncitem.getparent(pytest.Module).obj
def test_marker(ctestdir): ctestdir.makepyfile(""" import pytest from pytest_dependency import DependencyManager @pytest.mark.dependency() def test_marker(request): node = request.node.getparent(pytest.Module) assert hasattr(node, 'dependencyManager') assert isinstance(node.dependencyManager, DependencyManager) assert 'test_marker' in node.dependencyManager.results """) result = ctestdir.runpytest("--verbose") result.assert_outcomes(passed=1)
def test_getmodulecollector(self, testdir): item = testdir.getitem("def test_func(): pass") modcol = item.getparent(pytest.Module) assert isinstance(modcol, pytest.Module) assert hasattr(modcol.obj, 'test_func')
def test_makeitem_non_underscore(self, testdir, monkeypatch): modcol = testdir.getmodulecol("def _hello(): pass") l = [] monkeypatch.setattr(pytest.Module, 'makeitem', lambda self, name, obj: l.append(name)) l = modcol.collect() assert '_hello' not in l
def test_pytest_collect_file_from_sister_dir(self, testdir): sub1 = testdir.mkpydir("sub1") sub2 = testdir.mkpydir("sub2") conf1 = testdir.makeconftest(""" import pytest class MyModule1(pytest.Module): pass def pytest_collect_file(path, parent): if path.ext == ".py": return MyModule1(path, parent) """) conf1.move(sub1.join(conf1.basename)) conf2 = testdir.makeconftest(""" import pytest class MyModule2(pytest.Module): pass def pytest_collect_file(path, parent): if path.ext == ".py": return MyModule2(path, parent) """) conf2.move(sub2.join(conf2.basename)) p = testdir.makepyfile("def test_x(): pass") p.copy(sub1.join(p.basename)) p.copy(sub2.join(p.basename)) result = testdir.runpytest("--collect-only") result.stdout.fnmatch_lines([ "*MyModule1*", "*MyModule2*", "*test_x*" ])
def test_collect_custom_nodes_multi_id(self, testdir): p = testdir.makepyfile("def test_func(): pass") testdir.makeconftest(""" import pytest class SpecialItem(pytest.Item): def runtest(self): return # ok class SpecialFile(pytest.File): def collect(self): return [SpecialItem(name="check", parent=self)] def pytest_collect_file(path, parent): if path.basename == %r: return SpecialFile(fspath=path, parent=parent) """ % p.basename) id = p.basename items, hookrec = testdir.inline_genitems(id) py.std.pprint.pprint(hookrec.calls) assert len(items) == 2 hookrec.assert_contains([ ("pytest_collectstart", "collector.fspath == collector.session.fspath"), ("pytest_collectstart", "collector.__class__.__name__ == 'SpecialFile'"), ("pytest_collectstart", "collector.__class__.__name__ == 'Module'"), ("pytest_pycollect_makeitem", "name == 'test_func'"), ("pytest_collectreport", "report.nodeid.startswith(p.basename)"), #("pytest_collectreport", # "report.fspath == %r" % str(rcol.fspath)), ])
def test_global_file(self, testdir, tmpdir): x = tmpdir.ensure("x.py") config = testdir.parseconfigure(x) col = testdir.getnode(config, x) assert isinstance(col, pytest.Module) assert col.name == 'x.py' assert col.parent.name == testdir.tmpdir.basename assert col.parent.parent is None for col in col.listchain(): assert col.config is config
def pytest_runtest_setup(item): if isinstance(item, pytest.Function): if not item.fspath.relto(mydir): return mod = item.getparent(pytest.Module).obj if hasattr(mod, 'hello'): print ("mod.hello %r" % (mod.hello,))
def pytest_namespace(): raises.Exception = pytest.fail.Exception return { 'fixture': fixture, 'yield_fixture': yield_fixture, 'raises' : raises, 'collect': { 'Module': Module, 'Class': Class, 'Instance': Instance, 'Function': Function, 'Generator': Generator, '_fillfuncargs': fillfixtures} }
def pytest_pycollect_makemodule(path, parent): return Module(path, parent)
def _genfunctions(self, name, funcobj): module = self.getparent(Module).obj clscol = self.getparent(Class) cls = clscol and clscol.obj or None transfer_markers(funcobj, cls, module) fm = self.session._fixturemanager fixtureinfo = fm.getfixtureinfo(self, funcobj, cls) metafunc = Metafunc(funcobj, fixtureinfo, self.config, cls=cls, module=module) methods = [] if hasattr(module, "pytest_generate_tests"): methods.append(module.pytest_generate_tests) if hasattr(cls, "pytest_generate_tests"): methods.append(cls().pytest_generate_tests) if methods: self.ihook.pytest_generate_tests.call_extra(methods, dict(metafunc=metafunc)) else: self.ihook.pytest_generate_tests(metafunc=metafunc) Function = self._getcustomclass("Function") if not metafunc._calls: yield Function(name, parent=self, fixtureinfo=fixtureinfo) else: # add funcargs() as fixturedefs to fixtureinfo.arg2fixturedefs add_funcarg_pseudo_fixture_def(self, metafunc, fm) for callspec in metafunc._calls: subname = "%s[%s]" %(name, callspec.id) yield Function(name=subname, parent=self, callspec=callspec, callobj=funcobj, fixtureinfo=fixtureinfo, keywords={callspec.id:True})
def collect(self): self.session._fixturemanager.parsefactories(self) return super(Module, self).collect()
def add_funcarg_pseudo_fixture_def(collector, metafunc, fixturemanager): # this function will transform all collected calls to a functions # if they use direct funcargs (i.e. direct parametrization) # because we want later test execution to be able to rely on # an existing FixtureDef structure for all arguments. # XXX we can probably avoid this algorithm if we modify CallSpec2 # to directly care for creating the fixturedefs within its methods. if not metafunc._calls[0].funcargs: return # this function call does not have direct parametrization # collect funcargs of all callspecs into a list of values arg2params = {} arg2scope = {} for callspec in metafunc._calls: for argname, argvalue in callspec.funcargs.items(): assert argname not in callspec.params callspec.params[argname] = argvalue arg2params_list = arg2params.setdefault(argname, []) callspec.indices[argname] = len(arg2params_list) arg2params_list.append(argvalue) if argname not in arg2scope: scopenum = callspec._arg2scopenum.get(argname, scopenum_function) arg2scope[argname] = scopes[scopenum] callspec.funcargs.clear() # register artificial FixtureDef's so that later at test execution # time we can rely on a proper FixtureDef to exist for fixture setup. arg2fixturedefs = metafunc._arg2fixturedefs for argname, valuelist in arg2params.items(): # if we have a scope that is higher than function we need # to make sure we only ever create an according fixturedef on # a per-scope basis. We thus store and cache the fixturedef on the # node related to the scope. scope = arg2scope[argname] node = None if scope != "function": node = get_scope_node(collector, scope) if node is None: assert scope == "class" and isinstance(collector, pytest.Module) # use module-level collector for class-scope (for now) node = collector if node and argname in node._name2pseudofixturedef: arg2fixturedefs[argname] = [node._name2pseudofixturedef[argname]] else: fixturedef = FixtureDef(fixturemanager, '', argname, get_direct_param_fixture_func, arg2scope[argname], valuelist, False, False) arg2fixturedefs[argname] = [fixturedef] if node is not None: node._name2pseudofixturedef[argname] = fixturedef