Debian Codegraph @

testing/test_mark.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 import os
5 import sys
6 from unittest import mock
7
8 from _pytest.config import ExitCode
9 from _pytest.mark import MarkGenerator
10 from _pytest.mark.structures import EMPTY_PARAMETERSET_OPTION
11 from _pytest.nodes import Collector
12 from _pytest.nodes import Node
13 from _pytest.pytester import Pytester
14 import pytest
15
16
17 class TestMark:
18 @pytest.mark.parametrize("attr", ["mark", "param"])
19 def test_pytest_exists_in_namespace_all(self, attr: str) -> None:
20 module = sys.modules["pytest"]
21 assert attr in module.__all__
22
23 def test_pytest_mark_notcallable(self) -> None:
24 mark = MarkGenerator(_ispytest=True)
25 with pytest.raises(TypeError):
26 mark() # type: ignore[operator]
27
28 def test_mark_with_param(self):
29 def some_function(abc):
30 pass
31
32 class SomeClass:
33 pass
34
35 assert pytest.mark.foo(some_function) is some_function
36 marked_with_args = pytest.mark.foo.with_args(some_function)
37 assert marked_with_args is not some_function
38
39 assert pytest.mark.foo(SomeClass) is SomeClass
40 assert pytest.mark.foo.with_args(SomeClass) is not SomeClass # type: ignore[comparison-overlap]
41
42 def test_pytest_mark_name_starts_with_underscore(self) -> None:
43 mark = MarkGenerator(_ispytest=True)
44 with pytest.raises(AttributeError):
45 _ = mark._some_name
46
47
48 def test_marked_class_run_twice(pytester: Pytester) -> None:
49 """Test fails file is run twice that contains marked class.
50 See issue#683.
51 """
52 py_file = pytester.makepyfile(
53 """
54 import pytest
55 @pytest.mark.parametrize('abc', [1, 2, 3])
56 class Test1(object):
57 def test_1(self, abc):
58 assert abc in [1, 2, 3]
59 """
60 )
61 file_name = os.path.basename(py_file)
62 rec = pytester.inline_run("--keep-duplicates", file_name, file_name)
63 rec.assertoutcome(passed=6)
64
65
66 def test_ini_markers(pytester: Pytester) -> None:
67 pytester.makeini(
68 """
69 [pytest]
70 markers =
71 a1: this is a webtest marker
72 a2: this is a smoke marker
73 """
74 )
75 pytester.makepyfile(
76 """
77 def test_markers(pytestconfig):
78 markers = pytestconfig.getini("markers")
79 print(markers)
80 assert len(markers) >= 2
81 assert markers[0].startswith("a1:")
82 assert markers[1].startswith("a2:")
83 """
84 )
85 rec = pytester.inline_run()
86 rec.assertoutcome(passed=1)
87
88
89 def test_markers_option(pytester: Pytester) -> None:
90 pytester.makeini(
91 """
92 [pytest]
93 markers =
94 a1: this is a webtest marker
95 a1some: another marker
96 nodescription
97 """
98 )
99 result = pytester.runpytest("--markers")
100 result.stdout.fnmatch_lines(
101 ["*a1*this is a webtest*", "*a1some*another marker", "*nodescription*"]
102 )
103
104
105 def test_ini_markers_whitespace(pytester: Pytester) -> None:
106 pytester.makeini(
107 """
108 [pytest]
109 markers =
110 a1 : this is a whitespace marker
111 """
112 )
113 pytester.makepyfile(
114 """
115 import pytest
116
117 @pytest.mark.a1
118 def test_markers():
119 assert True
120 """
121 )
122 rec = pytester.inline_run("--strict-markers", "-m", "a1")
123 rec.assertoutcome(passed=1)
124
125
126 def test_marker_without_description(pytester: Pytester) -> None:
127 pytester.makefile(
128 ".cfg",
129 setup="""
130 [tool:pytest]
131 markers=slow
132 """,
133 )
134 pytester.makeconftest(
135 """
136 import pytest
137 pytest.mark.xfail('FAIL')
138 """
139 )
140 ftdir = pytester.mkdir("ft1_dummy")
141 pytester.path.joinpath("conftest.py").replace(ftdir.joinpath("conftest.py"))
142 rec = pytester.runpytest("--strict-markers")
143 rec.assert_outcomes()
144
145
146 def test_markers_option_with_plugin_in_current_dir(pytester: Pytester) -> None:
147 pytester.makeconftest('pytest_plugins = "flip_flop"')
148 pytester.makepyfile(
149 flip_flop="""\
150 def pytest_configure(config):
151 config.addinivalue_line("markers", "flip:flop")
152
153 def pytest_generate_tests(metafunc):
154 try:
155 mark = metafunc.function.flipper
156 except AttributeError:
157 return
158 metafunc.parametrize("x", (10, 20))"""
159 )
160 pytester.makepyfile(
161 """\
162 import pytest
163 @pytest.mark.flipper
164 def test_example(x):
165 assert x"""
166 )
167
168 result = pytester.runpytest("--markers")
169 result.stdout.fnmatch_lines(["*flip*flop*"])
170
171
172 def test_mark_on_pseudo_function(pytester: Pytester) -> None:
173 pytester.makepyfile(
174 """
175 import pytest
176
177 @pytest.mark.r(lambda x: 0/0)
178 def test_hello():
179 pass
180 """
181 )
182 reprec = pytester.inline_run()
183 reprec.assertoutcome(passed=1)
184
185
186 @pytest.mark.parametrize(
187 "option",
188 [
189 "--strict-markers",
190 "--strict",
191 "strict_markers = true",
192 "strict = true",
193 "addopts = --strict-markers",
194 ],
195 )
196 def test_strict_prohibits_unregistered_markers(pytester: Pytester, option: str) -> None:
197 pytester.makepyfile(
198 """
199 import pytest
200 @pytest.mark.unregisteredmark
201 def test_hello():
202 pass
203 """
204 )
205 if option.startswith("-"):
206 result = pytester.runpytest(option)
207 else:
208 pytester.makeini(
209 f"""
210 [pytest]
211 {option}
212 """
213 )
214 result = pytester.runpytest()
215 assert result.ret != 0
216 result.stdout.fnmatch_lines(
217 ["'unregisteredmark' not found in `markers` configuration option"]
218 )
219
220
221 @pytest.mark.parametrize(
222 ("expr", "expected_passed"),
223 [
224 ("xyz", ["test_one"]),
225 ("((( xyz)) )", ["test_one"]),
226 ("not not xyz", ["test_one"]),
227 ("xyz and xyz2", []),
228 ("xyz2", ["test_two"]),
229 ("xyz or xyz2", ["test_one", "test_two"]),
230 ],
231 )
232 def test_mark_option(
233 expr: str, expected_passed: list[str | None], pytester: Pytester
234 ) -> None:
235 pytester.makepyfile(
236 """
237 import pytest
238 @pytest.mark.xyz
239 def test_one():
240 pass
241 @pytest.mark.xyz2
242 def test_two():
243 pass
244 """
245 )
246 rec = pytester.inline_run("-m", expr)
247 passed, _skipped, _fail = rec.listoutcomes()
248 passed_str = [x.nodeid.split("::")[-1] for x in passed]
249 assert passed_str == expected_passed
250
251
252 @pytest.mark.parametrize(
253 ("expr", "expected_passed"),
254 [
255 ("car(color='red')", ["test_one"]),
256 ("car(color='red') or car(color='blue')", ["test_one", "test_two"]),
257 ("car and not car(temp=5)", ["test_one", "test_three"]),
258 ("car(temp=4)", ["test_one"]),
259 ("car(temp=4) or car(temp=5)", ["test_one", "test_two"]),
260 ("car(temp=4) and car(temp=5)", []),
261 ("car(temp=-5)", ["test_three"]),
262 ("car(ac=True)", ["test_one"]),
263 ("car(ac=False)", ["test_two"]),
264 ("car(ac=None)", ["test_three"]), # test NOT_NONE_SENTINEL
265 ],
266 ids=str,
267 )
268 def test_mark_option_with_kwargs(
269 expr: str, expected_passed: list[str | None], pytester: Pytester
270 ) -> None:
271 pytester.makepyfile(
272 """
273 import pytest
274 @pytest.mark.car
275 @pytest.mark.car(ac=True)
276 @pytest.mark.car(temp=4)
277 @pytest.mark.car(color="red")
278 def test_one():
279 pass
280 @pytest.mark.car
281 @pytest.mark.car(ac=False)
282 @pytest.mark.car(temp=5)
283 @pytest.mark.car(color="blue")
284 def test_two():
285 pass
286 @pytest.mark.car
287 @pytest.mark.car(ac=None)
288 @pytest.mark.car(temp=-5)
289 def test_three():
290 pass
291
292 """
293 )
294 rec = pytester.inline_run("-m", expr)
295 passed, _skipped, _fail = rec.listoutcomes()
296 passed_str = [x.nodeid.split("::")[-1] for x in passed]
297 assert passed_str == expected_passed
298
299
300 @pytest.mark.parametrize(
301 ("expr", "expected_passed"),
302 [("interface", ["test_interface"]), ("not interface", ["test_nointer"])],
303 )
304 def test_mark_option_custom(
305 expr: str, expected_passed: list[str], pytester: Pytester
306 ) -> None:
307 pytester.makeconftest(
308 """
309 import pytest
310 def pytest_collection_modifyitems(items):
311 for item in items:
312 if "interface" in item.nodeid:
313 item.add_marker(pytest.mark.interface)
314 """
315 )
316 pytester.makepyfile(
317 """
318 def test_interface():
319 pass
320 def test_nointer():
321 pass
322 """
323 )
324 rec = pytester.inline_run("-m", expr)
325 passed, _skipped, _fail = rec.listoutcomes()
326 passed_str = [x.nodeid.split("::")[-1] for x in passed]
327 assert passed_str == expected_passed
328
329
330 @pytest.mark.parametrize(
331 ("expr", "expected_passed"),
332 [
333 ("interface", ["test_interface"]),
334 ("not interface", ["test_nointer", "test_pass", "test_1", "test_2"]),
335 ("pass", ["test_pass"]),
336 ("not pass", ["test_interface", "test_nointer", "test_1", "test_2"]),
337 ("not not not (pass)", ["test_interface", "test_nointer", "test_1", "test_2"]),
338 ("1 or 2", ["test_1", "test_2"]),
339 ("not (1 or 2)", ["test_interface", "test_nointer", "test_pass"]),
340 ],
341 )
342 def test_keyword_option_custom(
343 expr: str, expected_passed: list[str], pytester: Pytester
344 ) -> None:
345 pytester.makepyfile(
346 """
347 def test_interface():
348 pass
349 def test_nointer():
350 pass
351 def test_pass():
352 pass
353 def test_1():
354 pass
355 def test_2():
356 pass
357 """
358 )
359 rec = pytester.inline_run("-k", expr)
360 passed, _skipped, _fail = rec.listoutcomes()
361 passed_str = [x.nodeid.split("::")[-1] for x in passed]
362 assert passed_str == expected_passed
363
364
365 def test_keyword_option_considers_mark(pytester: Pytester) -> None:
366 pytester.copy_example("marks/marks_considered_keywords")
367 rec = pytester.inline_run("-k", "foo")
368 passed = rec.listoutcomes()[0]
369 assert len(passed) == 1
370
371
372 @pytest.mark.parametrize(
373 ("expr", "expected_passed"),
374 [
375 ("None", ["test_func[None]"]),
376 ("[1.3]", ["test_func[1.3]"]),
377 ("2-3", ["test_func[2-3]"]),
378 ],
379 )
380 def test_keyword_option_parametrize(
381 expr: str, expected_passed: list[str], pytester: Pytester
382 ) -> None:
383 pytester.makepyfile(
384 """
385 import pytest
386 @pytest.mark.parametrize("arg", [None, 1.3, "2-3"])
387 def test_func(arg):
388 pass
389 """
390 )
391 rec = pytester.inline_run("-k", expr)
392 passed, _skipped, _fail = rec.listoutcomes()
393 passed_str = [x.nodeid.split("::")[-1] for x in passed]
394 assert passed_str == expected_passed
395
396
397 def test_parametrize_with_module(pytester: Pytester) -> None:
398 pytester.makepyfile(
399 """
400 import pytest
401 @pytest.mark.parametrize("arg", [pytest,])
402 def test_func(arg):
403 pass
404 """
405 )
406 rec = pytester.inline_run()
407 passed, _skipped, _fail = rec.listoutcomes()
408 expected_id = "test_func[" + pytest.__name__ + "]"
409 assert passed[0].nodeid.split("::")[-1] == expected_id
410
411
412 @pytest.mark.parametrize(
413 ("expr", "expected_error"),
414 [
415 (
416 "foo or",
417 "at column 7: expected not OR left parenthesis OR identifier; got end of input",
418 ),
419 (
420 "foo or or",
421 "at column 8: expected not OR left parenthesis OR identifier; got or",
422 ),
423 (
424 "(foo",
425 "at column 5: expected right parenthesis; got end of input",
426 ),
427 (
428 "foo bar",
429 "at column 5: expected end of input; got identifier",
430 ),
431 (
432 "or or",
433 "at column 1: expected not OR left parenthesis OR identifier; got or",
434 ),
435 (
436 "not or",
437 "at column 5: expected not OR left parenthesis OR identifier; got or",
438 ),
439 (
440 "nonexistent_mark(non_supported='kwarg')",
441 "Keyword expressions do not support call parameters",
442 ),
443 ],
444 )
445 def test_keyword_option_wrong_arguments(
446 expr: str, expected_error: str, pytester: Pytester, capsys
447 ) -> None:
448 pytester.makepyfile(
449 """
450 def test_func(arg):
451 pass
452 """
453 )
454 pytester.inline_run("-k", expr)
455 err = capsys.readouterr().err
456 assert expected_error in err
457
458
459 def test_parametrized_collected_from_command_line(pytester: Pytester) -> None:
460 """Parametrized test not collected if test named specified in command
461 line issue#649."""
462 py_file = pytester.makepyfile(
463 """
464 import pytest
465 @pytest.mark.parametrize("arg", [None, 1.3, "2-3"])
466 def test_func(arg):
467 pass
468 """
469 )
470 file_name = os.path.basename(py_file)
471 rec = pytester.inline_run(file_name + "::" + "test_func")
472 rec.assertoutcome(passed=3)
473
474
475 def test_parametrized_collect_with_wrong_args(pytester: Pytester) -> None:
476 """Test collect parametrized func with wrong number of args."""
477 py_file = pytester.makepyfile(
478 """
479 import pytest
480
481 @pytest.mark.parametrize('foo, bar', [(1, 2, 3)])
482 def test_func(foo, bar):
483 pass
484 """
485 )
486
487 result = pytester.runpytest(py_file)
488 result.stdout.fnmatch_lines(
489 [
490 'test_parametrized_collect_with_wrong_args.py::test_func: in "parametrize" the number of names (2):',
491 " ['foo', 'bar']",
492 "must be equal to the number of values (3):",
493 " (1, 2, 3)",
494 ]
495 )
496
497
498 def test_parametrized_with_kwargs(pytester: Pytester) -> None:
499 """Test collect parametrized func with wrong number of args."""
500 py_file = pytester.makepyfile(
501 """
502 import pytest
503
504 @pytest.fixture(params=[1,2])
505 def a(request):
506 return request.param
507
508 @pytest.mark.parametrize(argnames='b', argvalues=[1, 2])
509 def test_func(a, b):
510 pass
511 """
512 )
513
514 result = pytester.runpytest(py_file)
515 assert result.ret == 0
516
517
518 def test_parametrize_iterator(pytester: Pytester) -> None:
519 """`parametrize` should work with generators (#5354)."""
520 py_file = pytester.makepyfile(
521 """\
522 import pytest
523
524 def gen():
525 yield 1
526 yield 2
527 yield 3
528
529 @pytest.mark.parametrize('a', gen())
530 def test(a):
531 assert a >= 1
532 """
533 )
534 result = pytester.runpytest(py_file)
535 assert result.ret == 0
536 # should not skip any tests
537 result.stdout.fnmatch_lines(["*3 passed*"])
538
539
540 class TestFunctional:
541 def test_merging_markers_deep(self, pytester: Pytester) -> None:
542 # issue 199 - propagate markers into nested classes
543 p = pytester.makepyfile(
544 """
545 import pytest
546 class TestA(object):
547 pytestmark = pytest.mark.a
548 def test_b(self):
549 assert True
550 class TestC(object):
551 # this one didn't get marked
552 def test_d(self):
553 assert True
554 """
555 )
556 items, _rec = pytester.inline_genitems(p)
557 for item in items:
558 print(item, item.keywords)
559 assert [x for x in item.iter_markers() if x.name == "a"]
560
561 def test_mark_decorator_subclass_does_not_propagate_to_base(
562 self, pytester: Pytester
563 ) -> None:
564 p = pytester.makepyfile(
565 """
566 import pytest
567
568 @pytest.mark.a
569 class Base(object): pass
570
571 @pytest.mark.b
572 class Test1(Base):
573 def test_foo(self): pass
574
575 class Test2(Base):
576 def test_bar(self): pass
577 """
578 )
579 items, _rec = pytester.inline_genitems(p)
580 self.assert_markers(items, test_foo=("a", "b"), test_bar=("a",))
581
582 def test_mark_should_not_pass_to_siebling_class(self, pytester: Pytester) -> None:
583 """#568"""
584 p = pytester.makepyfile(
585 """
586 import pytest
587
588 class TestBase(object):
589 def test_foo(self):
590 pass
591
592 @pytest.mark.b
593 class TestSub(TestBase):
594 pass
595
596
597 class TestOtherSub(TestBase):
598 pass
599
600 """
601 )
602 items, _rec = pytester.inline_genitems(p)
603 base_item, sub_item, sub_item_other = items
604 print(items, [x.nodeid for x in items])
605 # new api segregates
606 assert not list(base_item.iter_markers(name="b"))
607 assert not list(sub_item_other.iter_markers(name="b"))
608 assert list(sub_item.iter_markers(name="b"))
609
610 def test_mark_decorator_baseclasses_merged(self, pytester: Pytester) -> None:
611 p = pytester.makepyfile(
612 """
613 import pytest
614
615 @pytest.mark.a
616 class Base(object): pass
617
618 @pytest.mark.b
619 class Base2(Base): pass
620
621 @pytest.mark.c
622 class Test1(Base2):
623 def test_foo(self): pass
624
625 class Test2(Base2):
626 @pytest.mark.d
627 def test_bar(self): pass
628 """
629 )
630 items, _rec = pytester.inline_genitems(p)
631 self.assert_markers(items, test_foo=("a", "b", "c"), test_bar=("a", "b", "d"))
632
633 def test_mark_closest(self, pytester: Pytester) -> None:
634 p = pytester.makepyfile(
635 """
636 import pytest
637
638 @pytest.mark.c(location="class")
639 class Test:
640 @pytest.mark.c(location="function")
641 def test_has_own(self):
642 pass
643
644 def test_has_inherited(self):
645 pass
646
647 """
648 )
649 items, _rec = pytester.inline_genitems(p)
650 has_own, has_inherited = items
651 has_own_marker = has_own.get_closest_marker("c")
652 has_inherited_marker = has_inherited.get_closest_marker("c")
653 assert has_own_marker is not None
654 assert has_inherited_marker is not None
655 assert has_own_marker.kwargs == {"location": "function"}
656 assert has_inherited_marker.kwargs == {"location": "class"}
657 assert has_own.get_closest_marker("missing") is None
658
659 def test_mark_with_wrong_marker(self, pytester: Pytester) -> None:
660 reprec = pytester.inline_runsource(
661 """
662 import pytest
663 class pytestmark(object):
664 pass
665 def test_func():
666 pass
667 """
668 )
669 values = reprec.getfailedcollections()
670 assert len(values) == 1
671 assert "TypeError" in str(values[0].longrepr)
672
673 def test_mark_dynamically_in_funcarg(self, pytester: Pytester) -> None:
674 pytester.makeconftest(
675 """
676 import pytest
677 @pytest.fixture
678 def arg(request):
679 request.applymarker(pytest.mark.hello)
680 def pytest_terminal_summary(terminalreporter):
681 values = terminalreporter.stats['passed']
682 terminalreporter._tw.line("keyword: %s" % values[0].keywords)
683 """
684 )
685 pytester.makepyfile(
686 """
687 def test_func(arg):
688 pass
689 """
690 )
691 result = pytester.runpytest()
692 result.stdout.fnmatch_lines(["keyword: *hello*"])
693
694 def test_no_marker_match_on_unmarked_names(self, pytester: Pytester) -> None:
695 p = pytester.makepyfile(
696 """
697 import pytest
698 @pytest.mark.shouldmatch
699 def test_marked():
700 assert 1
701
702 def test_unmarked():
703 assert 1
704 """
705 )
706 reprec = pytester.inline_run("-m", "test_unmarked", p)
707 passed, skipped, failed = reprec.listoutcomes()
708 assert len(passed) + len(skipped) + len(failed) == 0
709 dlist = reprec.getcalls("pytest_deselected")
710 deselected_tests = dlist[0].items
711 assert len(deselected_tests) == 2
712
713 def test_keywords_at_node_level(self, pytester: Pytester) -> None:
714 pytester.makepyfile(
715 """
716 import pytest
717 @pytest.fixture(scope="session", autouse=True)
718 def some(request):
719 request.keywords["hello"] = 42
720 assert "world" not in request.keywords
721
722 @pytest.fixture(scope="function", autouse=True)
723 def funcsetup(request):
724 assert "world" in request.keywords
725 assert "hello" in request.keywords
726
727 @pytest.mark.world
728 def test_function():
729 pass
730 """
731 )
732 reprec = pytester.inline_run()
733 reprec.assertoutcome(passed=1)
734
735 def test_keyword_added_for_session(self, pytester: Pytester) -> None:
736 pytester.makeconftest(
737 """
738 import pytest
739 def pytest_collection_modifyitems(session):
740 session.add_marker("mark1")
741 session.add_marker(pytest.mark.mark2)
742 session.add_marker(pytest.mark.mark3)
743 with pytest.raises(ValueError):
744 session.add_marker(10)
745 """
746 )
747 pytester.makepyfile(
748 """
749 def test_some(request):
750 assert "mark1" in request.keywords
751 assert "mark2" in request.keywords
752 assert "mark3" in request.keywords
753 assert 10 not in request.keywords
754 marker = request.node.get_closest_marker("mark1")
755 assert marker.name == "mark1"
756 assert marker.args == ()
757 assert marker.kwargs == {}
758 """
759 )
760 reprec = pytester.inline_run("-m", "mark1")
761 reprec.assertoutcome(passed=1)
762
763 def assert_markers(self, items, **expected) -> None:
764 """Assert that given items have expected marker names applied to them.
765 expected should be a dict of (item name -> seq of expected marker names).
766
767 Note: this could be moved to ``pytester`` if proven to be useful
768 to other modules.
769 """
770 items = {x.name: x for x in items}
771 for name, expected_markers in expected.items():
772 markers = {m.name for m in items[name].iter_markers()}
773 assert markers == set(expected_markers)
774
775 @pytest.mark.filterwarnings("ignore")
776 def test_mark_from_parameters(self, pytester: Pytester) -> None:
777 """#1540"""
778 pytester.makepyfile(
779 """
780 import pytest
781
782 pytestmark = pytest.mark.skipif(True, reason='skip all')
783
784 # skipifs inside fixture params
785 params = [pytest.mark.skipif(False, reason='dont skip')('parameter')]
786
787
788 @pytest.fixture(params=params)
789 def parameter(request):
790 return request.param
791
792
793 def test_1(parameter):
794 assert True
795 """
796 )
797 reprec = pytester.inline_run()
798 reprec.assertoutcome(skipped=1)
799
800 def test_reevaluate_dynamic_expr(self, pytester: Pytester) -> None:
801 """#7360"""
802 py_file1 = pytester.makepyfile(
803 test_reevaluate_dynamic_expr1="""
804 import pytest
805
806 skip = True
807
808 @pytest.mark.skipif("skip")
809 def test_should_skip():
810 assert True
811 """
812 )
813 py_file2 = pytester.makepyfile(
814 test_reevaluate_dynamic_expr2="""
815 import pytest
816
817 skip = False
818
819 @pytest.mark.skipif("skip")
820 def test_should_not_skip():
821 assert True
822 """
823 )
824
825 file_name1 = os.path.basename(py_file1)
826 file_name2 = os.path.basename(py_file2)
827 reprec = pytester.inline_run(file_name1, file_name2)
828 reprec.assertoutcome(passed=1, skipped=1)
829
830
831 class TestKeywordSelection:
832 def test_select_simple(self, pytester: Pytester) -> None:
833 file_test = pytester.makepyfile(
834 """
835 def test_one():
836 assert 0
837 class TestClass(object):
838 def test_method_one(self):
839 assert 42 == 43
840 """
841 )
842
843 def check(keyword, name):
844 reprec = pytester.inline_run("-s", "-k", keyword, file_test)
845 _passed, _skipped, failed = reprec.listoutcomes()
846 assert len(failed) == 1
847 assert failed[0].nodeid.split("::")[-1] == name
848 assert len(reprec.getcalls("pytest_deselected")) == 1
849
850 for keyword in ["test_one", "est_on"]:
851 check(keyword, "test_one")
852 check("TestClass and test", "test_method_one")
853
854 @pytest.mark.parametrize(
855 "keyword",
856 [
857 "xxx",
858 "xxx and test_2",
859 "TestClass",
860 "xxx and not test_1",
861 "TestClass and test_2",
862 "xxx and TestClass and test_2",
863 ],
864 )
865 def test_select_extra_keywords(self, pytester: Pytester, keyword) -> None:
866 p = pytester.makepyfile(
867 test_select="""
868 def test_1():
869 pass
870 class TestClass(object):
871 def test_2(self):
872 pass
873 """
874 )
875 pytester.makepyfile(
876 conftest="""
877 import pytest
878 @pytest.hookimpl(wrapper=True)
879 def pytest_pycollect_makeitem(name):
880 item = yield
881 if name == "TestClass":
882 item.extra_keyword_matches.add("xxx")
883 return item
884 """
885 )
886 reprec = pytester.inline_run(p.parent, "-s", "-k", keyword)
887 print("keyword", repr(keyword))
888 passed, _skipped, _failed = reprec.listoutcomes()
889 assert len(passed) == 1
890 assert passed[0].nodeid.endswith("test_2")
891 dlist = reprec.getcalls("pytest_deselected")
892 assert len(dlist) == 1
893 assert dlist[0].items[0].name == "test_1"
894
895 def test_keyword_extra(self, pytester: Pytester) -> None:
896 p = pytester.makepyfile(
897 """
898 def test_one():
899 assert 0
900 test_one.mykeyword = True
901 """
902 )
903 reprec = pytester.inline_run("-k", "mykeyword", p)
904 _passed, _skipped, failed = reprec.countoutcomes()
905 assert failed == 1
906
907 @pytest.mark.xfail
908 def test_keyword_extra_dash(self, pytester: Pytester) -> None:
909 p = pytester.makepyfile(
910 """
911 def test_one():
912 assert 0
913 test_one.mykeyword = True
914 """
915 )
916 # with argparse the argument to an option cannot
917 # start with '-'
918 reprec = pytester.inline_run("-k", "-mykeyword", p)
919 passed, skipped, failed = reprec.countoutcomes()
920 assert passed + skipped + failed == 0
921
922 @pytest.mark.parametrize(
923 "keyword",
924 ["__", "+", ".."],
925 )
926 def test_no_magic_values(self, pytester: Pytester, keyword: str) -> None:
927 """Make sure the tests do not match on magic values,
928 no double underscored values, like '__dict__' and '+'.
929 """
930 p = pytester.makepyfile(
931 """
932 def test_one(): assert 1
933 """
934 )
935
936 reprec = pytester.inline_run("-k", keyword, p)
937 passed, skipped, failed = reprec.countoutcomes()
938 dlist = reprec.getcalls("pytest_deselected")
939 assert passed + skipped + failed == 0
940 deselected_tests = dlist[0].items
941 assert len(deselected_tests) == 1
942
943 def test_no_match_directories_outside_the_suite(
944 self,
945 pytester: Pytester,
946 monkeypatch: pytest.MonkeyPatch,
947 ) -> None:
948 """`-k` should not match against directories containing the test suite (#7040)."""
949 pytester.makefile(
950 **{
951 "suite/pytest": """[pytest]""",
952 },
953 ext=".ini",
954 )
955 pytester.makepyfile(
956 **{
957 "suite/ddd/tests/__init__.py": "",
958 "suite/ddd/tests/test_foo.py": """
959 def test_aaa(): pass
960 def test_ddd(): pass
961 """,
962 }
963 )
964 monkeypatch.chdir(pytester.path / "suite")
965
966 def get_collected_names(*args: str) -> list[str]:
967 _, rec = pytester.inline_genitems(*args)
968 calls = rec.getcalls("pytest_collection_finish")
969 assert len(calls) == 1
970 return [x.name for x in calls[0].session.items]
971
972 # sanity check: collect both tests in normal runs
973 assert get_collected_names() == ["test_aaa", "test_ddd"]
974
975 # do not collect anything based on names outside the collection tree
976 assert get_collected_names("-k", pytester._name) == []
977
978
979 class TestMarkDecorator:
980 @pytest.mark.parametrize(
981 "lhs, rhs, expected",
982 [
983 (pytest.mark.foo(), pytest.mark.foo(), True),
984 (pytest.mark.foo(), pytest.mark.bar(), False),
985 (pytest.mark.foo(), "bar", False),
986 ("foo", pytest.mark.bar(), False),
987 ],
988 )
989 def test__eq__(self, lhs, rhs, expected) -> None:
990 assert (lhs == rhs) == expected
991
992 def test_aliases(self) -> None:
993 md = pytest.mark.foo(1, "2", three=3)
994 assert md.name == "foo"
995 assert md.args == (1, "2")
996 assert md.kwargs == {"three": 3}
997
998
999 @pytest.mark.parametrize("mark", [None, "", "skip", "xfail"])
1000 def test_parameterset_for_parametrize_marks(
1001 pytester: Pytester, mark: str | None
1002 ) -> None:
1003 if mark is not None:
1004 pytester.makeini(
1005 f"""
1006 [pytest]
1007 {EMPTY_PARAMETERSET_OPTION}={mark}
1008 """
1009 )
1010
1011 config = pytester.parseconfig()
1012 from _pytest.mark import get_empty_parameterset_mark
1013 from _pytest.mark import pytest_configure
1014
1015 pytest_configure(config)
1016 result_mark = get_empty_parameterset_mark(config, ["a"], all)
1017 if mark in (None, ""):
1018 # normalize to the requested name
1019 mark = "skip"
1020 assert result_mark.name == mark
1021 assert result_mark.kwargs["reason"].startswith("got empty parameter set ")
1022 if mark == "xfail":
1023 assert result_mark.kwargs.get("run") is False
1024
1025
1026 def test_parameterset_for_fail_at_collect(pytester: Pytester) -> None:
1027 pytester.makeini(
1028 f"""
1029 [pytest]
1030 {EMPTY_PARAMETERSET_OPTION}=fail_at_collect
1031 """
1032 )
1033
1034 config = pytester.parseconfig()
1035 from _pytest.mark import get_empty_parameterset_mark
1036 from _pytest.mark import pytest_configure
1037
1038 pytest_configure(config)
1039
1040 with pytest.raises(
1041 Collector.CollectError,
1042 match=r"Empty parameter set in 'pytest_configure' at line \d\d+",
1043 ):
1044 get_empty_parameterset_mark(config, ["a"], pytest_configure)
1045
1046 p1 = pytester.makepyfile(
1047 """
1048 import pytest
1049
1050 @pytest.mark.parametrize("empty", [])
1051 def test():
1052 pass
1053 """
1054 )
1055 result = pytester.runpytest(str(p1))
1056 result.stdout.fnmatch_lines(
1057 [
1058 "collected 0 items / 1 error",
1059 "* ERROR collecting test_parameterset_for_fail_at_collect.py *",
1060 "Empty parameter set in 'test' at line 3",
1061 "*= 1 error in *",
1062 ]
1063 )
1064 assert result.ret == ExitCode.INTERRUPTED
1065
1066
1067 def test_paramset_empty_no_idfunc(
1068 pytester: Pytester, monkeypatch: pytest.MonkeyPatch
1069 ) -> None:
1070 """An empty parameter set should not call the user provided id function (#13031)."""
1071 p1 = pytester.makepyfile(
1072 """
1073 import pytest
1074
1075 def idfunc(value):
1076 raise ValueError()
1077 @pytest.mark.parametrize("param", [], ids=idfunc)
1078 def test(param):
1079 pass
1080 """
1081 )
1082 result = pytester.runpytest(p1, "-v", "-rs")
1083 result.stdout.fnmatch_lines(
1084 [
1085 "* collected 1 item",
1086 "test_paramset_empty_no_idfunc* SKIPPED *",
1087 "SKIPPED [1] test_paramset_empty_no_idfunc.py:5: got empty parameter set for (param)",
1088 "*= 1 skipped in *",
1089 ]
1090 )
1091
1092
1093 def test_parameterset_for_parametrize_bad_markname(pytester: Pytester) -> None:
1094 with pytest.raises(pytest.UsageError):
1095 test_parameterset_for_parametrize_marks(pytester, "bad")
1096
1097
1098 def test_mark_expressions_no_smear(pytester: Pytester) -> None:
1099 pytester.makepyfile(
1100 """
1101 import pytest
1102
1103 class BaseTests(object):
1104 def test_something(self):
1105 pass
1106
1107 @pytest.mark.FOO
1108 class TestFooClass(BaseTests):
1109 pass
1110
1111 @pytest.mark.BAR
1112 class TestBarClass(BaseTests):
1113 pass
1114 """
1115 )
1116
1117 reprec = pytester.inline_run("-m", "FOO")
1118 passed, skipped, failed = reprec.countoutcomes()
1119 dlist = reprec.getcalls("pytest_deselected")
1120 assert passed == 1
1121 assert skipped == failed == 0
1122 deselected_tests = dlist[0].items
1123 assert len(deselected_tests) == 1
1124
1125 # todo: fixed
1126 # keywords smear - expected behaviour
1127 # reprec_keywords = pytester.inline_run("-k", "FOO")
1128 # passed_k, skipped_k, failed_k = reprec_keywords.countoutcomes()
1129 # assert passed_k == 2
1130 # assert skipped_k == failed_k == 0
1131
1132
1133 def test_addmarker_order(pytester) -> None:
1134 session = mock.Mock()
1135 session.own_markers = []
1136 session.parent = None
1137 session.nodeid = ""
1138 session.path = pytester.path
1139 node = Node.from_parent(session, name="Test")
1140 node.add_marker("foo")
1141 node.add_marker("bar")
1142 node.add_marker("baz", append=False)
1143 extracted = [x.name for x in node.iter_markers()]
1144 assert extracted == ["baz", "foo", "bar"]
1145
1146
1147 @pytest.mark.filterwarnings("ignore")
1148 def test_markers_from_parametrize(pytester: Pytester) -> None:
1149 """#3605"""
1150 pytester.makepyfile(
1151 """
1152 import pytest
1153
1154 first_custom_mark = pytest.mark.custom_marker
1155 custom_mark = pytest.mark.custom_mark
1156 @pytest.fixture(autouse=True)
1157 def trigger(request):
1158 custom_mark = list(request.node.iter_markers('custom_mark'))
1159 print("Custom mark %s" % custom_mark)
1160
1161 @custom_mark("custom mark non parametrized")
1162 def test_custom_mark_non_parametrized():
1163 print("Hey from test")
1164
1165 @pytest.mark.parametrize(
1166 "obj_type",
1167 [
1168 first_custom_mark("first custom mark")("template"),
1169 pytest.param( # Think this should be recommended way?
1170 "disk",
1171 marks=custom_mark('custom mark1')
1172 ),
1173 custom_mark("custom mark2")("vm"), # Tried also this
1174 ]
1175 )
1176 def test_custom_mark_parametrized(obj_type):
1177 print("obj_type is:", obj_type)
1178 """
1179 )
1180
1181 result = pytester.runpytest()
1182 result.assert_outcomes(passed=4)
1183
1184
1185 def test_pytest_param_id_requires_string() -> None:
1186 with pytest.raises(TypeError) as excinfo:
1187 pytest.param(id=True) # type: ignore[arg-type]
1188 (msg,) = excinfo.value.args
1189 expected = (
1190 "Expected id to be a string or a `pytest.HIDDEN_PARAM` sentinel, "
1191 "got <class 'bool'>: True"
1192 )
1193 assert msg == expected
1194
1195
1196 @pytest.mark.parametrize("s", (None, "hello world"))
1197 def test_pytest_param_id_allows_none_or_string(s) -> None:
1198 assert pytest.param(id=s)
1199
1200
1201 @pytest.mark.parametrize("expr", ("NOT internal_err", "NOT (internal_err)", "bogus="))
1202 def test_marker_expr_eval_failure_handling(pytester: Pytester, expr) -> None:
1203 foo = pytester.makepyfile(
1204 """
1205 import pytest
1206
1207 @pytest.mark.internal_err
1208 def test_foo():
1209 pass
1210 """
1211 )
1212 expected = f"ERROR: Wrong expression passed to '-m': {expr}: *"
1213 result = pytester.runpytest(foo, "-m", expr)
1214 result.stderr.fnmatch_lines([expected])
1215 assert result.ret == ExitCode.USAGE_ERROR
1216
1217
1218 def test_mark_mro() -> None:
1219 xfail = pytest.mark.xfail
1220
1221 @xfail("a")
1222 class A:
1223 pass
1224
1225 @xfail("b")
1226 class B:
1227 pass
1228
1229 @xfail("c")
1230 class C(A, B):
1231 pass
1232
1233 from _pytest.mark.structures import get_unpacked_marks
1234
1235 all_marks = get_unpacked_marks(C)
1236
1237 assert all_marks == [xfail("b").mark, xfail("a").mark, xfail("c").mark]
1238
1239 assert get_unpacked_marks(C, consider_mro=False) == [xfail("c").mark]
1240
1241
1242 # @pytest.mark.issue("https://github.com/pytest-dev/pytest/issues/10447")
1243 def test_mark_fixture_order_mro(pytester: Pytester):
1244 """This ensures we walk marks of the mro starting with the base classes
1245 the action at a distance fixtures are taken as minimal example from a real project
1246
1247 """
1248 foo = pytester.makepyfile(
1249 """
1250 import pytest
1251
1252 @pytest.fixture
1253 def add_attr1(request):
1254 request.instance.attr1 = object()
1255
1256
1257 @pytest.fixture
1258 def add_attr2(request):
1259 request.instance.attr2 = request.instance.attr1
1260
1261
1262 @pytest.mark.usefixtures('add_attr1')
1263 class Parent:
1264 pass
1265
1266
1267 @pytest.mark.usefixtures('add_attr2')
1268 class TestThings(Parent):
1269 def test_attrs(self):
1270 assert self.attr1 == self.attr2
1271 """
1272 )
1273 result = pytester.runpytest(foo)
1274 result.assert_outcomes(passed=1)
1275
1276
1277 def test_mark_parametrize_over_staticmethod(pytester: Pytester) -> None:
1278 """Check that applying marks works as intended on classmethods and staticmethods.
1279
1280 Regression test for #12863.
1281 """
1282 pytester.makepyfile(
1283 """
1284 import pytest
1285
1286 class TestClass:
1287 @pytest.mark.parametrize("value", [1, 2])
1288 @classmethod
1289 def test_classmethod_wrapper(cls, value: int):
1290 assert value in [1, 2]
1291
1292 @classmethod
1293 @pytest.mark.parametrize("value", [1, 2])
1294 def test_classmethod_wrapper_on_top(cls, value: int):
1295 assert value in [1, 2]
1296
1297 @pytest.mark.parametrize("value", [1, 2])
1298 @staticmethod
1299 def test_staticmethod_wrapper(value: int):
1300 assert value in [1, 2]
1301
1302 @staticmethod
1303 @pytest.mark.parametrize("value", [1, 2])
1304 def test_staticmethod_wrapper_on_top(value: int):
1305 assert value in [1, 2]
1306 """
1307 )
1308 result = pytester.runpytest()
1309 result.assert_outcomes(passed=8)
1310
1311
1312 def test_fixture_disallow_on_marked_functions() -> None:
1313 """Test that applying @pytest.fixture to a marked function errors (#3364)."""
1314 with pytest.raises(
1315 pytest.fail.Exception,
1316 match=r"Marks cannot be applied to fixtures",
1317 ):
1318
1319 @pytest.fixture
1320 @pytest.mark.parametrize("example", ["hello"])
1321 @pytest.mark.usefixtures("tmp_path")
1322 def foo():
1323 raise NotImplementedError()
1324
1325
1326 def test_fixture_disallow_marks_on_fixtures() -> None:
1327 """Test that applying a mark to a fixture errors (#3364)."""
1328 with pytest.raises(
1329 pytest.fail.Exception,
1330 match=r"Marks cannot be applied to fixtures",
1331 ):
1332
1333 @pytest.mark.parametrize("example", ["hello"])
1334 @pytest.mark.usefixtures("tmp_path")
1335 @pytest.fixture
1336 def foo():
1337 raise NotImplementedError()
1338
1339
1340 def test_fixture_disallowed_between_marks() -> None:
1341 """Test that applying a mark to a fixture errors (#3364)."""
1342 with pytest.raises(
1343 pytest.fail.Exception,
1344 match=r"Marks cannot be applied to fixtures",
1345 ):
1346
1347 @pytest.mark.parametrize("example", ["hello"])
1348 @pytest.fixture
1349 @pytest.mark.usefixtures("tmp_path")
1350 def foo():
1351 raise NotImplementedError()
1352
1353
1354 def test_module_getattr_without_attributeerror(pytester: Pytester) -> None:
1355 """
1356 Test that a helpful warning is emitted when a module-level
1357 __getattr__ returns None instead of raising AttributeError.
1358
1359 Regression test for https://github.com/pytest-dev/pytest/issues/8265
1360 """
1361 pytester.makepyfile(
1362 """
1363 def __getattr__(key):
1364 # Bug: should raise AttributeError, but returns None
1365 return None
1366
1367 def test_something():
1368 assert True
1369 """
1370 )
1371 result = pytester.runpytest("-W", "always::pytest.PytestCollectionWarning")
1372 result.stdout.fnmatch_lines(
1373 [
1374 "*PytestCollectionWarning*__getattr__*returns None*AttributeError*",
1375 ]
1376 )
1377 # The module is buggy (__getattr__ returns None for all attributes),
1378 # so no tests are collected, but pytest should NOT crash with a TypeError.
1379 assert result.ret != ExitCode.INTERNAL_ERROR