Debian Codegraph @

testing/test_assertrewrite.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 import ast
5 from collections.abc import Generator
6 from collections.abc import Mapping
7 import dis
8 import errno
9 from functools import partial
10 import glob
11 import importlib
12 import inspect
13 import marshal
14 import os
15 from pathlib import Path
16 import py_compile
17 import re
18 import stat
19 import sys
20 import textwrap
21 from typing import cast
22 from unittest import mock
23 import zipfile
24
25 import _pytest._code
26 from _pytest._io.saferepr import DEFAULT_REPR_MAX_SIZE
27 from _pytest.assertion import util
28 from _pytest.assertion.rewrite import _get_assertion_exprs
29 from _pytest.assertion.rewrite import _get_maxsize_for_saferepr
30 from _pytest.assertion.rewrite import _saferepr
31 from _pytest.assertion.rewrite import AssertionRewritingHook
32 from _pytest.assertion.rewrite import get_cache_dir
33 from _pytest.assertion.rewrite import PYC_TAIL
34 from _pytest.assertion.rewrite import PYTEST_TAG
35 from _pytest.assertion.rewrite import rewrite_asserts
36 from _pytest.config import Config
37 from _pytest.config import ExitCode
38 from _pytest.pathlib import make_numbered_dir
39 from _pytest.pytester import Pytester
40 import pytest
41
42
43 def rewrite(src: str) -> ast.Module:
44 tree = ast.parse(src)
45 rewrite_asserts(tree, src.encode())
46 return tree
47
48
49 def getmsg(
50 f, extra_ns: Mapping[str, object] | None = None, *, must_pass: bool = False
51 ) -> str | None:
52 """Rewrite the assertions in f, run it, and get the failure message."""
53 src = "\n".join(_pytest._code.Code.from_function(f).source().lines)
54 mod = rewrite(src)
55 code = compile(mod, "<test>", "exec")
56 ns: dict[str, object] = {}
57 if extra_ns is not None:
58 ns.update(extra_ns)
59 exec(code, ns)
60 func = ns[f.__name__]
61 try:
62 func() # type: ignore[operator]
63 except AssertionError:
64 if must_pass:
65 pytest.fail("shouldn't have raised")
66 s = str(sys.exc_info()[1])
67 if not s.startswith("assert"):
68 return "AssertionError: " + s
69 return s
70 else:
71 if not must_pass:
72 pytest.fail("function didn't raise at all")
73 return None
74
75
76 class TestAssertionRewrite:
77 def test_place_initial_imports(self) -> None:
78 s = """'Doc string'\nother = stuff"""
79 m = rewrite(s)
80 assert isinstance(m.body[0], ast.Expr)
81 for imp in m.body[1:3]:
82 assert isinstance(imp, ast.Import)
83 assert imp.lineno == 2
84 assert imp.col_offset == 0
85 assert isinstance(m.body[3], ast.Assign)
86 s = """from __future__ import division\nother_stuff"""
87 m = rewrite(s)
88 assert isinstance(m.body[0], ast.ImportFrom)
89 for imp in m.body[1:3]:
90 assert isinstance(imp, ast.Import)
91 assert imp.lineno == 2
92 assert imp.col_offset == 0
93 assert isinstance(m.body[3], ast.Expr)
94 s = """'doc string'\nfrom __future__ import division"""
95 m = rewrite(s)
96 assert isinstance(m.body[0], ast.Expr)
97 assert isinstance(m.body[1], ast.ImportFrom)
98 for imp in m.body[2:4]:
99 assert isinstance(imp, ast.Import)
100 assert imp.lineno == 2
101 assert imp.col_offset == 0
102 s = """'doc string'\nfrom __future__ import division\nother"""
103 m = rewrite(s)
104 assert isinstance(m.body[0], ast.Expr)
105 assert isinstance(m.body[1], ast.ImportFrom)
106 for imp in m.body[2:4]:
107 assert isinstance(imp, ast.Import)
108 assert imp.lineno == 3
109 assert imp.col_offset == 0
110 assert isinstance(m.body[4], ast.Expr)
111 s = """from . import relative\nother_stuff"""
112 m = rewrite(s)
113 for imp in m.body[:2]:
114 assert isinstance(imp, ast.Import)
115 assert imp.lineno == 1
116 assert imp.col_offset == 0
117 assert isinstance(m.body[3], ast.Expr)
118
119 def test_location_is_set(self) -> None:
120 s = textwrap.dedent(
121 """
122
123 assert False, (
124
125 "Ouch"
126 )
127
128 """
129 )
130 m = rewrite(s)
131 for node in m.body:
132 if isinstance(node, ast.Import):
133 continue
134 for n in [node, *ast.iter_child_nodes(node)]:
135 assert isinstance(n, ast.stmt | ast.expr)
136 for location in [
137 (n.lineno, n.col_offset),
138 (n.end_lineno, n.end_col_offset),
139 ]:
140 assert (3, 0) <= location <= (6, 3)
141
142 def test_positions_are_preserved(self) -> None:
143 """Ensure AST positions are preserved during rewriting (#12818)."""
144
145 def preserved(code: str) -> None:
146 s = textwrap.dedent(code)
147 locations = []
148
149 def loc(msg: str | None = None) -> None:
150 frame = inspect.currentframe()
151 assert frame
152 frame = frame.f_back
153 assert frame
154 frame = frame.f_back
155 assert frame
156
157 offset = frame.f_lasti
158
159 instructions = {i.offset: i for i in dis.get_instructions(frame.f_code)}
160
161 # skip CACHE instructions
162 while offset not in instructions and offset >= 0:
163 offset -= 1
164
165 instruction = instructions[offset]
166 if sys.version_info >= (3, 11):
167 position = instruction.positions
168 else:
169 position = instruction.starts_line
170
171 locations.append((msg, instruction.opname, position))
172
173 globals = {"loc": loc}
174
175 m = rewrite(s)
176 mod = compile(m, "<string>", "exec")
177 exec(mod, globals, globals)
178 transformed_locations = locations
179 locations = []
180
181 mod = compile(s, "<string>", "exec")
182 exec(mod, globals, globals)
183 original_locations = locations
184
185 assert len(original_locations) > 0
186 assert original_locations == transformed_locations
187
188 preserved("""
189 def f():
190 loc()
191 return 8
192
193 assert f() in [8]
194 assert (f()
195 in
196 [8])
197 """)
198
199 preserved("""
200 class T:
201 def __init__(self):
202 loc("init")
203 def __getitem__(self,index):
204 loc("getitem")
205 return index
206
207 assert T()[5] == 5
208 assert (T
209 ()
210 [5]
211 ==
212 5)
213 """)
214
215 for name, op in [
216 ("pos", "+"),
217 ("neg", "-"),
218 ("invert", "~"),
219 ]:
220 preserved(f"""
221 class T:
222 def __{name}__(self):
223 loc("{name}")
224 return "{name}"
225
226 assert {op}T() == "{name}"
227 assert ({op}
228 T
229 ()
230 ==
231 "{name}")
232 """)
233
234 for name, op in [
235 ("add", "+"),
236 ("sub", "-"),
237 ("mul", "*"),
238 ("truediv", "/"),
239 ("floordiv", "//"),
240 ("mod", "%"),
241 ("pow", "**"),
242 ("lshift", "<<"),
243 ("rshift", ">>"),
244 ("or", "|"),
245 ("xor", "^"),
246 ("and", "&"),
247 ("matmul", "@"),
248 ]:
249 preserved(f"""
250 class T:
251 def __{name}__(self,other):
252 loc("{name}")
253 return other
254
255 def __r{name}__(self,other):
256 loc("r{name}")
257 return other
258
259 assert T() {op} 2 == 2
260 assert 2 {op} T() == 2
261
262 assert (T
263 ()
264 {op}
265 2
266 ==
267 2)
268
269 assert (2
270 {op}
271 T
272 ()
273 ==
274 2)
275 """)
276
277 for name, op in [
278 ("eq", "=="),
279 ("ne", "!="),
280 ("lt", "<"),
281 ("le", "<="),
282 ("gt", ">"),
283 ("ge", ">="),
284 ]:
285 preserved(f"""
286 class T:
287 def __{name}__(self,other):
288 loc()
289 return True
290
291 assert T() {op} 5
292 assert (T
293 ()
294 {op}
295 5)
296 """)
297
298 for name, op in [
299 ("eq", "=="),
300 ("ne", "!="),
301 ("lt", ">"),
302 ("le", ">="),
303 ("gt", "<"),
304 ("ge", "<="),
305 ("contains", "in"),
306 ]:
307 preserved(f"""
308 class T:
309 def __{name}__(self,other):
310 loc()
311 return True
312
313 assert 5 {op} T()
314 assert (5
315 {op}
316 T
317 ())
318 """)
319
320 preserved("""
321 def func(value):
322 loc("func")
323 return value
324
325 class T:
326 def __iter__(self):
327 loc("iter")
328 return iter([5])
329
330 assert func(*T()) == 5
331 """)
332
333 preserved("""
334 class T:
335 def __getattr__(self,name):
336 loc()
337 return name
338
339 assert T().attr == "attr"
340 """)
341
342 def test_dont_rewrite(self) -> None:
343 s = """'PYTEST_DONT_REWRITE'\nassert 14"""
344 m = rewrite(s)
345 assert len(m.body) == 2
346 assert isinstance(m.body[1], ast.Assert)
347 assert m.body[1].msg is None
348
349 def test_dont_rewrite_plugin(self, pytester: Pytester) -> None:
350 contents = {
351 "conftest.py": "pytest_plugins = 'plugin'; import plugin",
352 "plugin.py": "'PYTEST_DONT_REWRITE'",
353 "test_foo.py": "def test_foo(): pass",
354 }
355 pytester.makepyfile(**contents)
356 result = pytester.runpytest_subprocess()
357 assert "warning" not in "".join(result.outlines)
358
359 def test_rewrites_plugin_as_a_package(self, pytester: Pytester) -> None:
360 pkgdir = pytester.mkpydir("plugin")
361 pkgdir.joinpath("__init__.py").write_text(
362 "import pytest\n"
363 "@pytest.fixture\n"
364 "def special_asserter():\n"
365 " def special_assert(x, y):\n"
366 " assert x == y\n"
367 " return special_assert\n",
368 encoding="utf-8",
369 )
370 pytester.makeconftest('pytest_plugins = ["plugin"]')
371 pytester.makepyfile("def test(special_asserter): special_asserter(1, 2)\n")
372 result = pytester.runpytest()
373 result.stdout.fnmatch_lines(["*assert 1 == 2*"])
374
375 def test_honors_pep_235(self, pytester: Pytester, monkeypatch) -> None:
376 # note: couldn't make it fail on macos with a single `sys.path` entry
377 # note: these modules are named `test_*` to trigger rewriting
378 pytester.makepyfile(test_y="x = 1")
379 xdir = pytester.mkdir("x")
380 pytester.mkpydir(str(xdir.joinpath("test_Y")))
381 xdir.joinpath("test_Y").joinpath("__init__.py").write_text(
382 "x = 2", encoding="utf-8"
383 )
384 pytester.makepyfile(
385 "import test_y\n"
386 "import test_Y\n"
387 "def test():\n"
388 " assert test_y.x == 1\n"
389 " assert test_Y.x == 2\n"
390 )
391 monkeypatch.syspath_prepend(str(xdir))
392 pytester.runpytest().assert_outcomes(passed=1)
393
394 def test_name(self, request) -> None:
395 def f1() -> None:
396 assert False
397
398 assert getmsg(f1) == "assert False"
399
400 def f2() -> None:
401 f = False
402 assert f
403
404 assert getmsg(f2) == "assert False"
405
406 def f3() -> None:
407 assert a_global # type: ignore[name-defined] # noqa: F821
408
409 assert getmsg(f3, {"a_global": False}) == "assert False"
410
411 def f4() -> None:
412 assert sys == 42 # type: ignore[comparison-overlap]
413
414 msg = getmsg(f4, {"sys": sys})
415 assert msg == "assert sys == 42"
416
417 def f5() -> None:
418 assert cls == 42 # type: ignore[name-defined] # noqa: F821
419
420 class X:
421 pass
422
423 msg = getmsg(f5, {"cls": X})
424 assert msg is not None
425 lines = msg.splitlines()
426 assert lines == ["assert cls == 42"]
427
428 def test_assertrepr_compare_same_width(self, request) -> None:
429 """Should use same width/truncation with same initial width."""
430
431 def f() -> None:
432 assert "1234567890" * 5 + "A" == "1234567890" * 5 + "B"
433
434 msg = getmsg(f)
435 assert msg is not None
436 line = msg.splitlines()[0]
437 if request.config.getoption("verbose") > 1:
438 assert line == (
439 "assert '12345678901234567890123456789012345678901234567890A' "
440 "== '12345678901234567890123456789012345678901234567890B'"
441 )
442 else:
443 assert line == (
444 "assert '123456789012...901234567890A' "
445 "== '123456789012...901234567890B'"
446 )
447
448 def test_dont_rewrite_if_hasattr_fails(self, request) -> None:
449 class Y:
450 """A class whose getattr fails, but not with `AttributeError`."""
451
452 def __getattr__(self, attribute_name):
453 raise KeyError()
454
455 def __repr__(self) -> str:
456 return "Y"
457
458 def __init__(self) -> None:
459 self.foo = 3
460
461 def f() -> None:
462 assert cls().foo == 2 # type: ignore[name-defined] # noqa: F821
463
464 # XXX: looks like the "where" should also be there in verbose mode?!
465 msg = getmsg(f, {"cls": Y})
466 assert msg is not None
467 lines = msg.splitlines()
468 assert lines == [
469 "assert 3 == 2",
470 " + where 3 = Y.foo",
471 " + where Y = cls()",
472 ]
473
474 def test_assert_already_has_message(self) -> None:
475 def f():
476 assert False, "something bad!"
477
478 assert getmsg(f) == "AssertionError: something bad!\nassert False"
479
480 def test_assertion_message(self, pytester: Pytester) -> None:
481 pytester.makepyfile(
482 """
483 def test_foo():
484 assert 1 == 2, "The failure message"
485 """
486 )
487 result = pytester.runpytest()
488 assert result.ret == 1
489 result.stdout.fnmatch_lines(
490 ["*AssertionError*The failure message*", "*assert 1 == 2*"]
491 )
492
493 def test_assertion_message_multiline(self, pytester: Pytester) -> None:
494 pytester.makepyfile(
495 """
496 def test_foo():
497 assert 1 == 2, "A multiline\\nfailure message"
498 """
499 )
500 result = pytester.runpytest()
501 assert result.ret == 1
502 result.stdout.fnmatch_lines(
503 ["*AssertionError*A multiline*", "*failure message*", "*assert 1 == 2*"]
504 )
505
506 def test_assertion_message_tuple(self, pytester: Pytester) -> None:
507 pytester.makepyfile(
508 """
509 def test_foo():
510 assert 1 == 2, (1, 2)
511 """
512 )
513 result = pytester.runpytest()
514 assert result.ret == 1
515 result.stdout.fnmatch_lines([f"*AssertionError*{(1, 2)!r}*", "*assert 1 == 2*"])
516
517 def test_assertion_message_expr(self, pytester: Pytester) -> None:
518 pytester.makepyfile(
519 """
520 def test_foo():
521 assert 1 == 2, 1 + 2
522 """
523 )
524 result = pytester.runpytest()
525 assert result.ret == 1
526 result.stdout.fnmatch_lines(["*AssertionError*3*", "*assert 1 == 2*"])
527
528 def test_assertion_message_escape(self, pytester: Pytester) -> None:
529 pytester.makepyfile(
530 """
531 def test_foo():
532 assert 1 == 2, 'To be escaped: %'
533 """
534 )
535 result = pytester.runpytest()
536 assert result.ret == 1
537 result.stdout.fnmatch_lines(
538 ["*AssertionError: To be escaped: %", "*assert 1 == 2"]
539 )
540
541 def test_assertion_messages_bytes(self, pytester: Pytester) -> None:
542 pytester.makepyfile("def test_bytes_assertion():\n assert False, b'ohai!'\n")
543 result = pytester.runpytest()
544 assert result.ret == 1
545 result.stdout.fnmatch_lines(["*AssertionError: b'ohai!'", "*assert False"])
546
547 def test_assertion_message_verbosity(self, pytester: Pytester) -> None:
548 """
549 Obey verbosity levels when printing the "message" part of assertions, when they are
550 non-strings (#6682).
551 """
552 pytester.makepyfile(
553 """
554 class LongRepr:
555
556 def __repr__(self):
557 return "A" * 500
558
559 def test_assertion_verbosity():
560 assert False, LongRepr()
561 """
562 )
563 # Normal verbosity: assertion message gets abbreviated.
564 result = pytester.runpytest()
565 assert result.ret == 1
566 result.stdout.re_match_lines(
567 [r".*AssertionError: A+\.\.\.A+$", ".*assert False"]
568 )
569
570 # High-verbosity: do not abbreviate the assertion message.
571 result = pytester.runpytest("-vv")
572 assert result.ret == 1
573 result.stdout.re_match_lines([r".*AssertionError: A+$", ".*assert False"])
574
575 def test_boolop(self) -> None:
576 def f1() -> None:
577 f = g = False
578 assert f and g
579
580 assert getmsg(f1) == "assert (False)"
581
582 def f2() -> None:
583 f = True
584 g = False
585 assert f and g
586
587 assert getmsg(f2) == "assert (True and False)"
588
589 def f3() -> None:
590 f = False
591 g = True
592 assert f and g
593
594 assert getmsg(f3) == "assert (False)"
595
596 def f4() -> None:
597 f = g = False
598 assert f or g
599
600 assert getmsg(f4) == "assert (False or False)"
601
602 def f5() -> None:
603 f = g = False
604 assert not f and not g
605
606 getmsg(f5, must_pass=True)
607
608 def x() -> bool:
609 return False
610
611 def f6() -> None:
612 assert x() and x()
613
614 assert (
615 getmsg(f6, {"x": x})
616 == """assert (False)
617 + where False = x()"""
618 )
619
620 def f7() -> None:
621 assert False or x()
622
623 assert (
624 getmsg(f7, {"x": x})
625 == """assert (False or False)
626 + where False = x()"""
627 )
628
629 def f8() -> None:
630 assert 1 in {} and 2 in {}
631
632 assert getmsg(f8) == "assert (1 in {})"
633
634 def f9() -> None:
635 x = 1
636 y = 2
637 assert x in {1: None} and y in {}
638
639 assert getmsg(f9) == "assert (1 in {1: None} and 2 in {})"
640
641 def f10() -> None:
642 f = True
643 g = False
644 assert f or g
645
646 getmsg(f10, must_pass=True)
647
648 def f11() -> None:
649 f = g = h = lambda: True
650 assert f() and g() and h()
651
652 getmsg(f11, must_pass=True)
653
654 def test_short_circuit_evaluation(self) -> None:
655 def f1() -> None:
656 assert True or explode # type: ignore[name-defined,unreachable] # noqa: F821
657
658 getmsg(f1, must_pass=True)
659
660 def f2() -> None:
661 x = 1
662 assert x == 1 or x == 2 # noqa: PLR1714
663
664 getmsg(f2, must_pass=True)
665
666 def test_unary_op(self) -> None:
667 def f1() -> None:
668 x = True
669 assert not x
670
671 assert getmsg(f1) == "assert not True"
672
673 def f2() -> None:
674 x = 0
675 assert ~x + 1
676
677 assert getmsg(f2) == "assert (~0 + 1)"
678
679 def f3() -> None:
680 x = 3
681 assert -x + x
682
683 assert getmsg(f3) == "assert (-3 + 3)"
684
685 def f4() -> None:
686 x = 0
687 assert +x + x
688
689 assert getmsg(f4) == "assert (+0 + 0)"
690
691 def test_binary_op(self) -> None:
692 def f1() -> None:
693 x = 1
694 y = -1
695 assert x + y
696
697 assert getmsg(f1) == "assert (1 + -1)"
698
699 def f2() -> None:
700 assert not 5 % 4
701
702 assert getmsg(f2) == "assert not (5 % 4)"
703
704 def test_boolop_percent(self) -> None:
705 def f1() -> None:
706 assert 3 % 2 and False
707
708 assert getmsg(f1) == "assert ((3 % 2) and False)"
709
710 def f2() -> None:
711 assert False or 4 % 2
712
713 assert getmsg(f2) == "assert (False or (4 % 2))"
714
715 def test_at_operator_issue1290(self, pytester: Pytester) -> None:
716 pytester.makepyfile(
717 """
718 class Matrix(object):
719 def __init__(self, num):
720 self.num = num
721 def __matmul__(self, other):
722 return self.num * other.num
723
724 def test_multmat_operator():
725 assert Matrix(2) @ Matrix(3) == 6"""
726 )
727 pytester.runpytest().assert_outcomes(passed=1)
728
729 def test_starred_with_side_effect(self, pytester: Pytester) -> None:
730 """See #4412"""
731 pytester.makepyfile(
732 """\
733 def test():
734 f = lambda x: x
735 x = iter([1, 2, 3])
736 assert 2 * next(x) == f(*[next(x)])
737 """
738 )
739 pytester.runpytest().assert_outcomes(passed=1)
740
741 def test_call(self) -> None:
742 def g(a=42, *args, **kwargs) -> bool:
743 return False
744
745 ns = {"g": g}
746
747 def f1() -> None:
748 assert g()
749
750 assert (
751 getmsg(f1, ns)
752 == """assert False
753 + where False = g()"""
754 )
755
756 def f2() -> None:
757 assert g(1)
758
759 assert (
760 getmsg(f2, ns)
761 == """assert False
762 + where False = g(1)"""
763 )
764
765 def f3() -> None:
766 assert g(1, 2)
767
768 assert (
769 getmsg(f3, ns)
770 == """assert False
771 + where False = g(1, 2)"""
772 )
773
774 def f4() -> None:
775 assert g(1, g=42)
776
777 assert (
778 getmsg(f4, ns)
779 == """assert False
780 + where False = g(1, g=42)"""
781 )
782
783 def f5() -> None:
784 assert g(1, 3, g=23)
785
786 assert (
787 getmsg(f5, ns)
788 == """assert False
789 + where False = g(1, 3, g=23)"""
790 )
791
792 def f6() -> None:
793 seq = [1, 2, 3]
794 assert g(*seq)
795
796 assert (
797 getmsg(f6, ns)
798 == """assert False
799 + where False = g(*[1, 2, 3])"""
800 )
801
802 def f7() -> None:
803 x = "a"
804 assert g(**{x: 2})
805
806 assert (
807 getmsg(f7, ns)
808 == """assert False
809 + where False = g(**{'a': 2})"""
810 )
811
812 def test_attribute(self) -> None:
813 class X:
814 g = 3
815
816 ns = {"x": X}
817
818 def f1() -> None:
819 assert not x.g # type: ignore[name-defined] # noqa: F821
820
821 assert (
822 getmsg(f1, ns)
823 == """assert not 3
824 + where 3 = x.g"""
825 )
826
827 def f2() -> None:
828 x.a = False # type: ignore[name-defined] # noqa: F821
829 assert x.a # type: ignore[name-defined] # noqa: F821
830
831 assert (
832 getmsg(f2, ns)
833 == """assert False
834 + where False = x.a"""
835 )
836
837 def test_comparisons(self) -> None:
838 def f1() -> None:
839 a, b = range(2)
840 assert b < a
841
842 assert getmsg(f1) == """assert 1 < 0"""
843
844 def f2() -> None:
845 a, b, c = range(3)
846 assert a > b > c
847
848 assert getmsg(f2) == """assert 0 > 1"""
849
850 def f3() -> None:
851 a, b, c = range(3)
852 assert a < b > c
853
854 assert getmsg(f3) == """assert 1 > 2"""
855
856 def f4() -> None:
857 a, b, c = range(3)
858 assert a < b <= c
859
860 getmsg(f4, must_pass=True)
861
862 def f5() -> None:
863 a, b, c = range(3)
864 assert a < b
865 assert b < c
866
867 getmsg(f5, must_pass=True)
868
869 def test_len(self, request) -> None:
870 def f():
871 values = list(range(10))
872 assert len(values) == 11
873
874 msg = getmsg(f)
875 assert msg == "assert 10 == 11\n + where 10 = len([0, 1, 2, 3, 4, 5, ...])"
876
877 def test_custom_reprcompare(self, monkeypatch) -> None:
878 def my_reprcompare1(op, left, right) -> str:
879 return "42"
880
881 monkeypatch.setattr(util, "_reprcompare", my_reprcompare1)
882
883 def f1() -> None:
884 assert 42 < 3
885
886 assert getmsg(f1) == "assert 42"
887
888 def my_reprcompare2(op, left, right) -> str:
889 return f"{left} {op} {right}"
890
891 monkeypatch.setattr(util, "_reprcompare", my_reprcompare2)
892
893 def f2() -> None:
894 assert 1 < 3 < 5 <= 4 < 7
895
896 assert getmsg(f2) == "assert 5 <= 4"
897
898 def test_assert_raising__bool__in_comparison(self) -> None:
899 def f() -> None:
900 class A:
901 def __bool__(self):
902 raise ValueError(42)
903
904 def __lt__(self, other):
905 return A()
906
907 def __repr__(self):
908 return "<MY42 object>"
909
910 def myany(x) -> bool:
911 return False
912
913 assert myany(A() < 0)
914
915 msg = getmsg(f)
916 assert msg is not None
917 assert "<MY42 object> < 0" in msg
918
919 def test_assert_handling_raise_in__iter__(self, pytester: Pytester) -> None:
920 pytester.makepyfile(
921 """\
922 class A:
923 def __iter__(self):
924 raise ValueError()
925
926 def __eq__(self, o: object) -> bool:
927 return self is o
928
929 def __repr__(self):
930 return "<A object>"
931
932 assert A() == A()
933 """
934 )
935 result = pytester.runpytest()
936 result.stdout.fnmatch_lines(["*E*assert <A object> == <A object>"])
937
938 def test_formatchar(self) -> None:
939 def f() -> None:
940 assert "%test" == "test" # type: ignore[comparison-overlap]
941
942 msg = getmsg(f)
943 assert msg is not None
944 assert msg.startswith("assert '%test' == 'test'")
945
946 def test_custom_repr(self, request) -> None:
947 def f() -> None:
948 class Foo:
949 a = 1
950
951 def __repr__(self):
952 return "\n{ \n~ \n}"
953
954 f = Foo()
955 assert 0 == f.a
956
957 msg = getmsg(f)
958 assert msg is not None
959 lines = util._format_lines([msg])
960 assert lines == ["assert 0 == 1\n + where 1 = \\n{ \\n~ \\n}.a"]
961
962 def test_custom_repr_non_ascii(self) -> None:
963 def f() -> None:
964 class A:
965 name = "ä"
966
967 def __repr__(self):
968 return self.name.encode("UTF-8") # only legal in python2
969
970 a = A()
971 assert not a.name
972
973 msg = getmsg(f)
974 assert msg is not None
975 assert "UnicodeDecodeError" not in msg
976 assert "UnicodeEncodeError" not in msg
977
978 def test_assert_fixture(self, pytester: Pytester) -> None:
979 pytester.makepyfile(
980 """\
981 import pytest
982 @pytest.fixture
983 def fixt():
984 return 42
985
986 def test_something(): # missing "fixt" argument
987 assert fixt == 42
988 """
989 )
990 result = pytester.runpytest()
991 result.stdout.fnmatch_lines(
992 ["*assert <pytest_fixture(<function fixt at *>)> == 42*"]
993 )
994
995
996 class TestRewriteOnImport:
997 def test_pycache_is_a_file(self, pytester: Pytester) -> None:
998 pytester.path.joinpath("__pycache__").write_text("Hello", encoding="utf-8")
999 pytester.makepyfile(
1000 """
1001 def test_rewritten():
1002 assert "@py_builtins" in globals()"""
1003 )
1004 assert pytester.runpytest().ret == 0
1005
1006 def test_pycache_is_readonly(self, pytester: Pytester) -> None:
1007 cache = pytester.mkdir("__pycache__")
1008 old_mode = cache.stat().st_mode
1009 cache.chmod(old_mode ^ stat.S_IWRITE)
1010 pytester.makepyfile(
1011 """
1012 def test_rewritten():
1013 assert "@py_builtins" in globals()"""
1014 )
1015 try:
1016 assert pytester.runpytest().ret == 0
1017 finally:
1018 cache.chmod(old_mode)
1019
1020 def test_zipfile(self, pytester: Pytester) -> None:
1021 z = pytester.path.joinpath("myzip.zip")
1022 z_fn = str(z)
1023 f = zipfile.ZipFile(z_fn, "w")
1024 try:
1025 f.writestr("test_gum/__init__.py", "")
1026 f.writestr("test_gum/test_lizard.py", "")
1027 finally:
1028 f.close()
1029 z.chmod(256)
1030 pytester.makepyfile(
1031 f"""
1032 import sys
1033 sys.path.append({z_fn!r})
1034 import test_gum.test_lizard"""
1035 )
1036 assert pytester.runpytest().ret == ExitCode.NO_TESTS_COLLECTED
1037
1038 def test_load_resource_via_files_with_rewrite(self, pytester: Pytester) -> None:
1039 example = pytester.path.joinpath("demo") / "example"
1040 init = pytester.path.joinpath("demo") / "__init__.py"
1041 pytester.makepyfile(
1042 **{
1043 "demo/__init__.py": """
1044 from importlib.resources import files
1045
1046 def load():
1047 return files(__name__)
1048 """,
1049 "test_load": f"""
1050 pytest_plugins = ["demo"]
1051
1052 def test_load():
1053 from demo import load
1054 found = {{str(i) for i in load().iterdir() if i.name != "__pycache__"}}
1055 assert found == {{{str(example)!r}, {str(init)!r}}}
1056 """,
1057 }
1058 )
1059 example.mkdir()
1060
1061 assert pytester.runpytest("-vv").ret == ExitCode.OK
1062
1063 def test_readonly(self, pytester: Pytester) -> None:
1064 sub = pytester.mkdir("testing")
1065 sub.joinpath("test_readonly.py").write_bytes(
1066 b"""
1067 def test_rewritten():
1068 assert "@py_builtins" in globals()
1069 """,
1070 )
1071 old_mode = sub.stat().st_mode
1072 sub.chmod(320)
1073 try:
1074 assert pytester.runpytest().ret == 0
1075 finally:
1076 sub.chmod(old_mode)
1077
1078 def test_dont_write_bytecode(self, pytester: Pytester, monkeypatch) -> None:
1079 monkeypatch.delenv("PYTHONPYCACHEPREFIX", raising=False)
1080
1081 pytester.makepyfile(
1082 """
1083 import os
1084 def test_no_bytecode():
1085 assert "__pycache__" in __spec__.cached
1086 assert not os.path.exists(__spec__.cached)
1087 assert not os.path.exists(os.path.dirname(__spec__.cached))
1088 """
1089 )
1090 monkeypatch.setenv("PYTHONDONTWRITEBYTECODE", "1")
1091 assert pytester.runpytest_subprocess().ret == 0
1092
1093 def test_orphaned_pyc_file(self, pytester: Pytester, monkeypatch) -> None:
1094 monkeypatch.delenv("PYTHONPYCACHEPREFIX", raising=False)
1095 monkeypatch.setattr(sys, "pycache_prefix", None, raising=False)
1096
1097 pytester.makepyfile(
1098 """
1099 import orphan
1100 def test_it():
1101 assert orphan.value == 17
1102 """
1103 )
1104 pytester.makepyfile(
1105 orphan="""
1106 value = 17
1107 """
1108 )
1109 py_compile.compile("orphan.py")
1110 os.remove("orphan.py")
1111
1112 # Python 3 puts the .pyc files in a __pycache__ directory, and will
1113 # not import from there without source. It will import a .pyc from
1114 # the source location though.
1115 if not os.path.exists("orphan.pyc"):
1116 pycs = glob.glob("__pycache__/orphan.*.pyc")
1117 assert len(pycs) == 1
1118 os.rename(pycs[0], "orphan.pyc")
1119
1120 assert pytester.runpytest().ret == 0
1121
1122 def test_cached_pyc_includes_pytest_version(
1123 self, pytester: Pytester, monkeypatch
1124 ) -> None:
1125 """Avoid stale caches (#1671)"""
1126 monkeypatch.delenv("PYTHONDONTWRITEBYTECODE", raising=False)
1127 monkeypatch.delenv("PYTHONPYCACHEPREFIX", raising=False)
1128 pytester.makepyfile(
1129 test_foo="""
1130 def test_foo():
1131 assert True
1132 """
1133 )
1134 result = pytester.runpytest_subprocess()
1135 assert result.ret == 0
1136 found_names = glob.glob(f"__pycache__/*-pytest-{pytest.__version__}.pyc")
1137 assert found_names, "pyc with expected tag not found in names: {}".format(
1138 glob.glob("__pycache__/*.pyc")
1139 )
1140
1141 @pytest.mark.skipif('"__pypy__" in sys.modules')
1142 def test_pyc_vs_pyo(
1143 self,
1144 pytester: Pytester,
1145 monkeypatch: pytest.MonkeyPatch,
1146 ) -> None:
1147 pytester.makepyfile(
1148 """
1149 import pytest
1150 def test_optimized():
1151 "hello"
1152 assert test_optimized.__doc__ is None"""
1153 )
1154 p = make_numbered_dir(root=Path(pytester.path), prefix="runpytest-")
1155 tmp = f"--basetemp={p}"
1156 with monkeypatch.context() as mp:
1157 mp.setenv("PYTHONOPTIMIZE", "2")
1158 mp.delenv("PYTHONDONTWRITEBYTECODE", raising=False)
1159 mp.delenv("PYTHONPYCACHEPREFIX", raising=False)
1160 assert pytester.runpytest_subprocess(tmp).ret == 0
1161 tagged = "test_pyc_vs_pyo." + PYTEST_TAG
1162 assert tagged + ".pyo" in os.listdir("__pycache__")
1163 monkeypatch.delenv("PYTHONDONTWRITEBYTECODE", raising=False)
1164 monkeypatch.delenv("PYTHONPYCACHEPREFIX", raising=False)
1165 assert pytester.runpytest_subprocess(tmp).ret == 1
1166 assert tagged + ".pyc" in os.listdir("__pycache__")
1167
1168 def test_package(self, pytester: Pytester) -> None:
1169 pkg = pytester.path.joinpath("pkg")
1170 pkg.mkdir()
1171 pkg.joinpath("__init__.py")
1172 pkg.joinpath("test_blah.py").write_text(
1173 """
1174 def test_rewritten():
1175 assert "@py_builtins" in globals()""",
1176 encoding="utf-8",
1177 )
1178 assert pytester.runpytest().ret == 0
1179
1180 def test_translate_newlines(self, pytester: Pytester) -> None:
1181 content = "def test_rewritten():\r\n assert '@py_builtins' in globals()"
1182 b = content.encode("utf-8")
1183 pytester.path.joinpath("test_newlines.py").write_bytes(b)
1184 assert pytester.runpytest().ret == 0
1185
1186 def test_package_without__init__py(self, pytester: Pytester) -> None:
1187 pkg = pytester.mkdir("a_package_without_init_py")
1188 pkg.joinpath("module.py").touch()
1189 pytester.makepyfile("import a_package_without_init_py.module")
1190 assert pytester.runpytest().ret == ExitCode.NO_TESTS_COLLECTED
1191
1192 def test_rewrite_warning(self, pytester: Pytester) -> None:
1193 pytester.makeconftest(
1194 """
1195 import pytest
1196 pytest.register_assert_rewrite("_pytest")
1197 """
1198 )
1199 # needs to be a subprocess because pytester explicitly disables this warning
1200 result = pytester.runpytest_subprocess()
1201 result.stdout.fnmatch_lines(["*Module already imported*; _pytest"])
1202
1203 def test_rewrite_warning_ignore(self, pytester: Pytester) -> None:
1204 pytester.makeconftest(
1205 """
1206 import pytest
1207 pytest.register_assert_rewrite("_pytest")
1208 """
1209 )
1210 # needs to be a subprocess because pytester explicitly disables this warning
1211 result = pytester.runpytest_subprocess(
1212 "-W",
1213 "ignore:Module already imported so cannot be rewritten; _pytest:pytest.PytestAssertRewriteWarning",
1214 )
1215 # Previously, when the message pattern used to contain an extra `:`, an error was raised.
1216 assert not result.stderr.str().strip()
1217 result.stdout.no_fnmatch_line("*Module already imported*; _pytest")
1218
1219 def test_rewrite_module_imported_from_conftest(self, pytester: Pytester) -> None:
1220 pytester.makeconftest(
1221 """
1222 import test_rewrite_module_imported
1223 """
1224 )
1225 pytester.makepyfile(
1226 test_rewrite_module_imported="""
1227 def test_rewritten():
1228 assert "@py_builtins" in globals()
1229 """
1230 )
1231 assert pytester.runpytest_subprocess().ret == 0
1232
1233 def test_remember_rewritten_modules(
1234 self, pytestconfig, pytester: Pytester, monkeypatch
1235 ) -> None:
1236 """`AssertionRewriteHook` should remember rewritten modules so it
1237 doesn't give false positives (#2005)."""
1238 monkeypatch.syspath_prepend(pytester.path)
1239 pytester.makepyfile(test_remember_rewritten_modules="")
1240 warnings = []
1241 hook = AssertionRewritingHook(pytestconfig)
1242 monkeypatch.setattr(
1243 hook, "_warn_already_imported", lambda code, msg: warnings.append(msg)
1244 )
1245 spec = hook.find_spec("test_remember_rewritten_modules")
1246 assert spec is not None
1247 module = importlib.util.module_from_spec(spec)
1248 hook.exec_module(module)
1249 hook.mark_rewrite("test_remember_rewritten_modules")
1250 hook.mark_rewrite("test_remember_rewritten_modules")
1251 assert warnings == []
1252
1253 def test_rewrite_warning_using_pytest_plugins(self, pytester: Pytester) -> None:
1254 pytester.makepyfile(
1255 **{
1256 "conftest.py": "pytest_plugins = ['core', 'gui', 'sci']",
1257 "core.py": "",
1258 "gui.py": "pytest_plugins = ['core', 'sci']",
1259 "sci.py": "pytest_plugins = ['core']",
1260 "test_rewrite_warning_pytest_plugins.py": "def test(): pass",
1261 }
1262 )
1263 pytester.chdir()
1264 result = pytester.runpytest_subprocess()
1265 result.stdout.fnmatch_lines(["*= 1 passed in *=*"])
1266 result.stdout.no_fnmatch_line("*pytest-warning summary*")
1267
1268 def test_rewrite_warning_using_pytest_plugins_env_var(
1269 self, pytester: Pytester, monkeypatch
1270 ) -> None:
1271 monkeypatch.setenv("PYTEST_PLUGINS", "plugin")
1272 pytester.makepyfile(
1273 **{
1274 "plugin.py": "",
1275 "test_rewrite_warning_using_pytest_plugins_env_var.py": """
1276 import plugin
1277 pytest_plugins = ['plugin']
1278 def test():
1279 pass
1280 """,
1281 }
1282 )
1283 pytester.chdir()
1284 result = pytester.runpytest_subprocess()
1285 result.stdout.fnmatch_lines(["*= 1 passed in *=*"])
1286 result.stdout.no_fnmatch_line("*pytest-warning summary*")
1287
1288
1289 class TestAssertionRewriteHookDetails:
1290 def test_sys_meta_path_munged(self, pytester: Pytester) -> None:
1291 pytester.makepyfile(
1292 """
1293 def test_meta_path():
1294 import sys; sys.meta_path = []"""
1295 )
1296 assert pytester.runpytest().ret == 0
1297
1298 def test_write_pyc(self, pytester: Pytester, tmp_path) -> None:
1299 from _pytest.assertion import AssertionState
1300 from _pytest.assertion.rewrite import _write_pyc
1301
1302 config = pytester.parseconfig()
1303 state = AssertionState(config, "rewrite")
1304 tmp_path.joinpath("source.py").touch()
1305 source_path = str(tmp_path)
1306 pycpath = tmp_path.joinpath("pyc")
1307 co = compile("1", "f.py", "single")
1308 assert _write_pyc(state, co, os.stat(source_path), pycpath)
1309
1310 with mock.patch.object(os, "replace", side_effect=OSError):
1311 assert not _write_pyc(state, co, os.stat(source_path), pycpath)
1312
1313 def test_resources_provider_for_loader(self, pytester: Pytester) -> None:
1314 """
1315 Attempts to load resources from a package should succeed normally,
1316 even when the AssertionRewriteHook is used to load the modules.
1317
1318 See #366 for details.
1319 """
1320 pytest.importorskip("pkg_resources")
1321
1322 pytester.mkpydir("testpkg")
1323 contents = {
1324 "testpkg/test_pkg": """
1325 import pkg_resources
1326
1327 import pytest
1328 from _pytest.assertion.rewrite import AssertionRewritingHook
1329
1330 def test_load_resource():
1331 assert isinstance(__loader__, AssertionRewritingHook)
1332 res = pkg_resources.resource_string(__name__, 'resource.txt')
1333 res = res.decode('ascii')
1334 assert res == 'Load me please.'
1335 """
1336 }
1337 pytester.makepyfile(**contents)
1338 pytester.maketxtfile(**{"testpkg/resource": "Load me please."})
1339
1340 result = pytester.runpytest_subprocess()
1341 result.assert_outcomes(passed=1)
1342
1343 def test_read_pyc(self, tmp_path: Path) -> None:
1344 """
1345 Ensure that the `_read_pyc` can properly deal with corrupted pyc files.
1346 In those circumstances it should just give up instead of generating
1347 an exception that is propagated to the caller.
1348 """
1349 import py_compile
1350
1351 from _pytest.assertion.rewrite import _read_pyc
1352
1353 source = tmp_path / "source.py"
1354 pyc = Path(str(source) + "c")
1355
1356 source.write_text("def test(): pass", encoding="utf-8")
1357 py_compile.compile(str(source), str(pyc))
1358
1359 contents = pyc.read_bytes()
1360 strip_bytes = 20 # header is around 16 bytes, strip a little more
1361 assert len(contents) > strip_bytes
1362 pyc.write_bytes(contents[:strip_bytes])
1363
1364 assert _read_pyc(source, pyc) is None # no error
1365
1366 def test_read_pyc_success(self, tmp_path: Path, pytester: Pytester) -> None:
1367 """
1368 Ensure that the _rewrite_test() -> _write_pyc() produces a pyc file
1369 that can be properly read with _read_pyc()
1370 """
1371 from _pytest.assertion import AssertionState
1372 from _pytest.assertion.rewrite import _read_pyc
1373 from _pytest.assertion.rewrite import _rewrite_test
1374 from _pytest.assertion.rewrite import _write_pyc
1375
1376 config = pytester.parseconfig()
1377 state = AssertionState(config, "rewrite")
1378
1379 fn = tmp_path / "source.py"
1380 pyc = Path(str(fn) + "c")
1381
1382 fn.write_text("def test(): assert True", encoding="utf-8")
1383
1384 source_stat, co = _rewrite_test(fn, config)
1385 _write_pyc(state, co, source_stat, pyc)
1386 assert _read_pyc(fn, pyc, state.trace) is not None
1387
1388 def test_read_pyc_more_invalid(self, tmp_path: Path) -> None:
1389 from _pytest.assertion.rewrite import _read_pyc
1390
1391 source = tmp_path / "source.py"
1392 pyc = tmp_path / "source.pyc"
1393
1394 source_bytes = b"def test(): pass\n"
1395 source.write_bytes(source_bytes)
1396
1397 magic = importlib.util.MAGIC_NUMBER
1398
1399 flags = b"\x00\x00\x00\x00"
1400
1401 mtime = b"\x58\x3c\xb0\x5f"
1402 mtime_int = int.from_bytes(mtime, "little")
1403 os.utime(source, (mtime_int, mtime_int))
1404
1405 size = len(source_bytes).to_bytes(4, "little")
1406
1407 code = marshal.dumps(compile(source_bytes, str(source), "exec"))
1408
1409 # Good header.
1410 pyc.write_bytes(magic + flags + mtime + size + code)
1411 assert _read_pyc(source, pyc, print) is not None
1412
1413 # Too short.
1414 pyc.write_bytes(magic + flags + mtime)
1415 assert _read_pyc(source, pyc, print) is None
1416
1417 # Bad magic.
1418 pyc.write_bytes(b"\x12\x34\x56\x78" + flags + mtime + size + code)
1419 assert _read_pyc(source, pyc, print) is None
1420
1421 # Unsupported flags.
1422 pyc.write_bytes(magic + b"\x00\xff\x00\x00" + mtime + size + code)
1423 assert _read_pyc(source, pyc, print) is None
1424
1425 # Bad mtime.
1426 pyc.write_bytes(magic + flags + b"\x58\x3d\xb0\x5f" + size + code)
1427 assert _read_pyc(source, pyc, print) is None
1428
1429 # Bad size.
1430 pyc.write_bytes(magic + flags + mtime + b"\x99\x00\x00\x00" + code)
1431 assert _read_pyc(source, pyc, print) is None
1432
1433 def test_reload_is_same_and_reloads(self, pytester: Pytester) -> None:
1434 """Reloading a (collected) module after change picks up the change."""
1435 pytester.makeini(
1436 """
1437 [pytest]
1438 python_files = *.py
1439 """
1440 )
1441 pytester.makepyfile(
1442 file="""
1443 def reloaded():
1444 return False
1445
1446 def rewrite_self():
1447 with open(__file__, 'w', encoding='utf-8') as self:
1448 self.write('def reloaded(): return True')
1449 """,
1450 test_fun="""
1451 import sys
1452 from importlib import reload
1453
1454 def test_loader():
1455 import file
1456 assert not file.reloaded()
1457 file.rewrite_self()
1458 assert sys.modules["file"] is reload(file)
1459 assert file.reloaded()
1460 """,
1461 )
1462 result = pytester.runpytest()
1463 result.stdout.fnmatch_lines(["* 1 passed*"])
1464
1465 def test_get_data_support(self, pytester: Pytester) -> None:
1466 """Implement optional PEP302 api (#808)."""
1467 path = pytester.mkpydir("foo")
1468 path.joinpath("test_foo.py").write_text(
1469 textwrap.dedent(
1470 """\
1471 class Test(object):
1472 def test_foo(self):
1473 import pkgutil
1474 data = pkgutil.get_data('foo.test_foo', 'data.txt')
1475 assert data == b'Hey'
1476 """
1477 ),
1478 encoding="utf-8",
1479 )
1480 path.joinpath("data.txt").write_text("Hey", encoding="utf-8")
1481 result = pytester.runpytest()
1482 result.stdout.fnmatch_lines(["*1 passed*"])
1483
1484
1485 def test_issue731(pytester: Pytester) -> None:
1486 pytester.makepyfile(
1487 """
1488 class LongReprWithBraces(object):
1489 def __repr__(self):
1490 return 'LongReprWithBraces({' + ('a' * 80) + '}' + ('a' * 120) + ')'
1491
1492 def some_method(self):
1493 return False
1494
1495 def test_long_repr():
1496 obj = LongReprWithBraces()
1497 assert obj.some_method()
1498 """
1499 )
1500 result = pytester.runpytest()
1501 result.stdout.no_fnmatch_line("*unbalanced braces*")
1502
1503
1504 class TestIssue925:
1505 def test_simple_case(self, pytester: Pytester) -> None:
1506 pytester.makepyfile(
1507 """
1508 def test_ternary_display():
1509 assert (False == False) == False
1510 """
1511 )
1512 result = pytester.runpytest()
1513 result.stdout.fnmatch_lines(["*E*assert (False == False) == False"])
1514
1515 def test_long_case(self, pytester: Pytester) -> None:
1516 pytester.makepyfile(
1517 """
1518 def test_ternary_display():
1519 assert False == (False == True) == True
1520 """
1521 )
1522 result = pytester.runpytest()
1523 result.stdout.fnmatch_lines(["*E*assert (False == True) == True"])
1524
1525 def test_many_brackets(self, pytester: Pytester) -> None:
1526 pytester.makepyfile(
1527 """
1528 def test_ternary_display():
1529 assert True == ((False == True) == True)
1530 """
1531 )
1532 result = pytester.runpytest()
1533 result.stdout.fnmatch_lines(["*E*assert True == ((False == True) == True)"])
1534
1535
1536 class TestIssue2121:
1537 def test_rewrite_python_files_contain_subdirs(self, pytester: Pytester) -> None:
1538 pytester.makepyfile(
1539 **{
1540 "tests/file.py": """
1541 def test_simple_failure():
1542 assert 1 + 1 == 3
1543 """
1544 }
1545 )
1546 pytester.makeini(
1547 """
1548 [pytest]
1549 python_files = tests/**.py
1550 """
1551 )
1552 result = pytester.runpytest()
1553 result.stdout.fnmatch_lines(["*E*assert (1 + 1) == 3"])
1554
1555
1556 class TestAssertionRewriteWalrusOperator:
1557 """See #10743"""
1558
1559 def test_assertion_walrus_operator(self, pytester: Pytester) -> None:
1560 pytester.makepyfile(
1561 """
1562 def my_func(before, after):
1563 return before == after
1564
1565 def change_value(value):
1566 return value.lower()
1567
1568 def test_walrus_conversion():
1569 a = "Hello"
1570 assert not my_func(a, a := change_value(a))
1571 assert a == "hello"
1572 """
1573 )
1574 result = pytester.runpytest()
1575 assert result.ret == 0
1576
1577 def test_assertion_walrus_operator_dont_rewrite(self, pytester: Pytester) -> None:
1578 pytester.makepyfile(
1579 """
1580 'PYTEST_DONT_REWRITE'
1581 def my_func(before, after):
1582 return before == after
1583
1584 def change_value(value):
1585 return value.lower()
1586
1587 def test_walrus_conversion_dont_rewrite():
1588 a = "Hello"
1589 assert not my_func(a, a := change_value(a))
1590 assert a == "hello"
1591 """
1592 )
1593 result = pytester.runpytest()
1594 assert result.ret == 0
1595
1596 def test_assertion_inline_walrus_operator(self, pytester: Pytester) -> None:
1597 pytester.makepyfile(
1598 """
1599 def my_func(before, after):
1600 return before == after
1601
1602 def test_walrus_conversion_inline():
1603 a = "Hello"
1604 assert not my_func(a, a := a.lower())
1605 assert a == "hello"
1606 """
1607 )
1608 result = pytester.runpytest()
1609 assert result.ret == 0
1610
1611 def test_assertion_inline_walrus_operator_reverse(self, pytester: Pytester) -> None:
1612 pytester.makepyfile(
1613 """
1614 def my_func(before, after):
1615 return before == after
1616
1617 def test_walrus_conversion_reverse():
1618 a = "Hello"
1619 assert my_func(a := a.lower(), a)
1620 assert a == 'hello'
1621 """
1622 )
1623 result = pytester.runpytest()
1624 assert result.ret == 0
1625
1626 def test_assertion_walrus_no_variable_name_conflict(
1627 self, pytester: Pytester
1628 ) -> None:
1629 pytester.makepyfile(
1630 """
1631 def test_walrus_conversion_no_conflict():
1632 a = "Hello"
1633 assert a == (b := a.lower())
1634 """
1635 )
1636 result = pytester.runpytest()
1637 assert result.ret == 1
1638 result.stdout.fnmatch_lines(["*AssertionError: assert 'Hello' == 'hello'"])
1639
1640 def test_assertion_walrus_operator_true_assertion_and_changes_variable_value(
1641 self, pytester: Pytester
1642 ) -> None:
1643 pytester.makepyfile(
1644 """
1645 def test_walrus_conversion_succeed():
1646 a = "Hello"
1647 assert a != (a := a.lower())
1648 assert a == 'hello'
1649 """
1650 )
1651 result = pytester.runpytest()
1652 assert result.ret == 0
1653
1654 def test_assertion_walrus_operator_fail_assertion(self, pytester: Pytester) -> None:
1655 pytester.makepyfile(
1656 """
1657 def test_walrus_conversion_fails():
1658 a = "Hello"
1659 assert a == (a := a.lower())
1660 """
1661 )
1662 result = pytester.runpytest()
1663 assert result.ret == 1
1664 result.stdout.fnmatch_lines(["*AssertionError: assert 'Hello' == 'hello'"])
1665
1666 def test_assertion_walrus_operator_boolean_composite(
1667 self, pytester: Pytester
1668 ) -> None:
1669 pytester.makepyfile(
1670 """
1671 def test_walrus_operator_change_boolean_value():
1672 a = True
1673 assert a and True and ((a := False) is False) and (a is False) and ((a := None) is None)
1674 assert a is None
1675 """
1676 )
1677 result = pytester.runpytest()
1678 assert result.ret == 0
1679
1680 def test_assertion_walrus_operator_compare_boolean_fails(
1681 self, pytester: Pytester
1682 ) -> None:
1683 pytester.makepyfile(
1684 """
1685 def test_walrus_operator_change_boolean_value():
1686 a = True
1687 assert not (a and ((a := False) is False))
1688 """
1689 )
1690 result = pytester.runpytest()
1691 assert result.ret == 1
1692 result.stdout.fnmatch_lines(["*assert not (True and False is False)"])
1693
1694 def test_assertion_walrus_operator_boolean_none_fails(
1695 self, pytester: Pytester
1696 ) -> None:
1697 pytester.makepyfile(
1698 """
1699 def test_walrus_operator_change_boolean_value():
1700 a = True
1701 assert not (a and ((a := None) is None))
1702 """
1703 )
1704 result = pytester.runpytest()
1705 assert result.ret == 1
1706 result.stdout.fnmatch_lines(["*assert not (True and None is None)"])
1707
1708 def test_assertion_walrus_operator_value_changes_cleared_after_each_test(
1709 self, pytester: Pytester
1710 ) -> None:
1711 pytester.makepyfile(
1712 """
1713 def test_walrus_operator_change_value():
1714 a = True
1715 assert (a := None) is None
1716
1717 def test_walrus_operator_not_override_value():
1718 a = True
1719 assert a is True
1720 """
1721 )
1722 result = pytester.runpytest()
1723 assert result.ret == 0
1724
1725 def test_assertion_namedexpr_compare_left_overwrite(
1726 self, pytester: Pytester
1727 ) -> None:
1728 pytester.makepyfile(
1729 """
1730 def test_namedexpr_compare_left_overwrite():
1731 a = "Hello"
1732 b = "World"
1733 c = "Test"
1734 assert (a := b) == c and (a := "Test") == "Test"
1735 """
1736 )
1737 result = pytester.runpytest()
1738 assert result.ret == 1
1739 result.stdout.fnmatch_lines(["*assert ('World' == 'Test'*"])
1740
1741
1742 class TestIssue11028:
1743 def test_assertion_walrus_operator_in_operand(self, pytester: Pytester) -> None:
1744 pytester.makepyfile(
1745 """
1746 def test_in_string():
1747 assert (obj := "foo") in obj
1748 """
1749 )
1750 result = pytester.runpytest()
1751 assert result.ret == 0
1752
1753 def test_assertion_walrus_operator_in_operand_json_dumps(
1754 self, pytester: Pytester
1755 ) -> None:
1756 pytester.makepyfile(
1757 """
1758 import json
1759
1760 def test_json_encoder():
1761 assert (obj := "foo") in json.dumps(obj)
1762 """
1763 )
1764 result = pytester.runpytest()
1765 assert result.ret == 0
1766
1767 def test_assertion_walrus_operator_equals_operand_function(
1768 self, pytester: Pytester
1769 ) -> None:
1770 pytester.makepyfile(
1771 """
1772 def f(a):
1773 return a
1774
1775 def test_call_other_function_arg():
1776 assert (obj := "foo") == f(obj)
1777 """
1778 )
1779 result = pytester.runpytest()
1780 assert result.ret == 0
1781
1782 def test_assertion_walrus_operator_equals_operand_function_keyword_arg(
1783 self, pytester: Pytester
1784 ) -> None:
1785 pytester.makepyfile(
1786 """
1787 def f(a='test'):
1788 return a
1789
1790 def test_call_other_function_k_arg():
1791 assert (obj := "foo") == f(a=obj)
1792 """
1793 )
1794 result = pytester.runpytest()
1795 assert result.ret == 0
1796
1797 def test_assertion_walrus_operator_equals_operand_function_arg_as_function(
1798 self, pytester: Pytester
1799 ) -> None:
1800 pytester.makepyfile(
1801 """
1802 def f(a='test'):
1803 return a
1804
1805 def test_function_of_function():
1806 assert (obj := "foo") == f(f(obj))
1807 """
1808 )
1809 result = pytester.runpytest()
1810 assert result.ret == 0
1811
1812 def test_assertion_walrus_operator_gt_operand_function(
1813 self, pytester: Pytester
1814 ) -> None:
1815 pytester.makepyfile(
1816 """
1817 def add_one(a):
1818 return a + 1
1819
1820 def test_gt():
1821 assert (obj := 4) > add_one(obj)
1822 """
1823 )
1824 result = pytester.runpytest()
1825 assert result.ret == 1
1826 result.stdout.fnmatch_lines(["*assert 4 > 5", "*where 5 = add_one(4)"])
1827
1828
1829 class TestIssue11239:
1830 def test_assertion_walrus_different_test_cases(self, pytester: Pytester) -> None:
1831 """Regression for (#11239)
1832
1833 Walrus operator rewriting would leak to separate test cases if they used the same variables.
1834 """
1835 pytester.makepyfile(
1836 """
1837 def test_1():
1838 state = {"x": 2}.get("x")
1839 assert state is not None
1840
1841 def test_2():
1842 db = {"x": 2}
1843 assert (state := db.get("x")) is not None
1844 """
1845 )
1846 result = pytester.runpytest()
1847 assert result.ret == 0
1848
1849
1850 @pytest.mark.skipif(
1851 sys.maxsize <= (2**31 - 1), reason="Causes OverflowError on 32bit systems"
1852 )
1853 @pytest.mark.parametrize("offset", [-1, +1])
1854 def test_source_mtime_long_long(pytester: Pytester, offset) -> None:
1855 """Support modification dates after 2038 in rewritten files (#4903).
1856
1857 pytest would crash with:
1858
1859 fp.write(struct.pack("<ll", mtime, size))
1860 E struct.error: argument out of range
1861 """
1862 p = pytester.makepyfile(
1863 """
1864 def test(): pass
1865 """
1866 )
1867 # use unsigned long timestamp which overflows signed long,
1868 # which was the cause of the bug
1869 # +1 offset also tests masking of 0xFFFFFFFF
1870 timestamp = 2**32 + offset
1871 os.utime(str(p), (timestamp, timestamp))
1872 result = pytester.runpytest()
1873 assert result.ret == 0
1874
1875
1876 def test_rewrite_infinite_recursion(
1877 pytester: Pytester, pytestconfig, monkeypatch
1878 ) -> None:
1879 """Fix infinite recursion when writing pyc files: if an import happens to be triggered when writing the pyc
1880 file, this would cause another call to the hook, which would trigger another pyc writing, which could
1881 trigger another import, and so on. (#3506)"""
1882 from _pytest.assertion import rewrite as rewritemod
1883
1884 pytester.syspathinsert()
1885 pytester.makepyfile(test_foo="def test_foo(): pass")
1886 pytester.makepyfile(test_bar="def test_bar(): pass")
1887
1888 original_write_pyc = rewritemod._write_pyc
1889
1890 write_pyc_called = []
1891
1892 def spy_write_pyc(*args, **kwargs):
1893 # make a note that we have called _write_pyc
1894 write_pyc_called.append(True)
1895 # try to import a module at this point: we should not try to rewrite this module
1896 assert hook.find_spec("test_bar") is None
1897 return original_write_pyc(*args, **kwargs)
1898
1899 monkeypatch.setattr(rewritemod, "_write_pyc", spy_write_pyc)
1900 monkeypatch.setattr(sys, "dont_write_bytecode", False)
1901
1902 hook = AssertionRewritingHook(pytestconfig)
1903 spec = hook.find_spec("test_foo")
1904 assert spec is not None
1905 module = importlib.util.module_from_spec(spec)
1906 hook.exec_module(module)
1907 assert len(write_pyc_called) == 1
1908
1909
1910 class TestEarlyRewriteBailout:
1911 @pytest.fixture
1912 def hook(
1913 self, pytestconfig, monkeypatch, pytester: Pytester
1914 ) -> Generator[AssertionRewritingHook]:
1915 """Returns a patched AssertionRewritingHook instance so we can configure its initial paths and track
1916 if PathFinder.find_spec has been called.
1917 """
1918 import importlib.machinery
1919
1920 self.find_spec_calls: list[str] = []
1921 self.initial_paths: set[Path] = set()
1922
1923 class StubSession:
1924 _initialpaths = self.initial_paths
1925
1926 def isinitpath(self, p):
1927 return p in self._initialpaths
1928
1929 def spy_find_spec(name, path):
1930 self.find_spec_calls.append(name)
1931 return importlib.machinery.PathFinder.find_spec(name, path)
1932
1933 hook = AssertionRewritingHook(pytestconfig)
1934 # use default patterns, otherwise we inherit pytest's testing config
1935 with mock.patch.object(hook, "fnpats", ["test_*.py", "*_test.py"]):
1936 monkeypatch.setattr(hook, "_find_spec", spy_find_spec)
1937 hook.set_session(StubSession()) # type: ignore[arg-type]
1938 pytester.syspathinsert()
1939 yield hook
1940
1941 def test_basic(self, pytester: Pytester, hook: AssertionRewritingHook) -> None:
1942 """
1943 Ensure we avoid calling PathFinder.find_spec when we know for sure a certain
1944 module will not be rewritten to optimize assertion rewriting (#3918).
1945 """
1946 pytester.makeconftest(
1947 """
1948 import pytest
1949 @pytest.fixture
1950 def fix(): return 1
1951 """
1952 )
1953 pytester.makepyfile(test_foo="def test_foo(): pass")
1954 pytester.makepyfile(bar="def bar(): pass")
1955 foobar_path = pytester.makepyfile(foobar="def foobar(): pass")
1956 self.initial_paths.add(foobar_path)
1957
1958 # conftest files should always be rewritten
1959 assert hook.find_spec("conftest") is not None
1960 assert self.find_spec_calls == ["conftest"]
1961
1962 # files matching "python_files" mask should always be rewritten
1963 assert hook.find_spec("test_foo") is not None
1964 assert self.find_spec_calls == ["conftest", "test_foo"]
1965
1966 # file does not match "python_files": early bailout
1967 assert hook.find_spec("bar") is None
1968 assert self.find_spec_calls == ["conftest", "test_foo"]
1969
1970 # file is an initial path (passed on the command-line): should be rewritten
1971 assert hook.find_spec("foobar") is not None
1972 assert self.find_spec_calls == ["conftest", "test_foo", "foobar"]
1973
1974 def test_pattern_contains_subdirectories(
1975 self, pytester: Pytester, hook: AssertionRewritingHook
1976 ) -> None:
1977 """If one of the python_files patterns contain subdirectories ("tests/**.py") we can't bailout early
1978 because we need to match with the full path, which can only be found by calling PathFinder.find_spec
1979 """
1980 pytester.makepyfile(
1981 **{
1982 "tests/file.py": """\
1983 def test_simple_failure():
1984 assert 1 + 1 == 3
1985 """
1986 }
1987 )
1988 pytester.syspathinsert("tests")
1989 with mock.patch.object(hook, "fnpats", ["tests/**.py"]):
1990 assert hook.find_spec("file") is not None
1991 assert self.find_spec_calls == ["file"]
1992
1993 @pytest.mark.skipif(
1994 sys.platform.startswith("win32"), reason="cannot remove cwd on Windows"
1995 )
1996 @pytest.mark.skipif(
1997 sys.platform.startswith("sunos5"), reason="cannot remove cwd on Solaris"
1998 )
1999 def test_cwd_changed(self, pytester: Pytester, monkeypatch) -> None:
2000 # Setup conditions for py's fspath trying to import pathlib on py34
2001 # always (previously triggered via xdist only).
2002 # Ref: https://github.com/pytest-dev/py/pull/207
2003 monkeypatch.syspath_prepend("")
2004 monkeypatch.delitem(sys.modules, "pathlib", raising=False)
2005
2006 pytester.makepyfile(
2007 **{
2008 "test_setup_nonexisting_cwd.py": """\
2009 import os
2010 import tempfile
2011
2012 with tempfile.TemporaryDirectory() as newpath:
2013 os.chdir(newpath)
2014 """,
2015 "test_test.py": """\
2016 def test():
2017 pass
2018 """,
2019 }
2020 )
2021 result = pytester.runpytest()
2022 result.stdout.fnmatch_lines(["* 1 passed in *"])
2023
2024
2025 class TestAssertionPass:
2026 def test_option_default(self, pytester: Pytester) -> None:
2027 config = pytester.parseconfig()
2028 assert config.getini("enable_assertion_pass_hook") is False
2029
2030 @pytest.fixture
2031 def flag_on(self, pytester: Pytester):
2032 pytester.makeini("[pytest]\nenable_assertion_pass_hook = True\n")
2033
2034 @pytest.fixture
2035 def hook_on(self, pytester: Pytester):
2036 pytester.makeconftest(
2037 """\
2038 def pytest_assertion_pass(item, lineno, orig, expl):
2039 raise Exception("Assertion Passed: {} {} at line {}".format(orig, expl, lineno))
2040 """
2041 )
2042
2043 def test_hook_call(self, pytester: Pytester, flag_on, hook_on) -> None:
2044 pytester.makepyfile(
2045 """\
2046 def test_simple():
2047 a=1
2048 b=2
2049 c=3
2050 d=0
2051
2052 assert a+b == c+d
2053
2054 # cover failing assertions with a message
2055 def test_fails():
2056 assert False, "assert with message"
2057 """
2058 )
2059 result = pytester.runpytest()
2060 result.stdout.fnmatch_lines(
2061 "*Assertion Passed: a+b == c+d (1 + 2) == (3 + 0) at line 7*"
2062 )
2063
2064 def test_hook_call_with_parens(self, pytester: Pytester, flag_on, hook_on) -> None:
2065 pytester.makepyfile(
2066 """\
2067 def f(): return 1
2068 def test():
2069 assert f()
2070 """
2071 )
2072 result = pytester.runpytest()
2073 result.stdout.fnmatch_lines("*Assertion Passed: f() 1")
2074
2075 def test_hook_not_called_without_hookimpl(
2076 self, pytester: Pytester, monkeypatch, flag_on
2077 ) -> None:
2078 """Assertion pass should not be called (and hence formatting should
2079 not occur) if there is no hook declared for pytest_assertion_pass"""
2080
2081 def raise_on_assertionpass(*_, **__):
2082 raise Exception("Assertion passed called when it shouldn't!")
2083
2084 monkeypatch.setattr(
2085 _pytest.assertion.rewrite, "_call_assertion_pass", raise_on_assertionpass
2086 )
2087
2088 pytester.makepyfile(
2089 """\
2090 def test_simple():
2091 a=1
2092 b=2
2093 c=3
2094 d=0
2095
2096 assert a+b == c+d
2097 """
2098 )
2099 result = pytester.runpytest()
2100 result.assert_outcomes(passed=1)
2101
2102 def test_hook_not_called_without_cmd_option(
2103 self, pytester: Pytester, monkeypatch
2104 ) -> None:
2105 """Assertion pass should not be called (and hence formatting should
2106 not occur) if there is no hook declared for pytest_assertion_pass"""
2107
2108 def raise_on_assertionpass(*_, **__):
2109 raise Exception("Assertion passed called when it shouldn't!")
2110
2111 monkeypatch.setattr(
2112 _pytest.assertion.rewrite, "_call_assertion_pass", raise_on_assertionpass
2113 )
2114
2115 pytester.makeconftest(
2116 """\
2117 def pytest_assertion_pass(item, lineno, orig, expl):
2118 raise Exception("Assertion Passed: {} {} at line {}".format(orig, expl, lineno))
2119 """
2120 )
2121
2122 pytester.makepyfile(
2123 """\
2124 def test_simple():
2125 a=1
2126 b=2
2127 c=3
2128 d=0
2129
2130 assert a+b == c+d
2131 """
2132 )
2133 result = pytester.runpytest()
2134 result.assert_outcomes(passed=1)
2135
2136
2137 # fmt: off
2138 @pytest.mark.parametrize(
2139 ("src", "expected"),
2140 (
2141 pytest.param(b"", {}, id="trivial"),
2142 pytest.param(
2143 b"def x(): assert 1\n",
2144 {1: "1"},
2145 id="assert statement not on own line",
2146 ),
2147 pytest.param(
2148 b"def x():\n"
2149 b" assert 1\n"
2150 b" assert 1+2\n",
2151 {2: "1", 3: "1+2"},
2152 id="multiple assertions",
2153 ),
2154 pytest.param(
2155 # changes in encoding cause the byte offsets to be different
2156 "# -*- coding: latin1\n"
2157 "def ÀÀÀÀÀ(): assert 1\n".encode("latin1"),
2158 {2: "1"},
2159 id="latin1 encoded on first line\n",
2160 ),
2161 pytest.param(
2162 # using the default utf-8 encoding
2163 "def ÀÀÀÀÀ(): assert 1\n".encode(),
2164 {1: "1"},
2165 id="utf-8 encoded on first line",
2166 ),
2167 pytest.param(
2168 b"def x():\n"
2169 b" assert (\n"
2170 b" 1 + 2 # comment\n"
2171 b" )\n",
2172 {2: "(\n 1 + 2 # comment\n )"},
2173 id="multi-line assertion",
2174 ),
2175 pytest.param(
2176 b"def x():\n"
2177 b" assert y == [\n"
2178 b" 1, 2, 3\n"
2179 b" ]\n",
2180 {2: "y == [\n 1, 2, 3\n ]"},
2181 id="multi line assert with list continuation",
2182 ),
2183 pytest.param(
2184 b"def x():\n"
2185 b" assert 1 + \\\n"
2186 b" 2\n",
2187 {2: "1 + \\\n 2"},
2188 id="backslash continuation",
2189 ),
2190 pytest.param(
2191 b"def x():\n"
2192 b" assert x, y\n",
2193 {2: "x"},
2194 id="assertion with message",
2195 ),
2196 pytest.param(
2197 b"def x():\n"
2198 b" assert (\n"
2199 b" f(1, 2, 3)\n"
2200 b" ), 'f did not work!'\n",
2201 {2: "(\n f(1, 2, 3)\n )"},
2202 id="assertion with message, test spanning multiple lines",
2203 ),
2204 pytest.param(
2205 b"def x():\n"
2206 b" assert \\\n"
2207 b" x\\\n"
2208 b" , 'failure message'\n",
2209 {2: "x"},
2210 id="escaped newlines plus message",
2211 ),
2212 pytest.param(
2213 b"def x(): assert 5",
2214 {1: "5"},
2215 id="no newline at end of file",
2216 ),
2217 ),
2218 )
2219 def test_get_assertion_exprs(src, expected) -> None:
2220 assert _get_assertion_exprs(src) == expected
2221 # fmt: on
2222
2223
2224 def test_try_makedirs(monkeypatch, tmp_path: Path) -> None:
2225 from _pytest.assertion.rewrite import try_makedirs
2226
2227 p = tmp_path / "foo"
2228
2229 # create
2230 assert try_makedirs(p)
2231 assert p.is_dir()
2232
2233 # already exist
2234 assert try_makedirs(p)
2235
2236 # monkeypatch to simulate all error situations
2237 def fake_mkdir(p, exist_ok=False, *, exc):
2238 assert isinstance(p, Path)
2239 raise exc
2240
2241 monkeypatch.setattr(os, "makedirs", partial(fake_mkdir, exc=FileNotFoundError()))
2242 assert not try_makedirs(p)
2243
2244 monkeypatch.setattr(os, "makedirs", partial(fake_mkdir, exc=NotADirectoryError()))
2245 assert not try_makedirs(p)
2246
2247 monkeypatch.setattr(os, "makedirs", partial(fake_mkdir, exc=PermissionError()))
2248 assert not try_makedirs(p)
2249
2250 err = OSError()
2251 err.errno = errno.EROFS
2252 monkeypatch.setattr(os, "makedirs", partial(fake_mkdir, exc=err))
2253 assert not try_makedirs(p)
2254
2255 err = OSError()
2256 err.errno = errno.ENOSYS
2257 monkeypatch.setattr(os, "makedirs", partial(fake_mkdir, exc=err))
2258 assert not try_makedirs(p)
2259
2260 # unhandled OSError should raise
2261 err = OSError()
2262 err.errno = errno.ECHILD
2263 monkeypatch.setattr(os, "makedirs", partial(fake_mkdir, exc=err))
2264 with pytest.raises(OSError) as exc_info:
2265 try_makedirs(p)
2266 assert exc_info.value.errno == errno.ECHILD
2267
2268
2269 class TestPyCacheDir:
2270 @pytest.mark.parametrize(
2271 "prefix, source, expected",
2272 [
2273 ("c:/tmp/pycs", "d:/projects/src/foo.py", "c:/tmp/pycs/projects/src"),
2274 (None, "d:/projects/src/foo.py", "d:/projects/src/__pycache__"),
2275 ("/tmp/pycs", "/home/projects/src/foo.py", "/tmp/pycs/home/projects/src"),
2276 (None, "/home/projects/src/foo.py", "/home/projects/src/__pycache__"),
2277 ],
2278 )
2279 def test_get_cache_dir(self, monkeypatch, prefix, source, expected) -> None:
2280 monkeypatch.delenv("PYTHONPYCACHEPREFIX", raising=False)
2281 monkeypatch.setattr(sys, "pycache_prefix", prefix, raising=False)
2282
2283 assert get_cache_dir(Path(source)) == Path(expected)
2284
2285 def test_sys_pycache_prefix_integration(
2286 self, tmp_path, monkeypatch, pytester: Pytester
2287 ) -> None:
2288 """Integration test for sys.pycache_prefix (#4730)."""
2289 pycache_prefix = tmp_path / "my/pycs"
2290 monkeypatch.setattr(sys, "pycache_prefix", str(pycache_prefix))
2291 monkeypatch.setattr(sys, "dont_write_bytecode", False)
2292
2293 pytester.makepyfile(
2294 **{
2295 "src/test_foo.py": """
2296 import bar
2297 def test_foo():
2298 pass
2299 """,
2300 "src/bar/__init__.py": "",
2301 }
2302 )
2303 result = pytester.runpytest()
2304 assert result.ret == 0
2305
2306 test_foo = pytester.path.joinpath("src/test_foo.py")
2307 bar_init = pytester.path.joinpath("src/bar/__init__.py")
2308 assert test_foo.is_file()
2309 assert bar_init.is_file()
2310
2311 # test file: rewritten, custom pytest cache tag
2312 test_foo_pyc = get_cache_dir(test_foo) / ("test_foo" + PYC_TAIL)
2313 assert test_foo_pyc.is_file()
2314
2315 # normal file: not touched by pytest, normal cache tag
2316 bar_init_pyc = (
2317 get_cache_dir(bar_init) / f"__init__.{sys.implementation.cache_tag}.pyc"
2318 )
2319 assert bar_init_pyc.is_file()
2320
2321
2322 class TestReprSizeVerbosity:
2323 """
2324 Check that verbosity also controls the string length threshold to shorten it using
2325 ellipsis.
2326 """
2327
2328 @pytest.mark.parametrize(
2329 "verbose, expected_size",
2330 [
2331 (0, DEFAULT_REPR_MAX_SIZE),
2332 (1, DEFAULT_REPR_MAX_SIZE * 10),
2333 (2, None),
2334 (3, None),
2335 ],
2336 )
2337 def test_get_maxsize_for_saferepr(self, verbose: int, expected_size) -> None:
2338 class FakeConfig:
2339 def get_verbosity(self, verbosity_type: str | None = None) -> int:
2340 return verbose
2341
2342 config = FakeConfig()
2343 assert _get_maxsize_for_saferepr(cast(Config, config)) == expected_size
2344
2345 def test_get_maxsize_for_saferepr_no_config(self) -> None:
2346 assert _get_maxsize_for_saferepr(None) == DEFAULT_REPR_MAX_SIZE
2347
2348 def create_test_file(self, pytester: Pytester, size: int) -> None:
2349 pytester.makepyfile(
2350 f"""
2351 def test_very_long_string():
2352 text = "x" * {size}
2353 assert "hello world" in text
2354 """
2355 )
2356
2357 def test_default_verbosity(self, pytester: Pytester) -> None:
2358 self.create_test_file(pytester, DEFAULT_REPR_MAX_SIZE)
2359 result = pytester.runpytest()
2360 result.stdout.fnmatch_lines(["*xxx...xxx*"])
2361
2362 def test_increased_verbosity(self, pytester: Pytester) -> None:
2363 self.create_test_file(pytester, DEFAULT_REPR_MAX_SIZE)
2364 result = pytester.runpytest("-v")
2365 result.stdout.no_fnmatch_line("*xxx...xxx*")
2366
2367 def test_max_increased_verbosity(self, pytester: Pytester) -> None:
2368 self.create_test_file(pytester, DEFAULT_REPR_MAX_SIZE * 10)
2369 result = pytester.runpytest("-vv")
2370 result.stdout.no_fnmatch_line("*xxx...xxx*")
2371
2372
2373 class TestIssue11140:
2374 def test_constant_not_picked_as_module_docstring(self, pytester: Pytester) -> None:
2375 pytester.makepyfile(
2376 """\
2377 0
2378
2379 def test_foo():
2380 pass
2381 """
2382 )
2383 result = pytester.runpytest()
2384 assert result.ret == 0
2385
2386
2387 class TestSafereprUnbounded:
2388 class Help:
2389 def bound_method(self): # pragma: no cover
2390 pass
2391
2392 def test_saferepr_bound_method(self):
2393 """saferepr() of a bound method should show only the method name"""
2394 assert _saferepr(self.Help().bound_method) == "bound_method"
2395
2396 def test_saferepr_unbounded(self):
2397 """saferepr() of an unbound method should still show the full information"""
2398 obj = self.Help()
2399 # using id() to fetch memory address fails on different platforms
2400 pattern = re.compile(
2401 rf"<{Path(__file__).stem}.{self.__class__.__name__}.Help object at 0x[0-9a-fA-F]*>",
2402 )
2403 assert pattern.match(_saferepr(obj))
2404 assert (
2405 _saferepr(self.Help)
2406 == f"<class '{Path(__file__).stem}.{self.__class__.__name__}.Help'>"
2407 )
2408
2409
2410 def test_assertion_failure_when_terminalreporter_is_disabled(
2411 pytester: Pytester,
2412 ) -> None:
2413 """Assertion rewriting doesn't crash when the terminalreporter plugin is
2414 disabled (#14378)."""
2415 pytester.makepyfile(
2416 """
2417 import pytest
2418
2419 def test():
2420 with pytest.raises(AssertionError) as excinfo:
2421 assert 0 == 1
2422 assert excinfo.value.args[0] == 'assert 0 == 1'
2423 """
2424 )
2425 reprec = pytester.inline_run("-p", "no:terminalreporter")
2426 reprec.assertoutcome(passed=1)