Debian Codegraph @

testing/python/collect.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 import os
5 import sys
6 import textwrap
7 from typing import Any
8
9 import _pytest._code
10 from _pytest.config import ExitCode
11 from _pytest.main import Session
12 from _pytest.monkeypatch import MonkeyPatch
13 from _pytest.nodes import Collector
14 from _pytest.pytester import Pytester
15 from _pytest.python import Class
16 from _pytest.python import Function
17 import pytest
18
19
20 class TestModule:
21 def test_failing_import(self, pytester: Pytester) -> None:
22 modcol = pytester.getmodulecol("import alksdjalskdjalkjals")
23 with pytest.raises(Collector.CollectError):
24 modcol.collect()
25
26 def test_import_duplicate(self, pytester: Pytester) -> None:
27 a = pytester.mkdir("a")
28 b = pytester.mkdir("b")
29 p1 = a.joinpath("test_whatever.py")
30 p1.touch()
31 p2 = b.joinpath("test_whatever.py")
32 p2.touch()
33 # ensure we don't have it imported already
34 sys.modules.pop(p1.stem, None)
35
36 result = pytester.runpytest()
37 result.stdout.fnmatch_lines(
38 [
39 "*import*mismatch*",
40 "*imported*test_whatever*",
41 f"*{p1}*",
42 "*not the same*",
43 f"*{p2}*",
44 "*HINT*",
45 ]
46 )
47
48 def test_import_prepend_append(
49 self, pytester: Pytester, monkeypatch: MonkeyPatch
50 ) -> None:
51 root1 = pytester.mkdir("root1")
52 root2 = pytester.mkdir("root2")
53 root1.joinpath("x456.py").touch()
54 root2.joinpath("x456.py").touch()
55 p = root2.joinpath("test_x456.py")
56 monkeypatch.syspath_prepend(str(root1))
57 p.write_text(
58 textwrap.dedent(
59 f"""\
60 import x456
61 def test():
62 assert x456.__file__.startswith({str(root2)!r})
63 """
64 ),
65 encoding="utf-8",
66 )
67 with monkeypatch.context() as mp:
68 mp.chdir(root2)
69 reprec = pytester.inline_run("--import-mode=append")
70 reprec.assertoutcome(passed=0, failed=1)
71 reprec = pytester.inline_run()
72 reprec.assertoutcome(passed=1)
73
74 def test_syntax_error_in_module(self, pytester: Pytester) -> None:
75 modcol = pytester.getmodulecol("this is a syntax error")
76 with pytest.raises(modcol.CollectError):
77 modcol.collect()
78 with pytest.raises(modcol.CollectError):
79 modcol.collect()
80
81 def test_module_considers_pluginmanager_at_import(self, pytester: Pytester) -> None:
82 modcol = pytester.getmodulecol("pytest_plugins='xasdlkj',")
83 with pytest.raises(ImportError):
84 modcol.obj()
85
86 def test_invalid_test_module_name(self, pytester: Pytester) -> None:
87 a = pytester.mkdir("a")
88 a.joinpath("test_one.part1.py").touch()
89 result = pytester.runpytest()
90 result.stdout.fnmatch_lines(
91 [
92 "ImportError while importing test module*test_one.part1*",
93 "Hint: make sure your test modules/packages have valid Python names.",
94 ]
95 )
96
97 @pytest.mark.parametrize("verbose", [0, 1, 2])
98 def test_show_traceback_import_error(
99 self, pytester: Pytester, verbose: int
100 ) -> None:
101 """Import errors when collecting modules should display the traceback (#1976).
102
103 With low verbosity we omit pytest and internal modules, otherwise show all traceback entries.
104 """
105 pytester.makepyfile(
106 foo_traceback_import_error="""
107 from bar_traceback_import_error import NOT_AVAILABLE
108 """,
109 bar_traceback_import_error="",
110 )
111 pytester.makepyfile(
112 """
113 import foo_traceback_import_error
114 """
115 )
116 args = ("-v",) * verbose
117 result = pytester.runpytest(*args)
118 result.stdout.fnmatch_lines(
119 [
120 "ImportError while importing test module*",
121 "Traceback:",
122 "*from bar_traceback_import_error import NOT_AVAILABLE",
123 "*cannot import name *NOT_AVAILABLE*",
124 ]
125 )
126 assert result.ret == 2
127
128 stdout = result.stdout.str()
129 if verbose == 2:
130 assert "_pytest" in stdout
131 else:
132 assert "_pytest" not in stdout
133
134 def test_show_traceback_import_error_unicode(self, pytester: Pytester) -> None:
135 """Check test modules collected which raise ImportError with unicode messages
136 are handled properly (#2336).
137 """
138 pytester.makepyfile("raise ImportError('Something bad happened ☺')")
139 result = pytester.runpytest()
140 result.stdout.fnmatch_lines(
141 [
142 "ImportError while importing test module*",
143 "Traceback:",
144 "*raise ImportError*Something bad happened*",
145 ]
146 )
147 assert result.ret == 2
148
149
150 class TestClass:
151 def test_class_with_init_warning(self, pytester: Pytester) -> None:
152 pytester.makepyfile(
153 """
154 class TestClass1(object):
155 def __init__(self):
156 pass
157 """
158 )
159 result = pytester.runpytest()
160 result.stdout.fnmatch_lines(
161 [
162 "*cannot collect test class 'TestClass1' because it has "
163 "a __init__ constructor (from: test_class_with_init_warning.py)"
164 ]
165 )
166
167 def test_class_with_new_warning(self, pytester: Pytester) -> None:
168 pytester.makepyfile(
169 """
170 class TestClass1(object):
171 def __new__(self):
172 pass
173 """
174 )
175 result = pytester.runpytest()
176 result.stdout.fnmatch_lines(
177 [
178 "*cannot collect test class 'TestClass1' because it has "
179 "a __new__ constructor (from: test_class_with_new_warning.py)"
180 ]
181 )
182
183 def test_class_subclassobject(self, pytester: Pytester) -> None:
184 pytester.getmodulecol(
185 """
186 class test(object):
187 pass
188 """
189 )
190 result = pytester.runpytest()
191 result.stdout.fnmatch_lines(["*collected 0*"])
192
193 def test_static_method(self, pytester: Pytester) -> None:
194 """Support for collecting staticmethod tests (#2528, #2699)"""
195 pytester.getmodulecol(
196 """
197 import pytest
198 class Test(object):
199 @staticmethod
200 def test_something():
201 pass
202
203 @pytest.fixture
204 def fix(self):
205 return 1
206
207 @staticmethod
208 def test_fix(fix):
209 assert fix == 1
210 """
211 )
212 result = pytester.runpytest()
213 result.stdout.fnmatch_lines(["*collected 2 items*", "*2 passed in*"])
214
215 def test_setup_teardown_class_as_classmethod(self, pytester: Pytester) -> None:
216 pytester.makepyfile(
217 test_mod1="""
218 class TestClassMethod(object):
219 @classmethod
220 def setup_class(cls):
221 pass
222 def test_1(self):
223 pass
224 @classmethod
225 def teardown_class(cls):
226 pass
227 """
228 )
229 result = pytester.runpytest()
230 result.stdout.fnmatch_lines(["*1 passed*"])
231
232 def test_issue1035_obj_has_getattr(self, pytester: Pytester) -> None:
233 modcol = pytester.getmodulecol(
234 """
235 class Chameleon(object):
236 def __getattr__(self, name):
237 return True
238 chameleon = Chameleon()
239 """
240 )
241 colitems = modcol.collect()
242 assert len(colitems) == 0
243
244 def test_issue1579_namedtuple(self, pytester: Pytester) -> None:
245 pytester.makepyfile(
246 """
247 import collections
248
249 TestCase = collections.namedtuple('TestCase', ['a'])
250 """
251 )
252 result = pytester.runpytest()
253 result.stdout.fnmatch_lines(
254 "*cannot collect test class 'TestCase' "
255 "because it has a __new__ constructor*"
256 )
257
258 def test_issue2234_property(self, pytester: Pytester) -> None:
259 pytester.makepyfile(
260 """
261 class TestCase(object):
262 @property
263 def prop(self):
264 raise NotImplementedError()
265 """
266 )
267 result = pytester.runpytest()
268 assert result.ret == ExitCode.NO_TESTS_COLLECTED
269
270 def test_does_not_discover_properties(self, pytester: Pytester) -> None:
271 """Regression test for #12446."""
272 pytester.makepyfile(
273 """\
274 class TestCase:
275 @property
276 def oops(self):
277 raise SystemExit('do not call me!')
278 """
279 )
280 result = pytester.runpytest()
281 assert result.ret == ExitCode.NO_TESTS_COLLECTED
282
283 def test_does_not_discover_instance_descriptors(self, pytester: Pytester) -> None:
284 """Regression test for #12446."""
285 pytester.makepyfile(
286 """\
287 # not `@property`, but it acts like one
288 # this should cover the case of things like `@cached_property` / etc.
289 class MyProperty:
290 def __init__(self, func):
291 self._func = func
292 def __get__(self, inst, owner):
293 if inst is None:
294 return self
295 else:
296 return self._func.__get__(inst, owner)()
297
298 class TestCase:
299 @MyProperty
300 def oops(self):
301 raise SystemExit('do not call me!')
302 """
303 )
304 result = pytester.runpytest()
305 assert result.ret == ExitCode.NO_TESTS_COLLECTED
306
307 def test_abstract_class_is_not_collected(self, pytester: Pytester) -> None:
308 """Regression test for #12275 (non-unittest version)."""
309 pytester.makepyfile(
310 """
311 import abc
312
313 class TestBase(abc.ABC):
314 @abc.abstractmethod
315 def abstract1(self): pass
316
317 @abc.abstractmethod
318 def abstract2(self): pass
319
320 def test_it(self): pass
321
322 class TestPartial(TestBase):
323 def abstract1(self): pass
324
325 class TestConcrete(TestPartial):
326 def abstract2(self): pass
327 """
328 )
329 result = pytester.runpytest()
330 assert result.ret == ExitCode.OK
331 result.assert_outcomes(passed=1)
332
333
334 class TestFunction:
335 def test_getmodulecollector(self, pytester: Pytester) -> None:
336 item = pytester.getitem("def test_func(): pass")
337 modcol = item.getparent(pytest.Module)
338 assert isinstance(modcol, pytest.Module)
339 assert hasattr(modcol.obj, "test_func")
340
341 @pytest.mark.filterwarnings("default")
342 def test_function_as_object_instance_ignored(self, pytester: Pytester) -> None:
343 pytester.makepyfile(
344 """
345 class A(object):
346 def __call__(self, tmp_path):
347 0/0
348
349 test_a = A()
350 """
351 )
352 result = pytester.runpytest()
353 result.stdout.fnmatch_lines(
354 [
355 "collected 0 items",
356 "*test_function_as_object_instance_ignored.py:2: "
357 "*cannot collect 'test_a' because it is not a function.",
358 ]
359 )
360
361 @staticmethod
362 def make_function(pytester: Pytester, **kwargs: Any) -> Any:
363 from _pytest.fixtures import FixtureManager
364
365 config = pytester.parseconfigure()
366 session = Session.from_config(config)
367 session._fixturemanager = FixtureManager(session)
368
369 return pytest.Function.from_parent(parent=session, **kwargs)
370
371 def test_function_equality(self, pytester: Pytester) -> None:
372 def func1():
373 pass
374
375 def func2():
376 pass
377
378 f1 = self.make_function(pytester, name="name", callobj=func1)
379 assert f1 == f1
380 f2 = self.make_function(
381 pytester, name="name", callobj=func2, originalname="foobar"
382 )
383 assert f1 != f2
384
385 def test_repr_produces_actual_test_id(self, pytester: Pytester) -> None:
386 f = self.make_function(
387 pytester, name=r"test[\xe5]", callobj=self.test_repr_produces_actual_test_id
388 )
389 assert repr(f) == r"<Function test[\xe5]>"
390
391 def test_issue197_parametrize_emptyset(self, pytester: Pytester) -> None:
392 pytester.makepyfile(
393 """
394 import pytest
395 @pytest.mark.parametrize('arg', [])
396 def test_function(arg):
397 pass
398 """
399 )
400 reprec = pytester.inline_run()
401 reprec.assertoutcome(skipped=1)
402
403 def test_single_tuple_unwraps_values(self, pytester: Pytester) -> None:
404 pytester.makepyfile(
405 """
406 import pytest
407 @pytest.mark.parametrize(('arg',), [(1,)])
408 def test_function(arg):
409 assert arg == 1
410 """
411 )
412 reprec = pytester.inline_run()
413 reprec.assertoutcome(passed=1)
414
415 def test_issue213_parametrize_value_no_equal(self, pytester: Pytester) -> None:
416 pytester.makepyfile(
417 """
418 import pytest
419 class A(object):
420 def __eq__(self, other):
421 raise ValueError("not possible")
422 @pytest.mark.parametrize('arg', [A()])
423 def test_function(arg):
424 assert arg.__class__.__name__ == "A"
425 """
426 )
427 reprec = pytester.inline_run("--fulltrace")
428 reprec.assertoutcome(passed=1)
429
430 def test_parametrize_with_non_hashable_values(self, pytester: Pytester) -> None:
431 """Test parametrization with non-hashable values."""
432 pytester.makepyfile(
433 """
434 archival_mapping = {
435 '1.0': {'tag': '1.0'},
436 '1.2.2a1': {'tag': 'release-1.2.2a1'},
437 }
438
439 import pytest
440 @pytest.mark.parametrize('key value'.split(),
441 archival_mapping.items())
442 def test_archival_to_version(key, value):
443 assert key in archival_mapping
444 assert value == archival_mapping[key]
445 """
446 )
447 rec = pytester.inline_run()
448 rec.assertoutcome(passed=2)
449
450 def test_parametrize_with_non_hashable_values_indirect(
451 self, pytester: Pytester
452 ) -> None:
453 """Test parametrization with non-hashable values with indirect parametrization."""
454 pytester.makepyfile(
455 """
456 archival_mapping = {
457 '1.0': {'tag': '1.0'},
458 '1.2.2a1': {'tag': 'release-1.2.2a1'},
459 }
460
461 import pytest
462
463 @pytest.fixture
464 def key(request):
465 return request.param
466
467 @pytest.fixture
468 def value(request):
469 return request.param
470
471 @pytest.mark.parametrize('key value'.split(),
472 archival_mapping.items(), indirect=True)
473 def test_archival_to_version(key, value):
474 assert key in archival_mapping
475 assert value == archival_mapping[key]
476 """
477 )
478 rec = pytester.inline_run()
479 rec.assertoutcome(passed=2)
480
481 def test_parametrize_overrides_fixture(self, pytester: Pytester) -> None:
482 """Test parametrization when parameter overrides existing fixture with same name."""
483 pytester.makepyfile(
484 """
485 import pytest
486
487 @pytest.fixture
488 def value():
489 return 'value'
490
491 @pytest.mark.parametrize('value',
492 ['overridden'])
493 def test_overridden_via_param(value):
494 assert value == 'overridden'
495
496 @pytest.mark.parametrize('somevalue', ['overridden'])
497 def test_not_overridden(value, somevalue):
498 assert value == 'value'
499 assert somevalue == 'overridden'
500
501 @pytest.mark.parametrize('other,value', [('foo', 'overridden')])
502 def test_overridden_via_multiparam(other, value):
503 assert other == 'foo'
504 assert value == 'overridden'
505 """
506 )
507 rec = pytester.inline_run()
508 rec.assertoutcome(passed=3)
509
510 def test_parametrize_overrides_parametrized_fixture(
511 self, pytester: Pytester
512 ) -> None:
513 """Test parametrization when parameter overrides existing parametrized fixture with same name."""
514 pytester.makepyfile(
515 """
516 import pytest
517
518 @pytest.fixture(params=[1, 2])
519 def value(request):
520 return request.param
521
522 @pytest.mark.parametrize('value',
523 ['overridden'])
524 def test_overridden_via_param(value):
525 assert value == 'overridden'
526 """
527 )
528 rec = pytester.inline_run()
529 rec.assertoutcome(passed=1)
530
531 def test_parametrize_overrides_parametrized_fixture_with_unrelated_indirect(
532 self, pytester: Pytester
533 ) -> None:
534 """Test parametrization when parameter overrides existing parametrized fixture with same name,
535 and there is an unrelated indirect param.
536
537 Regression test for #13974.
538 """
539 pytester.makepyfile(
540 """
541 import pytest
542
543 @pytest.fixture(params=["a", "b"])
544 def target(request):
545 return request.param
546
547 @pytest.fixture
548 def val(request):
549 return int(request.param)
550
551 @pytest.mark.parametrize(
552 ["val", "target"],
553 [
554 ("1", 1),
555 ("2", 2),
556 ],
557 indirect=["val"],
558 )
559 def test(val, target):
560 assert val == target
561 """
562 )
563 result = pytester.runpytest()
564 assert result.ret == 0
565 result.assert_outcomes(passed=2)
566
567 def test_parametrize_overrides_indirect_dependency_fixture(
568 self, pytester: Pytester
569 ) -> None:
570 """Test parametrization when parameter overrides a fixture that a test indirectly depends on"""
571 pytester.makepyfile(
572 """
573 import pytest
574
575 fix3_instantiated = False
576
577 @pytest.fixture
578 def fix1(fix2):
579 return fix2 + '1'
580
581 @pytest.fixture
582 def fix2(fix3):
583 return fix3 + '2'
584
585 @pytest.fixture
586 def fix3():
587 global fix3_instantiated
588 fix3_instantiated = True
589 return '3'
590
591 @pytest.mark.parametrize('fix2', ['2'])
592 def test_it(fix1):
593 assert fix1 == '21'
594 assert not fix3_instantiated
595 """
596 )
597 rec = pytester.inline_run()
598 rec.assertoutcome(passed=1)
599
600 def test_parametrize_with_mark(self, pytester: Pytester) -> None:
601 items = pytester.getitems(
602 """
603 import pytest
604 @pytest.mark.foo
605 @pytest.mark.parametrize('arg', [
606 1,
607 pytest.param(2, marks=[pytest.mark.baz, pytest.mark.bar])
608 ])
609 def test_function(arg):
610 pass
611 """
612 )
613 keywords = [item.keywords for item in items]
614 assert (
615 "foo" in keywords[0]
616 and "bar" not in keywords[0]
617 and "baz" not in keywords[0]
618 )
619 assert "foo" in keywords[1] and "bar" in keywords[1] and "baz" in keywords[1]
620
621 def test_parametrize_with_empty_string_arguments(self, pytester: Pytester) -> None:
622 items = pytester.getitems(
623 """\
624 import pytest
625
626 @pytest.mark.parametrize('v', ('', ' '))
627 @pytest.mark.parametrize('w', ('', ' '))
628 def test(v, w): ...
629 """
630 )
631 names = {item.name for item in items}
632 assert names == {"test[-]", "test[ -]", "test[- ]", "test[ - ]"}
633
634 def test_function_equality_with_callspec(self, pytester: Pytester) -> None:
635 items = pytester.getitems(
636 """
637 import pytest
638 @pytest.mark.parametrize('arg', [1,2])
639 def test_function(arg):
640 pass
641 """
642 )
643 assert items[0] != items[1]
644 assert not (items[0] == items[1])
645
646 def test_pyfunc_call(self, pytester: Pytester) -> None:
647 item = pytester.getitem("def test_func(): raise ValueError")
648 config = item.config
649
650 class MyPlugin1:
651 def pytest_pyfunc_call(self):
652 raise ValueError
653
654 class MyPlugin2:
655 def pytest_pyfunc_call(self):
656 return True
657
658 config.pluginmanager.register(MyPlugin1())
659 config.pluginmanager.register(MyPlugin2())
660 config.hook.pytest_runtest_setup(item=item)
661 config.hook.pytest_pyfunc_call(pyfuncitem=item)
662
663 def test_multiple_parametrize(self, pytester: Pytester) -> None:
664 modcol = pytester.getmodulecol(
665 """
666 import pytest
667 @pytest.mark.parametrize('x', [0, 1])
668 @pytest.mark.parametrize('y', [2, 3])
669 def test1(x, y):
670 pass
671 """
672 )
673 colitems = modcol.collect()
674 assert colitems[0].name == "test1[2-0]"
675 assert colitems[1].name == "test1[2-1]"
676 assert colitems[2].name == "test1[3-0]"
677 assert colitems[3].name == "test1[3-1]"
678
679 def test_issue751_multiple_parametrize_with_ids(self, pytester: Pytester) -> None:
680 modcol = pytester.getmodulecol(
681 """
682 import pytest
683 @pytest.mark.parametrize('x', [0], ids=['c'])
684 @pytest.mark.parametrize('y', [0, 1], ids=['a', 'b'])
685 class Test(object):
686 def test1(self, x, y):
687 pass
688 def test2(self, x, y):
689 pass
690 """
691 )
692 colitems = modcol.collect()[0].collect()
693 assert colitems[0].name == "test1[a-c]"
694 assert colitems[1].name == "test1[b-c]"
695 assert colitems[2].name == "test2[a-c]"
696 assert colitems[3].name == "test2[b-c]"
697
698 def test_parametrize_skipif(self, pytester: Pytester) -> None:
699 pytester.makepyfile(
700 """
701 import pytest
702
703 m = pytest.mark.skipif('True')
704
705 @pytest.mark.parametrize('x', [0, 1, pytest.param(2, marks=m)])
706 def test_skip_if(x):
707 assert x < 2
708 """
709 )
710 result = pytester.runpytest()
711 result.stdout.fnmatch_lines(["* 2 passed, 1 skipped in *"])
712
713 def test_parametrize_skip(self, pytester: Pytester) -> None:
714 pytester.makepyfile(
715 """
716 import pytest
717
718 m = pytest.mark.skip('')
719
720 @pytest.mark.parametrize('x', [0, 1, pytest.param(2, marks=m)])
721 def test_skip(x):
722 assert x < 2
723 """
724 )
725 result = pytester.runpytest()
726 result.stdout.fnmatch_lines(["* 2 passed, 1 skipped in *"])
727
728 def test_parametrize_skipif_no_skip(self, pytester: Pytester) -> None:
729 pytester.makepyfile(
730 """
731 import pytest
732
733 m = pytest.mark.skipif('False')
734
735 @pytest.mark.parametrize('x', [0, 1, m(2)])
736 def test_skipif_no_skip(x):
737 assert x < 2
738 """
739 )
740 result = pytester.runpytest()
741 result.stdout.fnmatch_lines(["* 1 failed, 2 passed in *"])
742
743 def test_parametrize_xfail(self, pytester: Pytester) -> None:
744 pytester.makepyfile(
745 """
746 import pytest
747
748 m = pytest.mark.xfail('True')
749
750 @pytest.mark.parametrize('x', [0, 1, pytest.param(2, marks=m)])
751 def test_xfail(x):
752 assert x < 2
753 """
754 )
755 result = pytester.runpytest()
756 result.stdout.fnmatch_lines(["* 2 passed, 1 xfailed in *"])
757
758 def test_parametrize_passed(self, pytester: Pytester) -> None:
759 pytester.makepyfile(
760 """
761 import pytest
762
763 m = pytest.mark.xfail('True')
764
765 @pytest.mark.parametrize('x', [0, 1, pytest.param(2, marks=m)])
766 def test_xfail(x):
767 pass
768 """
769 )
770 result = pytester.runpytest()
771 result.stdout.fnmatch_lines(["* 2 passed, 1 xpassed in *"])
772
773 def test_parametrize_xfail_passed(self, pytester: Pytester) -> None:
774 pytester.makepyfile(
775 """
776 import pytest
777
778 m = pytest.mark.xfail('False')
779
780 @pytest.mark.parametrize('x', [0, 1, m(2)])
781 def test_passed(x):
782 pass
783 """
784 )
785 result = pytester.runpytest()
786 result.stdout.fnmatch_lines(["* 3 passed in *"])
787
788 def test_function_originalname(self, pytester: Pytester) -> None:
789 items = pytester.getitems(
790 """
791 import pytest
792
793 @pytest.mark.parametrize('arg', [1,2])
794 def test_func(arg):
795 pass
796
797 def test_no_param():
798 pass
799 """
800 )
801 originalnames = []
802 for x in items:
803 assert isinstance(x, pytest.Function)
804 originalnames.append(x.originalname)
805 assert originalnames == [
806 "test_func",
807 "test_func",
808 "test_no_param",
809 ]
810
811 def test_function_with_square_brackets(self, pytester: Pytester) -> None:
812 """Check that functions with square brackets don't cause trouble."""
813 p1 = pytester.makepyfile(
814 """
815 locals()["test_foo[name]"] = lambda: None
816 """
817 )
818 result = pytester.runpytest("-v", str(p1))
819 result.stdout.fnmatch_lines(
820 [
821 "test_function_with_square_brackets.py::test_foo[[]name[]] PASSED *",
822 "*= 1 passed in *",
823 ]
824 )
825
826
827 class TestSorting:
828 def test_check_equality(self, pytester: Pytester) -> None:
829 modcol = pytester.getmodulecol(
830 """
831 def test_pass(): pass
832 def test_fail(): assert 0
833 """
834 )
835 fn1 = pytester.collect_by_name(modcol, "test_pass")
836 assert isinstance(fn1, pytest.Function)
837 fn2 = pytester.collect_by_name(modcol, "test_pass")
838 assert isinstance(fn2, pytest.Function)
839
840 assert fn1 == fn2
841 assert fn1 != modcol
842 assert hash(fn1) == hash(fn2)
843
844 fn3 = pytester.collect_by_name(modcol, "test_fail")
845 assert isinstance(fn3, pytest.Function)
846 assert not (fn1 == fn3)
847 assert fn1 != fn3
848
849 for fn in fn1, fn2, fn3:
850 assert fn != 3 # type: ignore[comparison-overlap]
851 assert fn != modcol
852 assert fn != [1, 2, 3] # type: ignore[comparison-overlap]
853 assert [1, 2, 3] != fn # type: ignore[comparison-overlap]
854 assert modcol != fn
855
856 def test_allow_sane_sorting_for_decorators(self, pytester: Pytester) -> None:
857 modcol = pytester.getmodulecol(
858 """
859 def dec(f):
860 g = lambda: f(2)
861 g.place_as = f
862 return g
863
864
865 def test_b(y):
866 pass
867 test_b = dec(test_b)
868
869 def test_a(y):
870 pass
871 test_a = dec(test_a)
872 """
873 )
874 colitems = modcol.collect()
875 assert len(colitems) == 2
876 assert [item.name for item in colitems] == ["test_b", "test_a"]
877
878 def test_ordered_by_definition_order(self, pytester: Pytester) -> None:
879 pytester.makepyfile(
880 """\
881 class Test1:
882 def test_foo(self): pass
883 def test_bar(self): pass
884 class Test2:
885 def test_foo(self): pass
886 test_bar = Test1.test_bar
887 class Test3(Test2):
888 def test_baz(self): pass
889 """
890 )
891 result = pytester.runpytest("--collect-only")
892 result.stdout.fnmatch_lines(
893 [
894 "*Class Test1*",
895 "*Function test_foo*",
896 "*Function test_bar*",
897 "*Class Test2*",
898 # previously the order was flipped due to Test1.test_bar reference
899 "*Function test_foo*",
900 "*Function test_bar*",
901 "*Class Test3*",
902 "*Function test_foo*",
903 "*Function test_bar*",
904 "*Function test_baz*",
905 ]
906 )
907
908
909 class TestConftestCustomization:
910 def test_pytest_pycollect_module(self, pytester: Pytester) -> None:
911 pytester.makeconftest(
912 """
913 import pytest
914 class MyModule(pytest.Module):
915 pass
916 def pytest_pycollect_makemodule(module_path, parent):
917 if module_path.name == "test_xyz.py":
918 return MyModule.from_parent(path=module_path, parent=parent)
919 """
920 )
921 pytester.makepyfile("def test_some(): pass")
922 pytester.makepyfile(test_xyz="def test_func(): pass")
923 result = pytester.runpytest("--collect-only")
924 result.stdout.fnmatch_lines(["*<Module*test_pytest*", "*<MyModule*xyz*"])
925
926 def test_customized_pymakemodule_issue205_subdir(self, pytester: Pytester) -> None:
927 b = pytester.path.joinpath("a", "b")
928 b.mkdir(parents=True)
929 b.joinpath("conftest.py").write_text(
930 textwrap.dedent(
931 """\
932 import pytest
933 @pytest.hookimpl(wrapper=True)
934 def pytest_pycollect_makemodule():
935 mod = yield
936 mod.obj.hello = "world"
937 return mod
938 """
939 ),
940 encoding="utf-8",
941 )
942 b.joinpath("test_module.py").write_text(
943 textwrap.dedent(
944 """\
945 def test_hello():
946 assert hello == "world"
947 """
948 ),
949 encoding="utf-8",
950 )
951 reprec = pytester.inline_run()
952 reprec.assertoutcome(passed=1)
953
954 def test_customized_pymakeitem(self, pytester: Pytester) -> None:
955 b = pytester.path.joinpath("a", "b")
956 b.mkdir(parents=True)
957 b.joinpath("conftest.py").write_text(
958 textwrap.dedent(
959 """\
960 import pytest
961 @pytest.hookimpl(wrapper=True)
962 def pytest_pycollect_makeitem():
963 result = yield
964 if result:
965 for func in result:
966 func._some123 = "world"
967 return result
968 """
969 ),
970 encoding="utf-8",
971 )
972 b.joinpath("test_module.py").write_text(
973 textwrap.dedent(
974 """\
975 import pytest
976
977 @pytest.fixture()
978 def obj(request):
979 return request.node._some123
980 def test_hello(obj):
981 assert obj == "world"
982 """
983 ),
984 encoding="utf-8",
985 )
986 reprec = pytester.inline_run()
987 reprec.assertoutcome(passed=1)
988
989 def test_pytest_pycollect_makeitem(self, pytester: Pytester) -> None:
990 pytester.makeconftest(
991 """
992 import pytest
993 class MyFunction(pytest.Function):
994 pass
995 def pytest_pycollect_makeitem(collector, name, obj):
996 if name == "some":
997 return MyFunction.from_parent(name=name, parent=collector)
998 """
999 )
1000 pytester.makepyfile("def some(): pass")
1001 result = pytester.runpytest("--collect-only")
1002 result.stdout.fnmatch_lines(["*MyFunction*some*"])
1003
1004 def test_issue2369_collect_module_fileext(self, pytester: Pytester) -> None:
1005 """Ensure we can collect files with weird file extensions as Python
1006 modules (#2369)"""
1007 # Implement a little meta path finder to import files containing
1008 # Python source code whose file extension is ".narf".
1009 pytester.makeconftest(
1010 """
1011 import sys
1012 import os.path
1013 from importlib.util import spec_from_loader
1014 from importlib.machinery import SourceFileLoader
1015 from _pytest.python import Module
1016
1017 class MetaPathFinder:
1018 def find_spec(self, fullname, path, target=None):
1019 if os.path.exists(fullname + ".narf"):
1020 return spec_from_loader(
1021 fullname,
1022 SourceFileLoader(fullname, fullname + ".narf"),
1023 )
1024 sys.meta_path.append(MetaPathFinder())
1025
1026 def pytest_collect_file(file_path, parent):
1027 if file_path.suffix == ".narf":
1028 return Module.from_parent(path=file_path, parent=parent)
1029 """
1030 )
1031 pytester.makefile(
1032 ".narf",
1033 """\
1034 def test_something():
1035 assert 1 + 1 == 2""",
1036 )
1037 # Use runpytest_subprocess, since we're futzing with sys.meta_path.
1038 result = pytester.runpytest_subprocess()
1039 result.stdout.fnmatch_lines(["*1 passed*"])
1040
1041 def test_early_ignored_attributes(self, pytester: Pytester) -> None:
1042 """Builtin attributes should be ignored early on, even if
1043 configuration would otherwise allow them.
1044
1045 This tests a performance optimization, not correctness, really,
1046 although it tests PytestCollectionWarning is not raised, while
1047 it would have been raised otherwise.
1048 """
1049 pytester.makeini(
1050 """
1051 [pytest]
1052 python_classes=*
1053 python_functions=*
1054 """
1055 )
1056 pytester.makepyfile(
1057 """
1058 class TestEmpty:
1059 pass
1060 test_empty = TestEmpty()
1061 def test_real():
1062 pass
1063 """
1064 )
1065 items, rec = pytester.inline_genitems()
1066 assert rec.ret == 0
1067 assert len(items) == 1
1068
1069
1070 def test_setup_only_available_in_subdir(pytester: Pytester) -> None:
1071 sub1 = pytester.mkpydir("sub1")
1072 sub2 = pytester.mkpydir("sub2")
1073 sub1.joinpath("conftest.py").write_text(
1074 textwrap.dedent(
1075 """\
1076 import pytest
1077 def pytest_runtest_setup(item):
1078 assert item.path.stem == "test_in_sub1"
1079 def pytest_runtest_call(item):
1080 assert item.path.stem == "test_in_sub1"
1081 def pytest_runtest_teardown(item):
1082 assert item.path.stem == "test_in_sub1"
1083 """
1084 ),
1085 encoding="utf-8",
1086 )
1087 sub2.joinpath("conftest.py").write_text(
1088 textwrap.dedent(
1089 """\
1090 import pytest
1091 def pytest_runtest_setup(item):
1092 assert item.path.stem == "test_in_sub2"
1093 def pytest_runtest_call(item):
1094 assert item.path.stem == "test_in_sub2"
1095 def pytest_runtest_teardown(item):
1096 assert item.path.stem == "test_in_sub2"
1097 """
1098 ),
1099 encoding="utf-8",
1100 )
1101 sub1.joinpath("test_in_sub1.py").write_text("def test_1(): pass", encoding="utf-8")
1102 sub2.joinpath("test_in_sub2.py").write_text("def test_2(): pass", encoding="utf-8")
1103 result = pytester.runpytest("-v", "-s")
1104 result.assert_outcomes(passed=2)
1105
1106
1107 def test_modulecol_roundtrip(pytester: Pytester) -> None:
1108 modcol = pytester.getmodulecol("pass", withinit=False)
1109 trail = modcol.nodeid
1110 newcol = modcol.session.perform_collect([trail], genitems=0)[0]
1111 assert modcol.name == newcol.name
1112
1113
1114 class TestTracebackCutting:
1115 def test_skip_simple(self):
1116 with pytest.raises(pytest.skip.Exception) as excinfo:
1117 pytest.skip("xxx")
1118 if sys.version_info >= (3, 11):
1119 assert excinfo.traceback[-1].frame.code.raw.co_qualname == "_Skip.__call__"
1120 assert excinfo.traceback[-1].ishidden(excinfo)
1121 assert excinfo.traceback[-2].frame.code.name == "test_skip_simple"
1122 assert not excinfo.traceback[-2].ishidden(excinfo)
1123
1124 def test_traceback_argsetup(self, pytester: Pytester) -> None:
1125 pytester.makeconftest(
1126 """
1127 import pytest
1128
1129 @pytest.fixture
1130 def hello(request):
1131 raise ValueError("xyz")
1132 """
1133 )
1134 p = pytester.makepyfile("def test(hello): pass")
1135 result = pytester.runpytest(p)
1136 assert result.ret != 0
1137 out = result.stdout.str()
1138 assert "xyz" in out
1139 assert "conftest.py:5: ValueError" in out
1140 numentries = out.count("_ _ _") # separator for traceback entries
1141 assert numentries == 0
1142
1143 result = pytester.runpytest("--fulltrace", p)
1144 out = result.stdout.str()
1145 assert "conftest.py:5: ValueError" in out
1146 numentries = out.count("_ _ _ _") # separator for traceback entries
1147 assert numentries > 3
1148
1149 def test_traceback_error_during_import(self, pytester: Pytester) -> None:
1150 pytester.makepyfile(
1151 """
1152 x = 1
1153 x = 2
1154 x = 17
1155 asd
1156 """
1157 )
1158 result = pytester.runpytest()
1159 assert result.ret != 0
1160 out = result.stdout.str()
1161 assert "x = 1" not in out
1162 assert "x = 2" not in out
1163 result.stdout.fnmatch_lines([" *asd*", "E*NameError*"])
1164 result = pytester.runpytest("--fulltrace")
1165 out = result.stdout.str()
1166 assert "x = 1" in out
1167 assert "x = 2" in out
1168 result.stdout.fnmatch_lines([">*asd*", "E*NameError*"])
1169
1170 def test_traceback_filter_error_during_fixture_collection(
1171 self, pytester: Pytester
1172 ) -> None:
1173 """Integration test for issue #995."""
1174 pytester.makepyfile(
1175 """
1176 import pytest
1177
1178 def fail_me(func):
1179 ns = {}
1180 exec('def w(): raise ValueError("fail me")', ns)
1181 return ns['w']
1182
1183 @pytest.fixture(scope='class')
1184 @fail_me
1185 def fail_fixture():
1186 pass
1187
1188 def test_failing_fixture(fail_fixture):
1189 pass
1190 """
1191 )
1192 result = pytester.runpytest()
1193 assert result.ret != 0
1194 out = result.stdout.str()
1195 assert "INTERNALERROR>" not in out
1196 result.stdout.fnmatch_lines(["*ValueError: fail me*", "* 1 error in *"])
1197
1198 def test_filter_traceback_generated_code(self) -> None:
1199 """Test that filter_traceback() works with the fact that
1200 _pytest._code.code.Code.path attribute might return an str object.
1201
1202 In this case, one of the entries on the traceback was produced by
1203 dynamically generated code.
1204 See: https://bitbucket.org/pytest-dev/py/issues/71
1205 This fixes #995.
1206 """
1207 from _pytest._code import filter_traceback
1208
1209 tb = None
1210 try:
1211 ns: dict[str, Any] = {}
1212 exec("def foo(): raise ValueError", ns)
1213 ns["foo"]()
1214 except ValueError:
1215 _, _, tb = sys.exc_info()
1216
1217 assert tb is not None
1218 traceback = _pytest._code.Traceback(tb)
1219 assert isinstance(traceback[-1].path, str)
1220 assert not filter_traceback(traceback[-1])
1221
1222 def test_filter_traceback_path_no_longer_valid(self, pytester: Pytester) -> None:
1223 """Test that filter_traceback() works with the fact that
1224 _pytest._code.code.Code.path attribute might return an str object.
1225
1226 In this case, one of the files in the traceback no longer exists.
1227 This fixes #1133.
1228 """
1229 from _pytest._code import filter_traceback
1230
1231 pytester.syspathinsert()
1232 pytester.makepyfile(
1233 filter_traceback_entry_as_str="""
1234 def foo():
1235 raise ValueError
1236 """
1237 )
1238 tb = None
1239 try:
1240 import filter_traceback_entry_as_str
1241
1242 filter_traceback_entry_as_str.foo()
1243 except ValueError:
1244 _, _, tb = sys.exc_info()
1245
1246 assert tb is not None
1247 pytester.path.joinpath("filter_traceback_entry_as_str.py").unlink()
1248 traceback = _pytest._code.Traceback(tb)
1249 assert isinstance(traceback[-1].path, str)
1250 assert filter_traceback(traceback[-1])
1251
1252
1253 class TestReportInfo:
1254 def test_itemreport_reportinfo(self, pytester: Pytester) -> None:
1255 pytester.makeconftest(
1256 """
1257 import pytest
1258 class MyFunction(pytest.Function):
1259 def reportinfo(self):
1260 return "ABCDE", 42, "custom"
1261 def pytest_pycollect_makeitem(collector, name, obj):
1262 if name == "test_func":
1263 return MyFunction.from_parent(name=name, parent=collector)
1264 """
1265 )
1266 item = pytester.getitem("def test_func(): pass")
1267 item.config.pluginmanager.getplugin("runner")
1268 assert item.location == ("ABCDE", 42, "custom")
1269
1270 def test_func_reportinfo(self, pytester: Pytester) -> None:
1271 item = pytester.getitem("def test_func(): pass")
1272 path, lineno, modpath = item.reportinfo()
1273 assert os.fspath(path) == str(item.path)
1274 assert lineno == 0
1275 assert modpath == "test_func"
1276
1277 def test_class_reportinfo(self, pytester: Pytester) -> None:
1278 modcol = pytester.getmodulecol(
1279 """
1280 # lineno 0
1281 class TestClass(object):
1282 def test_hello(self): pass
1283 """
1284 )
1285 classcol = pytester.collect_by_name(modcol, "TestClass")
1286 assert isinstance(classcol, Class)
1287 path, lineno, msg = classcol.reportinfo()
1288 assert os.fspath(path) == str(modcol.path)
1289 assert lineno == 1
1290 assert msg == "TestClass"
1291
1292 @pytest.mark.filterwarnings(
1293 "ignore:usage of Generator.Function is deprecated, please use pytest.Function instead"
1294 )
1295 def test_reportinfo_with_nasty_getattr(self, pytester: Pytester) -> None:
1296 # https://github.com/pytest-dev/pytest/issues/1204
1297 modcol = pytester.getmodulecol(
1298 """
1299 # lineno 0
1300 class TestClass:
1301 def __getattr__(self, name):
1302 return "this is not an int"
1303
1304 def __class_getattr__(cls, name):
1305 return "this is not an int"
1306
1307 def intest_foo(self):
1308 pass
1309
1310 def test_bar(self):
1311 pass
1312 """
1313 )
1314 classcol = pytester.collect_by_name(modcol, "TestClass")
1315 assert isinstance(classcol, Class)
1316 _path, _lineno, _msg = classcol.reportinfo()
1317 func = next(iter(classcol.collect()))
1318 assert isinstance(func, Function)
1319 _path, _lineno, _msg = func.reportinfo()
1320
1321
1322 def test_customized_python_discovery(pytester: Pytester) -> None:
1323 pytester.makeini(
1324 """
1325 [pytest]
1326 python_files=check_*.py
1327 python_classes=Check
1328 python_functions=check
1329 """
1330 )
1331 p = pytester.makepyfile(
1332 """
1333 def check_simple():
1334 pass
1335 class CheckMyApp(object):
1336 def check_meth(self):
1337 pass
1338 """
1339 )
1340 p2 = p.with_name(p.name.replace("test", "check"))
1341 p.rename(p2)
1342 result = pytester.runpytest("--collect-only", "-s")
1343 result.stdout.fnmatch_lines(
1344 ["*check_customized*", "*check_simple*", "*CheckMyApp*", "*check_meth*"]
1345 )
1346
1347 result = pytester.runpytest()
1348 assert result.ret == 0
1349 result.stdout.fnmatch_lines(["*2 passed*"])
1350
1351
1352 def test_customized_python_discovery_functions(pytester: Pytester) -> None:
1353 pytester.makeini(
1354 """
1355 [pytest]
1356 python_functions=_test
1357 """
1358 )
1359 pytester.makepyfile(
1360 """
1361 def _test_underscore():
1362 pass
1363 """
1364 )
1365 result = pytester.runpytest("--collect-only", "-s")
1366 result.stdout.fnmatch_lines(["*_test_underscore*"])
1367
1368 result = pytester.runpytest()
1369 assert result.ret == 0
1370 result.stdout.fnmatch_lines(["*1 passed*"])
1371
1372
1373 def test_unorderable_types(pytester: Pytester) -> None:
1374 pytester.makepyfile(
1375 """
1376 class TestJoinEmpty(object):
1377 pass
1378
1379 def make_test():
1380 class Test(object):
1381 pass
1382 Test.__name__ = "TestFoo"
1383 return Test
1384 TestFoo = make_test()
1385 """
1386 )
1387 result = pytester.runpytest()
1388 result.stdout.no_fnmatch_line("*TypeError*")
1389 assert result.ret == ExitCode.NO_TESTS_COLLECTED
1390
1391
1392 @pytest.mark.filterwarnings("default::pytest.PytestCollectionWarning")
1393 def test_dont_collect_non_function_callable(pytester: Pytester) -> None:
1394 """Test for issue https://github.com/pytest-dev/pytest/issues/331
1395
1396 In this case an INTERNALERROR occurred trying to report the failure of
1397 a test like this one because pytest failed to get the source lines.
1398 """
1399 pytester.makepyfile(
1400 """
1401 class Oh(object):
1402 def __call__(self):
1403 pass
1404
1405 test_a = Oh()
1406
1407 def test_real():
1408 pass
1409 """
1410 )
1411 result = pytester.runpytest()
1412 result.stdout.fnmatch_lines(
1413 [
1414 "*collected 1 item*",
1415 "*test_dont_collect_non_function_callable.py:2: *cannot collect 'test_a' because it is not a function*",
1416 "*1 passed, 1 warning in *",
1417 ]
1418 )
1419
1420
1421 def test_class_injection_does_not_break_collection(pytester: Pytester) -> None:
1422 """Tests whether injection during collection time will terminate testing.
1423
1424 In this case the error should not occur if the TestClass itself
1425 is modified during collection time, and the original method list
1426 is still used for collection.
1427 """
1428 pytester.makeconftest(
1429 """
1430 from test_inject import TestClass
1431 def pytest_generate_tests(metafunc):
1432 TestClass.changed_var = {}
1433 """
1434 )
1435 pytester.makepyfile(
1436 test_inject='''
1437 class TestClass(object):
1438 def test_injection(self):
1439 """Test being parametrized."""
1440 pass
1441 '''
1442 )
1443 result = pytester.runpytest()
1444 assert (
1445 "RuntimeError: dictionary changed size during iteration"
1446 not in result.stdout.str()
1447 )
1448 result.stdout.fnmatch_lines(["*1 passed*"])
1449
1450
1451 def test_syntax_error_with_non_ascii_chars(pytester: Pytester) -> None:
1452 """Fix decoding issue while formatting SyntaxErrors during collection (#578)."""
1453 pytester.makepyfile("☃")
1454 result = pytester.runpytest()
1455 result.stdout.fnmatch_lines(["*ERROR collecting*", "*SyntaxError*", "*1 error in*"])
1456
1457
1458 def test_collect_error_with_fulltrace(pytester: Pytester) -> None:
1459 pytester.makepyfile("assert 0")
1460 result = pytester.runpytest("--fulltrace")
1461 result.stdout.fnmatch_lines(
1462 [
1463 "collected 0 items / 1 error",
1464 "",
1465 "*= ERRORS =*",
1466 "*_ ERROR collecting test_collect_error_with_fulltrace.py _*",
1467 "",
1468 "> assert 0",
1469 "E assert 0",
1470 "",
1471 "test_collect_error_with_fulltrace.py:1: AssertionError",
1472 "*! Interrupted: 1 error during collection !*",
1473 ]
1474 )
1475
1476
1477 def test_skip_duplicates_by_default(pytester: Pytester) -> None:
1478 """Test for issue https://github.com/pytest-dev/pytest/issues/1609 (#1609)
1479
1480 Ignore duplicate directories.
1481 """
1482 a = pytester.mkdir("a")
1483 fh = a.joinpath("test_a.py")
1484 fh.write_text(
1485 textwrap.dedent(
1486 """\
1487 import pytest
1488 def test_real():
1489 pass
1490 """
1491 ),
1492 encoding="utf-8",
1493 )
1494 result = pytester.runpytest(str(a), str(a))
1495 result.stdout.fnmatch_lines(["*collected 1 item*"])
1496
1497
1498 def test_keep_duplicates(pytester: Pytester) -> None:
1499 """Test for issue https://github.com/pytest-dev/pytest/issues/1609 (#1609)
1500
1501 Use --keep-duplicates to collect tests from duplicate directories.
1502 """
1503 a = pytester.mkdir("a")
1504 fh = a.joinpath("test_a.py")
1505 fh.write_text(
1506 textwrap.dedent(
1507 """\
1508 import pytest
1509 def test_real():
1510 pass
1511 """
1512 ),
1513 encoding="utf-8",
1514 )
1515 result = pytester.runpytest("--keep-duplicates", str(a), str(a))
1516 result.stdout.fnmatch_lines(["*collected 2 item*"])
1517
1518
1519 def test_package_collection_infinite_recursion(pytester: Pytester) -> None:
1520 pytester.copy_example("collect/package_infinite_recursion")
1521 result = pytester.runpytest()
1522 result.stdout.fnmatch_lines(["*1 passed*"])
1523
1524
1525 def test_package_collection_init_given_as_argument(pytester: Pytester) -> None:
1526 """Regression test for #3749, #8976, #9263, #9313.
1527
1528 Specifying an __init__.py file directly should collect only the __init__.py
1529 Module, not the entire package.
1530 """
1531 p = pytester.copy_example("collect/package_init_given_as_arg")
1532 items, _hookrecorder = pytester.inline_genitems(p / "pkg" / "__init__.py")
1533 assert len(items) == 1
1534 assert items[0].name == "test_init"
1535
1536
1537 def test_package_with_modules(pytester: Pytester) -> None:
1538 """
1539 .
1540 └── root
1541 ├── __init__.py
1542 ├── sub1
1543 │ ├── __init__.py
1544 │ └── sub1_1
1545 │ ├── __init__.py
1546 │ └── test_in_sub1.py
1547 └── sub2
1548 └── test
1549 └── test_in_sub2.py
1550
1551 """
1552 root = pytester.mkpydir("root")
1553 sub1 = root.joinpath("sub1")
1554 sub1_test = sub1.joinpath("sub1_1")
1555 sub1_test.mkdir(parents=True)
1556 for d in (sub1, sub1_test):
1557 d.joinpath("__init__.py").touch()
1558
1559 sub2 = root.joinpath("sub2")
1560 sub2_test = sub2.joinpath("test")
1561 sub2_test.mkdir(parents=True)
1562
1563 sub1_test.joinpath("test_in_sub1.py").write_text(
1564 "def test_1(): pass", encoding="utf-8"
1565 )
1566 sub2_test.joinpath("test_in_sub2.py").write_text(
1567 "def test_2(): pass", encoding="utf-8"
1568 )
1569
1570 # Execute from .
1571 result = pytester.runpytest("-v", "-s")
1572 result.assert_outcomes(passed=2)
1573
1574 # Execute from . with one argument "root"
1575 result = pytester.runpytest("-v", "-s", "root")
1576 result.assert_outcomes(passed=2)
1577
1578 # Chdir into package's root and execute with no args
1579 os.chdir(root)
1580 result = pytester.runpytest("-v", "-s")
1581 result.assert_outcomes(passed=2)
1582
1583
1584 def test_package_ordering(pytester: Pytester) -> None:
1585 """
1586 .
1587 └── root
1588 ├── Test_root.py
1589 ├── __init__.py
1590 ├── sub1
1591 │ ├── Test_sub1.py
1592 │ └── __init__.py
1593 └── sub2
1594 └── test
1595 └── test_sub2.py
1596
1597 """
1598 pytester.makeini(
1599 """
1600 [pytest]
1601 python_files=*.py
1602 """
1603 )
1604 root = pytester.mkpydir("root")
1605 sub1 = root.joinpath("sub1")
1606 sub1.mkdir()
1607 sub1.joinpath("__init__.py").touch()
1608 sub2 = root.joinpath("sub2")
1609 sub2_test = sub2.joinpath("test")
1610 sub2_test.mkdir(parents=True)
1611
1612 root.joinpath("Test_root.py").write_text("def test_1(): pass", encoding="utf-8")
1613 sub1.joinpath("Test_sub1.py").write_text("def test_2(): pass", encoding="utf-8")
1614 sub2_test.joinpath("test_sub2.py").write_text(
1615 "def test_3(): pass", encoding="utf-8"
1616 )
1617
1618 # Execute from .
1619 result = pytester.runpytest("-v", "-s")
1620 result.assert_outcomes(passed=3)
1621
1622
1623 def test_collection_hierarchy(pytester: Pytester) -> None:
1624 """A general test checking that a filesystem hierarchy is collected as
1625 expected in various scenarios.
1626
1627 top/
1628 ├── aaa
1629 │ ├── pkg
1630 │ │ ├── __init__.py
1631 │ │ └── test_pkg.py
1632 │ └── test_aaa.py
1633 ├── test_a.py
1634 ├── test_b
1635 │ ├── __init__.py
1636 │ └── test_b.py
1637 ├── test_c.py
1638 └── zzz
1639 ├── dir
1640 │ └── test_dir.py
1641 ├── __init__.py
1642 └── test_zzz.py
1643 """
1644 pytester.makepyfile(
1645 **{
1646 "top/aaa/test_aaa.py": "def test_it(): pass",
1647 "top/aaa/pkg/__init__.py": "",
1648 "top/aaa/pkg/test_pkg.py": "def test_it(): pass",
1649 "top/test_a.py": "def test_it(): pass",
1650 "top/test_b/__init__.py": "",
1651 "top/test_b/test_b.py": "def test_it(): pass",
1652 "top/test_c.py": "def test_it(): pass",
1653 "top/zzz/__init__.py": "",
1654 "top/zzz/test_zzz.py": "def test_it(): pass",
1655 "top/zzz/dir/test_dir.py": "def test_it(): pass",
1656 }
1657 )
1658
1659 full = [
1660 "<Dir test_collection_hierarchy*>",
1661 " <Dir top>",
1662 " <Dir aaa>",
1663 " <Package pkg>",
1664 " <Module test_pkg.py>",
1665 " <Function test_it>",
1666 " <Module test_aaa.py>",
1667 " <Function test_it>",
1668 " <Module test_a.py>",
1669 " <Function test_it>",
1670 " <Package test_b>",
1671 " <Module test_b.py>",
1672 " <Function test_it>",
1673 " <Module test_c.py>",
1674 " <Function test_it>",
1675 " <Package zzz>",
1676 " <Dir dir>",
1677 " <Module test_dir.py>",
1678 " <Function test_it>",
1679 " <Module test_zzz.py>",
1680 " <Function test_it>",
1681 ]
1682 result = pytester.runpytest("--collect-only")
1683 result.stdout.fnmatch_lines(full, consecutive=True)
1684 result = pytester.runpytest("top", "--collect-only")
1685 result.stdout.fnmatch_lines(full, consecutive=True)
1686 result = pytester.runpytest("top", "top", "--collect-only")
1687 result.stdout.fnmatch_lines(full, consecutive=True)
1688
1689 result = pytester.runpytest(
1690 "top/aaa", "top/aaa/pkg", "--collect-only", "--keep-duplicates"
1691 )
1692 result.stdout.fnmatch_lines(
1693 [
1694 "<Dir test_collection_hierarchy*>",
1695 " <Dir top>",
1696 " <Dir aaa>",
1697 " <Package pkg>",
1698 " <Module test_pkg.py>",
1699 " <Function test_it>",
1700 " <Module test_aaa.py>",
1701 " <Function test_it>",
1702 " <Package pkg>",
1703 " <Module test_pkg.py>",
1704 " <Function test_it>",
1705 ],
1706 consecutive=True,
1707 )
1708
1709 result = pytester.runpytest(
1710 "top/aaa/pkg", "top/aaa", "--collect-only", "--keep-duplicates"
1711 )
1712 result.stdout.fnmatch_lines(
1713 [
1714 "<Dir test_collection_hierarchy*>",
1715 " <Dir top>",
1716 " <Dir aaa>",
1717 " <Package pkg>",
1718 " <Module test_pkg.py>",
1719 " <Function test_it>",
1720 " <Function test_it>",
1721 " <Module test_aaa.py>",
1722 " <Function test_it>",
1723 ],
1724 consecutive=True,
1725 )