Debian Codegraph @

testing/python/fixtures.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 from itertools import zip_longest
5 import os
6 from pathlib import Path
7 import sys
8 import textwrap
9
10 from _pytest.compat import getfuncargnames
11 from _pytest.config import ExitCode
12 from _pytest.fixtures import deduplicate_names
13 from _pytest.fixtures import TopRequest
14 from _pytest.monkeypatch import MonkeyPatch
15 from _pytest.pytester import get_public_names
16 from _pytest.pytester import Pytester
17 from _pytest.python import Function
18 import pytest
19
20
21 def test_getfuncargnames_functions():
22 """Test getfuncargnames for normal functions"""
23
24 def f():
25 raise NotImplementedError()
26
27 assert not getfuncargnames(f)
28
29 def g(arg):
30 raise NotImplementedError()
31
32 assert getfuncargnames(g) == ("arg",)
33
34 def h(arg1, arg2="hello"):
35 raise NotImplementedError()
36
37 assert getfuncargnames(h) == ("arg1",)
38
39 def j(arg1, arg2, arg3="hello"):
40 raise NotImplementedError()
41
42 assert getfuncargnames(j) == ("arg1", "arg2")
43
44
45 def test_getfuncargnames_methods():
46 """Test getfuncargnames for normal methods"""
47
48 class A:
49 def f(self, arg1, arg2="hello"):
50 raise NotImplementedError()
51
52 def g(self, /, arg1, arg2="hello"):
53 raise NotImplementedError()
54
55 def h(self, *, arg1, arg2="hello"):
56 raise NotImplementedError()
57
58 def j(self, arg1, *, arg2, arg3="hello"):
59 raise NotImplementedError()
60
61 def k(self, /, arg1, *, arg2, arg3="hello"):
62 raise NotImplementedError()
63
64 assert getfuncargnames(A().f) == ("arg1",)
65 assert getfuncargnames(A().g) == ("arg1",)
66 assert getfuncargnames(A().h) == ("arg1",)
67 assert getfuncargnames(A().j) == ("arg1", "arg2")
68 assert getfuncargnames(A().k) == ("arg1", "arg2")
69
70
71 def test_getfuncargnames_staticmethod():
72 """Test getfuncargnames for staticmethods"""
73
74 class A:
75 @staticmethod
76 def static(arg1, arg2, x=1):
77 raise NotImplementedError()
78
79 assert getfuncargnames(A.static, cls=A) == ("arg1", "arg2")
80
81
82 def test_getfuncargnames_staticmethod_inherited() -> None:
83 """Test getfuncargnames for inherited staticmethods (#8061)"""
84
85 class A:
86 @staticmethod
87 def static(arg1, arg2, x=1):
88 raise NotImplementedError()
89
90 class B(A):
91 pass
92
93 assert getfuncargnames(B.static, cls=B) == ("arg1", "arg2")
94
95
96 @pytest.mark.skipif(
97 sys.version_info >= (3, 13),
98 reason="""\
99 In python 3.13, this will raise FutureWarning:
100 functools.partial will be a method descriptor in future Python versions;
101 wrap it in staticmethod() if you want to preserve the old behavior
102
103 But the wrapped 'functools.partial' is tested by 'test_getfuncargnames_staticmethod_partial' below.
104 """,
105 )
106 def test_getfuncargnames_partial():
107 """Check getfuncargnames for methods defined with functools.partial (#5701)"""
108 import functools
109
110 def check(arg1, arg2, i):
111 raise NotImplementedError()
112
113 class T:
114 test_ok = functools.partial(check, i=2)
115
116 values = getfuncargnames(T().test_ok, name="test_ok")
117 assert values == ("arg1", "arg2")
118
119
120 def test_getfuncargnames_staticmethod_partial():
121 """Check getfuncargnames for staticmethods defined with functools.partial (#5701)"""
122 import functools
123
124 def check(arg1, arg2, i):
125 raise NotImplementedError()
126
127 class T:
128 test_ok = staticmethod(functools.partial(check, i=2))
129
130 values = getfuncargnames(T().test_ok, name="test_ok")
131 assert values == ("arg1", "arg2")
132
133
134 @pytest.mark.pytester_example_path("fixtures/fill_fixtures")
135 class TestFillFixtures:
136 def test_funcarg_lookupfails(self, pytester: Pytester) -> None:
137 pytester.copy_example()
138 result = pytester.runpytest() # "--collect-only")
139 assert result.ret != 0
140 result.stdout.fnmatch_lines(
141 """
142 *def test_func(some)*
143 *fixture*some*not found*
144 *xyzsomething*
145 """
146 )
147
148 def test_detect_recursive_dependency_error(self, pytester: Pytester) -> None:
149 pytester.copy_example()
150 result = pytester.runpytest()
151 result.stdout.fnmatch_lines(
152 ["*recursive dependency involving fixture 'fix1' detected*"]
153 )
154
155 def test_funcarg_basic(self, pytester: Pytester) -> None:
156 pytester.copy_example()
157 item = pytester.getitem(Path("test_funcarg_basic.py"))
158 assert isinstance(item, Function)
159 # Execute's item's setup, which fills fixtures.
160 item.session._setupstate.setup(item)
161 del item.funcargs["request"]
162 assert len(get_public_names(item.funcargs)) == 2
163 assert item.funcargs["some"] == "test_func"
164 assert item.funcargs["other"] == 42
165
166 def test_funcarg_lookup_modulelevel(self, pytester: Pytester) -> None:
167 pytester.copy_example()
168 reprec = pytester.inline_run()
169 reprec.assertoutcome(passed=2)
170
171 def test_funcarg_lookup_classlevel(self, pytester: Pytester) -> None:
172 p = pytester.copy_example()
173 result = pytester.runpytest(p)
174 result.stdout.fnmatch_lines(["*1 passed*"])
175
176 def test_conftest_funcargs_only_available_in_subdir(
177 self, pytester: Pytester
178 ) -> None:
179 pytester.copy_example()
180 result = pytester.runpytest("-v")
181 result.assert_outcomes(passed=2)
182
183 def test_extend_fixture_module_class(self, pytester: Pytester) -> None:
184 testfile = pytester.copy_example()
185 result = pytester.runpytest()
186 result.stdout.fnmatch_lines(["*1 passed*"])
187 result = pytester.runpytest(testfile)
188 result.stdout.fnmatch_lines(["*1 passed*"])
189
190 def test_extend_fixture_conftest_module(self, pytester: Pytester) -> None:
191 p = pytester.copy_example()
192 result = pytester.runpytest()
193 result.stdout.fnmatch_lines(["*1 passed*"])
194 result = pytester.runpytest(str(next(Path(str(p)).rglob("test_*.py"))))
195 result.stdout.fnmatch_lines(["*1 passed*"])
196
197 def test_extend_fixture_conftest_conftest(self, pytester: Pytester) -> None:
198 p = pytester.copy_example()
199 result = pytester.runpytest()
200 result.stdout.fnmatch_lines(["*1 passed*"])
201 result = pytester.runpytest(str(next(Path(str(p)).rglob("test_*.py"))))
202 result.stdout.fnmatch_lines(["*1 passed*"])
203
204 def test_extend_fixture_conftest_plugin(self, pytester: Pytester) -> None:
205 pytester.makepyfile(
206 testplugin="""
207 import pytest
208
209 @pytest.fixture
210 def foo():
211 return 7
212 """
213 )
214 pytester.syspathinsert()
215 pytester.makeconftest(
216 """
217 import pytest
218
219 pytest_plugins = 'testplugin'
220
221 @pytest.fixture
222 def foo(foo):
223 return foo + 7
224 """
225 )
226 pytester.makepyfile(
227 """
228 def test_foo(foo):
229 assert foo == 14
230 """
231 )
232 result = pytester.runpytest("-s")
233 assert result.ret == 0
234
235 def test_extend_fixture_plugin_plugin(self, pytester: Pytester) -> None:
236 # Two plugins should extend each order in loading order
237 pytester.makepyfile(
238 testplugin0="""
239 import pytest
240
241 @pytest.fixture
242 def foo():
243 return 7
244 """
245 )
246 pytester.makepyfile(
247 testplugin1="""
248 import pytest
249
250 @pytest.fixture
251 def foo(foo):
252 return foo + 7
253 """
254 )
255 pytester.syspathinsert()
256 pytester.makepyfile(
257 """
258 pytest_plugins = ['testplugin0', 'testplugin1']
259
260 def test_foo(foo):
261 assert foo == 14
262 """
263 )
264 result = pytester.runpytest()
265 assert result.ret == 0
266
267 def test_override_parametrized_fixture_conftest_module(
268 self, pytester: Pytester
269 ) -> None:
270 """Test override of the parametrized fixture with non-parametrized one on the test module level."""
271 pytester.makeconftest(
272 """
273 import pytest
274
275 @pytest.fixture(params=[1, 2, 3])
276 def spam(request):
277 return request.param
278 """
279 )
280 testfile = pytester.makepyfile(
281 """
282 import pytest
283
284 @pytest.fixture
285 def spam():
286 return 'spam'
287
288 def test_spam(spam):
289 assert spam == 'spam'
290 """
291 )
292 result = pytester.runpytest()
293 result.stdout.fnmatch_lines(["*1 passed*"])
294 result = pytester.runpytest(testfile)
295 result.stdout.fnmatch_lines(["*1 passed*"])
296
297 def test_override_parametrized_fixture_conftest_conftest(
298 self, pytester: Pytester
299 ) -> None:
300 """Test override of the parametrized fixture with non-parametrized one on the conftest level."""
301 pytester.makeconftest(
302 """
303 import pytest
304
305 @pytest.fixture(params=[1, 2, 3])
306 def spam(request):
307 return request.param
308 """
309 )
310 subdir = pytester.mkpydir("subdir")
311 subdir.joinpath("conftest.py").write_text(
312 textwrap.dedent(
313 """\
314 import pytest
315
316 @pytest.fixture
317 def spam():
318 return 'spam'
319 """
320 ),
321 encoding="utf-8",
322 )
323 testfile = subdir.joinpath("test_spam.py")
324 testfile.write_text(
325 textwrap.dedent(
326 """\
327 def test_spam(spam):
328 assert spam == "spam"
329 """
330 ),
331 encoding="utf-8",
332 )
333 result = pytester.runpytest()
334 result.stdout.fnmatch_lines(["*1 passed*"])
335 result = pytester.runpytest(testfile)
336 result.stdout.fnmatch_lines(["*1 passed*"])
337
338 def test_override_non_parametrized_fixture_conftest_module(
339 self, pytester: Pytester
340 ) -> None:
341 """Test override of the non-parametrized fixture with parametrized one on the test module level."""
342 pytester.makeconftest(
343 """
344 import pytest
345
346 @pytest.fixture
347 def spam():
348 return 'spam'
349 """
350 )
351 testfile = pytester.makepyfile(
352 """
353 import pytest
354
355 @pytest.fixture(params=[1, 2, 3])
356 def spam(request):
357 return request.param
358
359 params = {'spam': 1}
360
361 def test_spam(spam):
362 assert spam == params['spam']
363 params['spam'] += 1
364 """
365 )
366 result = pytester.runpytest()
367 result.stdout.fnmatch_lines(["*3 passed*"])
368 result = pytester.runpytest(testfile)
369 result.stdout.fnmatch_lines(["*3 passed*"])
370
371 def test_override_non_parametrized_fixture_conftest_conftest(
372 self, pytester: Pytester
373 ) -> None:
374 """Test override of the non-parametrized fixture with parametrized one on the conftest level."""
375 pytester.makeconftest(
376 """
377 import pytest
378
379 @pytest.fixture
380 def spam():
381 return 'spam'
382 """
383 )
384 subdir = pytester.mkpydir("subdir")
385 subdir.joinpath("conftest.py").write_text(
386 textwrap.dedent(
387 """\
388 import pytest
389
390 @pytest.fixture(params=[1, 2, 3])
391 def spam(request):
392 return request.param
393 """
394 ),
395 encoding="utf-8",
396 )
397 testfile = subdir.joinpath("test_spam.py")
398 testfile.write_text(
399 textwrap.dedent(
400 """\
401 params = {'spam': 1}
402
403 def test_spam(spam):
404 assert spam == params['spam']
405 params['spam'] += 1
406 """
407 ),
408 encoding="utf-8",
409 )
410 result = pytester.runpytest()
411 result.stdout.fnmatch_lines(["*3 passed*"])
412 result = pytester.runpytest(testfile)
413 result.stdout.fnmatch_lines(["*3 passed*"])
414
415 def test_override_autouse_fixture_with_parametrized_fixture_conftest_conftest(
416 self, pytester: Pytester
417 ) -> None:
418 """Test override of the autouse fixture with parametrized one on the conftest level.
419 This test covers the issue explained in issue 1601
420 """
421 pytester.makeconftest(
422 """
423 import pytest
424
425 @pytest.fixture(autouse=True)
426 def spam():
427 return 'spam'
428 """
429 )
430 subdir = pytester.mkpydir("subdir")
431 subdir.joinpath("conftest.py").write_text(
432 textwrap.dedent(
433 """\
434 import pytest
435
436 @pytest.fixture(params=[1, 2, 3])
437 def spam(request):
438 return request.param
439 """
440 ),
441 encoding="utf-8",
442 )
443 testfile = subdir.joinpath("test_spam.py")
444 testfile.write_text(
445 textwrap.dedent(
446 """\
447 params = {'spam': 1}
448
449 def test_spam(spam):
450 assert spam == params['spam']
451 params['spam'] += 1
452 """
453 ),
454 encoding="utf-8",
455 )
456 result = pytester.runpytest()
457 result.stdout.fnmatch_lines(["*3 passed*"])
458 result = pytester.runpytest(testfile)
459 result.stdout.fnmatch_lines(["*3 passed*"])
460
461 def test_override_fixture_reusing_super_fixture_parametrization(
462 self, pytester: Pytester
463 ) -> None:
464 """Override a fixture at a lower level, reusing the higher-level fixture that
465 is parametrized (#1953).
466 """
467 pytester.makeconftest(
468 """
469 import pytest
470
471 @pytest.fixture(params=[1, 2])
472 def foo(request):
473 return request.param
474 """
475 )
476 pytester.makepyfile(
477 """
478 import pytest
479
480 @pytest.fixture
481 def foo(foo):
482 return foo * 2
483
484 def test_spam(foo):
485 assert foo in (2, 4)
486 """
487 )
488 result = pytester.runpytest()
489 result.stdout.fnmatch_lines(["*2 passed*"])
490
491 def test_override_parametrize_fixture_and_indirect(
492 self, pytester: Pytester
493 ) -> None:
494 """Override a fixture at a lower level, reusing the higher-level fixture that
495 is parametrized, while also using indirect parametrization.
496 """
497 pytester.makeconftest(
498 """
499 import pytest
500
501 @pytest.fixture(params=[1, 2])
502 def foo(request):
503 return request.param
504 """
505 )
506 pytester.makepyfile(
507 """
508 import pytest
509
510 @pytest.fixture
511 def foo(foo):
512 return foo * 2
513
514 @pytest.fixture
515 def bar(request):
516 return request.param * 100
517
518 @pytest.mark.parametrize("bar", [42], indirect=True)
519 def test_spam(bar, foo):
520 assert bar == 4200
521 assert foo in (2, 4)
522 """
523 )
524 result = pytester.runpytest()
525 result.stdout.fnmatch_lines(["*2 passed*"])
526
527 def test_override_top_level_fixture_reusing_super_fixture_parametrization(
528 self, pytester: Pytester
529 ) -> None:
530 """Same as the above test, but with another level of overwriting."""
531 pytester.makeconftest(
532 """
533 import pytest
534
535 @pytest.fixture(params=['unused', 'unused'])
536 def foo(request):
537 return request.param
538 """
539 )
540 pytester.makepyfile(
541 """
542 import pytest
543
544 @pytest.fixture(params=[1, 2])
545 def foo(request):
546 return request.param
547
548 class Test:
549
550 @pytest.fixture
551 def foo(self, foo):
552 return foo * 2
553
554 def test_spam(self, foo):
555 assert foo in (2, 4)
556 """
557 )
558 result = pytester.runpytest()
559 result.stdout.fnmatch_lines(["*2 passed*"])
560
561 def test_override_parametrized_fixture_with_new_parametrized_fixture(
562 self, pytester: Pytester
563 ) -> None:
564 """Overriding a parametrized fixture, while also parametrizing the new fixture and
565 simultaneously requesting the overwritten fixture as parameter, yields the same value
566 as ``request.param``.
567 """
568 pytester.makeconftest(
569 """
570 import pytest
571
572 @pytest.fixture(params=['ignored', 'ignored'])
573 def foo(request):
574 return request.param
575 """
576 )
577 pytester.makepyfile(
578 """
579 import pytest
580
581 @pytest.fixture(params=[10, 20])
582 def foo(foo, request):
583 assert request.param == foo
584 return foo * 2
585
586 def test_spam(foo):
587 assert foo in (20, 40)
588 """
589 )
590 result = pytester.runpytest()
591 result.stdout.fnmatch_lines(["*2 passed*"])
592
593 @pytest.mark.xfail(reason="not handled currently")
594 def test_override_parametrized_fixture_via_transitive_fixture(
595 self, pytester: Pytester
596 ) -> None:
597 """Test that overriding a parametrized fixture works even the super
598 fixture is requested only transitively.
599
600 Regression test for #7737.
601 """
602 pytester.makepyfile(
603 """
604 import pytest
605
606 @pytest.fixture(params=[1, 2])
607 def foo(request):
608 return request.param
609
610 @pytest.fixture
611 def bar(foo):
612 return foo
613
614 class TestIt:
615 @pytest.fixture
616 def foo(self, bar):
617 return bar * 2
618
619 def test_it(self, foo):
620 pass
621 """
622 )
623 result = pytester.runpytest()
624 assert result.ret == ExitCode.OK
625 result.assert_outcomes(passed=2)
626
627 def test_autouse_fixture_plugin(self, pytester: Pytester) -> None:
628 # A fixture from a plugin has no baseid set, which screwed up
629 # the autouse fixture handling.
630 pytester.makepyfile(
631 testplugin="""
632 import pytest
633
634 @pytest.fixture(autouse=True)
635 def foo(request):
636 request.function.foo = 7
637 """
638 )
639 pytester.syspathinsert()
640 pytester.makepyfile(
641 """
642 pytest_plugins = 'testplugin'
643
644 def test_foo(request):
645 assert request.function.foo == 7
646 """
647 )
648 result = pytester.runpytest()
649 assert result.ret == 0
650
651 def test_funcarg_lookup_error(self, pytester: Pytester) -> None:
652 pytester.makeconftest(
653 """
654 import pytest
655
656 @pytest.fixture
657 def a_fixture(): pass
658
659 @pytest.fixture
660 def b_fixture(): pass
661
662 @pytest.fixture
663 def c_fixture(): pass
664
665 @pytest.fixture
666 def d_fixture(): pass
667 """
668 )
669 pytester.makepyfile(
670 """
671 def test_lookup_error(unknown):
672 pass
673 """
674 )
675 result = pytester.runpytest()
676 result.stdout.fnmatch_lines(
677 [
678 "*ERROR at setup of test_lookup_error*",
679 " def test_lookup_error(unknown):*",
680 "E fixture 'unknown' not found",
681 "> available fixtures:*a_fixture,*b_fixture,*c_fixture,*d_fixture*monkeypatch,*",
682 # sorted
683 "> use 'py*test --fixtures *' for help on them.",
684 "*1 error*",
685 ]
686 )
687 result.stdout.no_fnmatch_line("*INTERNAL*")
688
689 def test_fixture_excinfo_leak(self, pytester: Pytester) -> None:
690 # on python2 sys.excinfo would leak into fixture executions
691 pytester.makepyfile(
692 """
693 import sys
694 import traceback
695 import pytest
696
697 @pytest.fixture
698 def leak():
699 if sys.exc_info()[0]: # python3 bug :)
700 traceback.print_exc()
701 #fails
702 assert sys.exc_info() == (None, None, None)
703
704 def test_leak(leak):
705 if sys.exc_info()[0]: # python3 bug :)
706 traceback.print_exc()
707 assert sys.exc_info() == (None, None, None)
708 """
709 )
710 result = pytester.runpytest()
711 assert result.ret == 0
712
713
714 class TestRequestBasic:
715 def test_request_attributes(self, pytester: Pytester) -> None:
716 item = pytester.getitem(
717 """
718 import pytest
719
720 @pytest.fixture
721 def something(request): pass
722 def test_func(something): pass
723 """
724 )
725 assert isinstance(item, Function)
726 req = TopRequest(item, _ispytest=True)
727 assert req.function == item.obj
728 assert req.keywords == item.keywords
729 assert hasattr(req.module, "test_func")
730 assert req.cls is None
731 assert req.function.__name__ == "test_func"
732 assert req.config == item.config
733 assert repr(req).find(req.function.__name__) != -1
734
735 def test_request_attributes_method(self, pytester: Pytester) -> None:
736 (item,) = pytester.getitems(
737 """
738 import pytest
739 class TestB(object):
740
741 @pytest.fixture
742 def something(self, request):
743 return 1
744 def test_func(self, something):
745 pass
746 """
747 )
748 assert isinstance(item, Function)
749 req = item._request
750 assert req.cls.__name__ == "TestB"
751 assert req.instance.__class__ == req.cls
752
753 def test_request_contains_funcarg_arg2fixturedefs(self, pytester: Pytester) -> None:
754 modcol = pytester.getmodulecol(
755 """
756 import pytest
757 @pytest.fixture
758 def something(request):
759 pass
760 class TestClass(object):
761 def test_method(self, something):
762 pass
763 """
764 )
765 (item1,) = pytester.genitems([modcol])
766 assert isinstance(item1, Function)
767 assert item1.name == "test_method"
768 arg2fixturedefs = TopRequest(item1, _ispytest=True)._arg2fixturedefs
769 assert len(arg2fixturedefs) == 1
770 assert arg2fixturedefs["something"][0].argname == "something"
771
772 @pytest.mark.skipif(
773 hasattr(sys, "pypy_version_info"),
774 reason="this method of test doesn't work on pypy",
775 )
776 def test_request_garbage(self, pytester: Pytester) -> None:
777 try:
778 import xdist # noqa: F401
779 except ImportError:
780 pass
781 else:
782 pytest.xfail("this test is flaky when executed with xdist")
783 pytester.makepyfile(
784 """
785 import sys
786 import pytest
787 from _pytest.fixtures import RequestFixtureDef
788 import gc
789
790 @pytest.fixture(autouse=True)
791 def something(request):
792 original = gc.get_debug()
793 gc.set_debug(gc.DEBUG_SAVEALL)
794 gc.collect()
795
796 yield
797
798 try:
799 gc.collect()
800 leaked = [x for _ in gc.garbage if isinstance(_, RequestFixtureDef)]
801 assert leaked == []
802 finally:
803 gc.set_debug(original)
804
805 def test_func():
806 pass
807 """
808 )
809 result = pytester.runpytest_subprocess()
810 result.stdout.fnmatch_lines(["* 1 passed in *"])
811
812 def test_getfixturevalue_recursive(self, pytester: Pytester) -> None:
813 pytester.makeconftest(
814 """
815 import pytest
816
817 @pytest.fixture
818 def something(request):
819 return 1
820 """
821 )
822 pytester.makepyfile(
823 """
824 import pytest
825
826 @pytest.fixture
827 def something(request):
828 return request.getfixturevalue("something") + 1
829 def test_func(something):
830 assert something == 2
831 """
832 )
833 reprec = pytester.inline_run()
834 reprec.assertoutcome(passed=1)
835
836 def test_getfixturevalue_teardown(self, pytester: Pytester) -> None:
837 """
838 Issue #1895
839
840 `test_inner` requests `inner` fixture, which in turn requests `resource`
841 using `getfixturevalue`. `test_func` then requests `resource`.
842
843 `resource` is teardown before `inner` because the fixture mechanism won't consider
844 `inner` dependent on `resource` when it is used via `getfixturevalue`: `test_func`
845 will then cause the `resource`'s finalizer to be called first because of this.
846 """
847 pytester.makepyfile(
848 """
849 import pytest
850
851 @pytest.fixture(scope='session')
852 def resource():
853 r = ['value']
854 yield r
855 r.pop()
856
857 @pytest.fixture(scope='session')
858 def inner(request):
859 resource = request.getfixturevalue('resource')
860 assert resource == ['value']
861 yield
862 assert resource == ['value']
863
864 def test_inner(inner):
865 pass
866
867 def test_func(resource):
868 pass
869 """
870 )
871 result = pytester.runpytest()
872 result.stdout.fnmatch_lines(["* 2 passed in *"])
873
874 def test_getfixturevalue_teardown_previously_requested_does_not_warn(
875 self, pytester: Pytester
876 ) -> None:
877 """Test that requesting a fixture during teardown that was previously
878 requested is OK (#12882).
879
880 Note: this is still kinda dubious so don't let this test lock you in to
881 allowing this behavior forever...
882 """
883 pytester.makepyfile(
884 """
885 import pytest
886
887 @pytest.fixture
888 def fix(request, tmp_path):
889 yield
890 assert request.getfixturevalue("tmp_path") == tmp_path
891
892 def test_it(fix):
893 pass
894 """
895 )
896 result = pytester.runpytest("-Werror")
897 result.assert_outcomes(passed=1)
898
899 def test_getfixturevalue_teardown_new_fixture_deprecated(
900 self, pytester: Pytester
901 ) -> None:
902 """Test that requesting a fixture during teardown that was not
903 previously requested raises a deprecation warning (#12882).
904
905 Note: this is a case that previously worked but will become a hard
906 error after the deprecation is completed.
907 """
908 pytester.makepyfile(
909 """
910 import pytest
911
912 @pytest.fixture(scope="session")
913 def resource():
914 return "value"
915
916 @pytest.fixture
917 def fix(request):
918 yield
919 with pytest.warns(
920 pytest.PytestRemovedIn10Warning,
921 match=r'Calling request\\.getfixturevalue\\("resource"\\) during teardown is deprecated',
922 ):
923 assert request.getfixturevalue("resource") == "value"
924
925 def test_it(fix):
926 pass
927 """
928 )
929 result = pytester.runpytest()
930 result.assert_outcomes(passed=1)
931
932 def test_getfixturevalue_teardown_new_inactive_fixture_errors(
933 self, pytester: Pytester
934 ) -> None:
935 """Test that requesting a fixture during teardown that was not
936 previously requested raises an error (#12882)."""
937 pytester.makepyfile(
938 """
939 import pytest
940
941 @pytest.fixture
942 def fix(request):
943 yield
944 request.getfixturevalue("tmp_path")
945
946 def test_it(fix):
947 pass
948 """
949 )
950 result = pytester.runpytest()
951 result.assert_outcomes(passed=1, errors=1)
952 result.stdout.fnmatch_lines(
953 [
954 (
955 '*The fixture value for "tmp_path" is not available during '
956 "teardown because it was not previously requested.*"
957 ),
958 ]
959 )
960
961 def test_getfixturevalue_teardown_new_inactive_fixture_errors_top_request(
962 self, pytester: Pytester
963 ) -> None:
964 """Test that requesting a fixture during teardown that was not
965 previously requested raises an error (tricky case) (#12882)."""
966 pytester.makepyfile(
967 """
968 def test_it(request):
969 request.addfinalizer(lambda: request.getfixturevalue("tmp_path"))
970 """
971 )
972 result = pytester.runpytest()
973 result.assert_outcomes(passed=1, errors=1)
974 result.stdout.fnmatch_lines(
975 [
976 (
977 '*The fixture value for "tmp_path" is not available during '
978 "teardown because it was not previously requested.*"
979 ),
980 ]
981 )
982
983 def test_getfixturevalue(self, pytester: Pytester) -> None:
984 item = pytester.getitem(
985 """
986 import pytest
987
988 @pytest.fixture
989 def something(request):
990 return 1
991
992 values = [2]
993 @pytest.fixture
994 def other(request):
995 return values.pop()
996
997 def test_func(something): pass
998 """
999 )
1000 assert isinstance(item, Function)
1001 req = item._request
1002
1003 # Execute item's setup.
1004 item.session._setupstate.setup(item)
1005
1006 with pytest.raises(pytest.FixtureLookupError):
1007 req.getfixturevalue("notexists")
1008 val = req.getfixturevalue("something")
1009 assert val == 1
1010 val = req.getfixturevalue("something")
1011 assert val == 1
1012 val2 = req.getfixturevalue("other")
1013 assert val2 == 2
1014 val2 = req.getfixturevalue("other") # see about caching
1015 assert val2 == 2
1016 assert item.funcargs["something"] == 1
1017 assert len(get_public_names(item.funcargs)) == 2
1018 assert "request" in item.funcargs
1019
1020 def test_request_addfinalizer(self, pytester: Pytester) -> None:
1021 item = pytester.getitem(
1022 """
1023 import pytest
1024 teardownlist = []
1025 @pytest.fixture
1026 def something(request):
1027 request.addfinalizer(lambda: teardownlist.append(1))
1028 def test_func(something): pass
1029 """
1030 )
1031 assert isinstance(item, Function)
1032 item.session._setupstate.setup(item)
1033 item._request._fillfixtures()
1034 # successively check finalization calls
1035 parent = item.getparent(pytest.Module)
1036 assert parent is not None
1037 teardownlist = parent.obj.teardownlist
1038 ss = item.session._setupstate
1039 assert not teardownlist
1040 ss.teardown_exact(None)
1041 print(ss.stack)
1042 assert teardownlist == [1]
1043
1044 def test_request_addfinalizer_failing_setup(self, pytester: Pytester) -> None:
1045 pytester.makepyfile(
1046 """
1047 import pytest
1048 values = [1]
1049 @pytest.fixture
1050 def myfix(request):
1051 request.addfinalizer(values.pop)
1052 assert 0
1053 def test_fix(myfix):
1054 pass
1055 def test_finalizer_ran():
1056 assert not values
1057 """
1058 )
1059 reprec = pytester.inline_run("-s")
1060 reprec.assertoutcome(failed=1, passed=1)
1061
1062 def test_request_addfinalizer_failing_setup_module(
1063 self, pytester: Pytester
1064 ) -> None:
1065 pytester.makepyfile(
1066 """
1067 import pytest
1068 values = [1, 2]
1069 @pytest.fixture(scope="module")
1070 def myfix(request):
1071 request.addfinalizer(values.pop)
1072 request.addfinalizer(values.pop)
1073 assert 0
1074 def test_fix(myfix):
1075 pass
1076 """
1077 )
1078 reprec = pytester.inline_run("-s")
1079 mod = reprec.getcalls("pytest_runtest_setup")[0].item.module
1080 assert not mod.values
1081
1082 def test_request_addfinalizer_partial_setup_failure(
1083 self, pytester: Pytester
1084 ) -> None:
1085 p = pytester.makepyfile(
1086 """
1087 import pytest
1088 values = []
1089 @pytest.fixture
1090 def something(request):
1091 request.addfinalizer(lambda: values.append(None))
1092 def test_func(something, missingarg):
1093 pass
1094 def test_second():
1095 assert len(values) == 1
1096 """
1097 )
1098 result = pytester.runpytest(p)
1099 result.stdout.fnmatch_lines(
1100 ["*1 error*"] # XXX the whole module collection fails
1101 )
1102
1103 def test_request_subrequest_addfinalizer_exceptions(
1104 self, pytester: Pytester
1105 ) -> None:
1106 """
1107 Ensure exceptions raised during teardown by finalizers are suppressed
1108 until all finalizers are called, then re-raised together in an
1109 exception group (#2440)
1110 """
1111 pytester.makepyfile(
1112 """
1113 import pytest
1114 values = []
1115 def _excepts(where):
1116 raise Exception('Error in %s fixture' % where)
1117 @pytest.fixture
1118 def subrequest(request):
1119 return request
1120 @pytest.fixture
1121 def something(subrequest):
1122 subrequest.addfinalizer(lambda: values.append(1))
1123 subrequest.addfinalizer(lambda: values.append(2))
1124 subrequest.addfinalizer(lambda: _excepts('something'))
1125 @pytest.fixture
1126 def excepts(subrequest):
1127 subrequest.addfinalizer(lambda: _excepts('excepts'))
1128 subrequest.addfinalizer(lambda: values.append(3))
1129 def test_first(something, excepts):
1130 pass
1131 def test_second():
1132 assert values == [3, 2, 1]
1133 """
1134 )
1135 result = pytester.runpytest()
1136 result.assert_outcomes(passed=2, errors=1)
1137 result.stdout.fnmatch_lines(
1138 [
1139 ' | *ExceptionGroup: errors while tearing down fixture "subrequest" of <Function test_first> (2 sub-exceptions)', # noqa: E501
1140 " +-+---------------- 1 ----------------",
1141 " | Exception: Error in something fixture",
1142 " +---------------- 2 ----------------",
1143 " | Exception: Error in excepts fixture",
1144 " +------------------------------------",
1145 ],
1146 )
1147
1148 def test_request_getmodulepath(self, pytester: Pytester) -> None:
1149 modcol = pytester.getmodulecol("def test_somefunc(): pass")
1150 (item,) = pytester.genitems([modcol])
1151 assert isinstance(item, Function)
1152 req = TopRequest(item, _ispytest=True)
1153 assert req.path == modcol.path
1154
1155 def test_request_fixturenames(self, pytester: Pytester) -> None:
1156 pytester.makepyfile(
1157 """
1158 import pytest
1159 from _pytest.pytester import get_public_names
1160 @pytest.fixture()
1161 def arg1():
1162 pass
1163 @pytest.fixture()
1164 def farg(arg1):
1165 pass
1166 @pytest.fixture(autouse=True)
1167 def sarg(tmp_path):
1168 pass
1169 def test_function(request, farg):
1170 assert set(get_public_names(request.fixturenames)) == \
1171 set(["sarg", "arg1", "request", "farg",
1172 "tmp_path", "tmp_path_factory"])
1173 """
1174 )
1175 reprec = pytester.inline_run()
1176 reprec.assertoutcome(passed=1)
1177
1178 def test_request_fixturenames_dynamic_fixture(self, pytester: Pytester) -> None:
1179 """Regression test for #3057"""
1180 pytester.copy_example("fixtures/test_getfixturevalue_dynamic.py")
1181 result = pytester.runpytest("-vv")
1182 result.stdout.fnmatch_lines(["*1 passed*"])
1183
1184 def test_setupdecorator_and_xunit(self, pytester: Pytester) -> None:
1185 pytester.makepyfile(
1186 """
1187 import pytest
1188
1189 values = []
1190
1191 @pytest.fixture(scope='module', autouse=True)
1192 def setup_module():
1193 values.append("module")
1194
1195 @pytest.fixture(autouse=True)
1196 def setup_function():
1197 values.append("function")
1198
1199 def test_func():
1200 pass
1201
1202 class TestClass:
1203 @pytest.fixture(scope="class", autouse=True)
1204 @classmethod
1205 def setup_class(cls):
1206 values.append("class")
1207
1208 @pytest.fixture(autouse=True)
1209 def setup_method(self):
1210 values.append("method")
1211
1212 def test_method(self):
1213 pass
1214
1215 def test_all():
1216 assert values == [
1217 "module",
1218 "function",
1219 "class",
1220 "function",
1221 "method",
1222 "function",
1223 ]
1224 """
1225 )
1226 reprec = pytester.inline_run("-v")
1227 reprec.assertoutcome(passed=3)
1228
1229 def test_fixtures_sub_subdir_normalize_sep(self, pytester: Pytester) -> None:
1230 # this tests that normalization of nodeids takes place
1231 b = pytester.path.joinpath("tests", "unit")
1232 b.mkdir(parents=True)
1233 b.joinpath("conftest.py").write_text(
1234 textwrap.dedent(
1235 """\
1236 import pytest
1237 @pytest.fixture
1238 def arg1():
1239 pass
1240 """
1241 ),
1242 encoding="utf-8",
1243 )
1244 p = b.joinpath("test_module.py")
1245 p.write_text("def test_func(arg1): pass", encoding="utf-8")
1246 result = pytester.runpytest(p, "--fixtures")
1247 assert result.ret == 0
1248 result.stdout.fnmatch_lines(
1249 """
1250 *fixtures defined*conftest*
1251 *arg1*
1252 """
1253 )
1254
1255 def test_show_fixtures_color_yes(self, pytester: Pytester) -> None:
1256 pytester.makepyfile("def test_this(): assert 1")
1257 result = pytester.runpytest("--color=yes", "--fixtures")
1258 assert "\x1b[32mtmp_path" in result.stdout.str()
1259
1260 def test_newstyle_with_request(self, pytester: Pytester) -> None:
1261 pytester.makepyfile(
1262 """
1263 import pytest
1264 @pytest.fixture()
1265 def arg(request):
1266 pass
1267 def test_1(arg):
1268 pass
1269 """
1270 )
1271 reprec = pytester.inline_run()
1272 reprec.assertoutcome(passed=1)
1273
1274 def test_setupcontext_no_param(self, pytester: Pytester) -> None:
1275 pytester.makepyfile(
1276 """
1277 import pytest
1278 @pytest.fixture(params=[1,2])
1279 def arg(request):
1280 return request.param
1281
1282 @pytest.fixture(autouse=True)
1283 def mysetup(request, arg):
1284 assert not hasattr(request, "param")
1285 def test_1(arg):
1286 assert arg in (1,2)
1287 """
1288 )
1289 reprec = pytester.inline_run()
1290 reprec.assertoutcome(passed=2)
1291
1292
1293 class TestRequestSessionScoped:
1294 @pytest.fixture(scope="session")
1295 def session_request(self, request):
1296 return request
1297
1298 @pytest.mark.parametrize("name", ["path", "module"])
1299 def test_session_scoped_unavailable_attributes(self, session_request, name):
1300 with pytest.raises(
1301 AttributeError,
1302 match=f"{name} not available in session-scoped context",
1303 ):
1304 getattr(session_request, name)
1305
1306
1307 class TestRequestMarking:
1308 def test_applymarker(self, pytester: Pytester) -> None:
1309 item1, _item2 = pytester.getitems(
1310 """
1311 import pytest
1312
1313 @pytest.fixture
1314 def something(request):
1315 pass
1316 class TestClass(object):
1317 def test_func1(self, something):
1318 pass
1319 def test_func2(self, something):
1320 pass
1321 """
1322 )
1323 assert isinstance(item1, Function)
1324 req1 = TopRequest(item1, _ispytest=True)
1325 assert "xfail" not in item1.keywords
1326 req1.applymarker(pytest.mark.xfail)
1327 assert "xfail" in item1.keywords
1328 assert "skipif" not in item1.keywords
1329 req1.applymarker(pytest.mark.skipif)
1330 assert "skipif" in item1.keywords
1331 with pytest.raises(ValueError):
1332 req1.applymarker(42) # type: ignore[arg-type]
1333
1334 def test_accesskeywords(self, pytester: Pytester) -> None:
1335 pytester.makepyfile(
1336 """
1337 import pytest
1338 @pytest.fixture()
1339 def keywords(request):
1340 return request.keywords
1341 @pytest.mark.XYZ
1342 def test_function(keywords):
1343 assert keywords["XYZ"]
1344 assert "abc" not in keywords
1345 """
1346 )
1347 reprec = pytester.inline_run()
1348 reprec.assertoutcome(passed=1)
1349
1350 def test_accessmarker_dynamic(self, pytester: Pytester) -> None:
1351 pytester.makeconftest(
1352 """
1353 import pytest
1354 @pytest.fixture()
1355 def keywords(request):
1356 return request.keywords
1357
1358 @pytest.fixture(scope="class", autouse=True)
1359 def marking(request):
1360 request.applymarker(pytest.mark.XYZ("hello"))
1361 """
1362 )
1363 pytester.makepyfile(
1364 """
1365 import pytest
1366 def test_fun1(keywords):
1367 assert keywords["XYZ"] is not None
1368 assert "abc" not in keywords
1369 def test_fun2(keywords):
1370 assert keywords["XYZ"] is not None
1371 assert "abc" not in keywords
1372 """
1373 )
1374 reprec = pytester.inline_run()
1375 reprec.assertoutcome(passed=2)
1376
1377
1378 class TestFixtureUsages:
1379 def test_noargfixturedec(self, pytester: Pytester) -> None:
1380 pytester.makepyfile(
1381 """
1382 import pytest
1383 @pytest.fixture
1384 def arg1():
1385 return 1
1386
1387 def test_func(arg1):
1388 assert arg1 == 1
1389 """
1390 )
1391 reprec = pytester.inline_run()
1392 reprec.assertoutcome(passed=1)
1393
1394 def test_receives_funcargs(self, pytester: Pytester) -> None:
1395 pytester.makepyfile(
1396 """
1397 import pytest
1398 @pytest.fixture()
1399 def arg1():
1400 return 1
1401
1402 @pytest.fixture()
1403 def arg2(arg1):
1404 return arg1 + 1
1405
1406 def test_add(arg2):
1407 assert arg2 == 2
1408 def test_all(arg1, arg2):
1409 assert arg1 == 1
1410 assert arg2 == 2
1411 """
1412 )
1413 reprec = pytester.inline_run()
1414 reprec.assertoutcome(passed=2)
1415
1416 def test_receives_funcargs_scope_mismatch(self, pytester: Pytester) -> None:
1417 pytester.makepyfile(
1418 """
1419 import pytest
1420 @pytest.fixture(scope="function")
1421 def arg1():
1422 return 1
1423
1424 @pytest.fixture(scope="module")
1425 def arg2(arg1):
1426 return arg1 + 1
1427
1428 def test_add(arg2):
1429 assert arg2 == 2
1430 """
1431 )
1432 result = pytester.runpytest()
1433 result.stdout.fnmatch_lines(
1434 [
1435 "*ScopeMismatch*Requesting fixture stack*",
1436 "test_receives_funcargs_scope_mismatch.py:6: def arg2(arg1)",
1437 "Requested fixture:",
1438 "test_receives_funcargs_scope_mismatch.py:2: def arg1()",
1439 "*1 error*",
1440 ]
1441 )
1442
1443 def test_receives_funcargs_scope_mismatch_issue660(
1444 self, pytester: Pytester
1445 ) -> None:
1446 pytester.makepyfile(
1447 """
1448 import pytest
1449 @pytest.fixture(scope="function")
1450 def arg1():
1451 return 1
1452
1453 @pytest.fixture(scope="module")
1454 def arg2(arg1):
1455 return arg1 + 1
1456
1457 def test_add(arg1, arg2):
1458 assert arg2 == 2
1459 """
1460 )
1461 result = pytester.runpytest()
1462 result.stdout.fnmatch_lines(
1463 [
1464 "*ScopeMismatch*Requesting fixture stack*",
1465 "* def arg2(arg1)",
1466 "Requested fixture:",
1467 "* def arg1()",
1468 "*1 error*",
1469 ],
1470 )
1471
1472 def test_invalid_scope(self, pytester: Pytester) -> None:
1473 pytester.makepyfile(
1474 """
1475 import pytest
1476 @pytest.fixture(scope="functions")
1477 def badscope():
1478 pass
1479
1480 def test_nothing(badscope):
1481 pass
1482 """
1483 )
1484 result = pytester.runpytest_inprocess()
1485 result.stdout.fnmatch_lines(
1486 "*Fixture 'badscope' from test_invalid_scope.py got an unexpected scope value 'functions'"
1487 )
1488
1489 @pytest.mark.parametrize("scope", ["function", "session"])
1490 def test_parameters_without_eq_semantics(self, scope, pytester: Pytester) -> None:
1491 pytester.makepyfile(
1492 f"""
1493 class NoEq1: # fails on `a == b` statement
1494 def __eq__(self, _):
1495 raise RuntimeError
1496
1497 class NoEq2: # fails on `if a == b:` statement
1498 def __eq__(self, _):
1499 class NoBool:
1500 def __bool__(self):
1501 raise RuntimeError
1502 return NoBool()
1503
1504 import pytest
1505 @pytest.fixture(params=[NoEq1(), NoEq2()], scope={scope!r})
1506 def no_eq(request):
1507 return request.param
1508
1509 def test1(no_eq):
1510 pass
1511
1512 def test2(no_eq):
1513 pass
1514 """
1515 )
1516 result = pytester.runpytest()
1517 result.stdout.fnmatch_lines(["*4 passed*"])
1518
1519 def test_funcarg_parametrized_and_used_twice(self, pytester: Pytester) -> None:
1520 pytester.makepyfile(
1521 """
1522 import pytest
1523 values = []
1524 @pytest.fixture(params=[1,2])
1525 def arg1(request):
1526 values.append(1)
1527 return request.param
1528
1529 @pytest.fixture()
1530 def arg2(arg1):
1531 return arg1 + 1
1532
1533 def test_add(arg1, arg2):
1534 assert arg2 == arg1 + 1
1535 assert len(values) == arg1
1536 """
1537 )
1538 result = pytester.runpytest()
1539 result.stdout.fnmatch_lines(["*2 passed*"])
1540
1541 def test_factory_uses_unknown_funcarg_as_dependency_error(
1542 self, pytester: Pytester
1543 ) -> None:
1544 pytester.makepyfile(
1545 """
1546 import pytest
1547
1548 @pytest.fixture()
1549 def fail(missing):
1550 return
1551
1552 @pytest.fixture()
1553 def call_fail(fail):
1554 return
1555
1556 def test_missing(call_fail):
1557 pass
1558 """
1559 )
1560 result = pytester.runpytest()
1561 result.stdout.fnmatch_lines(
1562 """
1563 *pytest.fixture()*
1564 *def call_fail(fail)*
1565 *pytest.fixture()*
1566 *def fail*
1567 *fixture*'missing'*not found*
1568 """
1569 )
1570
1571 def test_factory_setup_as_classes_fails(self, pytester: Pytester) -> None:
1572 pytester.makepyfile(
1573 """
1574 import pytest
1575 class arg1(object):
1576 def __init__(self, request):
1577 self.x = 1
1578 arg1 = pytest.fixture()(arg1)
1579
1580 """
1581 )
1582 reprec = pytester.inline_run()
1583 values = reprec.getfailedcollections()
1584 assert len(values) == 1
1585
1586 def test_usefixtures_marker(self, pytester: Pytester) -> None:
1587 pytester.makepyfile(
1588 """
1589 import pytest
1590
1591 values = []
1592
1593 @pytest.fixture(scope="class")
1594 def myfix(request):
1595 request.cls.hello = "world"
1596 values.append(1)
1597
1598 class TestClass(object):
1599 def test_one(self):
1600 assert self.hello == "world"
1601 assert len(values) == 1
1602 def test_two(self):
1603 assert self.hello == "world"
1604 assert len(values) == 1
1605 pytest.mark.usefixtures("myfix")(TestClass)
1606 """
1607 )
1608 reprec = pytester.inline_run()
1609 reprec.assertoutcome(passed=2)
1610
1611 def test_empty_usefixtures_marker(self, pytester: Pytester) -> None:
1612 """Empty usefixtures() marker issues a warning (#12439)."""
1613 pytester.makepyfile(
1614 """
1615 import pytest
1616
1617 @pytest.mark.usefixtures()
1618 def test_one():
1619 assert 1 == 1
1620 """
1621 )
1622 result = pytester.runpytest()
1623 result.stdout.fnmatch_lines(
1624 "*PytestWarning: usefixtures() in test_empty_usefixtures_marker.py::test_one"
1625 " without arguments has no effect"
1626 )
1627
1628 def test_usefixtures_ini(self, pytester: Pytester) -> None:
1629 pytester.makeini(
1630 """
1631 [pytest]
1632 usefixtures = myfix
1633 """
1634 )
1635 pytester.makeconftest(
1636 """
1637 import pytest
1638
1639 @pytest.fixture(scope="class")
1640 def myfix(request):
1641 request.cls.hello = "world"
1642
1643 """
1644 )
1645 pytester.makepyfile(
1646 """
1647 class TestClass(object):
1648 def test_one(self):
1649 assert self.hello == "world"
1650 def test_two(self):
1651 assert self.hello == "world"
1652 """
1653 )
1654 reprec = pytester.inline_run()
1655 reprec.assertoutcome(passed=2)
1656
1657 def test_usefixtures_seen_in_showmarkers(self, pytester: Pytester) -> None:
1658 result = pytester.runpytest("--markers")
1659 result.stdout.fnmatch_lines(
1660 """
1661 *usefixtures(fixturename1*mark tests*fixtures*
1662 """
1663 )
1664
1665 def test_request_instance_issue203(self, pytester: Pytester) -> None:
1666 pytester.makepyfile(
1667 """
1668 import pytest
1669
1670 class TestClass(object):
1671 @pytest.fixture
1672 def setup1(self, request):
1673 assert self == request.instance
1674 self.arg1 = 1
1675 def test_hello(self, setup1):
1676 assert self.arg1 == 1
1677 """
1678 )
1679 reprec = pytester.inline_run()
1680 reprec.assertoutcome(passed=1)
1681
1682 def test_fixture_parametrized_with_iterator(self, pytester: Pytester) -> None:
1683 pytester.makepyfile(
1684 """
1685 import pytest
1686
1687 values = []
1688 def f():
1689 yield 1
1690 yield 2
1691 dec = pytest.fixture(scope="module", params=f())
1692
1693 @dec
1694 def arg(request):
1695 return request.param
1696 @dec
1697 def arg2(request):
1698 return request.param
1699
1700 def test_1(arg):
1701 values.append(arg)
1702 def test_2(arg2):
1703 values.append(arg2*10)
1704 """
1705 )
1706 reprec = pytester.inline_run("-v")
1707 reprec.assertoutcome(passed=4)
1708 values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
1709 assert values == [1, 2, 10, 20]
1710
1711 def test_setup_functions_as_fixtures(self, pytester: Pytester) -> None:
1712 """Ensure setup_* methods obey fixture scope rules (#517, #3094)."""
1713 pytester.makepyfile(
1714 """
1715 import pytest
1716
1717 DB_INITIALIZED = None
1718
1719 @pytest.fixture(scope="session", autouse=True)
1720 def db():
1721 global DB_INITIALIZED
1722 DB_INITIALIZED = True
1723 yield
1724 DB_INITIALIZED = False
1725
1726 def setup_module():
1727 assert DB_INITIALIZED
1728
1729 def teardown_module():
1730 assert DB_INITIALIZED
1731
1732 class TestClass(object):
1733
1734 def setup_method(self, method):
1735 assert DB_INITIALIZED
1736
1737 def teardown_method(self, method):
1738 assert DB_INITIALIZED
1739
1740 def test_printer_1(self):
1741 pass
1742
1743 def test_printer_2(self):
1744 pass
1745 """
1746 )
1747 result = pytester.runpytest()
1748 result.stdout.fnmatch_lines(["* 2 passed in *"])
1749
1750 def test_parameterized_fixture_caching(self, pytester: Pytester) -> None:
1751 """Regression test for #12600."""
1752 pytester.makepyfile(
1753 """
1754 import pytest
1755 from itertools import count
1756
1757 CACHE_MISSES = count(0)
1758
1759 def pytest_generate_tests(metafunc):
1760 if "my_fixture" in metafunc.fixturenames:
1761 # Use unique objects for parametrization (as opposed to small strings
1762 # and small integers which are singletons).
1763 metafunc.parametrize("my_fixture", [[1], [2]], indirect=True)
1764
1765 @pytest.fixture(scope='session')
1766 def my_fixture(request):
1767 next(CACHE_MISSES)
1768
1769 def test1(my_fixture):
1770 pass
1771
1772 def test2(my_fixture):
1773 pass
1774
1775 def teardown_module():
1776 assert next(CACHE_MISSES) == 2
1777 """
1778 )
1779 result = pytester.runpytest()
1780 result.stdout.no_fnmatch_line("* ERROR at teardown *")
1781
1782 def test_unwrapping_pytest_fixture(self, pytester: Pytester) -> None:
1783 """Ensure the unwrap method on `FixtureFunctionDefinition` correctly wraps and unwraps methods and functions"""
1784 pytester.makepyfile(
1785 """
1786 import pytest
1787 import inspect
1788
1789 class FixtureFunctionDefTestClass:
1790 def __init__(self) -> None:
1791 self.i = 10
1792
1793 @pytest.fixture
1794 def fixture_function_def_test_method(self):
1795 return self.i
1796
1797
1798 @pytest.fixture
1799 def fixture_function_def_test_func():
1800 return 9
1801
1802
1803 def test_get_wrapped_func_returns_method():
1804 obj = FixtureFunctionDefTestClass()
1805 wrapped_function_result = (
1806 obj.fixture_function_def_test_method._get_wrapped_function()
1807 )
1808 assert inspect.ismethod(wrapped_function_result)
1809 assert wrapped_function_result() == 10
1810
1811
1812 def test_get_wrapped_func_returns_function():
1813 assert fixture_function_def_test_func._get_wrapped_function()() == 9
1814 """
1815 )
1816 result = pytester.runpytest()
1817 result.assert_outcomes(passed=2)
1818
1819 def test_fixture_wrapped_looks_liked_wrapped_function(
1820 self, pytester: Pytester
1821 ) -> None:
1822 """Ensure that `FixtureFunctionDefinition` behaves like the function it wrapped."""
1823 pytester.makepyfile(
1824 """
1825 import pytest
1826
1827 @pytest.fixture
1828 def fixture_function_def_test_func():
1829 return 9
1830 fixture_function_def_test_func.__doc__ = "documentation"
1831
1832 def test_fixture_has_same_doc():
1833 assert fixture_function_def_test_func.__doc__ == "documentation"
1834 """
1835 )
1836 result = pytester.runpytest()
1837 result.assert_outcomes(passed=1)
1838
1839
1840 class TestFixtureManagerParseFactories:
1841 @pytest.fixture
1842 def pytester(self, pytester: Pytester) -> Pytester:
1843 pytester.makeconftest(
1844 """
1845 import pytest
1846
1847 @pytest.fixture
1848 def hello(request):
1849 return "conftest"
1850
1851 @pytest.fixture
1852 def fm(request):
1853 return request._fixturemanager
1854
1855 @pytest.fixture
1856 def item(request):
1857 return request._pyfuncitem
1858 """
1859 )
1860 return pytester
1861
1862 def test_parsefactories_evil_objects_issue214(self, pytester: Pytester) -> None:
1863 pytester.makepyfile(
1864 """
1865 class A(object):
1866 def __call__(self):
1867 pass
1868 def __getattr__(self, name):
1869 raise RuntimeError()
1870 a = A()
1871 def test_hello():
1872 pass
1873 """
1874 )
1875 reprec = pytester.inline_run()
1876 reprec.assertoutcome(passed=1, failed=0)
1877
1878 def test_parsefactories_conftest(self, pytester: Pytester) -> None:
1879 pytester.makepyfile(
1880 """
1881 def test_hello(item, fm):
1882 for name in ("fm", "hello", "item"):
1883 faclist = fm.getfixturedefs(name, item)
1884 assert len(faclist) == 1
1885 fac = faclist[0]
1886 assert fac.func.__name__ == name
1887 """
1888 )
1889 reprec = pytester.inline_run("-s")
1890 reprec.assertoutcome(passed=1)
1891
1892 def test_parsefactories_conftest_and_module_and_class(
1893 self, pytester: Pytester
1894 ) -> None:
1895 pytester.makepyfile(
1896 """\
1897 import pytest
1898
1899 @pytest.fixture
1900 def hello(request):
1901 return "module"
1902 class TestClass(object):
1903 @pytest.fixture
1904 def hello(self, request):
1905 return "class"
1906 def test_hello(self, item, fm):
1907 faclist = fm.getfixturedefs("hello", item)
1908 print(faclist)
1909 assert len(faclist) == 3
1910
1911 assert faclist[0].func(item._request) == "conftest"
1912 assert faclist[1].func(item._request) == "module"
1913 assert faclist[2].func(item._request) == "class"
1914 """
1915 )
1916 reprec = pytester.inline_run("-s")
1917 reprec.assertoutcome(passed=1)
1918
1919 def test_register_fixture_ordered_by_visibility(self, pytester: Pytester) -> None:
1920 """A fixturedef registered for a more specific node takes precedence
1921 over one registered for a more general (ancestor) node, regardless of
1922 the order in which they were registered (#14513)."""
1923 pytester.makeconftest(
1924 """
1925 import pytest
1926
1927 @pytest.hookimpl(wrapper=True)
1928 def pytest_collection(session):
1929 result = yield
1930 item = session.items[0]
1931 pytest.register_fixture(name="fix", func=lambda: "session1", node=session)
1932 # For coverage; can be removed once nodeid= deprecation is over.
1933 fm = session._fixturemanager
1934 fm._register_fixture(name="fix", func=lambda: "session-legacy", nodeid="")
1935 fm._register_fixture(name="fix", func=lambda: "broken-legacy", nodeid="broken")
1936 pytest.register_fixture(name="fix", func=lambda fix: f"item1-{fix}", node=item)
1937 pytest.register_fixture(name="fix", func=lambda fix: f"item2-{fix}", node=item)
1938 pytest.register_fixture(name="fix", func=lambda: "session2", node=session)
1939 return result
1940 """
1941 )
1942 pytester.makepyfile(
1943 """
1944 def test(fix):
1945 assert fix == "item2-item1-session2"
1946 """
1947 )
1948 reprec = pytester.inline_run()
1949 reprec.assertoutcome(passed=1)
1950
1951 def test_parsefactories_relative_node_ids(
1952 self, pytester: Pytester, monkeypatch: MonkeyPatch
1953 ) -> None:
1954 # example mostly taken from:
1955 # https://mail.python.org/pipermail/pytest-dev/2014-September/002617.html
1956 runner = pytester.mkdir("runner")
1957 package = pytester.mkdir("package")
1958 package.joinpath("conftest.py").write_text(
1959 textwrap.dedent(
1960 """\
1961 import pytest
1962 @pytest.fixture
1963 def one():
1964 return 1
1965 """
1966 ),
1967 encoding="utf-8",
1968 )
1969 package.joinpath("test_x.py").write_text(
1970 textwrap.dedent(
1971 """\
1972 def test_x(one):
1973 assert one == 1
1974 """
1975 ),
1976 encoding="utf-8",
1977 )
1978 sub = package.joinpath("sub")
1979 sub.mkdir()
1980 sub.joinpath("__init__.py").touch()
1981 sub.joinpath("conftest.py").write_text(
1982 textwrap.dedent(
1983 """\
1984 import pytest
1985 @pytest.fixture
1986 def one():
1987 return 2
1988 """
1989 ),
1990 encoding="utf-8",
1991 )
1992 sub.joinpath("test_y.py").write_text(
1993 textwrap.dedent(
1994 """\
1995 def test_x(one):
1996 assert one == 2
1997 """
1998 ),
1999 encoding="utf-8",
2000 )
2001 reprec = pytester.inline_run()
2002 reprec.assertoutcome(passed=2)
2003 with monkeypatch.context() as mp:
2004 mp.chdir(runner)
2005 reprec = pytester.inline_run("..")
2006 reprec.assertoutcome(passed=2)
2007
2008 def test_package_xunit_fixture(self, pytester: Pytester) -> None:
2009 pytester.makepyfile(
2010 __init__="""\
2011 values = []
2012 """
2013 )
2014 package = pytester.mkdir("package")
2015 package.joinpath("__init__.py").write_text(
2016 textwrap.dedent(
2017 """\
2018 from .. import values
2019 def setup_module():
2020 values.append("package")
2021 def teardown_module():
2022 values[:] = []
2023 """
2024 ),
2025 encoding="utf-8",
2026 )
2027 package.joinpath("test_x.py").write_text(
2028 textwrap.dedent(
2029 """\
2030 from .. import values
2031 def test_x():
2032 assert values == ["package"]
2033 """
2034 ),
2035 encoding="utf-8",
2036 )
2037 package = pytester.mkdir("package2")
2038 package.joinpath("__init__.py").write_text(
2039 textwrap.dedent(
2040 """\
2041 from .. import values
2042 def setup_module():
2043 values.append("package2")
2044 def teardown_module():
2045 values[:] = []
2046 """
2047 ),
2048 encoding="utf-8",
2049 )
2050 package.joinpath("test_x.py").write_text(
2051 textwrap.dedent(
2052 """\
2053 from .. import values
2054 def test_x():
2055 assert values == ["package2"]
2056 """
2057 ),
2058 encoding="utf-8",
2059 )
2060 reprec = pytester.inline_run()
2061 reprec.assertoutcome(passed=2)
2062
2063 def test_package_fixture_complex(self, pytester: Pytester) -> None:
2064 pytester.makepyfile(
2065 __init__="""\
2066 values = []
2067 """
2068 )
2069 pytester.syspathinsert(pytester.path.name)
2070 package = pytester.mkdir("package")
2071 package.joinpath("__init__.py").write_text("", encoding="utf-8")
2072 package.joinpath("conftest.py").write_text(
2073 textwrap.dedent(
2074 """\
2075 import pytest
2076 from .. import values
2077 @pytest.fixture(scope="package")
2078 def one():
2079 values.append("package")
2080 yield values
2081 values.pop()
2082 @pytest.fixture(scope="package", autouse=True)
2083 def two():
2084 values.append("package-auto")
2085 yield values
2086 values.pop()
2087 """
2088 ),
2089 encoding="utf-8",
2090 )
2091 package.joinpath("test_x.py").write_text(
2092 textwrap.dedent(
2093 """\
2094 from .. import values
2095 def test_package_autouse():
2096 assert values == ["package-auto"]
2097 def test_package(one):
2098 assert values == ["package-auto", "package"]
2099 """
2100 ),
2101 encoding="utf-8",
2102 )
2103 reprec = pytester.inline_run()
2104 reprec.assertoutcome(passed=2)
2105
2106 def test_collect_custom_items(self, pytester: Pytester) -> None:
2107 pytester.copy_example("fixtures/custom_item")
2108 result = pytester.runpytest("foo")
2109 result.stdout.fnmatch_lines(["*passed*"])
2110
2111
2112 class TestAutouseDiscovery:
2113 @pytest.fixture
2114 def pytester(self, pytester: Pytester) -> Pytester:
2115 pytester.makeconftest(
2116 """
2117 import pytest
2118 @pytest.fixture(autouse=True)
2119 def perfunction(request, tmp_path):
2120 pass
2121
2122 @pytest.fixture()
2123 def arg1(tmp_path):
2124 pass
2125 @pytest.fixture(autouse=True)
2126 def perfunction2(arg1):
2127 pass
2128
2129 @pytest.fixture
2130 def fm(request):
2131 return request._fixturemanager
2132
2133 @pytest.fixture
2134 def item(request):
2135 return request._pyfuncitem
2136 """
2137 )
2138 return pytester
2139
2140 def test_parsefactories_conftest(self, pytester: Pytester) -> None:
2141 pytester.makepyfile(
2142 """
2143 from _pytest.pytester import get_public_names
2144 def test_check_setup(item, fm):
2145 autousenames = list(fm._getautousenames(item))
2146 assert len(get_public_names(autousenames)) == 2
2147 assert "perfunction2" in autousenames
2148 assert "perfunction" in autousenames
2149 """
2150 )
2151 reprec = pytester.inline_run("-s")
2152 reprec.assertoutcome(passed=1)
2153
2154 def test_two_classes_separated_autouse(self, pytester: Pytester) -> None:
2155 pytester.makepyfile(
2156 """
2157 import pytest
2158 class TestA(object):
2159 values = []
2160 @pytest.fixture(autouse=True)
2161 def setup1(self):
2162 self.values.append(1)
2163 def test_setup1(self):
2164 assert self.values == [1]
2165 class TestB(object):
2166 values = []
2167 @pytest.fixture(autouse=True)
2168 def setup2(self):
2169 self.values.append(1)
2170 def test_setup2(self):
2171 assert self.values == [1]
2172 """
2173 )
2174 reprec = pytester.inline_run()
2175 reprec.assertoutcome(passed=2)
2176
2177 def test_setup_at_classlevel(self, pytester: Pytester) -> None:
2178 pytester.makepyfile(
2179 """
2180 import pytest
2181 class TestClass(object):
2182 @pytest.fixture(autouse=True)
2183 def permethod(self, request):
2184 request.instance.funcname = request.function.__name__
2185 def test_method1(self):
2186 assert self.funcname == "test_method1"
2187 def test_method2(self):
2188 assert self.funcname == "test_method2"
2189 """
2190 )
2191 reprec = pytester.inline_run("-s")
2192 reprec.assertoutcome(passed=2)
2193
2194 @pytest.mark.xfail(reason="'enabled' feature not implemented")
2195 def test_setup_enabled_functionnode(self, pytester: Pytester) -> None:
2196 pytester.makepyfile(
2197 """
2198 import pytest
2199
2200 def enabled(parentnode, markers):
2201 return "needsdb" in markers
2202
2203 @pytest.fixture(params=[1,2])
2204 def db(request):
2205 return request.param
2206
2207 @pytest.fixture(enabled=enabled, autouse=True)
2208 def createdb(db):
2209 pass
2210
2211 def test_func1(request):
2212 assert "db" not in request.fixturenames
2213
2214 @pytest.mark.needsdb
2215 def test_func2(request):
2216 assert "db" in request.fixturenames
2217 """
2218 )
2219 reprec = pytester.inline_run("-s")
2220 reprec.assertoutcome(passed=2)
2221
2222 def test_callables_nocode(self, pytester: Pytester) -> None:
2223 """An imported mock.call would break setup/factory discovery due to
2224 it being callable and __code__ not being a code object."""
2225 pytester.makepyfile(
2226 """
2227 class _call(tuple):
2228 def __call__(self, *k, **kw):
2229 pass
2230 def __getattr__(self, k):
2231 return self
2232
2233 call = _call()
2234 """
2235 )
2236 reprec = pytester.inline_run("-s")
2237 reprec.assertoutcome(failed=0, passed=0)
2238
2239 def test_autouse_in_conftests(self, pytester: Pytester) -> None:
2240 a = pytester.mkdir("a")
2241 b = pytester.mkdir("a1")
2242 conftest = pytester.makeconftest(
2243 """
2244 import pytest
2245 @pytest.fixture(autouse=True)
2246 def hello():
2247 xxx
2248 """
2249 )
2250 conftest.rename(a.joinpath(conftest.name))
2251 a.joinpath("test_something.py").write_text(
2252 "def test_func(): pass", encoding="utf-8"
2253 )
2254 b.joinpath("test_otherthing.py").write_text(
2255 "def test_func(): pass", encoding="utf-8"
2256 )
2257 result = pytester.runpytest()
2258 result.stdout.fnmatch_lines(
2259 """
2260 *1 passed*1 error*
2261 """
2262 )
2263
2264 def test_autouse_in_module_and_two_classes(self, pytester: Pytester) -> None:
2265 pytester.makepyfile(
2266 """
2267 import pytest
2268 values = []
2269 @pytest.fixture(autouse=True)
2270 def append1():
2271 values.append("module")
2272 def test_x():
2273 assert values == ["module"]
2274
2275 class TestA(object):
2276 @pytest.fixture(autouse=True)
2277 def append2(self):
2278 values.append("A")
2279 def test_hello(self):
2280 assert values == ["module", "module", "A"], values
2281 class TestA2(object):
2282 def test_world(self):
2283 assert values == ["module", "module", "A", "module"], values
2284 """
2285 )
2286 reprec = pytester.inline_run()
2287 reprec.assertoutcome(passed=3)
2288
2289
2290 class TestAutouseManagement:
2291 def test_autouse_conftest_mid_directory(self, pytester: Pytester) -> None:
2292 pkgdir = pytester.mkpydir("xyz123")
2293 pkgdir.joinpath("conftest.py").write_text(
2294 textwrap.dedent(
2295 """\
2296 import pytest
2297 @pytest.fixture(autouse=True)
2298 def app():
2299 import sys
2300 sys._myapp = "hello"
2301 """
2302 ),
2303 encoding="utf-8",
2304 )
2305 sub = pkgdir.joinpath("tests")
2306 sub.mkdir()
2307 t = sub.joinpath("test_app.py")
2308 t.touch()
2309 t.write_text(
2310 textwrap.dedent(
2311 """\
2312 import sys
2313 def test_app():
2314 assert sys._myapp == "hello"
2315 """
2316 ),
2317 encoding="utf-8",
2318 )
2319 reprec = pytester.inline_run("-s")
2320 reprec.assertoutcome(passed=1)
2321
2322 def test_funcarg_and_setup(self, pytester: Pytester) -> None:
2323 pytester.makepyfile(
2324 """
2325 import pytest
2326 values = []
2327 @pytest.fixture(scope="module")
2328 def arg():
2329 values.append(1)
2330 return 0
2331 @pytest.fixture(scope="module", autouse=True)
2332 def something(arg):
2333 values.append(2)
2334
2335 def test_hello(arg):
2336 assert len(values) == 2
2337 assert values == [1,2]
2338 assert arg == 0
2339
2340 def test_hello2(arg):
2341 assert len(values) == 2
2342 assert values == [1,2]
2343 assert arg == 0
2344 """
2345 )
2346 reprec = pytester.inline_run()
2347 reprec.assertoutcome(passed=2)
2348
2349 def test_uses_parametrized_resource(self, pytester: Pytester) -> None:
2350 pytester.makepyfile(
2351 """
2352 import pytest
2353 values = []
2354 @pytest.fixture(params=[1,2])
2355 def arg(request):
2356 return request.param
2357
2358 @pytest.fixture(autouse=True)
2359 def something(arg):
2360 values.append(arg)
2361
2362 def test_hello():
2363 if len(values) == 1:
2364 assert values == [1]
2365 elif len(values) == 2:
2366 assert values == [1, 2]
2367 else:
2368 0/0
2369
2370 """
2371 )
2372 reprec = pytester.inline_run("-s")
2373 reprec.assertoutcome(passed=2)
2374
2375 def test_session_parametrized_function(self, pytester: Pytester) -> None:
2376 pytester.makepyfile(
2377 """
2378 import pytest
2379
2380 values = []
2381
2382 @pytest.fixture(scope="session", params=[1,2])
2383 def arg(request):
2384 return request.param
2385
2386 @pytest.fixture(scope="function", autouse=True)
2387 def append(request, arg):
2388 if request.function.__name__ == "test_some":
2389 values.append(arg)
2390
2391 def test_some():
2392 pass
2393
2394 def test_result(arg):
2395 assert len(values) == arg
2396 assert values[:arg] == [1,2][:arg]
2397 """
2398 )
2399 reprec = pytester.inline_run("-v", "-s")
2400 reprec.assertoutcome(passed=4)
2401
2402 def test_class_function_parametrization_finalization(
2403 self, pytester: Pytester
2404 ) -> None:
2405 p = pytester.makeconftest(
2406 """
2407 import pytest
2408 import pprint
2409
2410 values = []
2411
2412 @pytest.fixture(scope="function", params=[1,2])
2413 def farg(request):
2414 return request.param
2415
2416 @pytest.fixture(scope="class", params=list("ab"))
2417 def carg(request):
2418 return request.param
2419
2420 @pytest.fixture(scope="function", autouse=True)
2421 def append(request, farg, carg):
2422 def fin():
2423 values.append("fin_%s%s" % (carg, farg))
2424 request.addfinalizer(fin)
2425 """
2426 )
2427 pytester.makepyfile(
2428 """
2429 import pytest
2430
2431 class TestClass(object):
2432 def test_1(self):
2433 pass
2434 class TestClass2(object):
2435 def test_2(self):
2436 pass
2437 """
2438 )
2439 reprec = pytester.inline_run("-v", "-s", "--confcutdir", pytester.path)
2440 reprec.assertoutcome(passed=8)
2441 config = reprec.getcalls("pytest_unconfigure")[0].config
2442 values = config.pluginmanager._getconftestmodules(p)[0].values
2443 assert values == ["fin_a1", "fin_a2", "fin_b1", "fin_b2"] * 2
2444
2445 def test_scope_ordering(self, pytester: Pytester) -> None:
2446 pytester.makepyfile(
2447 """
2448 import pytest
2449 values = []
2450 @pytest.fixture(scope="function", autouse=True)
2451 def fappend2():
2452 values.append(2)
2453 @pytest.fixture(scope="class", autouse=True)
2454 def classappend3():
2455 values.append(3)
2456 @pytest.fixture(scope="module", autouse=True)
2457 def mappend():
2458 values.append(1)
2459
2460 class TestHallo(object):
2461 def test_method(self):
2462 assert values == [1,3,2]
2463 """
2464 )
2465 reprec = pytester.inline_run()
2466 reprec.assertoutcome(passed=1)
2467
2468 def test_parametrization_setup_teardown_ordering(self, pytester: Pytester) -> None:
2469 pytester.makepyfile(
2470 """
2471 import pytest
2472
2473 values = []
2474
2475 def pytest_generate_tests(metafunc):
2476 if metafunc.cls is None:
2477 assert metafunc.function is test_finish
2478 if metafunc.cls is not None:
2479 metafunc.parametrize("item", [1,2], scope="class")
2480
2481 class TestClass:
2482 @pytest.fixture(scope="class", autouse=True)
2483 @classmethod
2484 def setup_teardown(cls, item):
2485 values.append("setup-%d" % item)
2486 yield
2487 values.append("teardown-%d" % item)
2488
2489 def test_step1(self, item):
2490 values.append("step1-%d" % item)
2491
2492 def test_step2(self, item):
2493 values.append("step2-%d" % item)
2494
2495 def test_finish():
2496 assert values == [
2497 "setup-1",
2498 "step1-1",
2499 "step2-1",
2500 "teardown-1",
2501 "setup-2",
2502 "step1-2",
2503 "step2-2",
2504 "teardown-2",
2505 ]
2506 """
2507 )
2508 result = pytester.inline_run("-vv")
2509 result.assertoutcome(passed=5)
2510
2511 def test_ordering_autouse_before_explicit(self, pytester: Pytester) -> None:
2512 pytester.makepyfile(
2513 """
2514 import pytest
2515
2516 values = []
2517 @pytest.fixture(autouse=True)
2518 def fix1():
2519 values.append(1)
2520 @pytest.fixture()
2521 def arg1():
2522 values.append(2)
2523 def test_hello(arg1):
2524 assert values == [1,2]
2525 """
2526 )
2527 reprec = pytester.inline_run()
2528 reprec.assertoutcome(passed=1)
2529
2530 @pytest.mark.parametrize("param1", ["", "params=[1]"], ids=["p00", "p01"])
2531 @pytest.mark.parametrize("param2", ["", "params=[1]"], ids=["p10", "p11"])
2532 def test_ordering_dependencies_torndown_first(
2533 self, pytester: Pytester, param1, param2
2534 ) -> None:
2535 """#226"""
2536 pytester.makepyfile(
2537 f"""
2538 import pytest
2539 values = []
2540 @pytest.fixture({param1})
2541 def arg1(request):
2542 request.addfinalizer(lambda: values.append("fin1"))
2543 values.append("new1")
2544 @pytest.fixture({param2})
2545 def arg2(request, arg1):
2546 request.addfinalizer(lambda: values.append("fin2"))
2547 values.append("new2")
2548
2549 def test_arg(arg2):
2550 pass
2551 def test_check():
2552 assert values == ["new1", "new2", "fin2", "fin1"]
2553 """
2554 )
2555 reprec = pytester.inline_run("-s")
2556 reprec.assertoutcome(passed=2)
2557
2558 def test_reordering_catastrophic_performance(self, pytester: Pytester) -> None:
2559 """Check that a certain high-scope parametrization pattern doesn't cause
2560 a catasrophic slowdown.
2561
2562 Regression test for #12355.
2563 """
2564 pytester.makepyfile("""
2565 import pytest
2566
2567 params = tuple("abcdefghijklmnopqrstuvwxyz")
2568 @pytest.mark.parametrize(params, [range(len(params))] * 3, scope="module")
2569 def test_parametrize(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z):
2570 pass
2571 """)
2572
2573 result = pytester.runpytest()
2574
2575 result.assert_outcomes(passed=3)
2576
2577
2578 class TestFixtureMarker:
2579 def test_parametrize(self, pytester: Pytester) -> None:
2580 pytester.makepyfile(
2581 """
2582 import pytest
2583 @pytest.fixture(params=["a", "b", "c"])
2584 def arg(request):
2585 return request.param
2586 values = []
2587 def test_param(arg):
2588 values.append(arg)
2589 def test_result():
2590 assert values == list("abc")
2591 """
2592 )
2593 reprec = pytester.inline_run()
2594 reprec.assertoutcome(passed=4)
2595
2596 def test_multiple_parametrization_issue_736(self, pytester: Pytester) -> None:
2597 pytester.makepyfile(
2598 """
2599 import pytest
2600
2601 @pytest.fixture(params=[1,2,3])
2602 def foo(request):
2603 return request.param
2604
2605 @pytest.mark.parametrize('foobar', [4,5,6])
2606 def test_issue(foo, foobar):
2607 assert foo in [1,2,3]
2608 assert foobar in [4,5,6]
2609 """
2610 )
2611 reprec = pytester.inline_run()
2612 reprec.assertoutcome(passed=9)
2613
2614 @pytest.mark.parametrize(
2615 "param_args",
2616 ["'fixt, val'", "'fixt,val'", "['fixt', 'val']", "('fixt', 'val')"],
2617 )
2618 def test_override_parametrized_fixture_issue_979(
2619 self, pytester: Pytester, param_args
2620 ) -> None:
2621 """Make sure a parametrized argument can override a parametrized fixture.
2622
2623 This was a regression introduced in the fix for #736.
2624 """
2625 pytester.makepyfile(
2626 f"""
2627 import pytest
2628
2629 @pytest.fixture(params=[1, 2])
2630 def fixt(request):
2631 return request.param
2632
2633 @pytest.mark.parametrize({param_args}, [(3, 'x'), (4, 'x')])
2634 def test_foo(fixt, val):
2635 pass
2636 """
2637 )
2638 reprec = pytester.inline_run()
2639 reprec.assertoutcome(passed=2)
2640
2641 def test_override_parametrized_fixture_with_indirect(
2642 self, pytester: Pytester
2643 ) -> None:
2644 """Make sure a parametrized argument can override a parametrized fixture.
2645
2646 This was a regression introduced in the fix for #736.
2647 """
2648 pytester.makepyfile(
2649 """
2650 import pytest
2651
2652 @pytest.fixture(params=["a"])
2653 def fixt(request):
2654 return request.param * 2
2655
2656 def test_fixt(fixt):
2657 assert fixt == "aa"
2658
2659 @pytest.mark.parametrize("fixt", ['b'], indirect=True)
2660 def test_indirect(fixt):
2661 assert fixt == "bb"
2662 """
2663 )
2664 reprec = pytester.inline_run()
2665 reprec.assertoutcome(passed=2)
2666
2667 def test_scope_session(self, pytester: Pytester) -> None:
2668 pytester.makepyfile(
2669 """
2670 import pytest
2671 values = []
2672 @pytest.fixture(scope="module")
2673 def arg():
2674 values.append(1)
2675 return 1
2676
2677 def test_1(arg):
2678 assert arg == 1
2679 def test_2(arg):
2680 assert arg == 1
2681 assert len(values) == 1
2682 class TestClass(object):
2683 def test3(self, arg):
2684 assert arg == 1
2685 assert len(values) == 1
2686 """
2687 )
2688 reprec = pytester.inline_run()
2689 reprec.assertoutcome(passed=3)
2690
2691 def test_scope_session_exc(self, pytester: Pytester) -> None:
2692 pytester.makepyfile(
2693 """
2694 import pytest
2695 values = []
2696 @pytest.fixture(scope="session")
2697 def fix():
2698 values.append(1)
2699 pytest.skip('skipping')
2700
2701 def test_1(fix):
2702 pass
2703 def test_2(fix):
2704 pass
2705 def test_last():
2706 assert values == [1]
2707 """
2708 )
2709 reprec = pytester.inline_run()
2710 reprec.assertoutcome(skipped=2, passed=1)
2711
2712 def test_scope_session_exc_two_fix(self, pytester: Pytester) -> None:
2713 pytester.makepyfile(
2714 """
2715 import pytest
2716 values = []
2717 m = []
2718 @pytest.fixture(scope="session")
2719 def a():
2720 values.append(1)
2721 pytest.skip('skipping')
2722 @pytest.fixture(scope="session")
2723 def b(a):
2724 m.append(1)
2725
2726 def test_1(b):
2727 pass
2728 def test_2(b):
2729 pass
2730 def test_last():
2731 assert values == [1]
2732 assert m == []
2733 """
2734 )
2735 reprec = pytester.inline_run()
2736 reprec.assertoutcome(skipped=2, passed=1)
2737
2738 def test_scope_exc(self, pytester: Pytester) -> None:
2739 pytester.makepyfile(
2740 test_foo="""
2741 def test_foo(fix):
2742 pass
2743 """,
2744 test_bar="""
2745 def test_bar(fix):
2746 pass
2747 """,
2748 conftest="""
2749 import pytest
2750 reqs = []
2751 @pytest.fixture(scope="session")
2752 def fix(request):
2753 reqs.append(1)
2754 pytest.skip()
2755 @pytest.fixture
2756 def req_list():
2757 return reqs
2758 """,
2759 test_real="""
2760 def test_last(req_list):
2761 assert req_list == [1]
2762 """,
2763 )
2764 reprec = pytester.inline_run()
2765 reprec.assertoutcome(skipped=2, passed=1)
2766
2767 def test_scope_module_uses_session(self, pytester: Pytester) -> None:
2768 pytester.makepyfile(
2769 """
2770 import pytest
2771 values = []
2772 @pytest.fixture(scope="module")
2773 def arg():
2774 values.append(1)
2775 return 1
2776
2777 def test_1(arg):
2778 assert arg == 1
2779 def test_2(arg):
2780 assert arg == 1
2781 assert len(values) == 1
2782 class TestClass(object):
2783 def test3(self, arg):
2784 assert arg == 1
2785 assert len(values) == 1
2786 """
2787 )
2788 reprec = pytester.inline_run()
2789 reprec.assertoutcome(passed=3)
2790
2791 def test_scope_module_and_finalizer(self, pytester: Pytester) -> None:
2792 pytester.makeconftest(
2793 """
2794 import pytest
2795 finalized_list = []
2796 created_list = []
2797 @pytest.fixture(scope="module")
2798 def arg(request):
2799 created_list.append(1)
2800 assert request.scope == "module"
2801 request.addfinalizer(lambda: finalized_list.append(1))
2802 @pytest.fixture
2803 def created(request):
2804 return len(created_list)
2805 @pytest.fixture
2806 def finalized(request):
2807 return len(finalized_list)
2808 """
2809 )
2810 pytester.makepyfile(
2811 test_mod1="""
2812 def test_1(arg, created, finalized):
2813 assert created == 1
2814 assert finalized == 0
2815 def test_2(arg, created, finalized):
2816 assert created == 1
2817 assert finalized == 0""",
2818 test_mod2="""
2819 def test_3(arg, created, finalized):
2820 assert created == 2
2821 assert finalized == 1""",
2822 test_mode3="""
2823 def test_4(arg, created, finalized):
2824 assert created == 3
2825 assert finalized == 2
2826 """,
2827 )
2828 reprec = pytester.inline_run()
2829 reprec.assertoutcome(passed=4)
2830
2831 def test_scope_mismatch_various(self, pytester: Pytester) -> None:
2832 pytester.makeconftest(
2833 """
2834 import pytest
2835 finalized = []
2836 created = []
2837 @pytest.fixture(scope="function")
2838 def arg(request):
2839 pass
2840 """
2841 )
2842 pytester.makepyfile(
2843 test_mod1="""
2844 import pytest
2845 @pytest.fixture(scope="session")
2846 def arg(request):
2847 request.getfixturevalue("arg")
2848 def test_1(arg):
2849 pass
2850 """
2851 )
2852 result = pytester.runpytest()
2853 assert result.ret != 0
2854 result.stdout.fnmatch_lines(
2855 ["*ScopeMismatch*You tried*function*session*request*"]
2856 )
2857
2858 def test_scope_mismatch_already_computed_dynamic(self, pytester: Pytester) -> None:
2859 pytester.makepyfile(
2860 test_it="""
2861 import pytest
2862
2863 @pytest.fixture(scope="function")
2864 def fixfunc(): pass
2865
2866 @pytest.fixture(scope="module")
2867 def fixmod(fixfunc): pass
2868
2869 def test_it(request, fixfunc):
2870 request.getfixturevalue("fixmod")
2871 """,
2872 )
2873
2874 result = pytester.runpytest()
2875 assert result.ret == ExitCode.TESTS_FAILED
2876 result.stdout.fnmatch_lines(
2877 [
2878 "*ScopeMismatch*Requesting fixture stack*",
2879 "test_it.py:6: def fixmod(fixfunc)",
2880 "Requested fixture:",
2881 "test_it.py:3: def fixfunc()",
2882 ]
2883 )
2884
2885 def test_dynamic_scope(self, pytester: Pytester) -> None:
2886 pytester.makeconftest(
2887 """
2888 import pytest
2889
2890
2891 def pytest_addoption(parser):
2892 parser.addoption("--extend-scope", action="store_true", default=False)
2893
2894
2895 def dynamic_scope(fixture_name, config):
2896 if config.getoption("--extend-scope"):
2897 return "session"
2898 return "function"
2899
2900
2901 @pytest.fixture(scope=dynamic_scope)
2902 def dynamic_fixture(calls=[]):
2903 calls.append("call")
2904 return len(calls)
2905
2906 """
2907 )
2908
2909 pytester.makepyfile(
2910 """
2911 def test_first(dynamic_fixture):
2912 assert dynamic_fixture == 1
2913
2914
2915 def test_second(dynamic_fixture):
2916 assert dynamic_fixture == 2
2917
2918 """
2919 )
2920
2921 reprec = pytester.inline_run()
2922 reprec.assertoutcome(passed=2)
2923
2924 reprec = pytester.inline_run("--extend-scope")
2925 reprec.assertoutcome(passed=1, failed=1)
2926
2927 def test_dynamic_scope_bad_return(self, pytester: Pytester) -> None:
2928 pytester.makepyfile(
2929 """
2930 import pytest
2931
2932 def dynamic_scope(**_):
2933 return "wrong-scope"
2934
2935 @pytest.fixture(scope=dynamic_scope)
2936 def fixture():
2937 pass
2938
2939 """
2940 )
2941 result = pytester.runpytest()
2942 result.stdout.fnmatch_lines(
2943 "Fixture 'fixture' from test_dynamic_scope_bad_return.py "
2944 "got an unexpected scope value 'wrong-scope'"
2945 )
2946
2947 def test_register_only_with_mark(self, pytester: Pytester) -> None:
2948 pytester.makeconftest(
2949 """
2950 import pytest
2951 @pytest.fixture()
2952 def arg():
2953 return 1
2954 """
2955 )
2956 pytester.makepyfile(
2957 test_mod1="""
2958 import pytest
2959 @pytest.fixture()
2960 def arg(arg):
2961 return arg + 1
2962 def test_1(arg):
2963 assert arg == 2
2964 """
2965 )
2966 reprec = pytester.inline_run()
2967 reprec.assertoutcome(passed=1)
2968
2969 def test_parametrize_and_scope(self, pytester: Pytester) -> None:
2970 pytester.makepyfile(
2971 """
2972 import pytest
2973 @pytest.fixture(scope="module", params=["a", "b", "c"])
2974 def arg(request):
2975 return request.param
2976 values = []
2977 def test_param(arg):
2978 values.append(arg)
2979 """
2980 )
2981 reprec = pytester.inline_run("-v")
2982 reprec.assertoutcome(passed=3)
2983 values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
2984 assert len(values) == 3
2985 assert "a" in values
2986 assert "b" in values
2987 assert "c" in values
2988
2989 def test_scope_mismatch(self, pytester: Pytester) -> None:
2990 pytester.makeconftest(
2991 """
2992 import pytest
2993 @pytest.fixture(scope="function")
2994 def arg(request):
2995 pass
2996 """
2997 )
2998 pytester.makepyfile(
2999 """
3000 import pytest
3001 @pytest.fixture(scope="session")
3002 def arg(arg):
3003 pass
3004 def test_mismatch(arg):
3005 pass
3006 """
3007 )
3008 result = pytester.runpytest()
3009 result.stdout.fnmatch_lines(["*ScopeMismatch*", "*1 error*"])
3010
3011 def test_parametrize_separated_order(self, pytester: Pytester) -> None:
3012 pytester.makepyfile(
3013 """
3014 import pytest
3015
3016 @pytest.fixture(scope="module", params=[1, 2])
3017 def arg(request):
3018 return request.param
3019
3020 values = []
3021 def test_1(arg):
3022 values.append(arg)
3023 def test_2(arg):
3024 values.append(arg)
3025 """
3026 )
3027 reprec = pytester.inline_run("-v")
3028 reprec.assertoutcome(passed=4)
3029 values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
3030 assert values == [1, 1, 2, 2]
3031
3032 def test_module_parametrized_ordering(self, pytester: Pytester) -> None:
3033 pytester.makeini(
3034 """
3035 [pytest]
3036 console_output_style=classic
3037 """
3038 )
3039 pytester.makeconftest(
3040 """
3041 import pytest
3042
3043 @pytest.fixture(scope="session", params="s1 s2".split())
3044 def sarg():
3045 pass
3046 @pytest.fixture(scope="module", params="m1 m2".split())
3047 def marg():
3048 pass
3049 """
3050 )
3051 pytester.makepyfile(
3052 test_mod1="""
3053 def test_func(sarg):
3054 pass
3055 def test_func1(marg):
3056 pass
3057 """,
3058 test_mod2="""
3059 def test_func2(sarg):
3060 pass
3061 def test_func3(sarg, marg):
3062 pass
3063 def test_func3b(sarg, marg):
3064 pass
3065 def test_func4(marg):
3066 pass
3067 """,
3068 )
3069 result = pytester.runpytest("-v")
3070 result.stdout.fnmatch_lines(
3071 """
3072 test_mod1.py::test_func[s1] PASSED
3073 test_mod2.py::test_func2[s1] PASSED
3074 test_mod2.py::test_func3[s1-m1] PASSED
3075 test_mod2.py::test_func3b[s1-m1] PASSED
3076 test_mod2.py::test_func3[s1-m2] PASSED
3077 test_mod2.py::test_func3b[s1-m2] PASSED
3078 test_mod1.py::test_func[s2] PASSED
3079 test_mod2.py::test_func2[s2] PASSED
3080 test_mod2.py::test_func3[s2-m1] PASSED
3081 test_mod2.py::test_func3b[s2-m1] PASSED
3082 test_mod2.py::test_func4[m1] PASSED
3083 test_mod2.py::test_func3[s2-m2] PASSED
3084 test_mod2.py::test_func3b[s2-m2] PASSED
3085 test_mod2.py::test_func4[m2] PASSED
3086 test_mod1.py::test_func1[m1] PASSED
3087 test_mod1.py::test_func1[m2] PASSED
3088 """
3089 )
3090
3091 def test_dynamic_parametrized_ordering(self, pytester: Pytester) -> None:
3092 pytester.makeini(
3093 """
3094 [pytest]
3095 console_output_style=classic
3096 """
3097 )
3098 pytester.makeconftest(
3099 """
3100 import pytest
3101
3102 def pytest_configure(config):
3103 class DynamicFixturePlugin(object):
3104 @pytest.fixture(scope='session', params=['flavor1', 'flavor2'])
3105 def flavor(self, request):
3106 return request.param
3107 config.pluginmanager.register(DynamicFixturePlugin(), 'flavor-fixture')
3108
3109 @pytest.fixture(scope='session', params=['vxlan', 'vlan'])
3110 def encap(request):
3111 return request.param
3112
3113 @pytest.fixture(scope='session', autouse='True')
3114 def reprovision(request, flavor, encap):
3115 pass
3116 """
3117 )
3118 pytester.makepyfile(
3119 """
3120 def test(reprovision):
3121 pass
3122 def test2(reprovision):
3123 pass
3124 """
3125 )
3126 result = pytester.runpytest("-v")
3127 result.stdout.fnmatch_lines(
3128 """
3129 test_dynamic_parametrized_ordering.py::test[flavor1-vxlan] PASSED
3130 test_dynamic_parametrized_ordering.py::test2[flavor1-vxlan] PASSED
3131 test_dynamic_parametrized_ordering.py::test[flavor1-vlan] PASSED
3132 test_dynamic_parametrized_ordering.py::test2[flavor1-vlan] PASSED
3133 test_dynamic_parametrized_ordering.py::test[flavor2-vlan] PASSED
3134 test_dynamic_parametrized_ordering.py::test2[flavor2-vlan] PASSED
3135 test_dynamic_parametrized_ordering.py::test[flavor2-vxlan] PASSED
3136 test_dynamic_parametrized_ordering.py::test2[flavor2-vxlan] PASSED
3137 """
3138 )
3139
3140 def test_class_ordering(self, pytester: Pytester) -> None:
3141 pytester.makeini(
3142 """
3143 [pytest]
3144 console_output_style=classic
3145 """
3146 )
3147 pytester.makeconftest(
3148 """
3149 import pytest
3150
3151 values = []
3152
3153 @pytest.fixture(scope="function", params=[1,2])
3154 def farg(request):
3155 return request.param
3156
3157 @pytest.fixture(scope="class", params=list("ab"))
3158 def carg(request):
3159 return request.param
3160
3161 @pytest.fixture(scope="function", autouse=True)
3162 def append(request, farg, carg):
3163 def fin():
3164 values.append("fin_%s%s" % (carg, farg))
3165 request.addfinalizer(fin)
3166 """
3167 )
3168 pytester.makepyfile(
3169 """
3170 import pytest
3171
3172 class TestClass2(object):
3173 def test_1(self):
3174 pass
3175 def test_2(self):
3176 pass
3177 class TestClass(object):
3178 def test_3(self):
3179 pass
3180 """
3181 )
3182 result = pytester.runpytest("-vs")
3183 result.stdout.re_match_lines(
3184 r"""
3185 test_class_ordering.py::TestClass2::test_1\[a-1\] PASSED
3186 test_class_ordering.py::TestClass2::test_1\[a-2\] PASSED
3187 test_class_ordering.py::TestClass2::test_2\[a-1\] PASSED
3188 test_class_ordering.py::TestClass2::test_2\[a-2\] PASSED
3189 test_class_ordering.py::TestClass2::test_1\[b-1\] PASSED
3190 test_class_ordering.py::TestClass2::test_1\[b-2\] PASSED
3191 test_class_ordering.py::TestClass2::test_2\[b-1\] PASSED
3192 test_class_ordering.py::TestClass2::test_2\[b-2\] PASSED
3193 test_class_ordering.py::TestClass::test_3\[a-1\] PASSED
3194 test_class_ordering.py::TestClass::test_3\[a-2\] PASSED
3195 test_class_ordering.py::TestClass::test_3\[b-1\] PASSED
3196 test_class_ordering.py::TestClass::test_3\[b-2\] PASSED
3197 """
3198 )
3199
3200 def test_parametrize_separated_order_higher_scope_first(
3201 self, pytester: Pytester
3202 ) -> None:
3203 pytester.makepyfile(
3204 """
3205 import pytest
3206
3207 @pytest.fixture(scope="function", params=[1, 2])
3208 def arg(request):
3209 param = request.param
3210 request.addfinalizer(lambda: values.append("fin:%s" % param))
3211 values.append("create:%s" % param)
3212 return request.param
3213
3214 @pytest.fixture(scope="module", params=["mod1", "mod2"])
3215 def modarg(request):
3216 param = request.param
3217 request.addfinalizer(lambda: values.append("fin:%s" % param))
3218 values.append("create:%s" % param)
3219 return request.param
3220
3221 values = []
3222 def test_1(arg):
3223 values.append("test1")
3224 def test_2(modarg):
3225 values.append("test2")
3226 def test_3(arg, modarg):
3227 values.append("test3")
3228 def test_4(modarg, arg):
3229 values.append("test4")
3230 """
3231 )
3232 reprec = pytester.inline_run("-v")
3233 reprec.assertoutcome(passed=12)
3234 values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
3235 expected = [
3236 "create:1",
3237 "test1",
3238 "fin:1",
3239 "create:2",
3240 "test1",
3241 "fin:2",
3242 "create:mod1",
3243 "test2",
3244 "create:1",
3245 "test3",
3246 "fin:1",
3247 "create:2",
3248 "test3",
3249 "fin:2",
3250 "create:1",
3251 "test4",
3252 "fin:1",
3253 "create:2",
3254 "test4",
3255 "fin:2",
3256 "fin:mod1",
3257 "create:mod2",
3258 "test2",
3259 "create:1",
3260 "test3",
3261 "fin:1",
3262 "create:2",
3263 "test3",
3264 "fin:2",
3265 "create:1",
3266 "test4",
3267 "fin:1",
3268 "create:2",
3269 "test4",
3270 "fin:2",
3271 "fin:mod2",
3272 ]
3273 import pprint
3274
3275 pprint.pprint(list(zip_longest(values, expected)))
3276 assert values == expected
3277
3278 def test_parametrized_fixture_teardown_order(self, pytester: Pytester) -> None:
3279 pytester.makepyfile(
3280 """
3281 import pytest
3282 @pytest.fixture(params=[1,2], scope="class")
3283 def param1(request):
3284 return request.param
3285
3286 values = []
3287
3288 class TestClass(object):
3289 @pytest.fixture(scope="class", autouse=True)
3290 @classmethod
3291 def setup1(cls, request, param1):
3292 values.append(1)
3293 request.addfinalizer(cls.teardown1)
3294
3295 @classmethod
3296 def teardown1(self):
3297 assert values.pop() == 1
3298
3299 @pytest.fixture(scope="class", autouse=True)
3300 @classmethod
3301 def setup2(cls, request, param1):
3302 values.append(2)
3303 request.addfinalizer(cls.teardown2)
3304
3305 @classmethod
3306 def teardown2(cls):
3307 assert values.pop() == 2
3308
3309 def test(self):
3310 pass
3311
3312 def test_finish():
3313 assert not values
3314 """
3315 )
3316 result = pytester.runpytest("-v")
3317 result.stdout.fnmatch_lines(
3318 """
3319 *3 passed*
3320 """
3321 )
3322 assert result.ret == 0
3323
3324 def test_fixture_finalizer(self, pytester: Pytester) -> None:
3325 pytester.makeconftest(
3326 """
3327 import pytest
3328 import sys
3329
3330 @pytest.fixture
3331 def browser(request):
3332
3333 def finalize():
3334 sys.stdout.write_text('Finalized', encoding='utf-8')
3335 request.addfinalizer(finalize)
3336 return {}
3337 """
3338 )
3339 b = pytester.mkdir("subdir")
3340 b.joinpath("test_overridden_fixture_finalizer.py").write_text(
3341 textwrap.dedent(
3342 """\
3343 import pytest
3344 @pytest.fixture
3345 def browser(browser):
3346 browser['visited'] = True
3347 return browser
3348
3349 def test_browser(browser):
3350 assert browser['visited'] is True
3351 """
3352 ),
3353 encoding="utf-8",
3354 )
3355 reprec = pytester.runpytest("-s")
3356 for test in ["test_browser"]:
3357 reprec.stdout.fnmatch_lines(["*Finalized*"])
3358
3359 def test_class_scope_with_normal_tests(self, pytester: Pytester) -> None:
3360 testpath = pytester.makepyfile(
3361 """
3362 import pytest
3363
3364 class Box(object):
3365 value = 0
3366
3367 @pytest.fixture(scope='class')
3368 def a(request):
3369 Box.value += 1
3370 return Box.value
3371
3372 def test_a(a):
3373 assert a == 1
3374
3375 class Test1(object):
3376 def test_b(self, a):
3377 assert a == 2
3378
3379 class Test2(object):
3380 def test_c(self, a):
3381 assert a == 3"""
3382 )
3383 reprec = pytester.inline_run(testpath)
3384 for test in ["test_a", "test_b", "test_c"]:
3385 assert reprec.matchreport(test).passed
3386
3387 def test_request_is_clean(self, pytester: Pytester) -> None:
3388 pytester.makepyfile(
3389 """
3390 import pytest
3391 values = []
3392 @pytest.fixture(params=[1, 2])
3393 def fix(request):
3394 request.addfinalizer(lambda: values.append(request.param))
3395 def test_fix(fix):
3396 pass
3397 """
3398 )
3399 reprec = pytester.inline_run("-s")
3400 values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
3401 assert values == [1, 2]
3402
3403 def test_parametrize_separated_lifecycle(self, pytester: Pytester) -> None:
3404 pytester.makepyfile(
3405 """
3406 import pytest
3407
3408 values = []
3409 @pytest.fixture(scope="module", params=[1, 2])
3410 def arg(request):
3411 x = request.param
3412 request.addfinalizer(lambda: values.append("fin%s" % x))
3413 return request.param
3414 def test_1(arg):
3415 values.append(arg)
3416 def test_2(arg):
3417 values.append(arg)
3418 """
3419 )
3420 reprec = pytester.inline_run("-vs")
3421 reprec.assertoutcome(passed=4)
3422 values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
3423 import pprint
3424
3425 pprint.pprint(values)
3426 # assert len(values) == 6
3427 assert values[0] == values[1] == 1
3428 assert values[2] == "fin1"
3429 assert values[3] == values[4] == 2
3430 assert values[5] == "fin2"
3431
3432 def test_parametrize_function_scoped_finalizers_called(
3433 self, pytester: Pytester
3434 ) -> None:
3435 pytester.makepyfile(
3436 """
3437 import pytest
3438
3439 @pytest.fixture(scope="function", params=[1, 2])
3440 def arg(request):
3441 x = request.param
3442 request.addfinalizer(lambda: values.append("fin%s" % x))
3443 return request.param
3444
3445 values = []
3446 def test_1(arg):
3447 values.append(arg)
3448 def test_2(arg):
3449 values.append(arg)
3450 def test_3():
3451 assert len(values) == 8
3452 assert values == [1, "fin1", 2, "fin2", 1, "fin1", 2, "fin2"]
3453 """
3454 )
3455 reprec = pytester.inline_run("-v")
3456 reprec.assertoutcome(passed=5)
3457
3458 @pytest.mark.parametrize("scope", ["session", "function", "module"])
3459 def test_finalizer_order_on_parametrization(
3460 self, scope, pytester: Pytester
3461 ) -> None:
3462 """#246"""
3463 pytester.makepyfile(
3464 f"""
3465 import pytest
3466 values = []
3467
3468 @pytest.fixture(scope={scope!r}, params=["1"])
3469 def fix1(request):
3470 return request.param
3471
3472 @pytest.fixture(scope={scope!r})
3473 def fix2(request, base):
3474 def cleanup_fix2():
3475 assert not values, "base should not have been finalized"
3476 request.addfinalizer(cleanup_fix2)
3477
3478 @pytest.fixture(scope={scope!r})
3479 def base(request, fix1):
3480 def cleanup_base():
3481 values.append("fin_base")
3482 print("finalizing base")
3483 request.addfinalizer(cleanup_base)
3484
3485 def test_begin():
3486 pass
3487 def test_baz(base, fix2):
3488 pass
3489 def test_other():
3490 pass
3491 """
3492 )
3493 reprec = pytester.inline_run("-lvs")
3494 reprec.assertoutcome(passed=3)
3495
3496 def test_class_scope_parametrization_ordering(self, pytester: Pytester) -> None:
3497 """#396"""
3498 pytester.makepyfile(
3499 """
3500 import pytest
3501 values = []
3502 @pytest.fixture(params=["John", "Doe"], scope="class")
3503 def human(request):
3504 request.addfinalizer(lambda: values.append("fin %s" % request.param))
3505 return request.param
3506
3507 class TestGreetings(object):
3508 def test_hello(self, human):
3509 values.append("test_hello")
3510
3511 class TestMetrics(object):
3512 def test_name(self, human):
3513 values.append("test_name")
3514
3515 def test_population(self, human):
3516 values.append("test_population")
3517 """
3518 )
3519 reprec = pytester.inline_run()
3520 reprec.assertoutcome(passed=6)
3521 values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
3522 assert values == [
3523 "test_hello",
3524 "fin John",
3525 "test_hello",
3526 "fin Doe",
3527 "test_name",
3528 "test_population",
3529 "fin John",
3530 "test_name",
3531 "test_population",
3532 "fin Doe",
3533 ]
3534
3535 def test_parametrize_setup_function(self, pytester: Pytester) -> None:
3536 pytester.makepyfile(
3537 """
3538 import pytest
3539
3540 @pytest.fixture(scope="module", params=[1, 2])
3541 def arg(request):
3542 return request.param
3543
3544 @pytest.fixture(scope="module", autouse=True)
3545 def mysetup(request, arg):
3546 request.addfinalizer(lambda: values.append("fin%s" % arg))
3547 values.append("setup%s" % arg)
3548
3549 values = []
3550 def test_1(arg):
3551 values.append(arg)
3552 def test_2(arg):
3553 values.append(arg)
3554 def test_3():
3555 import pprint
3556 pprint.pprint(values)
3557 if arg == 1:
3558 assert values == ["setup1", 1, 1, ]
3559 elif arg == 2:
3560 assert values == ["setup1", 1, 1, "fin1",
3561 "setup2", 2, 2, ]
3562
3563 """
3564 )
3565 reprec = pytester.inline_run("-v")
3566 reprec.assertoutcome(passed=6)
3567
3568 def test_fixture_marked_function_not_collected_as_test(
3569 self, pytester: Pytester
3570 ) -> None:
3571 pytester.makepyfile(
3572 """
3573 import pytest
3574 @pytest.fixture
3575 def test_app():
3576 return 1
3577
3578 def test_something(test_app):
3579 assert test_app == 1
3580 """
3581 )
3582 reprec = pytester.inline_run()
3583 reprec.assertoutcome(passed=1)
3584
3585 def test_params_and_ids(self, pytester: Pytester) -> None:
3586 pytester.makepyfile(
3587 """
3588 import pytest
3589
3590 @pytest.fixture(params=[object(), object()],
3591 ids=['alpha', 'beta'])
3592 def fix(request):
3593 return request.param
3594
3595 def test_foo(fix):
3596 assert 1
3597 """
3598 )
3599 res = pytester.runpytest("-v")
3600 res.stdout.fnmatch_lines(["*test_foo*alpha*", "*test_foo*beta*"])
3601
3602 def test_params_and_ids_yieldfixture(self, pytester: Pytester) -> None:
3603 pytester.makepyfile(
3604 """
3605 import pytest
3606
3607 @pytest.fixture(params=[object(), object()], ids=['alpha', 'beta'])
3608 def fix(request):
3609 yield request.param
3610
3611 def test_foo(fix):
3612 assert 1
3613 """
3614 )
3615 res = pytester.runpytest("-v")
3616 res.stdout.fnmatch_lines(["*test_foo*alpha*", "*test_foo*beta*"])
3617
3618 def test_deterministic_fixture_collection(
3619 self, pytester: Pytester, monkeypatch
3620 ) -> None:
3621 """#920"""
3622 pytester.makepyfile(
3623 """
3624 import pytest
3625
3626 @pytest.fixture(scope="module",
3627 params=["A",
3628 "B",
3629 "C"])
3630 def A(request):
3631 return request.param
3632
3633 @pytest.fixture(scope="module",
3634 params=["DDDDDDDDD", "EEEEEEEEEEEE", "FFFFFFFFFFF", "banansda"])
3635 def B(request, A):
3636 return request.param
3637
3638 def test_foo(B):
3639 # Something funky is going on here.
3640 # Despite specified seeds, on what is collected,
3641 # sometimes we get unexpected passes. hashing B seems
3642 # to help?
3643 assert hash(B) or True
3644 """
3645 )
3646 monkeypatch.setenv("PYTHONHASHSEED", "1")
3647 out1 = pytester.runpytest_subprocess("-v")
3648 monkeypatch.setenv("PYTHONHASHSEED", "2")
3649 out2 = pytester.runpytest_subprocess("-v")
3650 output1 = [
3651 line
3652 for line in out1.outlines
3653 if line.startswith("test_deterministic_fixture_collection.py::test_foo")
3654 ]
3655 output2 = [
3656 line
3657 for line in out2.outlines
3658 if line.startswith("test_deterministic_fixture_collection.py::test_foo")
3659 ]
3660 assert len(output1) == 12
3661 assert output1 == output2
3662
3663
3664 class TestRequestScopeAccess:
3665 pytestmark = pytest.mark.parametrize(
3666 ("scope", "ok", "error"),
3667 [
3668 ["session", "", "path class function module"],
3669 ["module", "module path", "cls function"],
3670 ["class", "module path cls", "function"],
3671 ["function", "module path cls function", ""],
3672 ],
3673 )
3674
3675 def test_setup(self, pytester: Pytester, scope, ok, error) -> None:
3676 pytester.makepyfile(
3677 f"""
3678 import pytest
3679 @pytest.fixture(scope={scope!r}, autouse=True)
3680 def myscoped(request):
3681 for x in {ok.split()}:
3682 assert hasattr(request, x)
3683 for x in {error.split()}:
3684 with pytest.raises(AttributeError):
3685 getattr(request, x)
3686 assert request.session
3687 assert request.config
3688 def test_func():
3689 pass
3690 """
3691 )
3692 reprec = pytester.inline_run("-l")
3693 reprec.assertoutcome(passed=1)
3694
3695 def test_funcarg(self, pytester: Pytester, scope, ok, error) -> None:
3696 pytester.makepyfile(
3697 f"""
3698 import pytest
3699 @pytest.fixture(scope={scope!r})
3700 def arg(request):
3701 for x in {ok.split()!r}:
3702 assert hasattr(request, x)
3703 for x in {error.split()!r}:
3704 with pytest.raises(AttributeError):
3705 getattr(request, x)
3706 assert request.session
3707 assert request.config
3708 def test_func(arg):
3709 pass
3710 """
3711 )
3712 reprec = pytester.inline_run()
3713 reprec.assertoutcome(passed=1)
3714
3715
3716 class TestErrors:
3717 def test_subfactory_missing_funcarg(self, pytester: Pytester) -> None:
3718 pytester.makepyfile(
3719 """
3720 import pytest
3721 @pytest.fixture()
3722 def gen(qwe123):
3723 return 1
3724 def test_something(gen):
3725 pass
3726 """
3727 )
3728 result = pytester.runpytest()
3729 assert result.ret != 0
3730 result.stdout.fnmatch_lines(
3731 ["*def gen(qwe123):*", "*fixture*qwe123*not found*", "*1 error*"]
3732 )
3733
3734 def test_issue498_fixture_finalizer_failing(self, pytester: Pytester) -> None:
3735 pytester.makepyfile(
3736 """
3737 import pytest
3738 @pytest.fixture
3739 def fix1(request):
3740 def f():
3741 raise KeyError
3742 request.addfinalizer(f)
3743 return object()
3744
3745 values = []
3746 def test_1(fix1):
3747 values.append(fix1)
3748 def test_2(fix1):
3749 values.append(fix1)
3750 def test_3():
3751 assert values[0] != values[1]
3752 """
3753 )
3754 result = pytester.runpytest()
3755 result.stdout.fnmatch_lines(
3756 """
3757 *ERROR*teardown*test_1*
3758 *KeyError*
3759 *ERROR*teardown*test_2*
3760 *KeyError*
3761 *3 pass*2 errors*
3762 """
3763 )
3764
3765 def test_setupfunc_missing_funcarg(self, pytester: Pytester) -> None:
3766 pytester.makepyfile(
3767 """
3768 import pytest
3769 @pytest.fixture(autouse=True)
3770 def gen(qwe123):
3771 return 1
3772 def test_something():
3773 pass
3774 """
3775 )
3776 result = pytester.runpytest()
3777 assert result.ret != 0
3778 result.stdout.fnmatch_lines(
3779 ["*def gen(qwe123):*", "*fixture*qwe123*not found*", "*1 error*"]
3780 )
3781
3782 def test_cached_exception_doesnt_get_longer(self, pytester: Pytester) -> None:
3783 """Regression test for #12204."""
3784 pytester.makepyfile(
3785 """
3786 import pytest
3787 @pytest.fixture(scope="session")
3788 def bad(): 1 / 0
3789
3790 def test_1(bad): pass
3791 def test_2(bad): pass
3792 def test_3(bad): pass
3793 """
3794 )
3795
3796 result = pytester.runpytest_inprocess("--tb=native")
3797 assert result.ret == ExitCode.TESTS_FAILED
3798 failures = result.reprec.getfailures() # type: ignore[attr-defined]
3799 assert len(failures) == 3
3800 lines1 = failures[1].longrepr.reprtraceback.reprentries[0].lines
3801 lines2 = failures[2].longrepr.reprtraceback.reprentries[0].lines
3802 assert len(lines1) == len(lines2)
3803
3804
3805 class TestShowFixtures:
3806 def test_funcarg_compat(self, pytester: Pytester) -> None:
3807 config = pytester.parseconfigure("--funcargs")
3808 assert config.option.showfixtures
3809
3810 def test_show_help(self, pytester: Pytester) -> None:
3811 result = pytester.runpytest("--fixtures", "--help")
3812 assert not result.ret
3813
3814 def test_show_fixtures(self, pytester: Pytester) -> None:
3815 result = pytester.runpytest("--fixtures")
3816 result.stdout.fnmatch_lines(
3817 [
3818 "tmp_path_factory [[]session scope[]] -- .../_pytest/tmpdir.py:*",
3819 "*for the test session*",
3820 "tmp_path -- .../_pytest/tmpdir.py:*",
3821 "*temporary directory*",
3822 ]
3823 )
3824
3825 def test_show_fixtures_verbose(self, pytester: Pytester) -> None:
3826 result = pytester.runpytest("--fixtures", "-v")
3827 result.stdout.fnmatch_lines(
3828 [
3829 "tmp_path_factory [[]session scope[]] -- .../_pytest/tmpdir.py:*",
3830 "*for the test session*",
3831 "tmp_path -- .../_pytest/tmpdir.py:*",
3832 "*temporary directory*",
3833 ]
3834 )
3835
3836 def test_show_fixtures_testmodule(self, pytester: Pytester) -> None:
3837 p = pytester.makepyfile(
3838 '''
3839 import pytest
3840 @pytest.fixture
3841 def _arg0():
3842 """ hidden """
3843 @pytest.fixture
3844 def arg1():
3845 """ hello world """
3846 '''
3847 )
3848 result = pytester.runpytest("--fixtures", p)
3849 result.stdout.fnmatch_lines(
3850 """
3851 *tmp_path -- *
3852 *fixtures defined from*
3853 *arg1 -- test_show_fixtures_testmodule.py:6*
3854 *hello world*
3855 """
3856 )
3857 result.stdout.no_fnmatch_line("*arg0*")
3858
3859 @pytest.mark.parametrize("testmod", [True, False])
3860 def test_show_fixtures_conftest(self, pytester: Pytester, testmod) -> None:
3861 pytester.makeconftest(
3862 '''
3863 import pytest
3864 @pytest.fixture
3865 def arg1():
3866 """ hello world """
3867 '''
3868 )
3869 if testmod:
3870 pytester.makepyfile(
3871 """
3872 def test_hello():
3873 pass
3874 """
3875 )
3876 result = pytester.runpytest("--fixtures")
3877 result.stdout.fnmatch_lines(
3878 """
3879 *tmp_path*
3880 *fixtures defined from*conftest*
3881 *arg1*
3882 *hello world*
3883 """
3884 )
3885
3886 def test_show_fixtures_trimmed_doc(self, pytester: Pytester) -> None:
3887 p = pytester.makepyfile(
3888 textwrap.dedent(
3889 '''\
3890 import pytest
3891 @pytest.fixture
3892 def arg1():
3893 """
3894 line1
3895 line2
3896
3897 """
3898 @pytest.fixture
3899 def arg2():
3900 """
3901 line1
3902 line2
3903
3904 """
3905 '''
3906 )
3907 )
3908 result = pytester.runpytest("--fixtures", p)
3909 result.stdout.fnmatch_lines(
3910 textwrap.dedent(
3911 """\
3912 * fixtures defined from test_show_fixtures_trimmed_doc *
3913 arg2 -- test_show_fixtures_trimmed_doc.py:10
3914 line1
3915 line2
3916 arg1 -- test_show_fixtures_trimmed_doc.py:3
3917 line1
3918 line2
3919 """
3920 )
3921 )
3922
3923 def test_show_fixtures_indented_doc(self, pytester: Pytester) -> None:
3924 p = pytester.makepyfile(
3925 textwrap.dedent(
3926 '''\
3927 import pytest
3928 @pytest.fixture
3929 def fixture1():
3930 """
3931 line1
3932 indented line
3933 """
3934 '''
3935 )
3936 )
3937 result = pytester.runpytest("--fixtures", p)
3938 result.stdout.fnmatch_lines(
3939 textwrap.dedent(
3940 """\
3941 * fixtures defined from test_show_fixtures_indented_doc *
3942 fixture1 -- test_show_fixtures_indented_doc.py:3
3943 line1
3944 indented line
3945 """
3946 )
3947 )
3948
3949 def test_show_fixtures_indented_doc_first_line_unindented(
3950 self, pytester: Pytester
3951 ) -> None:
3952 p = pytester.makepyfile(
3953 textwrap.dedent(
3954 '''\
3955 import pytest
3956 @pytest.fixture
3957 def fixture1():
3958 """line1
3959 line2
3960 indented line
3961 """
3962 '''
3963 )
3964 )
3965 result = pytester.runpytest("--fixtures", p)
3966 result.stdout.fnmatch_lines(
3967 textwrap.dedent(
3968 """\
3969 * fixtures defined from test_show_fixtures_indented_doc_first_line_unindented *
3970 fixture1 -- test_show_fixtures_indented_doc_first_line_unindented.py:3
3971 line1
3972 line2
3973 indented line
3974 """
3975 )
3976 )
3977
3978 def test_show_fixtures_indented_in_class(self, pytester: Pytester) -> None:
3979 p = pytester.makepyfile(
3980 textwrap.dedent(
3981 '''\
3982 import pytest
3983 class TestClass(object):
3984 @pytest.fixture
3985 def fixture1(self):
3986 """line1
3987 line2
3988 indented line
3989 """
3990 '''
3991 )
3992 )
3993 result = pytester.runpytest("--fixtures", p)
3994 result.stdout.fnmatch_lines(
3995 textwrap.dedent(
3996 """\
3997 * fixtures defined from test_show_fixtures_indented_in_class *
3998 fixture1 -- test_show_fixtures_indented_in_class.py:4
3999 line1
4000 line2
4001 indented line
4002 """
4003 )
4004 )
4005
4006 def test_show_fixtures_different_files(self, pytester: Pytester) -> None:
4007 """`--fixtures` only shows fixtures from first file (#833)."""
4008 pytester.makepyfile(
4009 test_a='''
4010 import pytest
4011
4012 @pytest.fixture
4013 def fix_a():
4014 """Fixture A"""
4015 pass
4016
4017 def test_a(fix_a):
4018 pass
4019 '''
4020 )
4021 pytester.makepyfile(
4022 test_b='''
4023 import pytest
4024
4025 @pytest.fixture
4026 def fix_b():
4027 """Fixture B"""
4028 pass
4029
4030 def test_b(fix_b):
4031 pass
4032 '''
4033 )
4034 result = pytester.runpytest("--fixtures")
4035 result.stdout.fnmatch_lines(
4036 """
4037 * fixtures defined from test_a *
4038 fix_a -- test_a.py:4
4039 Fixture A
4040
4041 * fixtures defined from test_b *
4042 fix_b -- test_b.py:4
4043 Fixture B
4044 """
4045 )
4046
4047 def test_show_fixtures_with_same_name(self, pytester: Pytester) -> None:
4048 pytester.makeconftest(
4049 '''
4050 import pytest
4051 @pytest.fixture
4052 def arg1():
4053 """Hello World in conftest.py"""
4054 return "Hello World"
4055 '''
4056 )
4057 pytester.makepyfile(
4058 """
4059 def test_foo(arg1):
4060 assert arg1 == "Hello World"
4061 """
4062 )
4063 pytester.makepyfile(
4064 '''
4065 import pytest
4066 @pytest.fixture
4067 def arg1():
4068 """Hi from test module"""
4069 return "Hi"
4070 def test_bar(arg1):
4071 assert arg1 == "Hi"
4072 '''
4073 )
4074 result = pytester.runpytest("--fixtures")
4075 result.stdout.fnmatch_lines(
4076 """
4077 * fixtures defined from conftest *
4078 arg1 -- conftest.py:3
4079 Hello World in conftest.py
4080
4081 * fixtures defined from test_show_fixtures_with_same_name *
4082 arg1 -- test_show_fixtures_with_same_name.py:3
4083 Hi from test module
4084 """
4085 )
4086
4087 def test_fixture_disallow_twice(self):
4088 """Test that applying @pytest.fixture twice generates an error (#2334)."""
4089 with pytest.raises(ValueError):
4090
4091 @pytest.fixture
4092 @pytest.fixture
4093 def foo():
4094 raise NotImplementedError()
4095
4096
4097 class TestContextManagerFixtureFuncs:
4098 def test_simple(self, pytester: Pytester) -> None:
4099 pytester.makepyfile(
4100 """
4101 import pytest
4102 @pytest.fixture
4103 def arg1():
4104 print("setup")
4105 yield 1
4106 print("teardown")
4107 def test_1(arg1):
4108 print("test1", arg1)
4109 def test_2(arg1):
4110 print("test2", arg1)
4111 assert 0
4112 """
4113 )
4114 result = pytester.runpytest("-s")
4115 result.stdout.fnmatch_lines(
4116 """
4117 *setup*
4118 *test1 1*
4119 *teardown*
4120 *setup*
4121 *test2 1*
4122 *teardown*
4123 """
4124 )
4125
4126 def test_scoped(self, pytester: Pytester) -> None:
4127 pytester.makepyfile(
4128 """
4129 import pytest
4130 @pytest.fixture(scope="module")
4131 def arg1():
4132 print("setup")
4133 yield 1
4134 print("teardown")
4135 def test_1(arg1):
4136 print("test1", arg1)
4137 def test_2(arg1):
4138 print("test2", arg1)
4139 """
4140 )
4141 result = pytester.runpytest("-s")
4142 result.stdout.fnmatch_lines(
4143 """
4144 *setup*
4145 *test1 1*
4146 *test2 1*
4147 *teardown*
4148 """
4149 )
4150
4151 def test_setup_exception(self, pytester: Pytester) -> None:
4152 pytester.makepyfile(
4153 """
4154 import pytest
4155 @pytest.fixture(scope="module")
4156 def arg1():
4157 pytest.fail("setup")
4158 yield 1
4159 def test_1(arg1):
4160 pass
4161 """
4162 )
4163 result = pytester.runpytest("-s")
4164 result.stdout.fnmatch_lines(
4165 """
4166 *pytest.fail*setup*
4167 *1 error*
4168 """
4169 )
4170
4171 def test_teardown_exception(self, pytester: Pytester) -> None:
4172 pytester.makepyfile(
4173 """
4174 import pytest
4175 @pytest.fixture(scope="module")
4176 def arg1():
4177 yield 1
4178 pytest.fail("teardown")
4179 def test_1(arg1):
4180 pass
4181 """
4182 )
4183 result = pytester.runpytest("-s")
4184 result.stdout.fnmatch_lines(
4185 """
4186 *pytest.fail*teardown*
4187 *1 passed*1 error*
4188 """
4189 )
4190
4191 def test_yields_more_than_one(self, pytester: Pytester) -> None:
4192 pytester.makepyfile(
4193 """
4194 import pytest
4195 @pytest.fixture(scope="module")
4196 def arg1():
4197 yield 1
4198 yield 2
4199 def test_1(arg1):
4200 pass
4201 """
4202 )
4203 result = pytester.runpytest("-s")
4204 result.stdout.fnmatch_lines(
4205 """
4206 *fixture function*
4207 *test_yields*:2*
4208 """
4209 )
4210
4211 def test_custom_name(self, pytester: Pytester) -> None:
4212 pytester.makepyfile(
4213 """
4214 import pytest
4215 @pytest.fixture(name='meow')
4216 def arg1():
4217 return 'mew'
4218 def test_1(meow):
4219 print(meow)
4220 """
4221 )
4222 result = pytester.runpytest("-s")
4223 result.stdout.fnmatch_lines(["*mew*"])
4224
4225
4226 class TestParameterizedSubRequest:
4227 def test_call_from_fixture(self, pytester: Pytester) -> None:
4228 pytester.makepyfile(
4229 test_call_from_fixture="""
4230 import pytest
4231
4232 @pytest.fixture(params=[0, 1, 2])
4233 def fix_with_param(request):
4234 return request.param
4235
4236 @pytest.fixture
4237 def get_named_fixture(request):
4238 return request.getfixturevalue('fix_with_param')
4239
4240 def test_foo(request, get_named_fixture):
4241 pass
4242 """
4243 )
4244 result = pytester.runpytest()
4245 result.stdout.fnmatch_lines(
4246 [
4247 "The requested fixture has no parameter defined for test:",
4248 " test_call_from_fixture.py::test_foo",
4249 "Requested fixture 'fix_with_param' defined in:",
4250 "test_call_from_fixture.py:4",
4251 "Requested here:",
4252 "test_call_from_fixture.py:9",
4253 "*1 error in*",
4254 ]
4255 )
4256
4257 def test_call_from_test(self, pytester: Pytester) -> None:
4258 pytester.makepyfile(
4259 test_call_from_test="""
4260 import pytest
4261
4262 @pytest.fixture(params=[0, 1, 2])
4263 def fix_with_param(request):
4264 return request.param
4265
4266 def test_foo(request):
4267 request.getfixturevalue('fix_with_param')
4268 """
4269 )
4270 result = pytester.runpytest()
4271 result.stdout.fnmatch_lines(
4272 [
4273 "The requested fixture has no parameter defined for test:",
4274 " test_call_from_test.py::test_foo",
4275 "Requested fixture 'fix_with_param' defined in:",
4276 "test_call_from_test.py:4",
4277 "Requested here:",
4278 "test_call_from_test.py:8",
4279 "*1 failed*",
4280 ]
4281 )
4282
4283 def test_external_fixture(self, pytester: Pytester) -> None:
4284 pytester.makeconftest(
4285 """
4286 import pytest
4287
4288 @pytest.fixture(params=[0, 1, 2])
4289 def fix_with_param(request):
4290 return request.param
4291 """
4292 )
4293
4294 pytester.makepyfile(
4295 test_external_fixture="""
4296 def test_foo(request):
4297 request.getfixturevalue('fix_with_param')
4298 """
4299 )
4300 result = pytester.runpytest()
4301 result.stdout.fnmatch_lines(
4302 [
4303 "The requested fixture has no parameter defined for test:",
4304 " test_external_fixture.py::test_foo",
4305 "",
4306 "Requested fixture 'fix_with_param' defined in:",
4307 "conftest.py:4",
4308 "Requested here:",
4309 "test_external_fixture.py:2",
4310 "*1 failed*",
4311 ]
4312 )
4313
4314 def test_non_relative_path(self, pytester: Pytester) -> None:
4315 tests_dir = pytester.mkdir("tests")
4316 fixdir = pytester.mkdir("fixtures")
4317 fixfile = fixdir.joinpath("fix.py")
4318 fixfile.write_text(
4319 textwrap.dedent(
4320 """\
4321 import pytest
4322
4323 @pytest.fixture(params=[0, 1, 2])
4324 def fix_with_param(request):
4325 return request.param
4326 """
4327 ),
4328 encoding="utf-8",
4329 )
4330
4331 testfile = tests_dir.joinpath("test_foos.py")
4332 testfile.write_text(
4333 textwrap.dedent(
4334 """\
4335 from fix import fix_with_param
4336
4337 def test_foo(request):
4338 request.getfixturevalue('fix_with_param')
4339 """
4340 ),
4341 encoding="utf-8",
4342 )
4343
4344 os.chdir(tests_dir)
4345 pytester.syspathinsert(fixdir)
4346 result = pytester.runpytest()
4347 result.stdout.fnmatch_lines(
4348 [
4349 "The requested fixture has no parameter defined for test:",
4350 " test_foos.py::test_foo",
4351 "",
4352 "Requested fixture 'fix_with_param' defined in:",
4353 f"{fixfile}:4",
4354 "Requested here:",
4355 "test_foos.py:4",
4356 "*1 failed*",
4357 ]
4358 )
4359
4360 # With non-overlapping rootdir, passing tests_dir.
4361 rootdir = pytester.mkdir("rootdir")
4362 os.chdir(rootdir)
4363 result = pytester.runpytest("--rootdir", rootdir, tests_dir)
4364 result.stdout.fnmatch_lines(
4365 [
4366 "The requested fixture has no parameter defined for test:",
4367 " test_foos.py::test_foo",
4368 "",
4369 "Requested fixture 'fix_with_param' defined in:",
4370 f"{fixfile}:4",
4371 "Requested here:",
4372 f"{testfile}:4",
4373 "*1 failed*",
4374 ]
4375 )
4376
4377
4378 def test_pytest_fixture_setup_and_post_finalizer_hook(pytester: Pytester) -> None:
4379 pytester.makeconftest(
4380 """
4381 def pytest_fixture_setup(fixturedef, request):
4382 print('ROOT setup hook called for {0} from {1}'.format(fixturedef.argname, request.node.name))
4383 def pytest_fixture_post_finalizer(fixturedef, request):
4384 print('ROOT finalizer hook called for {0} from {1}'.format(fixturedef.argname, request.node.name))
4385 """
4386 )
4387 pytester.makepyfile(
4388 **{
4389 "tests/conftest.py": """
4390 def pytest_fixture_setup(fixturedef, request):
4391 print('TESTS setup hook called for {0} from {1}'.format(fixturedef.argname, request.node.name))
4392 def pytest_fixture_post_finalizer(fixturedef, request):
4393 print('TESTS finalizer hook called for {0} from {1}'.format(fixturedef.argname, request.node.name))
4394 """,
4395 "tests/test_hooks.py": """
4396 import pytest
4397
4398 @pytest.fixture()
4399 def my_fixture():
4400 return 'some'
4401
4402 def test_func(my_fixture):
4403 print('TEST test_func')
4404 assert my_fixture == 'some'
4405 """,
4406 }
4407 )
4408 result = pytester.runpytest("-s")
4409 assert result.ret == 0
4410 result.stdout.fnmatch_lines(
4411 [
4412 "*TESTS setup hook called for my_fixture from test_func*",
4413 "*ROOT setup hook called for my_fixture from test_func*",
4414 "*TEST test_func*",
4415 "*TESTS finalizer hook called for my_fixture from test_func*",
4416 "*ROOT finalizer hook called for my_fixture from test_func*",
4417 ]
4418 )
4419
4420
4421 def test_fixture_post_finalizer_called_once(pytester: Pytester) -> None:
4422 """Test that pytest_fixture_post_finalizer is called only once per fixture teardown.
4423
4424 When a fixture depends on multiple parametrized fixtures and all their parameters
4425 change at the same time, the dependent fixture should be torn down only once,
4426 and pytest_fixture_post_finalizer should be called only once for it.
4427 """
4428 pytester.makeconftest(
4429 """
4430 import pytest
4431
4432 finalizer_calls = []
4433
4434 def pytest_fixture_post_finalizer(fixturedef, request):
4435 finalizer_calls.append(fixturedef.argname)
4436
4437 @pytest.fixture(autouse=True)
4438 def check_finalizer_calls(request):
4439 yield
4440 # After each test, verify no duplicate finalizer calls.
4441 if finalizer_calls:
4442 assert len(finalizer_calls) == len(set(finalizer_calls)), (
4443 f"Duplicate finalizer calls detected: {finalizer_calls}"
4444 )
4445 finalizer_calls.clear()
4446 """
4447 )
4448 pytester.makepyfile(
4449 test_fixtures="""
4450 import pytest
4451
4452 @pytest.fixture(scope="session")
4453 def foo(request):
4454 return request.param
4455
4456 @pytest.fixture(scope="session")
4457 def bar(request):
4458 return request.param
4459
4460 @pytest.fixture(scope="session")
4461 def baz(foo, bar):
4462 return f"{foo}-{bar}"
4463
4464 @pytest.mark.parametrize("foo,bar", [(1, 1)], indirect=True)
4465 def test_first(foo, bar, baz):
4466 assert foo == 1
4467 assert bar == 1
4468 assert baz == "1-1"
4469
4470 @pytest.mark.parametrize("foo,bar", [(2, 2)], indirect=True)
4471 def test_second(foo, bar, baz):
4472 assert foo == 2
4473 assert bar == 2
4474 assert baz == "2-2"
4475 """
4476 )
4477 result = pytester.runpytest("-v")
4478 # The test passes, which means no duplicate finalizer calls were detected
4479 # by the check_finalizer_calls autouse fixture.
4480 result.assert_outcomes(passed=2)
4481
4482
4483 def test_fixture_post_finalizer_hook_exception(pytester: Pytester) -> None:
4484 """Test that exceptions in pytest_fixture_post_finalizer hook are caught.
4485
4486 Also verifies that the fixture cache is properly reset even when the
4487 post_finalizer hook raises an exception, so the fixture can be rebuilt
4488 in subsequent tests.
4489 """
4490 pytester.makeconftest(
4491 """
4492 import pytest
4493
4494 def pytest_fixture_post_finalizer(fixturedef, request):
4495 if "test_first" in request.node.nodeid:
4496 raise RuntimeError("Error in post finalizer hook")
4497
4498 @pytest.fixture
4499 def my_fixture(request):
4500 yield request.node.nodeid
4501 """
4502 )
4503 pytester.makepyfile(
4504 test_fixtures="""
4505 def test_first(my_fixture):
4506 assert "test_first" in my_fixture
4507
4508 def test_second(my_fixture):
4509 assert "test_second" in my_fixture
4510 """
4511 )
4512 result = pytester.runpytest("-v", "--setup-show")
4513 result.assert_outcomes(passed=2, errors=1)
4514 result.stdout.fnmatch_lines(
4515 [
4516 "*test_first*PASSED",
4517 "*test_first*ERROR",
4518 "*RuntimeError: Error in post finalizer hook*",
4519 ]
4520 )
4521 # Verify fixture is setup twice (rebuilt for test_second despite error).
4522 result.stdout.fnmatch_lines(
4523 [
4524 "test_fixtures.py::test_first ",
4525 " SETUP F my_fixture",
4526 " test_fixtures.py::test_first (fixtures used: my_fixture, request) PASSED",
4527 "test_fixtures.py::test_first ERROR",
4528 "test_fixtures.py::test_second ",
4529 " SETUP F my_fixture",
4530 " test_fixtures.py::test_second (fixtures used: my_fixture, request) PASSED",
4531 " TEARDOWN F my_fixture",
4532 ],
4533 consecutive=True,
4534 )
4535
4536
4537 class TestScopeOrdering:
4538 """Class of tests that ensure fixtures are ordered based on their scopes (#2405)"""
4539
4540 @pytest.mark.parametrize("variant", ["mark", "autouse"])
4541 def test_func_closure_module_auto(
4542 self, pytester: Pytester, variant, monkeypatch
4543 ) -> None:
4544 """Semantically identical to the example posted in #2405 when ``use_mark=True``"""
4545 monkeypatch.setenv("FIXTURE_ACTIVATION_VARIANT", variant)
4546 pytester.makepyfile(
4547 """
4548 import warnings
4549 import os
4550 import pytest
4551 VAR = 'FIXTURE_ACTIVATION_VARIANT'
4552 VALID_VARS = ('autouse', 'mark')
4553
4554 VARIANT = os.environ.get(VAR)
4555 if VARIANT is None or VARIANT not in VALID_VARS:
4556 warnings.warn("{!r} is not in {}, assuming autouse".format(VARIANT, VALID_VARS) )
4557 variant = 'mark'
4558
4559 @pytest.fixture(scope='module', autouse=VARIANT == 'autouse')
4560 def m1(): pass
4561
4562 if VARIANT=='mark':
4563 pytestmark = pytest.mark.usefixtures('m1')
4564
4565 @pytest.fixture(scope='function', autouse=True)
4566 def f1(): pass
4567
4568 def test_func(m1):
4569 pass
4570 """
4571 )
4572 items, _ = pytester.inline_genitems()
4573 assert isinstance(items[0], Function)
4574 request = TopRequest(items[0], _ispytest=True)
4575 assert request.fixturenames == "m1 f1".split()
4576
4577 def test_func_closure_with_native_fixtures(self, pytester: Pytester) -> None:
4578 """Sanity check that verifies the order returned by the closures and the
4579 actual fixture execution order: the execution order may differ because
4580 of fixture inter-dependencies."""
4581 pytester.makepyfile(
4582 """
4583 import pytest
4584
4585 fixture_order = []
4586
4587 @pytest.fixture(scope="session")
4588 def s1():
4589 fixture_order.append("s1")
4590
4591 @pytest.fixture(scope="package")
4592 def p1():
4593 fixture_order.append("p1")
4594
4595 @pytest.fixture(scope="module")
4596 def m1():
4597 fixture_order.append("m1")
4598
4599 @pytest.fixture(scope="session")
4600 def my_tmp_path_factory():
4601 fixture_order.append("my_tmp_path_factory")
4602
4603 @pytest.fixture
4604 def my_tmp_path(my_tmp_path_factory):
4605 fixture_order.append("my_tmp_path")
4606
4607 @pytest.fixture
4608 def f1(my_tmp_path):
4609 fixture_order.append("f1")
4610
4611 @pytest.fixture
4612 def f2():
4613 fixture_order.append("f2")
4614
4615 def test_foo(f1, p1, m1, f2, s1):
4616 # Actual fixture execution differs from static order: dependent
4617 # fixtures must be created first ("my_tmp_path").
4618 assert fixture_order == [
4619 "my_tmp_path_factory",
4620 "s1",
4621 "p1",
4622 "m1",
4623 "my_tmp_path",
4624 "f1",
4625 "f2",
4626 ]
4627 """
4628 )
4629 items, _ = pytester.inline_genitems()
4630 assert isinstance(items[0], Function)
4631 request = TopRequest(items[0], _ispytest=True)
4632 # Static order of fixtures based on their scope and position in the
4633 # parameter list.
4634 assert request.fixturenames == [
4635 "my_tmp_path_factory",
4636 "s1",
4637 "p1",
4638 "m1",
4639 "f1",
4640 "my_tmp_path",
4641 "f2",
4642 ]
4643 result = pytester.runpytest("-vv")
4644 result.assert_outcomes(passed=1)
4645
4646 def test_func_closure_module(self, pytester: Pytester) -> None:
4647 pytester.makepyfile(
4648 """
4649 import pytest
4650
4651 @pytest.fixture(scope='module')
4652 def m1(): pass
4653
4654 @pytest.fixture(scope='function')
4655 def f1(): pass
4656
4657 def test_func(f1, m1):
4658 pass
4659 """
4660 )
4661 items, _ = pytester.inline_genitems()
4662 assert isinstance(items[0], Function)
4663 request = TopRequest(items[0], _ispytest=True)
4664 assert request.fixturenames == "m1 f1".split()
4665
4666 def test_func_closure_scopes_reordered(self, pytester: Pytester) -> None:
4667 """Test ensures that fixtures are ordered by scope regardless of the order of the parameters, although
4668 fixtures of same scope keep the declared order
4669 """
4670 pytester.makepyfile(
4671 """
4672 import pytest
4673
4674 @pytest.fixture(scope='session')
4675 def s1(): pass
4676
4677 @pytest.fixture(scope='module')
4678 def m1(): pass
4679
4680 @pytest.fixture(scope='function')
4681 def f1(): pass
4682
4683 @pytest.fixture(scope='function')
4684 def f2(): pass
4685
4686 class Test:
4687
4688 @pytest.fixture(scope='class')
4689 def c1(cls): pass
4690
4691 def test_func(self, f2, f1, c1, m1, s1):
4692 pass
4693 """
4694 )
4695 items, _ = pytester.inline_genitems()
4696 assert isinstance(items[0], Function)
4697 request = TopRequest(items[0], _ispytest=True)
4698 assert request.fixturenames == "s1 m1 c1 f2 f1".split()
4699
4700 def test_func_closure_same_scope_closer_root_first(
4701 self, pytester: Pytester
4702 ) -> None:
4703 """Auto-use fixtures of same scope are ordered by closer-to-root first"""
4704 pytester.makeconftest(
4705 """
4706 import pytest
4707
4708 @pytest.fixture(scope='module', autouse=True)
4709 def m_conf(): pass
4710 """
4711 )
4712 pytester.makepyfile(
4713 **{
4714 "sub/conftest.py": """
4715 import pytest
4716
4717 @pytest.fixture(scope='package', autouse=True)
4718 def p_sub(): pass
4719
4720 @pytest.fixture(scope='module', autouse=True)
4721 def m_sub(): pass
4722 """,
4723 "sub/__init__.py": "",
4724 "sub/test_func.py": """
4725 import pytest
4726
4727 @pytest.fixture(scope='module', autouse=True)
4728 def m_test(): pass
4729
4730 @pytest.fixture(scope='function')
4731 def f1(): pass
4732
4733 def test_func(m_test, f1):
4734 pass
4735 """,
4736 }
4737 )
4738 items, _ = pytester.inline_genitems()
4739 assert isinstance(items[0], Function)
4740 request = TopRequest(items[0], _ispytest=True)
4741 assert request.fixturenames == "p_sub m_conf m_sub m_test f1".split()
4742
4743 def test_func_closure_all_scopes_complex(self, pytester: Pytester) -> None:
4744 """Complex test involving all scopes and mixing autouse with normal fixtures"""
4745 pytester.makeconftest(
4746 """
4747 import pytest
4748
4749 @pytest.fixture(scope='session')
4750 def s1(): pass
4751
4752 @pytest.fixture(scope='package', autouse=True)
4753 def p1(): pass
4754 """
4755 )
4756 pytester.makepyfile(**{"__init__.py": ""})
4757 pytester.makepyfile(
4758 """
4759 import pytest
4760
4761 @pytest.fixture(scope='module', autouse=True)
4762 def m1(): pass
4763
4764 @pytest.fixture(scope='module')
4765 def m2(s1): pass
4766
4767 @pytest.fixture(scope='function')
4768 def f1(): pass
4769
4770 @pytest.fixture(scope='function')
4771 def f2(): pass
4772
4773 class Test:
4774
4775 @pytest.fixture(scope='class', autouse=True)
4776 def c1(self):
4777 pass
4778
4779 def test_func(self, f2, f1, m2):
4780 pass
4781 """
4782 )
4783 items, _ = pytester.inline_genitems()
4784 assert isinstance(items[0], Function)
4785 request = TopRequest(items[0], _ispytest=True)
4786 assert request.fixturenames == "s1 p1 m1 m2 c1 f2 f1".split()
4787
4788 def test_parametrized_package_scope_reordering(self, pytester: Pytester) -> None:
4789 """A parameterized package-scoped fixture correctly reorders items to
4790 minimize setups & teardowns.
4791
4792 Regression test for #12328.
4793 """
4794 pytester.makepyfile(
4795 __init__="",
4796 conftest="""
4797 import pytest
4798 @pytest.fixture(scope="package", params=["a", "b"])
4799 def fix(request):
4800 return request.param
4801 """,
4802 test_1="def test1(fix): pass",
4803 test_2="def test2(fix): pass",
4804 )
4805
4806 result = pytester.runpytest("--setup-plan")
4807 assert result.ret == ExitCode.OK
4808 result.stdout.fnmatch_lines(
4809 [
4810 " SETUP P fix['a']",
4811 " test_1.py::test1[a] (fixtures used: fix, request)",
4812 " test_2.py::test2[a] (fixtures used: fix, request)",
4813 " TEARDOWN P fix['a']",
4814 " SETUP P fix['b']",
4815 " test_1.py::test1[b] (fixtures used: fix, request)",
4816 " test_2.py::test2[b] (fixtures used: fix, request)",
4817 " TEARDOWN P fix['b']",
4818 ],
4819 )
4820
4821 def test_multiple_packages(self, pytester: Pytester) -> None:
4822 """Complex test involving multiple package fixtures. Make sure teardowns
4823 are executed in order.
4824 .
4825 └── root
4826 ├── __init__.py
4827 ├── sub1
4828 │ ├── __init__.py
4829 │ ├── conftest.py
4830 │ └── test_1.py
4831 └── sub2
4832 ├── __init__.py
4833 ├── conftest.py
4834 └── test_2.py
4835 """
4836 root = pytester.mkdir("root")
4837 root.joinpath("__init__.py").write_text("values = []", encoding="utf-8")
4838 sub1 = root.joinpath("sub1")
4839 sub1.mkdir()
4840 sub1.joinpath("__init__.py").touch()
4841 sub1.joinpath("conftest.py").write_text(
4842 textwrap.dedent(
4843 """\
4844 import pytest
4845 from .. import values
4846 @pytest.fixture(scope="package")
4847 def fix():
4848 values.append("pre-sub1")
4849 yield values
4850 assert values.pop() == "pre-sub1"
4851 """
4852 ),
4853 encoding="utf-8",
4854 )
4855 sub1.joinpath("test_1.py").write_text(
4856 textwrap.dedent(
4857 """\
4858 from .. import values
4859 def test_1(fix):
4860 assert values == ["pre-sub1"]
4861 """
4862 ),
4863 encoding="utf-8",
4864 )
4865 sub2 = root.joinpath("sub2")
4866 sub2.mkdir()
4867 sub2.joinpath("__init__.py").touch()
4868 sub2.joinpath("conftest.py").write_text(
4869 textwrap.dedent(
4870 """\
4871 import pytest
4872 from .. import values
4873 @pytest.fixture(scope="package")
4874 def fix():
4875 values.append("pre-sub2")
4876 yield values
4877 assert values.pop() == "pre-sub2"
4878 """
4879 ),
4880 encoding="utf-8",
4881 )
4882 sub2.joinpath("test_2.py").write_text(
4883 textwrap.dedent(
4884 """\
4885 from .. import values
4886 def test_2(fix):
4887 assert values == ["pre-sub2"]
4888 """
4889 ),
4890 encoding="utf-8",
4891 )
4892 reprec = pytester.inline_run()
4893 reprec.assertoutcome(passed=2)
4894
4895 def test_class_fixture_self_instance(self, pytester: Pytester) -> None:
4896 """Check that plugin classes which implement fixtures receive the plugin instance
4897 as self (see #2270).
4898 """
4899 pytester.makeconftest(
4900 """
4901 import pytest
4902
4903 def pytest_configure(config):
4904 config.pluginmanager.register(MyPlugin())
4905
4906 class MyPlugin():
4907 def __init__(self):
4908 self.arg = 1
4909
4910 @pytest.fixture(scope='function')
4911 def myfix(self):
4912 assert isinstance(self, MyPlugin)
4913 return self.arg
4914 """
4915 )
4916
4917 pytester.makepyfile(
4918 """
4919 class TestClass(object):
4920 def test_1(self, myfix):
4921 assert myfix == 1
4922 """
4923 )
4924 reprec = pytester.inline_run()
4925 reprec.assertoutcome(passed=1)
4926
4927
4928 def test_call_fixture_function_error():
4929 """Check if an error is raised if a fixture function is called directly (#4545)"""
4930
4931 @pytest.fixture
4932 def fix():
4933 raise NotImplementedError()
4934
4935 with pytest.raises(pytest.fail.Exception):
4936 assert fix() == 1
4937
4938
4939 def test_fixture_double_decorator(pytester: Pytester) -> None:
4940 """Check if an error is raised when using @pytest.fixture twice."""
4941 pytester.makepyfile(
4942 """
4943 import pytest
4944
4945 @pytest.fixture
4946 @pytest.fixture
4947 def fixt():
4948 pass
4949 """
4950 )
4951 result = pytester.runpytest()
4952 result.assert_outcomes(errors=1)
4953 result.stdout.fnmatch_lines(
4954 [
4955 "E * ValueError: @pytest.fixture is being applied more than once to the same function 'fixt'"
4956 ]
4957 )
4958
4959
4960 def test_fixture_class(pytester: Pytester) -> None:
4961 """Check if an error is raised when using @pytest.fixture on a class."""
4962 pytester.makepyfile(
4963 """
4964 import pytest
4965
4966 @pytest.fixture
4967 class A:
4968 pass
4969 """
4970 )
4971 result = pytester.runpytest()
4972 result.assert_outcomes(errors=1)
4973
4974
4975 def test_fixture_param_shadowing(pytester: Pytester) -> None:
4976 """Parametrized arguments would be shadowed if a fixture with the same name also exists (#5036)"""
4977 pytester.makepyfile(
4978 """
4979 import pytest
4980
4981 @pytest.fixture(params=['a', 'b'])
4982 def argroot(request):
4983 return request.param
4984
4985 @pytest.fixture
4986 def arg(argroot):
4987 return argroot
4988
4989 # This should only be parametrized directly
4990 @pytest.mark.parametrize("arg", [1])
4991 def test_direct(arg):
4992 assert arg == 1
4993
4994 # This should be parametrized based on the fixtures
4995 def test_normal_fixture(arg):
4996 assert isinstance(arg, str)
4997
4998 # Indirect should still work:
4999
5000 @pytest.fixture
5001 def arg2(request):
5002 return 2*request.param
5003
5004 @pytest.mark.parametrize("arg2", [1], indirect=True)
5005 def test_indirect(arg2):
5006 assert arg2 == 2
5007 """
5008 )
5009 # Only one test should have run
5010 result = pytester.runpytest("-v")
5011 result.assert_outcomes(passed=4)
5012 result.stdout.fnmatch_lines(["*::test_direct[[]1[]]*"])
5013 result.stdout.fnmatch_lines(["*::test_normal_fixture[[]a[]]*"])
5014 result.stdout.fnmatch_lines(["*::test_normal_fixture[[]b[]]*"])
5015 result.stdout.fnmatch_lines(["*::test_indirect[[]1[]]*"])
5016
5017
5018 def test_fixture_named_request(pytester: Pytester) -> None:
5019 pytester.copy_example("fixtures/test_fixture_named_request.py")
5020 result = pytester.runpytest()
5021 result.stdout.fnmatch_lines(
5022 [
5023 "*'request' is a reserved word for fixtures, use another name:",
5024 " *test_fixture_named_request.py:8",
5025 ]
5026 )
5027
5028
5029 def test_indirect_fixture_does_not_break_scope(pytester: Pytester) -> None:
5030 """Ensure that fixture scope is respected when using indirect fixtures (#570)"""
5031 pytester.makepyfile(
5032 """
5033 import pytest
5034 instantiated = []
5035
5036 @pytest.fixture(scope="session")
5037 def fixture_1(request):
5038 instantiated.append(("fixture_1", request.param))
5039
5040
5041 @pytest.fixture(scope="session")
5042 def fixture_2(request):
5043 instantiated.append(("fixture_2", request.param))
5044
5045
5046 scenarios = [
5047 ("A", "a1"),
5048 ("A", "a2"),
5049 ("B", "b1"),
5050 ("B", "b2"),
5051 ("C", "c1"),
5052 ("C", "c2"),
5053 ]
5054
5055 @pytest.mark.parametrize(
5056 "fixture_1,fixture_2", scenarios, indirect=["fixture_1", "fixture_2"]
5057 )
5058 def test_create_fixtures(fixture_1, fixture_2):
5059 pass
5060
5061
5062 def test_check_fixture_instantiations():
5063 assert instantiated == [
5064 ('fixture_1', 'A'),
5065 ('fixture_2', 'a1'),
5066 ('fixture_2', 'a2'),
5067 ('fixture_1', 'B'),
5068 ('fixture_2', 'b1'),
5069 ('fixture_2', 'b2'),
5070 ('fixture_1', 'C'),
5071 ('fixture_2', 'c1'),
5072 ('fixture_2', 'c2'),
5073 ]
5074 """
5075 )
5076 result = pytester.runpytest()
5077 result.assert_outcomes(passed=7)
5078
5079
5080 def test_fixture_parametrization_nparray(pytester: Pytester) -> None:
5081 pytest.importorskip("numpy")
5082
5083 pytester.makepyfile(
5084 """
5085 from numpy import linspace
5086 from pytest import fixture
5087
5088 @fixture(params=linspace(1, 10, 10))
5089 def value(request):
5090 return request.param
5091
5092 def test_bug(value):
5093 assert value == value
5094 """
5095 )
5096 result = pytester.runpytest()
5097 result.assert_outcomes(passed=10)
5098
5099
5100 def test_fixture_arg_ordering(pytester: Pytester) -> None:
5101 """
5102 This test describes how fixtures in the same scope but without explicit dependencies
5103 between them are created. While users should make dependencies explicit, often
5104 they rely on this order, so this test exists to catch regressions in this regard.
5105 See #6540 and #6492.
5106 """
5107 p1 = pytester.makepyfile(
5108 """
5109 import pytest
5110
5111 suffixes = []
5112
5113 @pytest.fixture
5114 def fix_1(): suffixes.append("fix_1")
5115 @pytest.fixture
5116 def fix_2(): suffixes.append("fix_2")
5117 @pytest.fixture
5118 def fix_3(): suffixes.append("fix_3")
5119 @pytest.fixture
5120 def fix_4(): suffixes.append("fix_4")
5121 @pytest.fixture
5122 def fix_5(): suffixes.append("fix_5")
5123
5124 @pytest.fixture
5125 def fix_combined(fix_1, fix_2, fix_3, fix_4, fix_5): pass
5126
5127 def test_suffix(fix_combined):
5128 assert suffixes == ["fix_1", "fix_2", "fix_3", "fix_4", "fix_5"]
5129 """
5130 )
5131 result = pytester.runpytest("-vv", str(p1))
5132 assert result.ret == 0
5133
5134
5135 def test_yield_fixture_with_no_value(pytester: Pytester) -> None:
5136 pytester.makepyfile(
5137 """
5138 import pytest
5139 @pytest.fixture(name='custom')
5140 def empty_yield():
5141 if False:
5142 yield
5143
5144 def test_fixt(custom):
5145 pass
5146 """
5147 )
5148 expected = "E ValueError: custom did not yield a value"
5149 result = pytester.runpytest()
5150 result.assert_outcomes(errors=1)
5151 result.stdout.fnmatch_lines([expected])
5152 assert result.ret == ExitCode.TESTS_FAILED
5153
5154
5155 def test_deduplicate_names() -> None:
5156 items = deduplicate_names("abacd")
5157 assert items == ("a", "b", "c", "d")
5158 items = deduplicate_names((*items, "g", "f", "g", "e", "b"))
5159 assert items == ("a", "b", "c", "d", "g", "f", "e")
5160
5161
5162 def test_staticmethod_classmethod_fixture_instance(pytester: Pytester) -> None:
5163 """Ensure that static and class methods get and have access to a fresh
5164 instance.
5165
5166 This also ensures `setup_method` works well with static and class methods.
5167
5168 Regression test for #12065.
5169 """
5170 pytester.makepyfile(
5171 """
5172 import pytest
5173
5174 class Test:
5175 ran_setup_method = False
5176 ran_fixture = False
5177
5178 def setup_method(self):
5179 assert not self.ran_setup_method
5180 self.ran_setup_method = True
5181
5182 @pytest.fixture(autouse=True)
5183 def fixture(self):
5184 assert not self.ran_fixture
5185 self.ran_fixture = True
5186
5187 def test_method(self):
5188 assert self.ran_setup_method
5189 assert self.ran_fixture
5190
5191 @staticmethod
5192 def test_1(request):
5193 assert request.instance.ran_setup_method
5194 assert request.instance.ran_fixture
5195
5196 @classmethod
5197 def test_2(cls, request):
5198 assert request.instance.ran_setup_method
5199 assert request.instance.ran_fixture
5200 """
5201 )
5202 result = pytester.runpytest()
5203 assert result.ret == ExitCode.OK
5204 result.assert_outcomes(passed=3)
5205
5206
5207 def test_scoped_fixture_caching(pytester: Pytester) -> None:
5208 """Make sure setup and finalization is only run once when using scoped fixture
5209 multiple times."""
5210 pytester.makepyfile(
5211 """
5212 from __future__ import annotations
5213
5214 from typing import Generator
5215
5216 import pytest
5217 executed: list[str] = []
5218 @pytest.fixture(scope="class")
5219 def fixture_1() -> Generator[None, None, None]:
5220 executed.append("fix setup")
5221 yield
5222 executed.append("fix teardown")
5223
5224
5225 class TestFixtureCaching:
5226 def test_1(self, fixture_1: None) -> None:
5227 assert executed == ["fix setup"]
5228
5229 def test_2(self, fixture_1: None) -> None:
5230 assert executed == ["fix setup"]
5231
5232
5233 def test_expected_setup_and_teardown() -> None:
5234 assert executed == ["fix setup", "fix teardown"]
5235 """
5236 )
5237 result = pytester.runpytest()
5238 assert result.ret == 0
5239
5240
5241 def test_scoped_fixture_caching_exception(pytester: Pytester) -> None:
5242 """Make sure setup & finalization is only run once for scoped fixture, with a cached exception."""
5243 pytester.makepyfile(
5244 """
5245 from __future__ import annotations
5246
5247 import pytest
5248 executed_crash: list[str] = []
5249
5250
5251 @pytest.fixture(scope="class")
5252 def fixture_crash(request: pytest.FixtureRequest) -> None:
5253 executed_crash.append("fix_crash setup")
5254
5255 def my_finalizer() -> None:
5256 executed_crash.append("fix_crash teardown")
5257
5258 request.addfinalizer(my_finalizer)
5259
5260 raise Exception("foo")
5261
5262
5263 class TestFixtureCachingException:
5264 @pytest.mark.xfail
5265 def test_crash_1(self, fixture_crash: None) -> None:
5266 ...
5267
5268 @pytest.mark.xfail
5269 def test_crash_2(self, fixture_crash: None) -> None:
5270 ...
5271
5272
5273 def test_crash_expected_setup_and_teardown() -> None:
5274 assert executed_crash == ["fix_crash setup", "fix_crash teardown"]
5275 """
5276 )
5277 result = pytester.runpytest()
5278 assert result.ret == 0
5279
5280
5281 def test_scoped_fixture_teardown_order(pytester: Pytester) -> None:
5282 """
5283 Make sure teardowns happen in reverse order of setup with scoped fixtures, when
5284 a later test only depends on a subset of scoped fixtures.
5285
5286 Regression test for https://github.com/pytest-dev/pytest/issues/1489
5287 """
5288 pytester.makepyfile(
5289 """
5290 from typing import Generator
5291
5292 import pytest
5293
5294
5295 last_executed = ""
5296
5297
5298 @pytest.fixture(scope="module")
5299 def fixture_1() -> Generator[None, None, None]:
5300 global last_executed
5301 assert last_executed == ""
5302 last_executed = "fixture_1_setup"
5303 yield
5304 assert last_executed == "fixture_2_teardown"
5305 last_executed = "fixture_1_teardown"
5306
5307
5308 @pytest.fixture(scope="module")
5309 def fixture_2() -> Generator[None, None, None]:
5310 global last_executed
5311 assert last_executed == "fixture_1_setup"
5312 last_executed = "fixture_2_setup"
5313 yield
5314 assert last_executed == "run_test"
5315 last_executed = "fixture_2_teardown"
5316
5317
5318 def test_fixture_teardown_order(fixture_1: None, fixture_2: None) -> None:
5319 global last_executed
5320 assert last_executed == "fixture_2_setup"
5321 last_executed = "run_test"
5322
5323
5324 def test_2(fixture_1: None) -> None:
5325 # This would previously queue an additional teardown of fixture_1,
5326 # despite fixture_1's value being cached, which caused fixture_1 to be
5327 # torn down before fixture_2 - violating the rule that teardowns should
5328 # happen in reverse order of setup.
5329 pass
5330 """
5331 )
5332 result = pytester.runpytest()
5333 assert result.ret == 0
5334
5335
5336 def test_subfixture_teardown_order(pytester: Pytester) -> None:
5337 """
5338 Make sure fixtures don't re-register their finalization in parent fixtures multiple
5339 times, causing ordering failure in their teardowns.
5340
5341 Regression test for #12135
5342 """
5343 pytester.makepyfile(
5344 """
5345 import pytest
5346
5347 execution_order = []
5348
5349 @pytest.fixture(scope="class")
5350 def fixture_1():
5351 ...
5352
5353 @pytest.fixture(scope="class")
5354 def fixture_2(fixture_1):
5355 execution_order.append("setup 2")
5356 yield
5357 execution_order.append("teardown 2")
5358
5359 @pytest.fixture(scope="class")
5360 def fixture_3(fixture_1):
5361 execution_order.append("setup 3")
5362 yield
5363 execution_order.append("teardown 3")
5364
5365 class TestFoo:
5366 def test_initialize_fixtures(self, fixture_2, fixture_3):
5367 ...
5368
5369 # This would previously reschedule fixture_2's finalizer in the parent fixture,
5370 # causing it to be torn down before fixture 3.
5371 def test_reschedule_fixture_2(self, fixture_2):
5372 ...
5373
5374 # Force finalization directly on fixture_1
5375 # Otherwise the cleanup would sequence 3&2 before 1 as normal.
5376 @pytest.mark.parametrize("fixture_1", [None], indirect=["fixture_1"])
5377 def test_finalize_fixture_1(self, fixture_1):
5378 ...
5379
5380 def test_result():
5381 assert execution_order == ["setup 2", "setup 3", "teardown 3", "teardown 2"]
5382 """
5383 )
5384 result = pytester.runpytest()
5385 assert result.ret == 0
5386
5387
5388 def test_parametrized_fixture_scope_allowed(pytester: Pytester) -> None:
5389 """
5390 Make sure scope from parametrize does not affect fixture's ability to be
5391 depended upon.
5392
5393 Regression test for #13248
5394 """
5395 pytester.makepyfile(
5396 """
5397 import pytest
5398
5399 @pytest.fixture(scope="session")
5400 def my_fixture(request):
5401 return getattr(request, "param", None)
5402
5403 @pytest.fixture(scope="session")
5404 def another_fixture(my_fixture):
5405 return my_fixture
5406
5407 @pytest.mark.parametrize("my_fixture", ["a value"], indirect=True, scope="function")
5408 def test_foo(another_fixture):
5409 assert another_fixture == "a value"
5410 """
5411 )
5412 result = pytester.runpytest()
5413 result.assert_outcomes(passed=1)
5414
5415
5416 def test_collect_positional_only(pytester: Pytester) -> None:
5417 """Support the collection of tests with positional-only arguments (#13376)."""
5418 pytester.makepyfile(
5419 """
5420 import pytest
5421
5422 class Test:
5423 @pytest.fixture
5424 def fix(self):
5425 return 1
5426
5427 def test_method(self, /, fix):
5428 assert fix == 1
5429 """
5430 )
5431 result = pytester.runpytest()
5432 result.assert_outcomes(passed=1)
5433
5434
5435 def test_parametrization_dependency_pruning(pytester: Pytester) -> None:
5436 """Test that when a fixture is dynamically shadowed by parameterization, it
5437 is properly pruned and not executed."""
5438 pytester.makepyfile(
5439 """
5440 import pytest
5441
5442
5443 # This fixture should never run because shadowed_fixture is parametrized.
5444 @pytest.fixture
5445 def boom():
5446 raise RuntimeError("BOOM!")
5447
5448
5449 # This fixture is shadowed by metafunc.parametrize in pytest_generate_tests.
5450 @pytest.fixture
5451 def shadowed_fixture(boom):
5452 return "fixture_value"
5453
5454
5455 # Dynamically parametrize shadowed_fixture, replacing the fixture with direct values.
5456 def pytest_generate_tests(metafunc):
5457 if "shadowed_fixture" in metafunc.fixturenames:
5458 metafunc.parametrize("shadowed_fixture", ["param1", "param2"])
5459
5460
5461 # This test should receive shadowed_fixture as a parametrized value, and
5462 # boom should not explode.
5463 def test_shadowed(shadowed_fixture):
5464 assert shadowed_fixture in ["param1", "param2"]
5465 """
5466 )
5467 result = pytester.runpytest()
5468 result.assert_outcomes(passed=2)
5469
5470
5471 def test_fixture_closure_with_overrides(pytester: Pytester) -> None:
5472 """Test that an item's static fixture closure properly includes transitive
5473 dependencies through overridden fixtures (#13773)."""
5474 pytester.makeconftest(
5475 """
5476 import pytest
5477
5478 @pytest.fixture
5479 def db(): pass
5480
5481 @pytest.fixture
5482 def app(db): pass
5483 """
5484 )
5485 pytester.makepyfile(
5486 """
5487 import pytest
5488
5489 # Overrides conftest-level `app` and requests it.
5490 @pytest.fixture
5491 def app(app): pass
5492
5493 class TestClass:
5494 # Overrides module-level `app` and requests it.
5495 @pytest.fixture
5496 def app(self, app): pass
5497
5498 def test_something(self, request, app):
5499 # Both dynamic and static fixture closures should include 'db'.
5500 assert 'db' in request.fixturenames
5501 assert 'db' in request.node.fixturenames
5502 # No dynamic dependencies, should be equal.
5503 assert set(request.fixturenames) == set(request.node.fixturenames)
5504 """
5505 )
5506 result = pytester.runpytest("-v")
5507 result.assert_outcomes(passed=1)
5508
5509
5510 def test_fixture_closure_with_overrides_and_intermediary(pytester: Pytester) -> None:
5511 """Test that an item's static fixture closure properly includes transitive
5512 dependencies through overridden fixtures (#13773).
5513
5514 A more complicated case than test_fixture_closure_with_overrides, adds an
5515 intermediary so the override chain is not direct.
5516 """
5517 pytester.makeconftest(
5518 """
5519 import pytest
5520
5521 @pytest.fixture
5522 def db(): pass
5523
5524 @pytest.fixture
5525 def app(db): pass
5526
5527 @pytest.fixture
5528 def intermediate(app): pass
5529 """
5530 )
5531 pytester.makepyfile(
5532 """
5533 import pytest
5534
5535 # Overrides conftest-level `app` and requests it.
5536 @pytest.fixture
5537 def app(intermediate): pass
5538
5539 class TestClass:
5540 # Overrides module-level `app` and requests it.
5541 @pytest.fixture
5542 def app(self, app): pass
5543
5544 def test_something(self, request, app):
5545 # Both dynamic and static fixture closures should include 'db'.
5546 assert 'db' in request.fixturenames
5547 assert 'db' in request.node.fixturenames
5548 # No dynamic dependencies, should be equal.
5549 assert set(request.fixturenames) == set(request.node.fixturenames)
5550 """
5551 )
5552 result = pytester.runpytest("-v")
5553 result.assert_outcomes(passed=1)
5554
5555
5556 def test_fixture_closure_with_overrides_and_parametrization(pytester: Pytester) -> None:
5557 """Test that an item's static fixture closure properly includes transitive
5558 dependencies through overridden fixtures (#13773) when also including
5559 parametrization (#14248)."""
5560 pytester.makeconftest(
5561 """
5562 import pytest
5563
5564 @pytest.fixture
5565 def db(): pass
5566
5567 @pytest.fixture
5568 def app(db): pass
5569 """
5570 )
5571 pytester.makepyfile(
5572 """
5573 import pytest
5574
5575 # Overrides conftest-level `app` and requests it.
5576 @pytest.fixture
5577 def app(app): pass
5578
5579 class TestClass:
5580 # Overrides module-level `app` and requests it.
5581 @pytest.fixture
5582 def app(self, app): pass
5583
5584 @pytest.mark.parametrize("a", [1])
5585 def test_something(self, request, app, a):
5586 # Both dynamic and static fixture closures should include 'db'.
5587 assert 'db' in request.fixturenames
5588 assert 'db' in request.node.fixturenames
5589 # No dynamic dependencies, should be equal.
5590 assert set(request.fixturenames) == set(request.node.fixturenames)
5591 """
5592 )
5593 result = pytester.runpytest("-v")
5594 result.assert_outcomes(passed=1)
5595
5596
5597 def test_fixture_closure_with_broken_override_chain(pytester: Pytester) -> None:
5598 """Test that an item's static fixture closure properly includes transitive
5599 dependencies through overridden fixtures (#13773).
5600
5601 A more complicated case than test_fixture_closure_with_overrides, one of the
5602 fixtures in the chain doesn't call its super, so it shouldn't be included.
5603 """
5604 pytester.makeconftest(
5605 """
5606 import pytest
5607
5608 @pytest.fixture
5609 def db(): pass
5610
5611 @pytest.fixture
5612 def app(db): pass
5613 """
5614 )
5615 pytester.makepyfile(
5616 """
5617 import pytest
5618
5619 # Overrides conftest-level `app` and *doesn't* request it.
5620 @pytest.fixture
5621 def app(): pass
5622
5623 class TestClass:
5624 # Overrides module-level `app` and requests it.
5625 @pytest.fixture
5626 def app(self, app): pass
5627
5628 def test_something(self, request, app):
5629 # Both dynamic and static fixture closures should include 'db'.
5630 assert 'db' not in request.fixturenames
5631 assert 'db' not in request.node.fixturenames
5632 # No dynamic dependencies, should be equal.
5633 assert set(request.fixturenames) == set(request.node.fixturenames)
5634 """
5635 )
5636 result = pytester.runpytest("-v")
5637 result.assert_outcomes(passed=1)
5638
5639
5640 def test_fixture_closure_handles_circular_dependencies(pytester: Pytester) -> None:
5641 """Test that getfixtureclosure properly handles circular dependencies.
5642
5643 The test will error in the runtest phase due to the fixture loop,
5644 but the closure computation still completes.
5645 """
5646 pytester.makepyfile(
5647 """
5648 import pytest
5649
5650 # Direct circular dependency.
5651 @pytest.fixture
5652 def fix_a(fix_b): pass
5653
5654 @pytest.fixture
5655 def fix_b(fix_a): pass
5656
5657 # Indirect circular dependency through multiple fixtures.
5658 @pytest.fixture
5659 def fix_x(fix_y): pass
5660
5661 @pytest.fixture
5662 def fix_y(fix_z): pass
5663
5664 @pytest.fixture
5665 def fix_z(fix_x): pass
5666
5667 def test_circular_deps(fix_a, fix_x):
5668 pass
5669 """
5670 )
5671 items, _hookrec = pytester.inline_genitems()
5672 assert isinstance(items[0], Function)
5673 assert items[0].fixturenames == ["fix_a", "fix_b", "fix_x", "fix_y", "fix_z"]
5674
5675
5676 def test_fixture_closure_handles_diamond_dependencies(pytester: Pytester) -> None:
5677 """Test that getfixtureclosure properly handles diamond dependencies."""
5678 pytester.makepyfile(
5679 """
5680 import pytest
5681
5682 @pytest.fixture
5683 def db(): pass
5684
5685 @pytest.fixture
5686 def user(db): pass
5687
5688 @pytest.fixture
5689 def session(db): pass
5690
5691 @pytest.fixture
5692 def app(user, session): pass
5693
5694 def test_diamond_deps(request, app):
5695 assert request.node.fixturenames == ["request", "app", "user", "db", "session"]
5696 assert request.fixturenames == ["request", "app", "user", "db", "session"]
5697 """
5698 )
5699 result = pytester.runpytest("-v")
5700 result.assert_outcomes(passed=1)
5701
5702
5703 def test_fixture_closure_with_complex_override_and_shared_deps(
5704 pytester: Pytester,
5705 ) -> None:
5706 """Test that shared dependencies in override chains are processed only once."""
5707 pytester.makeconftest(
5708 """
5709 import pytest
5710
5711 @pytest.fixture
5712 def db(): pass
5713
5714 @pytest.fixture
5715 def cache(): pass
5716
5717 @pytest.fixture
5718 def settings(): pass
5719
5720 @pytest.fixture
5721 def app(db, cache, settings): pass
5722 """
5723 )
5724 pytester.makepyfile(
5725 """
5726 import pytest
5727
5728 # Override app, but also directly use cache and settings.
5729 # This creates multiple paths to the same fixtures.
5730 @pytest.fixture
5731 def app(app, cache, settings): pass
5732
5733 class TestClass:
5734 # Another override that uses both app and cache.
5735 @pytest.fixture
5736 def app(self, app, cache): pass
5737
5738 def test_shared_deps(self, request, app):
5739 assert request.node.fixturenames == ["request", "app", "db", "cache", "settings"]
5740 """
5741 )
5742 result = pytester.runpytest("-v")
5743 result.assert_outcomes(passed=1)
5744
5745
5746 def test_fixture_closure_with_parametrize_ignore(pytester: Pytester) -> None:
5747 """Test that getfixtureclosure properly handles parametrization argnames
5748 which override a fixture."""
5749 pytester.makepyfile(
5750 """
5751 import pytest
5752
5753 @pytest.fixture
5754 def fix1(fix2): pass
5755
5756 @pytest.fixture
5757 def fix2(fix3): pass
5758
5759 @pytest.fixture
5760 def fix3(): pass
5761
5762 @pytest.mark.parametrize('fix2', ['2'])
5763 def test_it(request, fix1):
5764 assert request.node.fixturenames == ["request", "fix1", "fix2"]
5765 assert request.fixturenames == ["request", "fix1", "fix2"]
5766 """
5767 )
5768 result = pytester.runpytest("-v")
5769 result.assert_outcomes(passed=1)
5770
5771
5772 def test_overridden_fixture_depends_on_parametrized(pytester: Pytester) -> None:
5773 """#11075"""
5774 pytester.makepyfile(
5775 """
5776 import pytest
5777
5778 @pytest.fixture(params=["foo"])
5779 def fixture_foo(request):
5780 yield request.param
5781
5782 @pytest.fixture
5783 def fixture_bar(fixture_foo):
5784 yield fixture_foo
5785
5786 class TestFoobar:
5787 @pytest.fixture
5788 def fixture_bar(self, fixture_bar):
5789 yield fixture_bar
5790
5791 def test_foobar(self, fixture_bar):
5792 assert fixture_bar == "foo"
5793 """
5794 )
5795 result = pytester.runpytest("-v")
5796 result.assert_outcomes(passed=1)