Python pytest 模块,Item() 实例源码
我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用pytest.Item()。
def __init__(self, env, flag, item):
"""Create PidChecker instance.
Args:
env (testlib.common3.Environment): Environment instance from 'env' fixture.
flag (bool): Flag to kNow if plugin should skip process validation.
item (pytest.Item): Test case instance.
"""
self.env = env
self.processes = {}
self.flag = flag
self.item_name = item.name
self.skip_details = item.get_marker("skip_pidchecker")
if self.skip_details and self.skip_details.args != ():
self.skip_prcheck = self.skip_details.args
else:
self.skip_prcheck = None
def _send_post_request(self, item):
"""Send post request to reporting server or add it to queue.
Args:
item(pytest.Item): test case item
"""
tc_name = get_tcname(item)
try:
env_prop = item.config.env.env_prop
except AttributeError:
buildname = self.UNDEFINED_BUILD
else:
buildname = self.buildname(env_prop)
suite_name = get_suite_name(item.nodeid)
info = {"brief": get_brief(item, tc_name), "description": get_steps(item, tc_name)}
if self.post_queue:
self._send_post_queue(item, buildname)
self.server_cmd("post", [self.self_name, buildname, suite_name, tc_name, "Run", "", info, self._get_build_info(item)])
def _send_post_queue(self, item=None, buildname=None, sanity=False):
"""Send info about test execution to the Reporting Server.
Args:
item(pytest.Item): test case item
buildname(str): buildname
sanity(bool): True if sanity test
"""
if buildname is None:
buildname = 'undetermined'
if sanity:
buildname += "-sanity"
self.server_cmd("post", self._get_build_info(item)])
for post_req in self.post_queue:
post_req[1] = buildname
# Add empty description and brief. In synapsert new TC won't create
post_req.append(('', ''))
post_req.append(self._get_build_info(item))
self.server_cmd("post", post_req)
self.post_queue[:] = []
def _get_build_info(self, item=None):
"""Get info about build.
Args:
item(pytest.Item): test case item
Returns:
dict{"platform": str,"build": str}: build info
"""
if item is not None and item.config and hasattr(item.config, 'env')\
and item.config.env and "chipName" in item.config.env.env_prop \
and "switchppVersion" in item.config.env.env_prop and self.platform == 'undetermined':
self.platform = item.config.env.env_prop["chipName"]
self.build = item.config.env.env_prop["switchppVersion"]
return {'platform': self.platform, 'build': self.build}
def _sessionstart(self, item):
"""Tell to XMLRPC Server that we are going to interact with it.
Args:
item(pytest.Item): test case item
"""
self.class_logger.info("Configuring reporting server...")
self.server_cmd("open", [self.self_name])
for _var in MODULES:
if "reports_conf." in _var:
commands = MODULES[_var].ReportingServerConfig._sessionstart( # pylint: disable=protected-access
self.class_logger, item, self.self_name, self.buildname(item.config.env.env_prop))
for comm in commands:
self.server_cmd(*comm)
# Order TM reporting to server.
# Order and configure XML report to server.
def test_xfail_item(testdir):
# Ensure pytest.xfail works with non-Python Item
testdir.makeconftest("""
import pytest
class MyItem(pytest.Item):
nodeid = 'foo'
def runtest(self):
pytest.xfail("Expected Failure")
def pytest_collect_file(path,parent):
return MyItem("foo",parent)
""")
result = testdir.inline_run()
passed, skipped, Failed = result.listoutcomes()
assert not Failed
xFailed = [r for r in skipped if hasattr(r, 'wasxfail')]
assert xFailed
def test_issue88_initial_file_multinodes(self, testdir):
testdir.makeconftest("""
import pytest
class MyFile(pytest.File):
def collect(self):
return [MyItem("hello",parent=self)]
def pytest_collect_file(path,parent):
return MyFile(path,parent)
class MyItem(pytest.Item):
pass
""")
p = testdir.makepyfile("def test_hello(): pass")
result = testdir.runpytest(p, "--collect-only")
result.stdout.fnmatch_lines([
"*MyFile*test_issue88*",
"*Module*test_issue88*",
])
def test_multiple_items_per_collector_byid(self, testdir):
c = testdir.makeconftest("""
import pytest
class MyItem(pytest.Item):
def runtest(self):
pass
class MyCollector(pytest.File):
def collect(self):
return [MyItem(name="xyz",parent):
if path.basename.startswith("conftest"):
return MyCollector(path,parent)
""")
result = testdir.runpytest(c.basename+"::"+"xyz")
assert result.ret == 0
result.stdout.fnmatch_lines([
"*1 pass*",
])
def pytest_collectreport(self, report):
if report.Failed:
self.stats.setdefault("error", []).append(report)
elif report.skipped:
self.stats.setdefault("skipped", []).append(report)
items = [x for x in report.result if isinstance(x, pytest.Item)]
self._numcollected += len(items)
if self.isatty:
#self.write_fspath_result(report.nodeid,'E')
self.report_collect()
def pytest_namespace():
collect = dict(Item=Item, Collector=Collector, File=File, Session=Session)
return dict(collect=collect)
def _matchnodes(self, matching, names):
if not matching or not names:
return matching
name = names[0]
assert name
nextnames = names[1:]
resultnodes = []
for node in matching:
if isinstance(node, pytest.Item):
if not names:
resultnodes.append(node)
continue
assert isinstance(node, pytest.Collector)
rep = collect_one_node(node)
if rep.passed:
has_matched = False
for x in rep.result:
# Todo: remove parametrized workaround once collection structure contains parametrization
if x.name == name or x.name.split("[")[0] == name:
resultnodes.extend(self.matchnodes([x], nextnames))
has_matched = True
# XXX accept IDs that don't have "()" for class instances
if not has_matched and len(rep.result) == 1 and x.name == "()":
nextnames.insert(0, name)
resultnodes.extend(self.matchnodes([x], nextnames))
node.ihook.pytest_collectreport(report=rep)
return resultnodes
def genitems(self, node):
self.trace("genitems", node)
if isinstance(node, pytest.Item):
node.ihook.pytest_itemcollected(item=node)
yield node
else:
assert isinstance(node, pytest.Collector)
rep = collect_one_node(node)
if rep.passed:
for subnode in rep.result:
for x in self.genitems(subnode):
yield x
node.ihook.pytest_collectreport(report=rep)
def _getscopeitem(self, scope):
if scope == "function":
# this might also be a non-function Item despite its attribute name
return self._pyfuncitem
node = get_scope_node(self._pyfuncitem, scope)
if node is None and scope == "class":
# fallback to function item itself
node = self._pyfuncitem
assert node
return node
def get_last_record_from_log(self, log, item):
"""Return last log records for TC.
Args:
log(str): log file
item(pytest.Item): test case item
Returns:
str: Log related to specified test item
"""
started = False
tc_name = get_tcname(item)
fin = open(log)
lines = []
while True:
line = fin.readline()
# EOF
if line == "":
break
# Select last block "TC started ... TC finished" in log
if not started:
if tc_name in line and "started" in line:
started = True
lines = []
lines.append(line)
else:
lines.append(line)
if tc_name in line and "finished" in line:
started = False
fin.close()
return " ".join(lines)
def pytest_runtest_setup(self, item):
"""Add info about test case start time.
Args:
item(pytest.Item): test case item
"""
if not item.config.option.tc_duration:
self.detailed_duration[item.nodeid] = dict()
self.detailed_duration[item.nodeid]['setup'] = time.time()
if self._buildname is not None:
self._send_post_request(item)
def pytest_collectreport(self,'E')
self.report_collect()
def pytest_namespace():
collect = dict(Item=Item, Session=Session)
return dict(collect=collect)
def __init__(self, session)
self._report_sections = []
def _matchnodes(self, nextnames))
node.ihook.pytest_collectreport(report=rep)
return resultnodes
def genitems(self, pytest.Collector)
rep = collect_one_node(node)
if rep.passed:
for subnode in rep.result:
for x in self.genitems(subnode):
yield x
node.ihook.pytest_collectreport(report=rep)
def pytest_collectreport(report):
i = 0
for x in report.result:
if isinstance(x, pytest.Item):
try:
# Call our setup (which may do a skip,in which
# case we won't count it).
pytest_runtest_setup(x)
i += 1
except:
continue
State.numcollected += i
def pytest_collectreport(self,'E')
self.report_collect()
def pytest_namespace():
collect = dict(Item=Item, Session=Session)
return dict(collect=collect)
def _matchnodes(self, nextnames))
node.ihook.pytest_collectreport(report=rep)
return resultnodes
def genitems(self, pytest.Collector)
rep = collect_one_node(node)
if rep.passed:
for subnode in rep.result:
for x in self.genitems(subnode):
yield x
node.ihook.pytest_collectreport(report=rep)
def pytest_collectreport(self,'E')
self.report_collect()
def pytest_namespace():
collect = dict(Item=Item, Session=Session)
return dict(collect=collect)
def _matchnodes(self, nextnames))
node.ihook.pytest_collectreport(report=rep)
return resultnodes
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 test_summing_simple(self, testdir):
testdir.makeconftest("""
import pytest
def pytest_collect_file(path,parent):
if path.ext == ".xyz":
return MyItem(path,parent)
class MyItem(pytest.Item):
def __init__(self,path,parent):
super(MyItem,self).__init__(path.basename,parent)
self.fspath = path
def runtest(self):
raise ValueError(42)
def repr_failure(self,excinfo):
return "custom item runtest Failed"
""")
testdir.tmpdir.join("myfile.xyz").write("hello")
result, dom = runandparse(testdir)
assert result.ret
node = dom.getElementsByTagName("testsuite")[0]
assert_attr(node, errors=0, failures=1, skips=0, tests=1)
tnode = node.getElementsByTagName("testcase")[0]
assert_attr(tnode,
#classname="test_collect_error",
name="myfile.xyz")
fnode = tnode.getElementsByTagName("failure")[0]
assert_attr(fnode, message="custom item runtest Failed")
assert "custom item runtest Failed" in fnode.toxml()
def test_import_star_py_dot_test(self, testdir):
p = testdir.makepyfile("""
from py.test import *
#collect
#cmdline
#Item
#assert collect.Item is Item
#assert collect.Collector is Collector
main
skip
xfail
""")
result = testdir.runpython(p)
assert result.ret == 0
def test_namespace_early_from_import(self, testdir):
p = testdir.makepyfile("""
from pytest import Item
from pytest import Item as Item2
assert Item is Item2
""")
result = testdir.runpython(p)
assert result.ret == 0
def test_collect_versus_item(self):
from pytest import Collector, Item
assert not issubclass(Collector, Item)
assert not issubclass(Item, Collector)
def test_compat_attributes(self, testdir, recwarn):
modcol = testdir.getmodulecol("""
def test_pass(): pass
def test_fail(): assert 0
""")
recwarn.clear()
assert modcol.Module == pytest.Module
assert modcol.Class == pytest.Class
assert modcol.Item == pytest.Item
assert modcol.File == pytest.File
assert modcol.Function == pytest.Function
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):
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'"),
"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_matchnodes_two_collections_same_file(testdir):
testdir.makeconftest("""
import pytest
def pytest_configure(config):
config.pluginmanager.register(Plugin2())
class Plugin2:
def pytest_collect_file(self,parent):
if path.ext == ".abc":
return MyFile2(path,parent)
def pytest_collect_file(path,parent):
if path.ext == ".abc":
return MyFile1(path,parent)
class MyFile1(pytest.Item,pytest.File):
def runtest(self):
pass
class MyFile2(pytest.File):
def collect(self):
return [Item2("hello",parent=self)]
class Item2(pytest.Item):
def runtest(self):
pass
""")
p = testdir.makefile(".abc", "")
result = testdir.runpytest()
assert result.ret == 0
result.stdout.fnmatch_lines([
"*2 passed*",
])
res = testdir.runpytest("%s::hello" % p.basename)
res.stdout.fnmatch_lines([
"*1 passed*",
])
def pytest_collectreport(self, pytest.Item)]
self._numcollected += len(items)
if self.hasmarkup:
#self.write_fspath_result(report.nodeid,'E')
self.report_collect()
def pytest_namespace():
collect = dict(Item=Item, Session=Session)
return dict(collect=collect)
def _matchnodes(self, pytest.Collector)
rep = collect_one_node(node)
if rep.passed:
has_matched = False
for x in rep.result:
if x.name == name:
resultnodes.extend(self.matchnodes([x], nextnames))
node.ihook.pytest_collectreport(report=rep)
return resultnodes
def genitems(self, pytest.Collector)
rep = collect_one_node(node)
if rep.passed:
for subnode in rep.result:
for x in self.genitems(subnode):
yield x
node.ihook.pytest_collectreport(report=rep)
def test_it_works_with_the_simplest_test_items(ourtestdir):
ourtestdir.makepyfile(
conftest="""
import pytest
class MyCollector(pytest.Collector):
def __init__(self,fspath,items,**kwargs):
super(MyCollector,self).__init__(fspath,**kwargs)
self.items = items
def collect(self):
return self.items
class NoOpItem(pytest.Item):
def __init__(self,parent,module=None):
super(NoOpItem,self).__init__(path,parent)
if module is not None:
self.module = module
def runtest(self):
pass
def pytest_collect_file(path,parent):
if not str(path).endswith('.py'):
return
return MyCollector(
fspath=str(path),
items=[
NoOpItem(str(path),'foo'),
NoOpItem(str(path),parent),
],
parent=parent,
)
"""
)
args = ['-v']
out = ourtestdir.runpytest(*args)
out.assert_outcomes(passed=2)