Best Python code snippet using pytest-play_python
test_collection.py
Source:test_collection.py
...60 testdir.makepyfile(conftest="""61 import pytest62 class CustomFile(pytest.File):63 pass64 def pytest_collect_file(path, parent):65 if path.ext == ".xxx":66 return CustomFile(path, parent=parent)67 """)68 node = testdir.getpathnode(hello)69 assert isinstance(node, pytest.File)70 assert node.name == "hello.xxx"71 nodes = node.session.perform_collect([node.nodeid], genitems=False)72 assert len(nodes) == 173 assert isinstance(nodes[0], pytest.File)74class TestCollectFS:75 def test_ignored_certain_directories(self, testdir):76 tmpdir = testdir.tmpdir77 tmpdir.ensure("_darcs", 'test_notfound.py')78 tmpdir.ensure("CVS", 'test_notfound.py')79 tmpdir.ensure("{arch}", 'test_notfound.py')80 tmpdir.ensure(".whatever", 'test_notfound.py')81 tmpdir.ensure(".bzr", 'test_notfound.py')82 tmpdir.ensure("normal", 'test_found.py')83 for x in tmpdir.visit("test_*.py"):84 x.write("def test_hello(): pass")85 result = testdir.runpytest("--collect-only")86 s = result.stdout.str()87 assert "test_notfound" not in s88 assert "test_found" in s89 def test_custom_norecursedirs(self, testdir):90 testdir.makeini("""91 [pytest]92 norecursedirs = mydir xyz*93 """)94 tmpdir = testdir.tmpdir95 tmpdir.ensure("mydir", "test_hello.py").write("def test_1(): pass")96 tmpdir.ensure("xyz123", "test_2.py").write("def test_2(): 0/0")97 tmpdir.ensure("xy", "test_ok.py").write("def test_3(): pass")98 rec = testdir.inline_run()99 rec.assertoutcome(passed=1)100 rec = testdir.inline_run("xyz123/test_2.py")101 rec.assertoutcome(failed=1)102class TestCollectPluginHookRelay:103 def test_pytest_collect_file(self, testdir):104 wascalled = []105 class Plugin:106 def pytest_collect_file(self, path, parent):107 wascalled.append(path)108 testdir.makefile(".abc", "xyz")109 pytest.main([testdir.tmpdir], plugins=[Plugin()])110 assert len(wascalled) == 1111 assert wascalled[0].ext == '.abc'112 def test_pytest_collect_directory(self, testdir):113 wascalled = []114 class Plugin:115 def pytest_collect_directory(self, path, parent):116 wascalled.append(path.basename)117 testdir.mkdir("hello")118 testdir.mkdir("world")119 pytest.main(testdir.tmpdir, plugins=[Plugin()])120 assert "hello" in wascalled121 assert "world" in wascalled122class TestPrunetraceback:123 def test_collection_error(self, testdir):124 p = testdir.makepyfile("""125 import not_exists126 """)127 result = testdir.runpytest(p)128 assert "__import__" not in result.stdout.str(), "too long traceback"129 result.stdout.fnmatch_lines([130 "*ERROR collecting*",131 "*mport*not_exists*"132 ])133 def test_custom_repr_failure(self, testdir):134 p = testdir.makepyfile("""135 import not_exists136 """)137 testdir.makeconftest("""138 import pytest139 def pytest_collect_file(path, parent):140 return MyFile(path, parent)141 class MyError(Exception):142 pass143 class MyFile(pytest.File):144 def collect(self):145 raise MyError()146 def repr_failure(self, excinfo):147 if excinfo.errisinstance(MyError):148 return "hello world"149 return pytest.File.repr_failure(self, excinfo)150 """)151 result = testdir.runpytest(p)152 result.stdout.fnmatch_lines([153 "*ERROR collecting*",154 "*hello world*",155 ])156 @pytest.mark.xfail(reason="other mechanism for adding to reporting needed")157 def test_collect_report_postprocessing(self, testdir):158 p = testdir.makepyfile("""159 import not_exists160 """)161 testdir.makeconftest("""162 import pytest163 def pytest_make_collect_report(__multicall__):164 rep = __multicall__.execute()165 rep.headerlines += ["header1"]166 return rep167 """)168 result = testdir.runpytest(p)169 result.stdout.fnmatch_lines([170 "*ERROR collecting*",171 "*header1*",172 ])173class TestCustomConftests:174 def test_ignore_collect_path(self, testdir):175 testdir.makeconftest("""176 def pytest_ignore_collect(path, config):177 return path.basename.startswith("x") or \178 path.basename == "test_one.py"179 """)180 sub = testdir.mkdir("xy123")181 sub.ensure("test_hello.py").write("syntax error")182 sub.join("conftest.py").write("syntax error")183 testdir.makepyfile("def test_hello(): pass")184 testdir.makepyfile(test_one="syntax error")185 result = testdir.runpytest("--fulltrace")186 assert result.ret == 0187 result.stdout.fnmatch_lines(["*1 passed*"])188 def test_ignore_collect_not_called_on_argument(self, testdir):189 testdir.makeconftest("""190 def pytest_ignore_collect(path, config):191 return True192 """)193 p = testdir.makepyfile("def test_hello(): pass")194 result = testdir.runpytest(p)195 assert result.ret == 0196 assert "1 passed" in result.stdout.str()197 result = testdir.runpytest()198 assert result.ret == 0199 assert "1 passed" not in result.stdout.str()200 def test_collectignore_exclude_on_option(self, testdir):201 testdir.makeconftest("""202 collect_ignore = ['hello', 'test_world.py']203 def pytest_addoption(parser):204 parser.addoption("--XX", action="store_true", default=False)205 def pytest_configure(config):206 if config.getvalue("XX"):207 collect_ignore[:] = []208 """)209 testdir.mkdir("hello")210 testdir.makepyfile(test_world="def test_hello(): pass")211 result = testdir.runpytest()212 assert result.ret == 0213 assert "passed" not in result.stdout.str()214 result = testdir.runpytest("--XX")215 assert result.ret == 0216 assert "passed" in result.stdout.str()217 def test_pytest_fs_collect_hooks_are_seen(self, testdir):218 testdir.makeconftest("""219 import pytest220 class MyModule(pytest.Module):221 pass222 def pytest_collect_file(path, parent):223 if path.ext == ".py":224 return MyModule(path, parent)225 """)226 testdir.mkdir("sub")227 testdir.makepyfile("def test_x(): pass")228 result = testdir.runpytest("--collect-only")229 result.stdout.fnmatch_lines([230 "*MyModule*",231 "*test_x*"232 ])233 def test_pytest_collect_file_from_sister_dir(self, testdir):234 sub1 = testdir.mkpydir("sub1")235 sub2 = testdir.mkpydir("sub2")236 conf1 = testdir.makeconftest("""237 import pytest238 class MyModule1(pytest.Module):239 pass240 def pytest_collect_file(path, parent):241 if path.ext == ".py":242 return MyModule1(path, parent)243 """)244 conf1.move(sub1.join(conf1.basename))245 conf2 = testdir.makeconftest("""246 import pytest247 class MyModule2(pytest.Module):248 pass249 def pytest_collect_file(path, parent):250 if path.ext == ".py":251 return MyModule2(path, parent)252 """)253 conf2.move(sub2.join(conf2.basename))254 p = testdir.makepyfile("def test_x(): pass")255 p.copy(sub1.join(p.basename))256 p.copy(sub2.join(p.basename))257 result = testdir.runpytest("--collect-only")258 result.stdout.fnmatch_lines([259 "*MyModule1*",260 "*MyModule2*",261 "*test_x*"262 ])263class TestSession:264 def test_parsearg(self, testdir):265 p = testdir.makepyfile("def test_func(): pass")266 subdir = testdir.mkdir("sub")267 subdir.ensure("__init__.py")268 target = subdir.join(p.basename)269 p.move(target)270 testdir.chdir()271 subdir.chdir()272 config = testdir.parseconfig(p.basename)273 rcol = Session(config=config)274 assert rcol.fspath == subdir275 parts = rcol._parsearg(p.basename)276 assert parts[0] == target277 assert len(parts) == 1278 parts = rcol._parsearg(p.basename + "::test_func")279 assert parts[0] == target280 assert parts[1] == "test_func"281 assert len(parts) == 2282 def test_collect_topdir(self, testdir):283 p = testdir.makepyfile("def test_func(): pass")284 id = "::".join([p.basename, "test_func"])285 # XXX migrate to inline_genitems? (see below)286 config = testdir.parseconfig(id)287 topdir = testdir.tmpdir288 rcol = Session(config)289 assert topdir == rcol.fspath290 #rootid = rcol.nodeid291 #root2 = rcol.perform_collect([rcol.nodeid], genitems=False)[0]292 #assert root2 == rcol, rootid293 colitems = rcol.perform_collect([rcol.nodeid], genitems=False)294 assert len(colitems) == 1295 assert colitems[0].fspath == p296 def test_collect_protocol_single_function(self, testdir):297 p = testdir.makepyfile("def test_func(): pass")298 id = "::".join([p.basename, "test_func"])299 items, hookrec = testdir.inline_genitems(id)300 item, = items301 assert item.name == "test_func"302 newid = item.nodeid303 assert newid == id304 py.std.pprint.pprint(hookrec.calls)305 topdir = testdir.tmpdir # noqa306 hookrec.assert_contains([307 ("pytest_collectstart", "collector.fspath == topdir"),308 ("pytest_make_collect_report", "collector.fspath == topdir"),309 ("pytest_collectstart", "collector.fspath == p"),310 ("pytest_make_collect_report", "collector.fspath == p"),311 ("pytest_pycollect_makeitem", "name == 'test_func'"),312 ("pytest_collectreport", "report.nodeid.startswith(p.basename)"),313 ("pytest_collectreport", "report.nodeid == ''")314 ])315 def test_collect_protocol_method(self, testdir):316 p = testdir.makepyfile("""317 class TestClass:318 def test_method(self):319 pass320 """)321 normid = p.basename + "::TestClass::()::test_method"322 for id in [p.basename,323 p.basename + "::TestClass",324 p.basename + "::TestClass::()",325 normid,326 ]:327 items, hookrec = testdir.inline_genitems(id)328 assert len(items) == 1329 assert items[0].name == "test_method"330 newid = items[0].nodeid331 assert newid == normid332 def test_collect_custom_nodes_multi_id(self, testdir):333 p = testdir.makepyfile("def test_func(): pass")334 testdir.makeconftest("""335 import pytest336 class SpecialItem(pytest.Item):337 def runtest(self):338 return # ok339 class SpecialFile(pytest.File):340 def collect(self):341 return [SpecialItem(name="check", parent=self)]342 def pytest_collect_file(path, parent):343 if path.basename == %r:344 return SpecialFile(fspath=path, parent=parent)345 """ % p.basename)346 id = p.basename347 items, hookrec = testdir.inline_genitems(id)348 py.std.pprint.pprint(hookrec.calls)349 assert len(items) == 2350 hookrec.assert_contains([351 ("pytest_collectstart",352 "collector.fspath == collector.session.fspath"),353 ("pytest_collectstart",354 "collector.__class__.__name__ == 'SpecialFile'"),355 ("pytest_collectstart",356 "collector.__class__.__name__ == 'Module'"),357 ("pytest_pycollect_makeitem", "name == 'test_func'"),358 ("pytest_collectreport", "report.nodeid.startswith(p.basename)"),359 #("pytest_collectreport",360 # "report.fspath == %r" % str(rcol.fspath)),361 ])362 def test_collect_subdir_event_ordering(self, testdir):363 p = testdir.makepyfile("def test_func(): pass")364 aaa = testdir.mkpydir("aaa")365 test_aaa = aaa.join("test_aaa.py")366 p.move(test_aaa)367 items, hookrec = testdir.inline_genitems()368 assert len(items) == 1369 py.std.pprint.pprint(hookrec.calls)370 hookrec.assert_contains([371 ("pytest_collectstart", "collector.fspath == test_aaa"),372 ("pytest_pycollect_makeitem", "name == 'test_func'"),373 ("pytest_collectreport",374 "report.nodeid.startswith('aaa/test_aaa.py')"),375 ])376 def test_collect_two_commandline_args(self, testdir):377 p = testdir.makepyfile("def test_func(): pass")378 aaa = testdir.mkpydir("aaa")379 bbb = testdir.mkpydir("bbb")380 test_aaa = aaa.join("test_aaa.py")381 p.copy(test_aaa)382 test_bbb = bbb.join("test_bbb.py")383 p.move(test_bbb)384 id = "."385 items, hookrec = testdir.inline_genitems(id)386 assert len(items) == 2387 py.std.pprint.pprint(hookrec.calls)388 hookrec.assert_contains([389 ("pytest_collectstart", "collector.fspath == test_aaa"),390 ("pytest_pycollect_makeitem", "name == 'test_func'"),391 ("pytest_collectreport", "report.nodeid == 'aaa/test_aaa.py'"),392 ("pytest_collectstart", "collector.fspath == test_bbb"),393 ("pytest_pycollect_makeitem", "name == 'test_func'"),394 ("pytest_collectreport", "report.nodeid == 'bbb/test_bbb.py'"),395 ])396 def test_serialization_byid(self, testdir):397 testdir.makepyfile("def test_func(): pass")398 items, hookrec = testdir.inline_genitems()399 assert len(items) == 1400 item, = items401 items2, hookrec = testdir.inline_genitems(item.nodeid)402 item2, = items2403 assert item2.name == item.name404 assert item2.fspath == item.fspath405 def test_find_byid_without_instance_parents(self, testdir):406 p = testdir.makepyfile("""407 class TestClass:408 def test_method(self):409 pass410 """)411 arg = p.basename + ("::TestClass::test_method")412 items, hookrec = testdir.inline_genitems(arg)413 assert len(items) == 1414 item, = items415 assert item.nodeid.endswith("TestClass::()::test_method")416class Test_getinitialnodes:417 def test_global_file(self, testdir, tmpdir):418 x = tmpdir.ensure("x.py")419 config = testdir.parseconfigure(x)420 col = testdir.getnode(config, x)421 assert isinstance(col, pytest.Module)422 assert col.name == 'x.py'423 assert col.parent.name == testdir.tmpdir.basename424 assert col.parent.parent is None425 for col in col.listchain():426 assert col.config is config427 def test_pkgfile(self, testdir):428 testdir.chdir()429 tmpdir = testdir.tmpdir430 subdir = tmpdir.join("subdir")431 x = subdir.ensure("x.py")432 subdir.ensure("__init__.py")433 config = testdir.parseconfigure(x)434 col = testdir.getnode(config, x)435 assert isinstance(col, pytest.Module)436 assert col.name == 'x.py'437 assert col.parent.parent is None438 for col in col.listchain():439 assert col.config is config440class Test_genitems:441 def test_check_collect_hashes(self, testdir):442 p = testdir.makepyfile("""443 def test_1():444 pass445 def test_2():446 pass447 """)448 p.copy(p.dirpath(p.purebasename + "2" + ".py"))449 items, reprec = testdir.inline_genitems(p.dirpath())450 assert len(items) == 4451 for numi, i in enumerate(items):452 for numj, j in enumerate(items):453 if numj != numi:454 assert hash(i) != hash(j)455 assert i != j456 def test_example_items1(self, testdir):457 p = testdir.makepyfile('''458 def testone():459 pass460 class TestX:461 def testmethod_one(self):462 pass463 class TestY(TestX):464 pass465 ''')466 items, reprec = testdir.inline_genitems(p)467 assert len(items) == 3468 assert items[0].name == 'testone'469 assert items[1].name == 'testmethod_one'470 assert items[2].name == 'testmethod_one'471 # let's also test getmodpath here472 assert items[0].getmodpath() == "testone"473 assert items[1].getmodpath() == "TestX.testmethod_one"474 assert items[2].getmodpath() == "TestY.testmethod_one"475 s = items[0].getmodpath(stopatmodule=False)476 assert s.endswith("test_example_items1.testone")477 print(s)478 def test_class_and_functions_discovery_using_glob(self, testdir):479 """480 tests that python_classes and python_functions config options work481 as prefixes and glob-like patterns (issue #600).482 """483 testdir.makeini("""484 [pytest]485 python_classes = *Suite Test486 python_functions = *_test test487 """)488 p = testdir.makepyfile('''489 class MyTestSuite:490 def x_test(self):491 pass492 class TestCase:493 def test_y(self):494 pass495 ''')496 items, reprec = testdir.inline_genitems(p)497 ids = [x.getmodpath() for x in items]498 assert ids == ['MyTestSuite.x_test', 'TestCase.test_y']499def test_matchnodes_two_collections_same_file(testdir):500 testdir.makeconftest("""501 import pytest502 def pytest_configure(config):503 config.pluginmanager.register(Plugin2())504 class Plugin2:505 def pytest_collect_file(self, path, parent):506 if path.ext == ".abc":507 return MyFile2(path, parent)508 def pytest_collect_file(path, parent):509 if path.ext == ".abc":510 return MyFile1(path, parent)511 class MyFile1(pytest.Item, pytest.File):512 def runtest(self):513 pass514 class MyFile2(pytest.File):515 def collect(self):516 return [Item2("hello", parent=self)]517 class Item2(pytest.Item):518 def runtest(self):519 pass520 """)521 p = testdir.makefile(".abc", "")522 result = testdir.runpytest()...
notebook_collector_plugin.py
Source:notebook_collector_plugin.py
...12 PYTEST_VERSION = tuple(int(x) for x in pytest.__version__.split('.'))13except Exception:14 PYTEST_VERSION = (0, 0, 0)15if PYTEST_VERSION >= (7, 0, 0):16 def pytest_collect_file(file_path, path, parent):17 """pytest hook.18 Create a Collector for the given path, or None if not relevant.19 The new node needs to have the specified parent as a parent.20 """21 if path.ext == ".ipynb":22 return IpynbFile.from_parent(parent, path=file_path)23else:24 def pytest_collect_file(path, parent):25 """pytest hook.26 Create a Collector for the given path, or None if not relevant.27 The new node needs to have the specified parent as a parent.28 """29 if path.ext == ".ipynb":30 return IpynbFile.from_parent(parent, fspath=path)31class IpynbFile(pytest.File):32 TEST_PATTERN = re.compile(r"(?i)^\s*#+\s*(test.*?)\s*$")33 def collect(self):34 mod = import_from_path(self.fspath)35 setup_cells = []36 for cell in get_cells(mod):37 lines = cell.source.splitlines() or [""] # dummy list so the next line works38 match = re.match(self.TEST_PATTERN, lines[0])...
test_plugin.py
Source:test_plugin.py
...18PYTEST_VERSION_INFO = tuple(int(part) for part in PYTEST_VERSION.split(".")[:3])19ERROR = Severity.ERROR20NOTE = Severity.NOTE21WARNING = Severity.WARNING22def call_pytest_collect_file(fspath, parent):23 if PYTEST_VERSION_INFO < (7,):24 return pytest_collect_file(fspath, parent)25 else:26 return pytest_collect_file(pathlib.Path(str(fspath)), fspath, parent) # type: ignore27def test_create_mypy_assertion_error():28 MypyAssertionError(None, [])29def mk_dummy_parent(tmp_path, filename, content=""):30 path = tmp_path / filename31 path.write_text(content)32 config = Mock(spec=Config)33 config.rootdir = str(tmp_path)34 config.rootpath = str(tmp_path)35 config.getini.return_value = ["test_*.py", "*_test.py"]36 session = SimpleNamespace(37 config=config, isinitpath=lambda p: True, _initialpaths=[]38 )39 parent = SimpleNamespace(40 config=config,41 session=session,42 nodeid="dummy",43 fspath=LocalPath(path),44 path=path,45 )46 return parent47@pytest.mark.parametrize("filename", ["z.py", "test_z.mypy-testing"])48def test_pytest_collect_file_not_test_file_name(tmp_path, filename: str):49 parent = mk_dummy_parent(tmp_path, filename)50 fspath = parent.fspath51 actual = call_pytest_collect_file(fspath, parent)52 assert actual is None53@pytest.mark.parametrize("filename", ["test_z.py", "test_z.mypy-testing"])54def test_pytest_collect_file(tmp_path, filename):55 content = dedent(56 """57 @pytest.mark.mypy_testing58 def foo():59 pass60 """61 )62 parent = mk_dummy_parent(tmp_path, filename, content)63 expected = MypyTestFile(64 filename=str(parent.path), source_lines=content.splitlines()65 )66 fspath = parent.fspath67 actual = call_pytest_collect_file(fspath, parent)68 assert isinstance(actual, PytestMypyFile)69 assert len(actual.mypy_file.items) == 170 actual.mypy_file.items = []...
plugin.py
Source:plugin.py
...11 item.name = item.name.encode("utf-8").decode("unicode_escape")12 item._nodeid = item.nodeid.encode("utf-8").decode("unicode_escape")13# def pytest_collect_directory(path, parent):14# print(path. parent)15# def pytest_collect_file(path, parent):16# print(path, parent)17def pytest_collect_file(parent, path):18 allowYamlFile = [".yaml", ".yml"]19 if path.ext in allowYamlFile and path.basename.startswith("test"):20 return YamlFile(path, parent)21class YamlFile(pytest.File):22 def collect(self):23 items = yaml.safe_load(self.fspath.open(encoding="utf-8"))24 if not isinstance(items, dict):25 raise CaseParserError("case file must be a dict")26 caseType, cases, authConfig = (27 items.get("type"),28 items.get("cases"),29 items.get("config"),30 )31 # check case...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!