Debian Codegraph @

testing/test_conftest.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 from collections.abc import Generator
5 from collections.abc import Sequence
6 import os
7 from pathlib import Path
8 import textwrap
9 from typing import cast
10
11 from _pytest.config import ExitCode
12 from _pytest.config import PytestPluginManager
13 from _pytest.monkeypatch import MonkeyPatch
14 from _pytest.pathlib import symlink_or_skip
15 from _pytest.pytester import Pytester
16 from _pytest.tmpdir import TempPathFactory
17 import pytest
18
19
20 def ConftestWithSetinitial(path) -> PytestPluginManager:
21 conftest = PytestPluginManager()
22 conftest_setinitial(conftest, [path])
23 return conftest
24
25
26 def conftest_setinitial(
27 conftest: PytestPluginManager,
28 args: Sequence[str | Path],
29 confcutdir: Path | None = None,
30 ) -> None:
31 conftest._set_initial_conftests(
32 args=args,
33 pyargs=False,
34 noconftest=False,
35 rootpath=Path(args[0]),
36 confcutdir=confcutdir,
37 invocation_dir=Path.cwd(),
38 importmode="prepend",
39 consider_namespace_packages=False,
40 )
41
42
43 @pytest.mark.usefixtures("_sys_snapshot")
44 class TestConftestValueAccessGlobal:
45 @pytest.fixture(scope="module", params=["global", "inpackage"])
46 def basedir(self, request, tmp_path_factory: TempPathFactory) -> Generator[Path]:
47 tmp_path = tmp_path_factory.mktemp("basedir", numbered=True)
48 tmp_path.joinpath("adir/b").mkdir(parents=True)
49 tmp_path.joinpath("adir/conftest.py").write_text(
50 "a=1 ; Directory = 3", encoding="utf-8"
51 )
52 tmp_path.joinpath("adir/b/conftest.py").write_text(
53 "b=2 ; a = 1.5", encoding="utf-8"
54 )
55 if request.param == "inpackage":
56 tmp_path.joinpath("adir/__init__.py").touch()
57 tmp_path.joinpath("adir/b/__init__.py").touch()
58
59 yield tmp_path
60
61 def test_basic_init(self, basedir: Path) -> None:
62 conftest = PytestPluginManager()
63 p = basedir / "adir"
64 conftest._loadconftestmodules(
65 p, importmode="prepend", rootpath=basedir, consider_namespace_packages=False
66 )
67 assert conftest._rget_with_confmod("a", p)[1] == 1
68
69 def test_immediate_initialization_and_incremental_are_the_same(
70 self, basedir: Path
71 ) -> None:
72 conftest = PytestPluginManager()
73 assert not len(conftest._dirpath2confmods)
74 conftest._loadconftestmodules(
75 basedir,
76 importmode="prepend",
77 rootpath=basedir,
78 consider_namespace_packages=False,
79 )
80 snap1 = len(conftest._dirpath2confmods)
81 assert snap1 == 1
82 conftest._loadconftestmodules(
83 basedir / "adir",
84 importmode="prepend",
85 rootpath=basedir,
86 consider_namespace_packages=False,
87 )
88 assert len(conftest._dirpath2confmods) == snap1 + 1
89 conftest._loadconftestmodules(
90 basedir / "b",
91 importmode="prepend",
92 rootpath=basedir,
93 consider_namespace_packages=False,
94 )
95 assert len(conftest._dirpath2confmods) == snap1 + 2
96
97 def test_value_access_not_existing(self, basedir: Path) -> None:
98 conftest = ConftestWithSetinitial(basedir)
99 with pytest.raises(KeyError):
100 conftest._rget_with_confmod("a", basedir)
101
102 def test_value_access_by_path(self, basedir: Path) -> None:
103 conftest = ConftestWithSetinitial(basedir)
104 adir = basedir / "adir"
105 conftest._loadconftestmodules(
106 adir,
107 importmode="prepend",
108 rootpath=basedir,
109 consider_namespace_packages=False,
110 )
111 assert conftest._rget_with_confmod("a", adir)[1] == 1
112 conftest._loadconftestmodules(
113 adir / "b",
114 importmode="prepend",
115 rootpath=basedir,
116 consider_namespace_packages=False,
117 )
118 assert conftest._rget_with_confmod("a", adir / "b")[1] == 1.5
119
120 def test_value_access_with_confmod(self, basedir: Path) -> None:
121 startdir = basedir / "adir" / "b"
122 startdir.joinpath("xx").mkdir()
123 conftest = ConftestWithSetinitial(startdir)
124 mod, value = conftest._rget_with_confmod("a", startdir)
125 assert value == 1.5
126 assert mod.__file__ is not None
127 path = Path(mod.__file__)
128 assert path.parent == basedir / "adir" / "b"
129 assert path.stem == "conftest"
130
131
132 def test_conftest_in_nonpkg_with_init(tmp_path: Path, _sys_snapshot) -> None:
133 tmp_path.joinpath("adir-1.0/b").mkdir(parents=True)
134 tmp_path.joinpath("adir-1.0/conftest.py").write_text(
135 "a=1 ; Directory = 3", encoding="utf-8"
136 )
137 tmp_path.joinpath("adir-1.0/b/conftest.py").write_text(
138 "b=2 ; a = 1.5", encoding="utf-8"
139 )
140 tmp_path.joinpath("adir-1.0/b/__init__.py").touch()
141 tmp_path.joinpath("adir-1.0/__init__.py").touch()
142 ConftestWithSetinitial(tmp_path.joinpath("adir-1.0", "b"))
143
144
145 def test_doubledash_considered(pytester: Pytester) -> None:
146 conf = pytester.mkdir("--option")
147 conf.joinpath("conftest.py").touch()
148 conftest = PytestPluginManager()
149 conftest_setinitial(conftest, [conf.name, conf.name])
150 values = conftest._getconftestmodules(conf)
151 assert len(values) == 1
152
153
154 def test_issue151_load_all_conftests(pytester: Pytester) -> None:
155 names = "code proj src".split()
156 for name in names:
157 p = pytester.mkdir(name)
158 p.joinpath("conftest.py").touch()
159
160 pm = PytestPluginManager()
161 conftest_setinitial(pm, names)
162 assert len(set(pm.get_plugins()) - {pm}) == len(names)
163
164
165 def test_conftest_global_import(pytester: Pytester) -> None:
166 pytester.makeconftest("x=3")
167 p = pytester.makepyfile(
168 """
169 from pathlib import Path
170 import pytest
171 from _pytest.config import PytestPluginManager
172 conf = PytestPluginManager()
173 mod = conf._importconftest(
174 Path("conftest.py"),
175 importmode="prepend",
176 rootpath=Path.cwd(),
177 consider_namespace_packages=False,
178 )
179 assert mod.x == 3
180 import conftest
181 assert conftest is mod, (conftest, mod)
182 sub = Path("sub")
183 sub.mkdir()
184 subconf = sub / "conftest.py"
185 subconf.write_text("y=4", encoding="utf-8")
186 mod2 = conf._importconftest(
187 subconf,
188 importmode="prepend",
189 rootpath=Path.cwd(),
190 consider_namespace_packages=False,
191 )
192 assert mod != mod2
193 assert mod2.y == 4
194 import conftest
195 assert conftest is mod2, (conftest, mod)
196 """
197 )
198 res = pytester.runpython(p)
199 assert res.ret == 0
200
201
202 def test_conftestcutdir(pytester: Pytester) -> None:
203 conf = pytester.makeconftest("")
204 p = pytester.mkdir("x")
205 conftest = PytestPluginManager()
206 conftest_setinitial(conftest, [pytester.path], confcutdir=p)
207 conftest._loadconftestmodules(
208 p,
209 importmode="prepend",
210 rootpath=pytester.path,
211 consider_namespace_packages=False,
212 )
213 values = conftest._getconftestmodules(p)
214 assert len(values) == 0
215 conftest._loadconftestmodules(
216 conf.parent,
217 importmode="prepend",
218 rootpath=pytester.path,
219 consider_namespace_packages=False,
220 )
221 values = conftest._getconftestmodules(conf.parent)
222 assert len(values) == 0
223 assert not conftest.has_plugin(str(conf))
224 # but we can still import a conftest directly
225 conftest._importconftest(
226 conf,
227 importmode="prepend",
228 rootpath=pytester.path,
229 consider_namespace_packages=False,
230 )
231 values = conftest._getconftestmodules(conf.parent)
232 assert values[0].__file__ is not None
233 assert values[0].__file__.startswith(str(conf))
234 # and all sub paths get updated properly
235 values = conftest._getconftestmodules(p)
236 assert len(values) == 1
237 assert values[0].__file__ is not None
238 assert values[0].__file__.startswith(str(conf))
239
240
241 def test_conftestcutdir_inplace_considered(pytester: Pytester) -> None:
242 conf = pytester.makeconftest("")
243 conftest = PytestPluginManager()
244 conftest_setinitial(conftest, [conf.parent], confcutdir=conf.parent)
245 values = conftest._getconftestmodules(conf.parent)
246 assert len(values) == 1
247 assert values[0].__file__ is not None
248 assert values[0].__file__.startswith(str(conf))
249
250
251 @pytest.mark.parametrize("name", "test tests whatever .dotdir".split())
252 def test_setinitial_conftest_subdirs(pytester: Pytester, name: str) -> None:
253 sub = pytester.mkdir(name)
254 subconftest = sub.joinpath("conftest.py")
255 subconftest.touch()
256 pm = PytestPluginManager()
257 conftest_setinitial(pm, [sub.parent], confcutdir=pytester.path)
258 key = subconftest.resolve()
259 if name not in ("whatever", ".dotdir"):
260 assert pm.has_plugin(str(key))
261 assert len(set(pm.get_plugins()) - {pm}) == 1
262 else:
263 assert not pm.has_plugin(str(key))
264 assert len(set(pm.get_plugins()) - {pm}) == 0
265
266
267 def test_conftest_confcutdir(pytester: Pytester) -> None:
268 pytester.makeconftest("assert 0")
269 x = pytester.mkdir("x")
270 x.joinpath("conftest.py").write_text(
271 textwrap.dedent(
272 """\
273 def pytest_addoption(parser):
274 parser.addoption("--xyz", action="store_true")
275 """
276 ),
277 encoding="utf-8",
278 )
279 result = pytester.runpytest("-h", f"--confcutdir={x}", x)
280 result.stdout.fnmatch_lines(["*--xyz*"])
281 result.stdout.no_fnmatch_line("*warning: could not load initial*")
282
283
284 def test_installed_conftest_is_picked_up(pytester: Pytester, tmp_path: Path) -> None:
285 """When using `--pyargs` to run tests in an installed packages (located e.g.
286 in a site-packages in the PYTHONPATH), conftest files in there are picked
287 up.
288
289 Regression test for #9767.
290 """
291 # pytester dir - the source tree.
292 # tmp_path - the simulated site-packages dir (not in source tree).
293
294 pytester.syspathinsert(tmp_path)
295 pytester.makepyprojecttoml("[tool.pytest.ini_options]")
296 tmp_path.joinpath("foo").mkdir()
297 tmp_path.joinpath("foo", "__init__.py").touch()
298 tmp_path.joinpath("foo", "conftest.py").write_text(
299 textwrap.dedent(
300 """\
301 import pytest
302 @pytest.fixture
303 def fix(): return None
304 """
305 ),
306 encoding="utf-8",
307 )
308 tmp_path.joinpath("foo", "test_it.py").write_text(
309 "def test_it(fix): pass", encoding="utf-8"
310 )
311 result = pytester.runpytest("--pyargs", "foo")
312 assert result.ret == 0
313
314
315 def test_conftest_symlink(pytester: Pytester) -> None:
316 """`conftest.py` discovery follows normal path resolution and does not resolve symlinks."""
317 # Structure:
318 # /real
319 # /real/conftest.py
320 # /real/app
321 # /real/app/tests
322 # /real/app/tests/test_foo.py
323
324 # Links:
325 # /symlinktests -> /real/app/tests (running at symlinktests should fail)
326 # /symlink -> /real (running at /symlink should work)
327
328 real = pytester.mkdir("real")
329 realtests = real.joinpath("app/tests")
330 realtests.mkdir(parents=True)
331 symlink_or_skip(realtests, pytester.path.joinpath("symlinktests"))
332 symlink_or_skip(real, pytester.path.joinpath("symlink"))
333 pytester.makepyfile(
334 **{
335 "real/app/tests/test_foo.py": "def test1(fixture): pass",
336 "real/conftest.py": textwrap.dedent(
337 """
338 import pytest
339
340 print("conftest_loaded")
341
342 @pytest.fixture
343 def fixture():
344 print("fixture_used")
345 """
346 ),
347 }
348 )
349
350 # Should fail because conftest cannot be found from the link structure.
351 result = pytester.runpytest("-vs", "symlinktests")
352 result.stdout.fnmatch_lines(["*fixture 'fixture' not found*"])
353 assert result.ret == ExitCode.TESTS_FAILED
354
355 # Should not cause "ValueError: Plugin already registered" (#4174).
356 result = pytester.runpytest("-vs", "symlink")
357 assert result.ret == ExitCode.OK
358
359
360 def test_conftest_symlink_files(pytester: Pytester) -> None:
361 """Symlinked conftest.py are found when pytest is executed in a directory with symlinked
362 files."""
363 real = pytester.mkdir("real")
364 source = {
365 "app/test_foo.py": "def test1(fixture): pass",
366 "app/__init__.py": "",
367 "app/conftest.py": textwrap.dedent(
368 """
369 import pytest
370
371 print("conftest_loaded")
372
373 @pytest.fixture
374 def fixture():
375 print("fixture_used")
376 """
377 ),
378 }
379 pytester.makepyfile(**{f"real/{k}": v for k, v in source.items()})
380
381 # Create a build directory that contains symlinks to actual files
382 # but doesn't symlink actual directories.
383 build = pytester.mkdir("build")
384 build.joinpath("app").mkdir()
385 for f in source:
386 symlink_or_skip(real.joinpath(f), build.joinpath(f))
387 os.chdir(build)
388 result = pytester.runpytest("-vs", "app/test_foo.py")
389 result.stdout.fnmatch_lines(["*conftest_loaded*", "PASSED"])
390 assert result.ret == ExitCode.OK
391
392
393 @pytest.mark.skipif(
394 os.path.normcase("x") != os.path.normcase("X"),
395 reason="only relevant for case-insensitive file systems",
396 )
397 def test_conftest_badcase(pytester: Pytester) -> None:
398 """Check conftest.py loading when directory casing is wrong (#5792)."""
399 pytester.path.joinpath("JenkinsRoot/test").mkdir(parents=True)
400 source = {"setup.py": "", "test/__init__.py": "", "test/conftest.py": ""}
401 pytester.makepyfile(**{f"JenkinsRoot/{k}": v for k, v in source.items()})
402
403 os.chdir(pytester.path.joinpath("jenkinsroot/test"))
404 result = pytester.runpytest()
405 assert result.ret == ExitCode.NO_TESTS_COLLECTED
406
407
408 def test_conftest_uppercase(pytester: Pytester) -> None:
409 """Check conftest.py whose qualified name contains uppercase characters (#5819)"""
410 source = {"__init__.py": "", "Foo/conftest.py": "", "Foo/__init__.py": ""}
411 pytester.makepyfile(**source)
412
413 os.chdir(pytester.path)
414 result = pytester.runpytest()
415 assert result.ret == ExitCode.NO_TESTS_COLLECTED
416
417
418 def test_no_conftest(pytester: Pytester) -> None:
419 pytester.makeconftest("assert 0")
420 result = pytester.runpytest("--noconftest")
421 assert result.ret == ExitCode.NO_TESTS_COLLECTED
422
423 result = pytester.runpytest()
424 assert result.ret == ExitCode.USAGE_ERROR
425
426
427 def test_conftest_existing_junitxml(pytester: Pytester) -> None:
428 x = pytester.mkdir("tests")
429 x.joinpath("conftest.py").write_text(
430 textwrap.dedent(
431 """\
432 def pytest_addoption(parser):
433 parser.addoption("--xyz", action="store_true")
434 """
435 ),
436 encoding="utf-8",
437 )
438 pytester.makefile(ext=".xml", junit="") # Writes junit.xml
439 result = pytester.runpytest("-h", "--junitxml", "junit.xml")
440 result.stdout.fnmatch_lines(["*--xyz*"])
441
442
443 def test_conftests_in_invocation_dir_tests_is_initial(pytester: Pytester) -> None:
444 """An option registered in a conftest under ``test*`` subdir of the
445 invocation dir is loaded as initial when no command-line arguments
446 or `testpaths` are given (#14608).
447 """
448 pytester.makepyfile(
449 **{
450 "tests/conftest.py": """
451 def pytest_addoption(parser):
452 parser.addoption("--db-url")
453 """,
454 "test_it.py": """
455 def test_it(request):
456 assert request.config.getoption("--db-url") == "scheme://host/db"
457 """,
458 }
459 )
460 result = pytester.runpytest("--db-url", "scheme://host/db")
461 assert result.ret == ExitCode.OK
462 result.assert_outcomes(passed=1)
463
464
465 def test_conftest_import_order(pytester: Pytester, monkeypatch: MonkeyPatch) -> None:
466 ct1 = pytester.makeconftest("")
467 sub = pytester.mkdir("sub")
468 ct2 = sub / "conftest.py"
469 ct2.write_text("", encoding="utf-8")
470
471 def impct(p, importmode, root, consider_namespace_packages):
472 return p
473
474 conftest = PytestPluginManager()
475 conftest._confcutdir = pytester.path
476 monkeypatch.setattr(conftest, "_importconftest", impct)
477 conftest._loadconftestmodules(
478 sub,
479 importmode="prepend",
480 rootpath=pytester.path,
481 consider_namespace_packages=False,
482 )
483 mods = cast(list[Path], conftest._getconftestmodules(sub))
484 expected = [ct1, ct2]
485 assert mods == expected
486
487
488 def test_fixture_dependency(pytester: Pytester) -> None:
489 pytester.makeconftest("")
490 pytester.path.joinpath("__init__.py").touch()
491 sub = pytester.mkdir("sub")
492 sub.joinpath("__init__.py").touch()
493 sub.joinpath("conftest.py").write_text(
494 textwrap.dedent(
495 """\
496 import pytest
497
498 @pytest.fixture
499 def not_needed():
500 assert False, "Should not be called!"
501
502 @pytest.fixture
503 def foo():
504 assert False, "Should not be called!"
505
506 @pytest.fixture
507 def bar(foo):
508 return 'bar'
509 """
510 ),
511 encoding="utf-8",
512 )
513 subsub = sub.joinpath("subsub")
514 subsub.mkdir()
515 subsub.joinpath("__init__.py").touch()
516 subsub.joinpath("test_bar.py").write_text(
517 textwrap.dedent(
518 """\
519 import pytest
520
521 @pytest.fixture
522 def bar():
523 return 'sub bar'
524
525 def test_event_fixture(bar):
526 assert bar == 'sub bar'
527 """
528 ),
529 encoding="utf-8",
530 )
531 result = pytester.runpytest("sub")
532 result.stdout.fnmatch_lines(["*1 passed*"])
533
534
535 def test_conftest_found_with_double_dash(pytester: Pytester) -> None:
536 sub = pytester.mkdir("sub")
537 sub.joinpath("conftest.py").write_text(
538 textwrap.dedent(
539 """\
540 def pytest_addoption(parser):
541 parser.addoption("--hello-world", action="store_true")
542 """
543 ),
544 encoding="utf-8",
545 )
546 p = sub.joinpath("test_hello.py")
547 p.write_text("def test_hello(): pass", encoding="utf-8")
548 result = pytester.runpytest(str(p) + "::test_hello", "-h")
549 result.stdout.fnmatch_lines(
550 """
551 *--hello-world*
552 """
553 )
554
555
556 class TestConftestVisibility:
557 def _setup_tree(self, pytester: Pytester) -> dict[str, Path]: # for issue616
558 # example mostly taken from:
559 # https://mail.python.org/pipermail/pytest-dev/2014-September/002617.html
560 runner = pytester.mkdir("empty")
561 package = pytester.mkdir("package")
562
563 package.joinpath("conftest.py").write_text(
564 textwrap.dedent(
565 """\
566 import pytest
567 @pytest.fixture
568 def fxtr():
569 return "from-package"
570 """
571 ),
572 encoding="utf-8",
573 )
574 package.joinpath("test_pkgroot.py").write_text(
575 textwrap.dedent(
576 """\
577 def test_pkgroot(fxtr):
578 assert fxtr == "from-package"
579 """
580 ),
581 encoding="utf-8",
582 )
583
584 swc = package.joinpath("swc")
585 swc.mkdir()
586 swc.joinpath("__init__.py").touch()
587 swc.joinpath("conftest.py").write_text(
588 textwrap.dedent(
589 """\
590 import pytest
591 @pytest.fixture
592 def fxtr():
593 return "from-swc"
594 """
595 ),
596 encoding="utf-8",
597 )
598 swc.joinpath("test_with_conftest.py").write_text(
599 textwrap.dedent(
600 """\
601 def test_with_conftest(fxtr):
602 assert fxtr == "from-swc"
603 """
604 ),
605 encoding="utf-8",
606 )
607
608 snc = package.joinpath("snc")
609 snc.mkdir()
610 snc.joinpath("__init__.py").touch()
611 snc.joinpath("test_no_conftest.py").write_text(
612 textwrap.dedent(
613 """\
614 def test_no_conftest(fxtr):
615 assert fxtr == "from-package" # No local conftest.py, so should
616 # use value from parent dir's
617 """
618 ),
619 encoding="utf-8",
620 )
621 print("created directory structure:")
622 for x in pytester.path.glob("**/"):
623 print(" " + str(x.relative_to(pytester.path)))
624
625 return {"runner": runner, "package": package, "swc": swc, "snc": snc}
626
627 # N.B.: "swc" stands for "subdir with conftest.py"
628 # "snc" stands for "subdir no [i.e. without] conftest.py"
629 @pytest.mark.parametrize(
630 "chdir,testarg,expect_ntests_passed",
631 [
632 # Effective target: package/..
633 ("runner", "..", 3),
634 ("package", "..", 3),
635 ("swc", "../..", 3),
636 ("snc", "../..", 3),
637 # Effective target: package
638 ("runner", "../package", 3),
639 ("package", ".", 3),
640 ("swc", "..", 3),
641 ("snc", "..", 3),
642 # Effective target: package/swc
643 ("runner", "../package/swc", 1),
644 ("package", "./swc", 1),
645 ("swc", ".", 1),
646 ("snc", "../swc", 1),
647 # Effective target: package/snc
648 ("runner", "../package/snc", 1),
649 ("package", "./snc", 1),
650 ("swc", "../snc", 1),
651 ("snc", ".", 1),
652 ],
653 )
654 def test_parsefactories_relative_node_ids(
655 self, pytester: Pytester, chdir: str, testarg: str, expect_ntests_passed: int
656 ) -> None:
657 """#616"""
658 dirs = self._setup_tree(pytester)
659 print(f"pytest run in cwd: {dirs[chdir].relative_to(pytester.path)}")
660 print(f"pytestarg : {testarg}")
661 print(f"expected pass : {expect_ntests_passed}")
662 os.chdir(dirs[chdir])
663 reprec = pytester.inline_run(
664 testarg,
665 "-q",
666 "--traceconfig",
667 "--confcutdir",
668 pytester.path,
669 )
670 reprec.assertoutcome(passed=expect_ntests_passed)
671
672
673 @pytest.mark.parametrize(
674 "confcutdir,passed,error", [(".", 2, 0), ("src", 1, 1), (None, 1, 1)]
675 )
676 def test_search_conftest_up_to_inifile(
677 pytester: Pytester, confcutdir: str, passed: int, error: int
678 ) -> None:
679 """Test that conftest files are detected only up to a configuration file, unless
680 an explicit --confcutdir option is given.
681 """
682 root = pytester.path
683 src = root.joinpath("src")
684 src.mkdir()
685 src.joinpath("pytest.ini").write_text("[pytest]", encoding="utf-8")
686 src.joinpath("conftest.py").write_text(
687 textwrap.dedent(
688 """\
689 import pytest
690 @pytest.fixture
691 def fix1(): pass
692 """
693 ),
694 encoding="utf-8",
695 )
696 src.joinpath("test_foo.py").write_text(
697 textwrap.dedent(
698 """\
699 def test_1(fix1):
700 pass
701 def test_2(out_of_reach):
702 pass
703 """
704 ),
705 encoding="utf-8",
706 )
707 root.joinpath("conftest.py").write_text(
708 textwrap.dedent(
709 """\
710 import pytest
711 @pytest.fixture
712 def out_of_reach(): pass
713 """
714 ),
715 encoding="utf-8",
716 )
717
718 args = [str(src)]
719 if confcutdir:
720 args = [f"--confcutdir={root.joinpath(confcutdir)}"]
721 result = pytester.runpytest(*args)
722 match = ""
723 if passed:
724 match += f"*{passed} passed*"
725 if error:
726 match += f"*{error} error*"
727 result.stdout.fnmatch_lines(match)
728
729
730 def test_issue1073_conftest_special_objects(pytester: Pytester) -> None:
731 pytester.makeconftest(
732 """\
733 class DontTouchMe(object):
734 def __getattr__(self, x):
735 raise Exception('cant touch me')
736
737 x = DontTouchMe()
738 """
739 )
740 pytester.makepyfile(
741 """\
742 def test_some():
743 pass
744 """
745 )
746 res = pytester.runpytest()
747 assert res.ret == 0
748
749
750 def test_conftest_exception_handling(pytester: Pytester) -> None:
751 pytester.makeconftest(
752 """\
753 raise ValueError()
754 """
755 )
756 pytester.makepyfile(
757 """\
758 def test_some():
759 pass
760 """
761 )
762 res = pytester.runpytest()
763 assert res.ret == 4
764 assert "raise ValueError()" in [line.strip() for line in res.errlines]
765
766
767 def test_hook_proxy(pytester: Pytester) -> None:
768 """Session's gethookproxy() would cache conftests incorrectly (#2016).
769 It was decided to remove the cache altogether.
770 """
771 pytester.makepyfile(
772 **{
773 "root/demo-0/test_foo1.py": "def test1(): pass",
774 "root/demo-a/test_foo2.py": "def test1(): pass",
775 "root/demo-a/conftest.py": """\
776 def pytest_ignore_collect(collection_path, config):
777 return True
778 """,
779 "root/demo-b/test_foo3.py": "def test1(): pass",
780 "root/demo-c/test_foo4.py": "def test1(): pass",
781 }
782 )
783 result = pytester.runpytest()
784 result.stdout.fnmatch_lines(
785 ["*test_foo1.py*", "*test_foo3.py*", "*test_foo4.py*", "*3 passed*"]
786 )
787
788
789 def test_conftest_fixture_scoping_with_testpaths_outside_rootdir(
790 pytester: Pytester,
791 ) -> None:
792 """Regression test for #14004.
793
794 When testpaths points to a directory outside rootdir, conftest fixtures
795 from nested directories should not leak to sibling test directories.
796
797 Layout:
798 sdk/
799 pyproject.toml (rootdir, testpaths = ["../tests/sdk"])
800 tests/
801 sdk/
802 conftest.py (outer fixture)
803 test_outer.py
804 inner/
805 conftest.py (inner fixture - should NOT be visible in test_outer)
806 test_inner.py
807 """
808 root = pytester.path
809 sdk = root / "sdk"
810 sdk.mkdir()
811 sdk.joinpath("pyproject.toml").write_text(
812 textwrap.dedent("""\
813 [tool.pytest.ini_options]
814 testpaths = ["../tests/sdk"]
815 """),
816 encoding="utf-8",
817 )
818
819 tests_sdk = root / "tests" / "sdk"
820 tests_sdk.mkdir(parents=True)
821 tests_sdk.joinpath("conftest.py").write_text(
822 textwrap.dedent("""\
823 import pytest
824
825 @pytest.fixture(autouse=True)
826 def outer_fixture():
827 pass
828 """),
829 encoding="utf-8",
830 )
831 tests_sdk.joinpath("test_outer.py").write_text(
832 textwrap.dedent("""\
833 def test_outer(request):
834 fixturenames = request.fixturenames
835 assert "outer_fixture" in fixturenames
836 assert "inner_fixture" not in fixturenames
837 """),
838 encoding="utf-8",
839 )
840
841 inner = tests_sdk / "inner"
842 inner.mkdir()
843 inner.joinpath("conftest.py").write_text(
844 textwrap.dedent("""\
845 import pytest
846
847 @pytest.fixture(autouse=True)
848 def inner_fixture():
849 pass
850 """),
851 encoding="utf-8",
852 )
853 inner.joinpath("test_inner.py").write_text(
854 textwrap.dedent("""\
855 def test_inner(request):
856 fixturenames = request.fixturenames
857 assert "outer_fixture" in fixturenames
858 assert "inner_fixture" in fixturenames
859 """),
860 encoding="utf-8",
861 )
862
863 result = pytester.runpytest("--rootdir", str(sdk), "-v")
864 result.stdout.fnmatch_lines(
865 [
866 "*test_inner*PASSED*",
867 "*test_outer*PASSED*",
868 "*2 passed*",
869 ]
870 )
871
872
873 def test_conftest_fixture_from_ancestor_above_rootdir(
874 pytester: Pytester,
875 ) -> None:
876 """Conftests from ancestor directories above rootdir that are loaded as
877 initial conftests get Session (global) visibility.
878
879 Layout:
880 project/
881 conftest.py (defines ancestor_fixture)
882 sub/
883 pyproject.toml (rootdir)
884 test_it.py (should see ancestor_fixture)
885 """
886 root = pytester.path
887 root.joinpath("conftest.py").write_text(
888 textwrap.dedent("""\
889 import pytest
890
891 @pytest.fixture
892 def ancestor_fixture():
893 return "from-ancestor"
894 """),
895 encoding="utf-8",
896 )
897 sub = root / "sub"
898 sub.mkdir()
899 sub.joinpath("pyproject.toml").write_text(
900 "[tool.pytest.ini_options]\n", encoding="utf-8"
901 )
902 sub.joinpath("test_it.py").write_text(
903 textwrap.dedent("""\
904 def test_uses_ancestor(ancestor_fixture):
905 assert ancestor_fixture == "from-ancestor"
906 """),
907 encoding="utf-8",
908 )
909
910 result = pytester.runpytest("--rootdir", str(sub), "--confcutdir", str(root), "-v")
911 result.stdout.fnmatch_lines(["*test_uses_ancestor*PASSED*", "*1 passed*"])
912
913
914 def test_required_option_help(pytester: Pytester) -> None:
915 pytester.makeconftest("assert 0")
916 x = pytester.mkdir("x")
917 x.joinpath("conftest.py").write_text(
918 textwrap.dedent(
919 """\
920 def pytest_addoption(parser):
921 parser.addoption("--xyz", action="store_true", required=True)
922 """
923 ),
924 encoding="utf-8",
925 )
926 result = pytester.runpytest("-h", x)
927 result.stdout.no_fnmatch_line("*argument --xyz is required*")
928 assert "general:" in result.stdout.str()