Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/testing/test_assertion.py

raw
1 # mypy: allow-untyped-defs
2 import sys
3 import textwrap
4 from typing import Any
5 from typing import List
6 from typing import MutableSequence
7 from typing import NamedTuple
8 from typing import Optional
9
10 import attr
11
12 from _pytest import outcomes
13 import _pytest.assertion as plugin
14 from _pytest.assertion import truncate
15 from _pytest.assertion import util
16 from _pytest.config import Config as _Config
17 from _pytest.monkeypatch import MonkeyPatch
18 from _pytest.pytester import Pytester
19 import pytest
20
21
22 def mock_config(verbose: int = 0, assertion_override: Optional[int] = None):
23 class TerminalWriter:
24 def _highlight(self, source, lexer="python"):
25 return source
26
27 class Config:
28 def get_terminal_writer(self):
29 return TerminalWriter()
30
31 def get_verbosity(self, verbosity_type: Optional[str] = None) -> int:
32 if verbosity_type is None:
33 return verbose
34 if verbosity_type == _Config.VERBOSITY_ASSERTIONS:
35 if assertion_override is not None:
36 return assertion_override
37 return verbose
38
39 raise KeyError(f"Not mocked out: {verbosity_type}")
40
41 return Config()
42
43
44 class TestMockConfig:
45 SOME_VERBOSITY_LEVEL = 3
46 SOME_OTHER_VERBOSITY_LEVEL = 10
47
48 def test_verbose_exposes_value(self):
49 config = mock_config(verbose=TestMockConfig.SOME_VERBOSITY_LEVEL)
50
51 assert config.get_verbosity() == TestMockConfig.SOME_VERBOSITY_LEVEL
52
53 def test_get_assertion_override_not_set_verbose_value(self):
54 config = mock_config(verbose=TestMockConfig.SOME_VERBOSITY_LEVEL)
55
56 assert (
57 config.get_verbosity(_Config.VERBOSITY_ASSERTIONS)
58 == TestMockConfig.SOME_VERBOSITY_LEVEL
59 )
60
61 def test_get_assertion_override_set_custom_value(self):
62 config = mock_config(
63 verbose=TestMockConfig.SOME_VERBOSITY_LEVEL,
64 assertion_override=TestMockConfig.SOME_OTHER_VERBOSITY_LEVEL,
65 )
66
67 assert (
68 config.get_verbosity(_Config.VERBOSITY_ASSERTIONS)
69 == TestMockConfig.SOME_OTHER_VERBOSITY_LEVEL
70 )
71
72 def test_get_unsupported_type_error(self):
73 config = mock_config(verbose=TestMockConfig.SOME_VERBOSITY_LEVEL)
74
75 with pytest.raises(KeyError):
76 config.get_verbosity("--- NOT A VERBOSITY LEVEL ---")
77
78
79 class TestImportHookInstallation:
80 @pytest.mark.parametrize("initial_conftest", [True, False])
81 @pytest.mark.parametrize("mode", ["plain", "rewrite"])
82 def test_conftest_assertion_rewrite(
83 self, pytester: Pytester, initial_conftest, mode
84 ) -> None:
85 """Test that conftest files are using assertion rewrite on import (#1619)."""
86 pytester.mkdir("foo")
87 pytester.mkdir("foo/tests")
88 conftest_path = "conftest.py" if initial_conftest else "foo/conftest.py"
89 contents = {
90 conftest_path: """
91 import pytest
92 @pytest.fixture
93 def check_first():
94 def check(values, value):
95 assert values.pop(0) == value
96 return check
97 """,
98 "foo/tests/test_foo.py": """
99 def test(check_first):
100 check_first([10, 30], 30)
101 """,
102 }
103 pytester.makepyfile(**contents)
104 result = pytester.runpytest_subprocess("--assert=%s" % mode)
105 if mode == "plain":
106 expected = "E AssertionError"
107 elif mode == "rewrite":
108 expected = "*assert 10 == 30*"
109 else:
110 assert 0
111 result.stdout.fnmatch_lines([expected])
112
113 def test_rewrite_assertions_pytester_plugin(self, pytester: Pytester) -> None:
114 """
115 Assertions in the pytester plugin must also benefit from assertion
116 rewriting (#1920).
117 """
118 pytester.makepyfile(
119 """
120 pytest_plugins = ['pytester']
121 def test_dummy_failure(pytester): # how meta!
122 pytester.makepyfile('def test(): assert 0')
123 r = pytester.inline_run()
124 r.assertoutcome(passed=1)
125 """
126 )
127 result = pytester.runpytest_subprocess()
128 result.stdout.fnmatch_lines(
129 [
130 "> r.assertoutcome(passed=1)",
131 "E AssertionError: ([[][]], [[][]], [[]<TestReport *>[]])*",
132 "E assert {'failed': 1,... 'skipped': 0} == {'failed': 0,... 'skipped': 0}",
133 "E Omitting 1 identical items, use -vv to show",
134 "E Differing items:",
135 "E Use -v to get more diff",
136 ]
137 )
138 # XXX: unstable output.
139 result.stdout.fnmatch_lines_random(
140 [
141 "E {'failed': 1} != {'failed': 0}",
142 "E {'passed': 0} != {'passed': 1}",
143 ]
144 )
145
146 @pytest.mark.parametrize("mode", ["plain", "rewrite"])
147 def test_pytest_plugins_rewrite(self, pytester: Pytester, mode) -> None:
148 contents = {
149 "conftest.py": """
150 pytest_plugins = ['ham']
151 """,
152 "ham.py": """
153 import pytest
154 @pytest.fixture
155 def check_first():
156 def check(values, value):
157 assert values.pop(0) == value
158 return check
159 """,
160 "test_foo.py": """
161 def test_foo(check_first):
162 check_first([10, 30], 30)
163 """,
164 }
165 pytester.makepyfile(**contents)
166 result = pytester.runpytest_subprocess("--assert=%s" % mode)
167 if mode == "plain":
168 expected = "E AssertionError"
169 elif mode == "rewrite":
170 expected = "*assert 10 == 30*"
171 else:
172 assert 0
173 result.stdout.fnmatch_lines([expected])
174
175 @pytest.mark.parametrize("mode", ["str", "list"])
176 def test_pytest_plugins_rewrite_module_names(
177 self, pytester: Pytester, mode
178 ) -> None:
179 """Test that pluginmanager correct marks pytest_plugins variables
180 for assertion rewriting if they are defined as plain strings or
181 list of strings (#1888).
182 """
183 plugins = '"ham"' if mode == "str" else '["ham"]'
184 contents = {
185 "conftest.py": f"""
186 pytest_plugins = {plugins}
187 """,
188 "ham.py": """
189 import pytest
190 """,
191 "test_foo.py": """
192 def test_foo(pytestconfig):
193 assert 'ham' in pytestconfig.pluginmanager.rewrite_hook._must_rewrite
194 """,
195 }
196 pytester.makepyfile(**contents)
197 result = pytester.runpytest_subprocess("--assert=rewrite")
198 assert result.ret == 0
199
200 def test_pytest_plugins_rewrite_module_names_correctly(
201 self, pytester: Pytester
202 ) -> None:
203 """Test that we match files correctly when they are marked for rewriting (#2939)."""
204 contents = {
205 "conftest.py": """\
206 pytest_plugins = "ham"
207 """,
208 "ham.py": "",
209 "hamster.py": "",
210 "test_foo.py": """\
211 def test_foo(pytestconfig):
212 assert pytestconfig.pluginmanager.rewrite_hook.find_spec('ham') is not None
213 assert pytestconfig.pluginmanager.rewrite_hook.find_spec('hamster') is None
214 """,
215 }
216 pytester.makepyfile(**contents)
217 result = pytester.runpytest_subprocess("--assert=rewrite")
218 assert result.ret == 0
219
220 @pytest.mark.parametrize("mode", ["plain", "rewrite"])
221 def test_installed_plugin_rewrite(
222 self, pytester: Pytester, mode, monkeypatch
223 ) -> None:
224 monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", raising=False)
225 # Make sure the hook is installed early enough so that plugins
226 # installed via setuptools are rewritten.
227 pytester.mkdir("hampkg")
228 contents = {
229 "hampkg/__init__.py": """\
230 import pytest
231
232 @pytest.fixture
233 def check_first2():
234 def check(values, value):
235 assert values.pop(0) == value
236 return check
237 """,
238 "spamplugin.py": """\
239 import pytest
240 from hampkg import check_first2
241
242 @pytest.fixture
243 def check_first():
244 def check(values, value):
245 assert values.pop(0) == value
246 return check
247 """,
248 "mainwrapper.py": """\
249 import importlib.metadata
250 import pytest
251
252 class DummyEntryPoint(object):
253 name = 'spam'
254 module_name = 'spam.py'
255 group = 'pytest11'
256
257 def load(self):
258 import spamplugin
259 return spamplugin
260
261 class DummyDistInfo(object):
262 version = '1.0'
263 files = ('spamplugin.py', 'hampkg/__init__.py')
264 entry_points = (DummyEntryPoint(),)
265 metadata = {'name': 'foo'}
266
267 def distributions():
268 return (DummyDistInfo(),)
269
270 importlib.metadata.distributions = distributions
271 pytest.main()
272 """,
273 "test_foo.py": """\
274 def test(check_first):
275 check_first([10, 30], 30)
276
277 def test2(check_first2):
278 check_first([10, 30], 30)
279 """,
280 }
281 pytester.makepyfile(**contents)
282 result = pytester.run(
283 sys.executable, "mainwrapper.py", "-s", "--assert=%s" % mode
284 )
285 if mode == "plain":
286 expected = "E AssertionError"
287 elif mode == "rewrite":
288 expected = "*assert 10 == 30*"
289 else:
290 assert 0
291 result.stdout.fnmatch_lines([expected])
292
293 def test_rewrite_ast(self, pytester: Pytester) -> None:
294 pytester.mkdir("pkg")
295 contents = {
296 "pkg/__init__.py": """
297 import pytest
298 pytest.register_assert_rewrite('pkg.helper')
299 """,
300 "pkg/helper.py": """
301 def tool():
302 a, b = 2, 3
303 assert a == b
304 """,
305 "pkg/plugin.py": """
306 import pytest, pkg.helper
307 @pytest.fixture
308 def tool():
309 return pkg.helper.tool
310 """,
311 "pkg/other.py": """
312 values = [3, 2]
313 def tool():
314 assert values.pop() == 3
315 """,
316 "conftest.py": """
317 pytest_plugins = ['pkg.plugin']
318 """,
319 "test_pkg.py": """
320 import pkg.other
321 def test_tool(tool):
322 tool()
323 def test_other():
324 pkg.other.tool()
325 """,
326 }
327 pytester.makepyfile(**contents)
328 result = pytester.runpytest_subprocess("--assert=rewrite")
329 result.stdout.fnmatch_lines(
330 [
331 ">*assert a == b*",
332 "E*assert 2 == 3*",
333 ">*assert values.pop() == 3*",
334 "E*AssertionError",
335 ]
336 )
337
338 def test_register_assert_rewrite_checks_types(self) -> None:
339 with pytest.raises(TypeError):
340 pytest.register_assert_rewrite(["pytest_tests_internal_non_existing"]) # type: ignore
341 pytest.register_assert_rewrite(
342 "pytest_tests_internal_non_existing", "pytest_tests_internal_non_existing2"
343 )
344
345
346 class TestBinReprIntegration:
347 def test_pytest_assertrepr_compare_called(self, pytester: Pytester) -> None:
348 pytester.makeconftest(
349 """
350 import pytest
351 values = []
352 def pytest_assertrepr_compare(op, left, right):
353 values.append((op, left, right))
354
355 @pytest.fixture
356 def list(request):
357 return values
358 """
359 )
360 pytester.makepyfile(
361 """
362 def test_hello():
363 assert 0 == 1
364 def test_check(list):
365 assert list == [("==", 0, 1)]
366 """
367 )
368 result = pytester.runpytest("-v")
369 result.stdout.fnmatch_lines(["*test_hello*FAIL*", "*test_check*PASS*"])
370
371
372 def callop(op: str, left: Any, right: Any, verbose: int = 0) -> Optional[List[str]]:
373 config = mock_config(verbose=verbose)
374 return plugin.pytest_assertrepr_compare(config, op, left, right)
375
376
377 def callequal(left: Any, right: Any, verbose: int = 0) -> Optional[List[str]]:
378 return callop("==", left, right, verbose)
379
380
381 class TestAssert_reprcompare:
382 def test_different_types(self) -> None:
383 assert callequal([0, 1], "foo") is None
384
385 def test_summary(self) -> None:
386 lines = callequal([0, 1], [0, 2])
387 assert lines is not None
388 summary = lines[0]
389 assert len(summary) < 65
390
391 def test_text_diff(self) -> None:
392 assert callequal("spam", "eggs") == [
393 "'spam' == 'eggs'",
394 "",
395 "- eggs",
396 "+ spam",
397 ]
398
399 def test_text_skipping(self) -> None:
400 lines = callequal("a" * 50 + "spam", "a" * 50 + "eggs")
401 assert lines is not None
402 assert "Skipping" in lines[2]
403 for line in lines:
404 assert "a" * 50 not in line
405
406 def test_text_skipping_verbose(self) -> None:
407 lines = callequal("a" * 50 + "spam", "a" * 50 + "eggs", verbose=1)
408 assert lines is not None
409 assert "- " + "a" * 50 + "eggs" in lines
410 assert "+ " + "a" * 50 + "spam" in lines
411
412 def test_multiline_text_diff(self) -> None:
413 left = "foo\nspam\nbar"
414 right = "foo\neggs\nbar"
415 diff = callequal(left, right)
416 assert diff is not None
417 assert "- eggs" in diff
418 assert "+ spam" in diff
419
420 def test_bytes_diff_normal(self) -> None:
421 """Check special handling for bytes diff (#5260)"""
422 diff = callequal(b"spam", b"eggs")
423
424 assert diff == [
425 "b'spam' == b'eggs'",
426 "",
427 "At index 0 diff: b's' != b'e'",
428 "Use -v to get more diff",
429 ]
430
431 def test_bytes_diff_verbose(self) -> None:
432 """Check special handling for bytes diff (#5260)"""
433 diff = callequal(b"spam", b"eggs", verbose=1)
434 assert diff == [
435 "b'spam' == b'eggs'",
436 "",
437 "At index 0 diff: b's' != b'e'",
438 "",
439 "Full diff:",
440 "- b'eggs'",
441 "+ b'spam'",
442 ]
443
444 def test_list(self) -> None:
445 expl = callequal([0, 1], [0, 2])
446 assert expl is not None
447 assert len(expl) > 1
448
449 @pytest.mark.parametrize(
450 ["left", "right", "expected"],
451 [
452 pytest.param(
453 [0, 1],
454 [0, 2],
455 """
456 Full diff:
457 [
458 0,
459 - 2,
460 ? ^
461 + 1,
462 ? ^
463 ]
464 """,
465 id="lists",
466 ),
467 pytest.param(
468 {0: 1},
469 {0: 2},
470 """
471 Full diff:
472 {
473 - 0: 2,
474 ? ^
475 + 0: 1,
476 ? ^
477 }
478 """,
479 id="dicts",
480 ),
481 pytest.param(
482 {0, 1},
483 {0, 2},
484 """
485 Full diff:
486 {
487 0,
488 - 2,
489 ? ^
490 + 1,
491 ? ^
492 }
493 """,
494 id="sets",
495 ),
496 ],
497 )
498 def test_iterable_full_diff(self, left, right, expected) -> None:
499 """Test the full diff assertion failure explanation.
500
501 When verbose is False, then just a -v notice to get the diff is rendered,
502 when verbose is True, then ndiff of the pprint is returned.
503 """
504 expl = callequal(left, right, verbose=0)
505 assert expl is not None
506 assert expl[-1] == "Use -v to get more diff"
507 verbose_expl = callequal(left, right, verbose=1)
508 assert verbose_expl is not None
509 assert "\n".join(verbose_expl).endswith(textwrap.dedent(expected).strip())
510
511 def test_iterable_quiet(self) -> None:
512 expl = callequal([1, 2], [10, 2], verbose=-1)
513 assert expl == [
514 "[1, 2] == [10, 2]",
515 "",
516 "At index 0 diff: 1 != 10",
517 "Use -v to get more diff",
518 ]
519
520 def test_iterable_full_diff_ci(
521 self, monkeypatch: MonkeyPatch, pytester: Pytester
522 ) -> None:
523 pytester.makepyfile(
524 r"""
525 def test_full_diff():
526 left = [0, 1]
527 right = [0, 2]
528 assert left == right
529 """
530 )
531 monkeypatch.setenv("CI", "true")
532 result = pytester.runpytest()
533 result.stdout.fnmatch_lines(["E Full diff:"])
534
535 monkeypatch.delenv("CI", raising=False)
536 result = pytester.runpytest()
537 result.stdout.fnmatch_lines(["E Use -v to get more diff"])
538
539 def test_list_different_lengths(self) -> None:
540 expl = callequal([0, 1], [0, 1, 2])
541 assert expl is not None
542 assert len(expl) > 1
543 expl = callequal([0, 1, 2], [0, 1])
544 assert expl is not None
545 assert len(expl) > 1
546
547 def test_list_wrap_for_multiple_lines(self) -> None:
548 long_d = "d" * 80
549 l1 = ["a", "b", "c"]
550 l2 = ["a", "b", "c", long_d]
551 diff = callequal(l1, l2, verbose=True)
552 assert diff == [
553 "['a', 'b', 'c'] == ['a', 'b', 'c...dddddddddddd']",
554 "",
555 "Right contains one more item: '" + long_d + "'",
556 "",
557 "Full diff:",
558 " [",
559 " 'a',",
560 " 'b',",
561 " 'c',",
562 "- '" + long_d + "',",
563 " ]",
564 ]
565
566 diff = callequal(l2, l1, verbose=True)
567 assert diff == [
568 "['a', 'b', 'c...dddddddddddd'] == ['a', 'b', 'c']",
569 "",
570 "Left contains one more item: '" + long_d + "'",
571 "",
572 "Full diff:",
573 " [",
574 " 'a',",
575 " 'b',",
576 " 'c',",
577 "+ '" + long_d + "',",
578 " ]",
579 ]
580
581 def test_list_wrap_for_width_rewrap_same_length(self) -> None:
582 long_a = "a" * 30
583 long_b = "b" * 30
584 long_c = "c" * 30
585 l1 = [long_a, long_b, long_c]
586 l2 = [long_b, long_c, long_a]
587 diff = callequal(l1, l2, verbose=True)
588 assert diff == [
589 "['aaaaaaaaaaa...cccccccccccc'] == ['bbbbbbbbbbb...aaaaaaaaaaaa']",
590 "",
591 "At index 0 diff: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' != 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'",
592 "",
593 "Full diff:",
594 " [",
595 "+ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',",
596 " 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',",
597 " 'cccccccccccccccccccccccccccccc',",
598 "- 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',",
599 " ]",
600 ]
601
602 def test_list_dont_wrap_strings(self) -> None:
603 long_a = "a" * 10
604 l1 = ["a"] + [long_a for _ in range(7)]
605 l2 = ["should not get wrapped"]
606 diff = callequal(l1, l2, verbose=True)
607 assert diff == [
608 "['a', 'aaaaaa...aaaaaaa', ...] == ['should not get wrapped']",
609 "",
610 "At index 0 diff: 'a' != 'should not get wrapped'",
611 "Left contains 7 more items, first extra item: 'aaaaaaaaaa'",
612 "",
613 "Full diff:",
614 " [",
615 "- 'should not get wrapped',",
616 "+ 'a',",
617 "+ 'aaaaaaaaaa',",
618 "+ 'aaaaaaaaaa',",
619 "+ 'aaaaaaaaaa',",
620 "+ 'aaaaaaaaaa',",
621 "+ 'aaaaaaaaaa',",
622 "+ 'aaaaaaaaaa',",
623 "+ 'aaaaaaaaaa',",
624 " ]",
625 ]
626
627 def test_dict_wrap(self) -> None:
628 d1 = {"common": 1, "env": {"env1": 1, "env2": 2}}
629 d2 = {"common": 1, "env": {"env1": 1}}
630
631 diff = callequal(d1, d2, verbose=True)
632 assert diff == [
633 "{'common': 1,...1, 'env2': 2}} == {'common': 1,...: {'env1': 1}}",
634 "",
635 "Omitting 1 identical items, use -vv to show",
636 "Differing items:",
637 "{'env': {'env1': 1, 'env2': 2}} != {'env': {'env1': 1}}",
638 "",
639 "Full diff:",
640 " {",
641 " 'common': 1,",
642 " 'env': {",
643 " 'env1': 1,",
644 "+ 'env2': 2,",
645 " },",
646 " }",
647 ]
648
649 long_a = "a" * 80
650 sub = {"long_a": long_a, "sub1": {"long_a": "substring that gets wrapped " * 3}}
651 d1 = {"env": {"sub": sub}}
652 d2 = {"env": {"sub": sub}, "new": 1}
653 diff = callequal(d1, d2, verbose=True)
654 assert diff == [
655 "{'env': {'sub... wrapped '}}}} == {'env': {'sub...}}}, 'new': 1}",
656 "",
657 "Omitting 1 identical items, use -vv to show",
658 "Right contains 1 more item:",
659 "{'new': 1}",
660 "",
661 "Full diff:",
662 " {",
663 " 'env': {",
664 " 'sub': {",
665 f" 'long_a': '{long_a}',",
666 " 'sub1': {",
667 " 'long_a': 'substring that gets wrapped substring that gets wrapped '",
668 " 'substring that gets wrapped ',",
669 " },",
670 " },",
671 " },",
672 "- 'new': 1,",
673 " }",
674 ]
675
676 def test_dict(self) -> None:
677 expl = callequal({"a": 0}, {"a": 1})
678 assert expl is not None
679 assert len(expl) > 1
680
681 def test_dict_omitting(self) -> None:
682 lines = callequal({"a": 0, "b": 1}, {"a": 1, "b": 1})
683 assert lines is not None
684 assert lines[2].startswith("Omitting 1 identical item")
685 assert "Common items" not in lines
686 for line in lines[1:]:
687 assert "b" not in line
688
689 def test_dict_omitting_with_verbosity_1(self) -> None:
690 """Ensure differing items are visible for verbosity=1 (#1512)."""
691 lines = callequal({"a": 0, "b": 1}, {"a": 1, "b": 1}, verbose=1)
692 assert lines is not None
693 assert lines[1] == ""
694 assert lines[2].startswith("Omitting 1 identical item")
695 assert lines[3].startswith("Differing items")
696 assert lines[4] == "{'a': 0} != {'a': 1}"
697 assert "Common items" not in lines
698
699 def test_dict_omitting_with_verbosity_2(self) -> None:
700 lines = callequal({"a": 0, "b": 1}, {"a": 1, "b": 1}, verbose=2)
701 assert lines is not None
702 assert lines[2].startswith("Common items:")
703 assert "Omitting" not in lines[2]
704 assert lines[3] == "{'b': 1}"
705
706 def test_dict_different_items(self) -> None:
707 lines = callequal({"a": 0}, {"b": 1, "c": 2}, verbose=2)
708 assert lines == [
709 "{'a': 0} == {'b': 1, 'c': 2}",
710 "",
711 "Left contains 1 more item:",
712 "{'a': 0}",
713 "Right contains 2 more items:",
714 "{'b': 1, 'c': 2}",
715 "",
716 "Full diff:",
717 " {",
718 "- 'b': 1,",
719 "? ^ ^",
720 "+ 'a': 0,",
721 "? ^ ^",
722 "- 'c': 2,",
723 " }",
724 ]
725 lines = callequal({"b": 1, "c": 2}, {"a": 0}, verbose=2)
726 assert lines == [
727 "{'b': 1, 'c': 2} == {'a': 0}",
728 "",
729 "Left contains 2 more items:",
730 "{'b': 1, 'c': 2}",
731 "Right contains 1 more item:",
732 "{'a': 0}",
733 "",
734 "Full diff:",
735 " {",
736 "- 'a': 0,",
737 "? ^ ^",
738 "+ 'b': 1,",
739 "? ^ ^",
740 "+ 'c': 2,",
741 " }",
742 ]
743
744 def test_sequence_different_items(self) -> None:
745 lines = callequal((1, 2), (3, 4, 5), verbose=2)
746 assert lines == [
747 "(1, 2) == (3, 4, 5)",
748 "",
749 "At index 0 diff: 1 != 3",
750 "Right contains one more item: 5",
751 "",
752 "Full diff:",
753 " (",
754 "- 3,",
755 "? ^",
756 "+ 1,",
757 "? ^",
758 "- 4,",
759 "? ^",
760 "+ 2,",
761 "? ^",
762 "- 5,",
763 " )",
764 ]
765 lines = callequal((1, 2, 3), (4,), verbose=2)
766 assert lines == [
767 "(1, 2, 3) == (4,)",
768 "",
769 "At index 0 diff: 1 != 4",
770 "Left contains 2 more items, first extra item: 2",
771 "",
772 "Full diff:",
773 " (",
774 "- 4,",
775 "? ^",
776 "+ 1,",
777 "? ^",
778 "+ 2,",
779 "+ 3,",
780 " )",
781 ]
782 lines = callequal((1, 2, 3), (1, 20, 3), verbose=2)
783 assert lines == [
784 "(1, 2, 3) == (1, 20, 3)",
785 "",
786 "At index 1 diff: 2 != 20",
787 "",
788 "Full diff:",
789 " (",
790 " 1,",
791 "- 20,",
792 "? -",
793 "+ 2,",
794 " 3,",
795 " )",
796 ]
797
798 def test_set(self) -> None:
799 expl = callequal({0, 1}, {0, 2})
800 assert expl is not None
801 assert len(expl) > 1
802
803 def test_frozenzet(self) -> None:
804 expl = callequal(frozenset([0, 1]), {0, 2})
805 assert expl is not None
806 assert len(expl) > 1
807
808 def test_Sequence(self) -> None:
809 # Test comparing with a Sequence subclass.
810 class TestSequence(MutableSequence[int]):
811 def __init__(self, iterable):
812 self.elements = list(iterable)
813
814 def __getitem__(self, item):
815 return self.elements[item]
816
817 def __len__(self):
818 return len(self.elements)
819
820 def __setitem__(self, item, value):
821 pass
822
823 def __delitem__(self, item):
824 pass
825
826 def insert(self, item, index):
827 pass
828
829 expl = callequal(TestSequence([0, 1]), list([0, 2]))
830 assert expl is not None
831 assert len(expl) > 1
832
833 def test_list_tuples(self) -> None:
834 expl = callequal([], [(1, 2)])
835 assert expl is not None
836 assert len(expl) > 1
837 expl = callequal([(1, 2)], [])
838 assert expl is not None
839 assert len(expl) > 1
840
841 def test_list_bad_repr(self) -> None:
842 class A:
843 def __repr__(self):
844 raise ValueError(42)
845
846 expl = callequal([], [A()])
847 assert expl is not None
848 assert "ValueError" in "".join(expl)
849 expl = callequal({}, {"1": A()}, verbose=2)
850 assert expl is not None
851 assert expl[0].startswith("{} == <[ValueError")
852 assert "raised in repr" in expl[0]
853 assert expl[2:] == [
854 "(pytest_assertion plugin: representation of details failed:"
855 f" {__file__}:{A.__repr__.__code__.co_firstlineno + 1}: ValueError: 42.",
856 " Probably an object has a faulty __repr__.)",
857 ]
858
859 def test_one_repr_empty(self) -> None:
860 """The faulty empty string repr did trigger an unbound local error in _diff_text."""
861
862 class A(str):
863 def __repr__(self):
864 return ""
865
866 expl = callequal(A(), "")
867 assert not expl
868
869 def test_repr_no_exc(self) -> None:
870 expl = callequal("foo", "bar")
871 assert expl is not None
872 assert "raised in repr()" not in " ".join(expl)
873
874 def test_unicode(self) -> None:
875 assert callequal("£€", "£") == [
876 "'£€' == '£'",
877 "",
878 "- £",
879 "+ £€",
880 ]
881
882 def test_nonascii_text(self) -> None:
883 """
884 :issue: 877
885 non ascii python2 str caused a UnicodeDecodeError
886 """
887
888 class A(str):
889 def __repr__(self):
890 return "\xff"
891
892 expl = callequal(A(), "1")
893 assert expl == ["ÿ == '1'", "", "- 1"]
894
895 def test_format_nonascii_explanation(self) -> None:
896 assert util.format_explanation("λ")
897
898 def test_mojibake(self) -> None:
899 # issue 429
900 left = b"e"
901 right = b"\xc3\xa9"
902 expl = callequal(left, right)
903 assert expl is not None
904 for line in expl:
905 assert isinstance(line, str)
906 msg = "\n".join(expl)
907 assert msg
908
909 def test_nfc_nfd_same_string(self) -> None:
910 # issue 3426
911 left = "hyv\xe4"
912 right = "hyva\u0308"
913 expl = callequal(left, right)
914 assert expl == [
915 r"'hyv\xe4' == 'hyva\u0308'",
916 "",
917 f"- {right!s}",
918 f"+ {left!s}",
919 ]
920
921 expl = callequal(left, right, verbose=2)
922 assert expl == [
923 r"'hyv\xe4' == 'hyva\u0308'",
924 "",
925 f"- {right!s}",
926 f"+ {left!s}",
927 ]
928
929
930 class TestAssert_reprcompare_dataclass:
931 def test_dataclasses(self, pytester: Pytester) -> None:
932 p = pytester.copy_example("dataclasses/test_compare_dataclasses.py")
933 result = pytester.runpytest(p)
934 result.assert_outcomes(failed=1, passed=0)
935 result.stdout.fnmatch_lines(
936 [
937 "E Omitting 1 identical items, use -vv to show",
938 "E Differing attributes:",
939 "E ['field_b']",
940 "E ",
941 "E Drill down into differing attribute field_b:",
942 "E field_b: 'b' != 'c'",
943 "E - c",
944 "E + b",
945 ],
946 consecutive=True,
947 )
948
949 def test_recursive_dataclasses(self, pytester: Pytester) -> None:
950 p = pytester.copy_example("dataclasses/test_compare_recursive_dataclasses.py")
951 result = pytester.runpytest(p)
952 result.assert_outcomes(failed=1, passed=0)
953 result.stdout.fnmatch_lines(
954 [
955 "E Omitting 1 identical items, use -vv to show",
956 "E Differing attributes:",
957 "E ['g', 'h', 'j']",
958 "E ",
959 "E Drill down into differing attribute g:",
960 "E g: S(a=10, b='ten') != S(a=20, b='xxx')...",
961 "E ",
962 "E ...Full output truncated (51 lines hidden), use '-vv' to show",
963 ],
964 consecutive=True,
965 )
966
967 def test_recursive_dataclasses_verbose(self, pytester: Pytester) -> None:
968 p = pytester.copy_example("dataclasses/test_compare_recursive_dataclasses.py")
969 result = pytester.runpytest(p, "-vv")
970 result.assert_outcomes(failed=1, passed=0)
971 result.stdout.fnmatch_lines(
972 [
973 "E Matching attributes:",
974 "E ['i']",
975 "E Differing attributes:",
976 "E ['g', 'h', 'j']",
977 "E ",
978 "E Drill down into differing attribute g:",
979 "E g: S(a=10, b='ten') != S(a=20, b='xxx')",
980 "E ",
981 "E Differing attributes:",
982 "E ['a', 'b']",
983 "E ",
984 "E Drill down into differing attribute a:",
985 "E a: 10 != 20",
986 "E ",
987 "E Drill down into differing attribute b:",
988 "E b: 'ten' != 'xxx'",
989 "E - xxx",
990 "E + ten",
991 "E ",
992 "E Drill down into differing attribute h:",
993 ],
994 consecutive=True,
995 )
996
997 def test_dataclasses_verbose(self, pytester: Pytester) -> None:
998 p = pytester.copy_example("dataclasses/test_compare_dataclasses_verbose.py")
999 result = pytester.runpytest(p, "-vv")
1000 result.assert_outcomes(failed=1, passed=0)
1001 result.stdout.fnmatch_lines(
1002 [
1003 "*Matching attributes:*",
1004 "*['field_a']*",
1005 "*Differing attributes:*",
1006 "*field_b: 'b' != 'c'*",
1007 ]
1008 )
1009
1010 def test_dataclasses_with_attribute_comparison_off(
1011 self, pytester: Pytester
1012 ) -> None:
1013 p = pytester.copy_example(
1014 "dataclasses/test_compare_dataclasses_field_comparison_off.py"
1015 )
1016 result = pytester.runpytest(p, "-vv")
1017 result.assert_outcomes(failed=0, passed=1)
1018
1019 def test_comparing_two_different_data_classes(self, pytester: Pytester) -> None:
1020 p = pytester.copy_example(
1021 "dataclasses/test_compare_two_different_dataclasses.py"
1022 )
1023 result = pytester.runpytest(p, "-vv")
1024 result.assert_outcomes(failed=0, passed=1)
1025
1026 def test_data_classes_with_custom_eq(self, pytester: Pytester) -> None:
1027 p = pytester.copy_example(
1028 "dataclasses/test_compare_dataclasses_with_custom_eq.py"
1029 )
1030 # issue 9362
1031 result = pytester.runpytest(p, "-vv")
1032 result.assert_outcomes(failed=1, passed=0)
1033 result.stdout.no_re_match_line(".*Differing attributes.*")
1034
1035 def test_data_classes_with_initvar(self, pytester: Pytester) -> None:
1036 p = pytester.copy_example("dataclasses/test_compare_initvar.py")
1037 # issue 9820
1038 result = pytester.runpytest(p, "-vv")
1039 result.assert_outcomes(failed=1, passed=0)
1040 result.stdout.no_re_match_line(".*AttributeError.*")
1041
1042
1043 class TestAssert_reprcompare_attrsclass:
1044 def test_attrs(self) -> None:
1045 @attr.s
1046 class SimpleDataObject:
1047 field_a = attr.ib()
1048 field_b = attr.ib()
1049
1050 left = SimpleDataObject(1, "b")
1051 right = SimpleDataObject(1, "c")
1052
1053 lines = callequal(left, right)
1054 assert lines is not None
1055 assert lines[2].startswith("Omitting 1 identical item")
1056 assert "Matching attributes" not in lines
1057 for line in lines[2:]:
1058 assert "field_a" not in line
1059
1060 def test_attrs_recursive(self) -> None:
1061 @attr.s
1062 class OtherDataObject:
1063 field_c = attr.ib()
1064 field_d = attr.ib()
1065
1066 @attr.s
1067 class SimpleDataObject:
1068 field_a = attr.ib()
1069 field_b = attr.ib()
1070
1071 left = SimpleDataObject(OtherDataObject(1, "a"), "b")
1072 right = SimpleDataObject(OtherDataObject(1, "b"), "b")
1073
1074 lines = callequal(left, right)
1075 assert lines is not None
1076 assert "Matching attributes" not in lines
1077 for line in lines[1:]:
1078 assert "field_b:" not in line
1079 assert "field_c:" not in line
1080
1081 def test_attrs_recursive_verbose(self) -> None:
1082 @attr.s
1083 class OtherDataObject:
1084 field_c = attr.ib()
1085 field_d = attr.ib()
1086
1087 @attr.s
1088 class SimpleDataObject:
1089 field_a = attr.ib()
1090 field_b = attr.ib()
1091
1092 left = SimpleDataObject(OtherDataObject(1, "a"), "b")
1093 right = SimpleDataObject(OtherDataObject(1, "b"), "b")
1094
1095 lines = callequal(left, right)
1096 assert lines is not None
1097 # indentation in output because of nested object structure
1098 assert " field_d: 'a' != 'b'" in lines
1099
1100 def test_attrs_verbose(self) -> None:
1101 @attr.s
1102 class SimpleDataObject:
1103 field_a = attr.ib()
1104 field_b = attr.ib()
1105
1106 left = SimpleDataObject(1, "b")
1107 right = SimpleDataObject(1, "c")
1108
1109 lines = callequal(left, right, verbose=2)
1110 assert lines is not None
1111 assert lines[2].startswith("Matching attributes:")
1112 assert "Omitting" not in lines[2]
1113 assert lines[3] == "['field_a']"
1114
1115 def test_attrs_with_attribute_comparison_off(self) -> None:
1116 @attr.s
1117 class SimpleDataObject:
1118 field_a = attr.ib()
1119 field_b = attr.ib(eq=False)
1120
1121 left = SimpleDataObject(1, "b")
1122 right = SimpleDataObject(1, "b")
1123
1124 lines = callequal(left, right, verbose=2)
1125 assert lines is not None
1126 assert lines[2].startswith("Matching attributes:")
1127 assert "Omitting" not in lines[1]
1128 assert lines[3] == "['field_a']"
1129 for line in lines[3:]:
1130 assert "field_b" not in line
1131
1132 def test_comparing_two_different_attrs_classes(self) -> None:
1133 @attr.s
1134 class SimpleDataObjectOne:
1135 field_a = attr.ib()
1136 field_b = attr.ib()
1137
1138 @attr.s
1139 class SimpleDataObjectTwo:
1140 field_a = attr.ib()
1141 field_b = attr.ib()
1142
1143 left = SimpleDataObjectOne(1, "b")
1144 right = SimpleDataObjectTwo(1, "c")
1145
1146 lines = callequal(left, right)
1147 assert lines is None
1148
1149 def test_attrs_with_auto_detect_and_custom_eq(self) -> None:
1150 @attr.s(
1151 auto_detect=True
1152 ) # attr.s doesn't ignore a custom eq if auto_detect=True
1153 class SimpleDataObject:
1154 field_a = attr.ib()
1155
1156 def __eq__(self, other): # pragma: no cover
1157 return super().__eq__(other)
1158
1159 left = SimpleDataObject(1)
1160 right = SimpleDataObject(2)
1161 # issue 9362
1162 lines = callequal(left, right, verbose=2)
1163 assert lines is None
1164
1165 def test_attrs_with_custom_eq(self) -> None:
1166 @attr.define(slots=False)
1167 class SimpleDataObject:
1168 field_a = attr.ib()
1169
1170 def __eq__(self, other): # pragma: no cover
1171 return super().__eq__(other)
1172
1173 left = SimpleDataObject(1)
1174 right = SimpleDataObject(2)
1175 # issue 9362
1176 lines = callequal(left, right, verbose=2)
1177 assert lines is None
1178
1179
1180 class TestAssert_reprcompare_namedtuple:
1181 def test_namedtuple(self) -> None:
1182 class NT(NamedTuple):
1183 a: Any
1184 b: Any
1185
1186 left = NT(1, "b")
1187 right = NT(1, "c")
1188
1189 lines = callequal(left, right)
1190 assert lines == [
1191 "NT(a=1, b='b') == NT(a=1, b='c')",
1192 "",
1193 "Omitting 1 identical items, use -vv to show",
1194 "Differing attributes:",
1195 "['b']",
1196 "",
1197 "Drill down into differing attribute b:",
1198 " b: 'b' != 'c'",
1199 " - c",
1200 " + b",
1201 "Use -v to get more diff",
1202 ]
1203
1204 def test_comparing_two_different_namedtuple(self) -> None:
1205 class NT1(NamedTuple):
1206 a: Any
1207 b: Any
1208
1209 class NT2(NamedTuple):
1210 a: Any
1211 b: Any
1212
1213 left = NT1(1, "b")
1214 right = NT2(2, "b")
1215
1216 lines = callequal(left, right)
1217 # Because the types are different, uses the generic sequence matcher.
1218 assert lines == [
1219 "NT1(a=1, b='b') == NT2(a=2, b='b')",
1220 "",
1221 "At index 0 diff: 1 != 2",
1222 "Use -v to get more diff",
1223 ]
1224
1225
1226 class TestFormatExplanation:
1227 def test_special_chars_full(self, pytester: Pytester) -> None:
1228 # Issue 453, for the bug this would raise IndexError
1229 pytester.makepyfile(
1230 """
1231 def test_foo():
1232 assert '\\n}' == ''
1233 """
1234 )
1235 result = pytester.runpytest()
1236 assert result.ret == 1
1237 result.stdout.fnmatch_lines(["*AssertionError*"])
1238
1239 def test_fmt_simple(self) -> None:
1240 expl = "assert foo"
1241 assert util.format_explanation(expl) == "assert foo"
1242
1243 def test_fmt_where(self) -> None:
1244 expl = "\n".join(["assert 1", "{1 = foo", "} == 2"])
1245 res = "\n".join(["assert 1 == 2", " + where 1 = foo"])
1246 assert util.format_explanation(expl) == res
1247
1248 def test_fmt_and(self) -> None:
1249 expl = "\n".join(["assert 1", "{1 = foo", "} == 2", "{2 = bar", "}"])
1250 res = "\n".join(["assert 1 == 2", " + where 1 = foo", " + and 2 = bar"])
1251 assert util.format_explanation(expl) == res
1252
1253 def test_fmt_where_nested(self) -> None:
1254 expl = "\n".join(["assert 1", "{1 = foo", "{foo = bar", "}", "} == 2"])
1255 res = "\n".join(["assert 1 == 2", " + where 1 = foo", " + where foo = bar"])
1256 assert util.format_explanation(expl) == res
1257
1258 def test_fmt_newline(self) -> None:
1259 expl = "\n".join(['assert "foo" == "bar"', "~- foo", "~+ bar"])
1260 res = "\n".join(['assert "foo" == "bar"', " - foo", " + bar"])
1261 assert util.format_explanation(expl) == res
1262
1263 def test_fmt_newline_escaped(self) -> None:
1264 expl = "\n".join(["assert foo == bar", "baz"])
1265 res = "assert foo == bar\\nbaz"
1266 assert util.format_explanation(expl) == res
1267
1268 def test_fmt_newline_before_where(self) -> None:
1269 expl = "\n".join(
1270 [
1271 "the assertion message here",
1272 ">assert 1",
1273 "{1 = foo",
1274 "} == 2",
1275 "{2 = bar",
1276 "}",
1277 ]
1278 )
1279 res = "\n".join(
1280 [
1281 "the assertion message here",
1282 "assert 1 == 2",
1283 " + where 1 = foo",
1284 " + and 2 = bar",
1285 ]
1286 )
1287 assert util.format_explanation(expl) == res
1288
1289 def test_fmt_multi_newline_before_where(self) -> None:
1290 expl = "\n".join(
1291 [
1292 "the assertion",
1293 "~message here",
1294 ">assert 1",
1295 "{1 = foo",
1296 "} == 2",
1297 "{2 = bar",
1298 "}",
1299 ]
1300 )
1301 res = "\n".join(
1302 [
1303 "the assertion",
1304 " message here",
1305 "assert 1 == 2",
1306 " + where 1 = foo",
1307 " + and 2 = bar",
1308 ]
1309 )
1310 assert util.format_explanation(expl) == res
1311
1312
1313 class TestTruncateExplanation:
1314 # The number of lines in the truncation explanation message. Used
1315 # to calculate that results have the expected length.
1316 LINES_IN_TRUNCATION_MSG = 2
1317
1318 def test_doesnt_truncate_when_input_is_empty_list(self) -> None:
1319 expl: List[str] = []
1320 result = truncate._truncate_explanation(expl, max_lines=8, max_chars=100)
1321 assert result == expl
1322
1323 def test_doesnt_truncate_at_when_input_is_5_lines_and_LT_max_chars(self) -> None:
1324 expl = ["a" * 100 for x in range(5)]
1325 result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80)
1326 assert result == expl
1327
1328 def test_truncates_at_8_lines_when_given_list_of_empty_strings(self) -> None:
1329 expl = ["" for x in range(50)]
1330 result = truncate._truncate_explanation(expl, max_lines=8, max_chars=100)
1331 assert len(result) != len(expl)
1332 assert result != expl
1333 assert len(result) == 8 + self.LINES_IN_TRUNCATION_MSG
1334 assert "Full output truncated" in result[-1]
1335 assert "42 lines hidden" in result[-1]
1336 last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]
1337 assert last_line_before_trunc_msg.endswith("...")
1338
1339 def test_truncates_at_8_lines_when_first_8_lines_are_LT_max_chars(self) -> None:
1340 total_lines = 100
1341 expl = ["a" for x in range(total_lines)]
1342 result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80)
1343 assert result != expl
1344 assert len(result) == 8 + self.LINES_IN_TRUNCATION_MSG
1345 assert "Full output truncated" in result[-1]
1346 assert f"{total_lines - 8} lines hidden" in result[-1]
1347 last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]
1348 assert last_line_before_trunc_msg.endswith("...")
1349
1350 def test_truncates_at_8_lines_when_there_is_one_line_to_remove(self) -> None:
1351 """The number of line in the result is 9, the same number as if we truncated."""
1352 expl = ["a" for x in range(9)]
1353 result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80)
1354 assert result == expl
1355 assert "truncated" not in result[-1]
1356
1357 def test_truncates_edgecase_when_truncation_message_makes_the_result_longer_for_chars(
1358 self,
1359 ) -> None:
1360 line = "a" * 10
1361 expl = [line, line]
1362 result = truncate._truncate_explanation(expl, max_lines=10, max_chars=10)
1363 assert result == [line, line]
1364
1365 def test_truncates_edgecase_when_truncation_message_makes_the_result_longer_for_lines(
1366 self,
1367 ) -> None:
1368 line = "a" * 10
1369 expl = [line, line]
1370 result = truncate._truncate_explanation(expl, max_lines=1, max_chars=100)
1371 assert result == [line, line]
1372
1373 def test_truncates_at_8_lines_when_first_8_lines_are_EQ_max_chars(self) -> None:
1374 expl = [chr(97 + x) * 80 for x in range(16)]
1375 result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80)
1376 assert result != expl
1377 assert len(result) == 16 - 8 + self.LINES_IN_TRUNCATION_MSG
1378 assert "Full output truncated" in result[-1]
1379 assert "8 lines hidden" in result[-1]
1380 last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]
1381 assert last_line_before_trunc_msg.endswith("...")
1382
1383 def test_truncates_at_4_lines_when_first_4_lines_are_GT_max_chars(self) -> None:
1384 expl = ["a" * 250 for x in range(10)]
1385 result = truncate._truncate_explanation(expl, max_lines=8, max_chars=999)
1386 assert result != expl
1387 assert len(result) == 4 + self.LINES_IN_TRUNCATION_MSG
1388 assert "Full output truncated" in result[-1]
1389 assert "7 lines hidden" in result[-1]
1390 last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]
1391 assert last_line_before_trunc_msg.endswith("...")
1392
1393 def test_truncates_at_1_line_when_first_line_is_GT_max_chars(self) -> None:
1394 expl = ["a" * 250 for x in range(1000)]
1395 result = truncate._truncate_explanation(expl, max_lines=8, max_chars=100)
1396 assert result != expl
1397 assert len(result) == 1 + self.LINES_IN_TRUNCATION_MSG
1398 assert "Full output truncated" in result[-1]
1399 assert "1000 lines hidden" in result[-1]
1400 last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]
1401 assert last_line_before_trunc_msg.endswith("...")
1402
1403 def test_full_output_truncated(self, monkeypatch, pytester: Pytester) -> None:
1404 """Test against full runpytest() output."""
1405 line_count = 7
1406 line_len = 100
1407 expected_truncated_lines = 2
1408 pytester.makepyfile(
1409 r"""
1410 def test_many_lines():
1411 a = list([str(i)[0] * %d for i in range(%d)])
1412 b = a[::2]
1413 a = '\n'.join(map(str, a))
1414 b = '\n'.join(map(str, b))
1415 assert a == b
1416 """
1417 % (line_len, line_count)
1418 )
1419 monkeypatch.delenv("CI", raising=False)
1420
1421 result = pytester.runpytest()
1422 # without -vv, truncate the message showing a few diff lines only
1423 result.stdout.fnmatch_lines(
1424 [
1425 "*+ 1*",
1426 "*+ 3*",
1427 "*truncated (%d lines hidden)*use*-vv*" % expected_truncated_lines,
1428 ]
1429 )
1430
1431 result = pytester.runpytest("-vv")
1432 result.stdout.fnmatch_lines(["* 6*"])
1433
1434 monkeypatch.setenv("CI", "1")
1435 result = pytester.runpytest()
1436 result.stdout.fnmatch_lines(["* 6*"])
1437
1438
1439 def test_python25_compile_issue257(pytester: Pytester) -> None:
1440 pytester.makepyfile(
1441 """
1442 def test_rewritten():
1443 assert 1 == 2
1444 # some comment
1445 """
1446 )
1447 result = pytester.runpytest()
1448 assert result.ret == 1
1449 result.stdout.fnmatch_lines(
1450 """
1451 *E*assert 1 == 2*
1452 *1 failed*
1453 """
1454 )
1455
1456
1457 def test_rewritten(pytester: Pytester) -> None:
1458 pytester.makepyfile(
1459 """
1460 def test_rewritten():
1461 assert "@py_builtins" in globals()
1462 """
1463 )
1464 assert pytester.runpytest().ret == 0
1465
1466
1467 def test_reprcompare_notin() -> None:
1468 assert callop("not in", "foo", "aaafoobbb") == [
1469 "'foo' not in 'aaafoobbb'",
1470 "",
1471 "'foo' is contained here:",
1472 " aaafoobbb",
1473 "? +++",
1474 ]
1475
1476
1477 def test_reprcompare_whitespaces() -> None:
1478 assert callequal("\r\n", "\n") == [
1479 r"'\r\n' == '\n'",
1480 "",
1481 r"Strings contain only whitespace, escaping them using repr()",
1482 r"- '\n'",
1483 r"+ '\r\n'",
1484 r"? ++",
1485 ]
1486
1487
1488 class TestSetAssertions:
1489 @pytest.mark.parametrize("op", [">=", ">", "<=", "<", "=="])
1490 def test_set_extra_item(self, op, pytester: Pytester) -> None:
1491 pytester.makepyfile(
1492 f"""
1493 def test_hello():
1494 x = set("hello x")
1495 y = set("hello y")
1496 assert x {op} y
1497 """
1498 )
1499
1500 result = pytester.runpytest()
1501 result.stdout.fnmatch_lines(
1502 [
1503 "*def test_hello():*",
1504 f"*assert x {op} y*",
1505 ]
1506 )
1507 if op in [">=", ">", "=="]:
1508 result.stdout.fnmatch_lines(
1509 [
1510 "*E*Extra items in the right set:*",
1511 "*E*'y'",
1512 ]
1513 )
1514 if op in ["<=", "<", "=="]:
1515 result.stdout.fnmatch_lines(
1516 [
1517 "*E*Extra items in the left set:*",
1518 "*E*'x'",
1519 ]
1520 )
1521
1522 @pytest.mark.parametrize("op", [">", "<", "!="])
1523 def test_set_proper_superset_equal(self, pytester: Pytester, op) -> None:
1524 pytester.makepyfile(
1525 f"""
1526 def test_hello():
1527 x = set([1, 2, 3])
1528 y = x.copy()
1529 assert x {op} y
1530 """
1531 )
1532
1533 result = pytester.runpytest()
1534 result.stdout.fnmatch_lines(
1535 [
1536 "*def test_hello():*",
1537 f"*assert x {op} y*",
1538 "*E*Both sets are equal*",
1539 ]
1540 )
1541
1542 def test_pytest_assertrepr_compare_integration(self, pytester: Pytester) -> None:
1543 pytester.makepyfile(
1544 """
1545 def test_hello():
1546 x = set(range(100))
1547 y = x.copy()
1548 y.remove(50)
1549 assert x == y
1550 """
1551 )
1552 result = pytester.runpytest()
1553 result.stdout.fnmatch_lines(
1554 [
1555 "*def test_hello():*",
1556 "*assert x == y*",
1557 "*E*Extra items*left*",
1558 "*E*50*",
1559 "*= 1 failed in*",
1560 ]
1561 )
1562
1563
1564 def test_assertrepr_loaded_per_dir(pytester: Pytester) -> None:
1565 pytester.makepyfile(test_base=["def test_base(): assert 1 == 2"])
1566 a = pytester.mkdir("a")
1567 a.joinpath("test_a.py").write_text("def test_a(): assert 1 == 2", encoding="utf-8")
1568 a.joinpath("conftest.py").write_text(
1569 'def pytest_assertrepr_compare(): return ["summary a"]', encoding="utf-8"
1570 )
1571 b = pytester.mkdir("b")
1572 b.joinpath("test_b.py").write_text("def test_b(): assert 1 == 2", encoding="utf-8")
1573 b.joinpath("conftest.py").write_text(
1574 'def pytest_assertrepr_compare(): return ["summary b"]', encoding="utf-8"
1575 )
1576
1577 result = pytester.runpytest()
1578 result.stdout.fnmatch_lines(
1579 [
1580 "*def test_a():*",
1581 "*E*assert summary a*",
1582 "*def test_b():*",
1583 "*E*assert summary b*",
1584 "*def test_base():*",
1585 "*E*assert 1 == 2*",
1586 ]
1587 )
1588
1589
1590 def test_assertion_options(pytester: Pytester) -> None:
1591 pytester.makepyfile(
1592 """
1593 def test_hello():
1594 x = 3
1595 assert x == 4
1596 """
1597 )
1598 result = pytester.runpytest()
1599 assert "3 == 4" in result.stdout.str()
1600 result = pytester.runpytest_subprocess("--assert=plain")
1601 result.stdout.no_fnmatch_line("*3 == 4*")
1602
1603
1604 def test_triple_quoted_string_issue113(pytester: Pytester) -> None:
1605 pytester.makepyfile(
1606 """
1607 def test_hello():
1608 assert "" == '''
1609 '''"""
1610 )
1611 result = pytester.runpytest("--fulltrace")
1612 result.stdout.fnmatch_lines(["*1 failed*"])
1613 result.stdout.no_fnmatch_line("*SyntaxError*")
1614
1615
1616 def test_traceback_failure(pytester: Pytester) -> None:
1617 p1 = pytester.makepyfile(
1618 """
1619 def g():
1620 return 2
1621 def f(x):
1622 assert x == g()
1623 def test_onefails():
1624 f(3)
1625 """
1626 )
1627 result = pytester.runpytest(p1, "--tb=long")
1628 result.stdout.fnmatch_lines(
1629 [
1630 "*test_traceback_failure.py F*",
1631 "====* FAILURES *====",
1632 "____*____",
1633 "",
1634 " def test_onefails():",
1635 "> f(3)",
1636 "",
1637 "*test_*.py:6: ",
1638 "_ _ _ *",
1639 # "",
1640 " def f(x):",
1641 "> assert x == g()",
1642 "E assert 3 == 2",
1643 "E + where 2 = g()",
1644 "",
1645 "*test_traceback_failure.py:4: AssertionError",
1646 ]
1647 )
1648
1649 result = pytester.runpytest(p1) # "auto"
1650 result.stdout.fnmatch_lines(
1651 [
1652 "*test_traceback_failure.py F*",
1653 "====* FAILURES *====",
1654 "____*____",
1655 "",
1656 " def test_onefails():",
1657 "> f(3)",
1658 "",
1659 "*test_*.py:6: ",
1660 "",
1661 " def f(x):",
1662 "> assert x == g()",
1663 "E assert 3 == 2",
1664 "E + where 2 = g()",
1665 "",
1666 "*test_traceback_failure.py:4: AssertionError",
1667 ]
1668 )
1669
1670
1671 def test_exception_handling_no_traceback(pytester: Pytester) -> None:
1672 """Handle chain exceptions in tasks submitted by the multiprocess module (#1984)."""
1673 p1 = pytester.makepyfile(
1674 """
1675 from multiprocessing import Pool
1676
1677 def process_task(n):
1678 assert n == 10
1679
1680 def multitask_job():
1681 tasks = [1]
1682 with Pool(processes=1) as pool:
1683 pool.map(process_task, tasks)
1684
1685 def test_multitask_job():
1686 multitask_job()
1687 """
1688 )
1689 pytester.syspathinsert()
1690 result = pytester.runpytest(p1, "--tb=long")
1691 result.stdout.fnmatch_lines(
1692 [
1693 "====* FAILURES *====",
1694 "*multiprocessing.pool.RemoteTraceback:*",
1695 "Traceback (most recent call last):",
1696 "*assert n == 10",
1697 "The above exception was the direct cause of the following exception:",
1698 "> * multitask_job()",
1699 ]
1700 )
1701
1702
1703 @pytest.mark.skipif("'__pypy__' in sys.builtin_module_names")
1704 @pytest.mark.parametrize(
1705 "cmdline_args, warning_output",
1706 [
1707 (
1708 ["-OO", "-m", "pytest", "-h"],
1709 ["warning :*PytestConfigWarning:*assert statements are not executed*"],
1710 ),
1711 (
1712 ["-OO", "-m", "pytest"],
1713 [
1714 "=*= warnings summary =*=",
1715 "*PytestConfigWarning:*assert statements are not executed*",
1716 ],
1717 ),
1718 (
1719 ["-OO", "-m", "pytest", "--assert=plain"],
1720 [
1721 "=*= warnings summary =*=",
1722 "*PytestConfigWarning: ASSERTIONS ARE NOT EXECUTED and FAILING TESTS WILL PASS. "
1723 "Are you using python -O?",
1724 ],
1725 ),
1726 ],
1727 )
1728 def test_warn_missing(pytester: Pytester, cmdline_args, warning_output) -> None:
1729 pytester.makepyfile("")
1730
1731 result = pytester.run(sys.executable, *cmdline_args)
1732 result.stdout.fnmatch_lines(warning_output)
1733
1734
1735 def test_recursion_source_decode(pytester: Pytester) -> None:
1736 pytester.makepyfile(
1737 """
1738 def test_something():
1739 pass
1740 """
1741 )
1742 pytester.makeini(
1743 """
1744 [pytest]
1745 python_files = *.py
1746 """
1747 )
1748 result = pytester.runpytest("--collect-only")
1749 result.stdout.fnmatch_lines(
1750 [
1751 " <Module*>",
1752 ]
1753 )
1754
1755
1756 def test_AssertionError_message(pytester: Pytester) -> None:
1757 pytester.makepyfile(
1758 """
1759 def test_hello():
1760 x,y = 1,2
1761 assert 0, (x,y)
1762 """
1763 )
1764 result = pytester.runpytest()
1765 result.stdout.fnmatch_lines(
1766 """
1767 *def test_hello*
1768 *assert 0, (x,y)*
1769 *AssertionError: (1, 2)*
1770 """
1771 )
1772
1773
1774 def test_diff_newline_at_end(pytester: Pytester) -> None:
1775 pytester.makepyfile(
1776 r"""
1777 def test_diff():
1778 assert 'asdf' == 'asdf\n'
1779 """
1780 )
1781
1782 result = pytester.runpytest()
1783 result.stdout.fnmatch_lines(
1784 r"""
1785 *assert 'asdf' == 'asdf\n'
1786 * - asdf
1787 * ? -
1788 * + asdf
1789 """
1790 )
1791
1792
1793 @pytest.mark.filterwarnings("default")
1794 def test_assert_tuple_warning(pytester: Pytester) -> None:
1795 msg = "assertion is always true"
1796 pytester.makepyfile(
1797 """
1798 def test_tuple():
1799 assert(False, 'you shall not pass')
1800 """
1801 )
1802 result = pytester.runpytest()
1803 result.stdout.fnmatch_lines([f"*test_assert_tuple_warning.py:2:*{msg}*"])
1804
1805 # tuples with size != 2 should not trigger the warning
1806 pytester.makepyfile(
1807 """
1808 def test_tuple():
1809 assert ()
1810 """
1811 )
1812 result = pytester.runpytest()
1813 assert msg not in result.stdout.str()
1814
1815
1816 def test_assert_indirect_tuple_no_warning(pytester: Pytester) -> None:
1817 pytester.makepyfile(
1818 """
1819 def test_tuple():
1820 tpl = ('foo', 'bar')
1821 assert tpl
1822 """
1823 )
1824 result = pytester.runpytest()
1825 output = "\n".join(result.stdout.lines)
1826 assert "WR1" not in output
1827
1828
1829 def test_assert_with_unicode(pytester: Pytester) -> None:
1830 pytester.makepyfile(
1831 """\
1832 def test_unicode():
1833 assert '유니코드' == 'Unicode'
1834 """
1835 )
1836 result = pytester.runpytest()
1837 result.stdout.fnmatch_lines(["*AssertionError*"])
1838
1839
1840 def test_raise_unprintable_assertion_error(pytester: Pytester) -> None:
1841 pytester.makepyfile(
1842 r"""
1843 def test_raise_assertion_error():
1844 raise AssertionError('\xff')
1845 """
1846 )
1847 result = pytester.runpytest()
1848 result.stdout.fnmatch_lines(
1849 [r"> raise AssertionError('\xff')", "E AssertionError: *"]
1850 )
1851
1852
1853 def test_raise_assertion_error_raising_repr(pytester: Pytester) -> None:
1854 pytester.makepyfile(
1855 """
1856 class RaisingRepr(object):
1857 def __repr__(self):
1858 raise Exception()
1859 def test_raising_repr():
1860 raise AssertionError(RaisingRepr())
1861 """
1862 )
1863 result = pytester.runpytest()
1864 result.stdout.fnmatch_lines(["E AssertionError: <exception str() failed>"])
1865
1866
1867 def test_issue_1944(pytester: Pytester) -> None:
1868 pytester.makepyfile(
1869 """
1870 def f():
1871 return
1872
1873 assert f() == 10
1874 """
1875 )
1876 result = pytester.runpytest()
1877 result.stdout.fnmatch_lines(["*1 error*"])
1878 assert (
1879 "AttributeError: 'Module' object has no attribute '_obj'"
1880 not in result.stdout.str()
1881 )
1882
1883
1884 def test_exit_from_assertrepr_compare(monkeypatch) -> None:
1885 def raise_exit(obj):
1886 outcomes.exit("Quitting debugger")
1887
1888 monkeypatch.setattr(util, "istext", raise_exit)
1889
1890 with pytest.raises(outcomes.Exit, match="Quitting debugger"):
1891 callequal(1, 1)
1892
1893
1894 def test_assertion_location_with_coverage(pytester: Pytester) -> None:
1895 """This used to report the wrong location when run with coverage (#5754)."""
1896 p = pytester.makepyfile(
1897 """
1898 def test():
1899 assert False, 1
1900 assert False, 2
1901 """
1902 )
1903 result = pytester.runpytest(str(p))
1904 result.stdout.fnmatch_lines(
1905 [
1906 "> assert False, 1",
1907 "E AssertionError: 1",
1908 "E assert False",
1909 "*= 1 failed in*",
1910 ]
1911 )
1912
1913
1914 def test_reprcompare_verbose_long() -> None:
1915 a = {f"v{i}": i for i in range(11)}
1916 b = a.copy()
1917 b["v2"] += 10
1918 lines = callop("==", a, b, verbose=2)
1919 assert lines is not None
1920 assert lines[0] == (
1921 "{'v0': 0, 'v1': 1, 'v2': 2, 'v3': 3, 'v4': 4, 'v5': 5, "
1922 "'v6': 6, 'v7': 7, 'v8': 8, 'v9': 9, 'v10': 10}"
1923 " == "
1924 "{'v0': 0, 'v1': 1, 'v2': 12, 'v3': 3, 'v4': 4, 'v5': 5, "
1925 "'v6': 6, 'v7': 7, 'v8': 8, 'v9': 9, 'v10': 10}"
1926 )
1927
1928
1929 @pytest.mark.parametrize("enable_colors", [True, False])
1930 @pytest.mark.parametrize(
1931 ("test_code", "expected_lines"),
1932 (
1933 (
1934 """
1935 def test():
1936 assert [0, 1] == [0, 2]
1937 """,
1938 [
1939 "{bold}{red}E At index 1 diff: {reset}{number}1{hl-reset}{endline} != {reset}{number}2*",
1940 "{bold}{red}E {light-red}- 2,{hl-reset}{endline}{reset}",
1941 "{bold}{red}E {light-green}+ 1,{hl-reset}{endline}{reset}",
1942 ],
1943 ),
1944 (
1945 """
1946 def test():
1947 assert {f"number-is-{i}": i for i in range(1, 6)} == {
1948 f"number-is-{i}": i for i in range(5)
1949 }
1950 """,
1951 [
1952 "{bold}{red}E Common items:{reset}",
1953 "{bold}{red}E {reset}{{{str}'{hl-reset}{str}number-is-1{hl-reset}{str}'{hl-reset}: {number}1*",
1954 "{bold}{red}E Left contains 1 more item:{reset}",
1955 "{bold}{red}E {reset}{{{str}'{hl-reset}{str}number-is-5{hl-reset}{str}'{hl-reset}: {number}5*",
1956 "{bold}{red}E Right contains 1 more item:{reset}",
1957 "{bold}{red}E {reset}{{{str}'{hl-reset}{str}number-is-0{hl-reset}{str}'{hl-reset}: {number}0*",
1958 "{bold}{red}E {reset}{light-gray} {hl-reset} {{{endline}{reset}",
1959 "{bold}{red}E {light-gray} {hl-reset} 'number-is-1': 1,{endline}{reset}",
1960 "{bold}{red}E {light-green}+ 'number-is-5': 5,{hl-reset}{endline}{reset}",
1961 ],
1962 ),
1963 ),
1964 )
1965 def test_comparisons_handle_colors(
1966 pytester: Pytester, color_mapping, enable_colors, test_code, expected_lines
1967 ) -> None:
1968 p = pytester.makepyfile(test_code)
1969 result = pytester.runpytest(
1970 f"--color={'yes' if enable_colors else 'no'}", "-vv", str(p)
1971 )
1972 formatter = (
1973 color_mapping.format_for_fnmatch
1974 if enable_colors
1975 else color_mapping.strip_colors
1976 )
1977
1978 result.stdout.fnmatch_lines(formatter(expected_lines), consecutive=False)
1979
1980
1981 def test_fine_grained_assertion_verbosity(pytester: Pytester):
1982 long_text = "Lorem ipsum dolor sit amet " * 10
1983 p = pytester.makepyfile(
1984 f"""
1985 def test_ok():
1986 pass
1987
1988
1989 def test_words_fail():
1990 fruits1 = ["banana", "apple", "grapes", "melon", "kiwi"]
1991 fruits2 = ["banana", "apple", "orange", "melon", "kiwi"]
1992 assert fruits1 == fruits2
1993
1994
1995 def test_numbers_fail():
1996 number_to_text1 = {{str(x): x for x in range(5)}}
1997 number_to_text2 = {{str(x * 10): x * 10 for x in range(5)}}
1998 assert number_to_text1 == number_to_text2
1999
2000
2001 def test_long_text_fail():
2002 long_text = "{long_text}"
2003 assert "hello world" in long_text
2004 """
2005 )
2006 pytester.makeini(
2007 """
2008 [pytest]
2009 verbosity_assertions = 2
2010 """
2011 )
2012 result = pytester.runpytest(p)
2013
2014 result.stdout.fnmatch_lines(
2015 [
2016 f"{p.name} .FFF [100%]",
2017 "E At index 2 diff: 'grapes' != 'orange'",
2018 "E Full diff:",
2019 "E [",
2020 "E 'banana',",
2021 "E 'apple',",
2022 "E - 'orange',",
2023 "E ? ^ ^^",
2024 "E + 'grapes',",
2025 "E ? ^ ^ +",
2026 "E 'melon',",
2027 "E 'kiwi',",
2028 "E ]",
2029 "E Full diff:",
2030 "E {",
2031 "E '0': 0,",
2032 "E - '10': 10,",
2033 "E ? - -",
2034 "E + '1': 1,",
2035 "E - '20': 20,",
2036 "E ? - -",
2037 "E + '2': 2,",
2038 "E - '30': 30,",
2039 "E ? - -",
2040 "E + '3': 3,",
2041 "E - '40': 40,",
2042 "E ? - -",
2043 "E + '4': 4,",
2044 "E }",
2045 f"E AssertionError: assert 'hello world' in '{long_text}'",
2046 ]
2047 )