summaryrefslogtreecommitdiff
path: root/testing/test_assertrewrite.py
blob: bedf6e27606566be5842f332e7098a35bc48f000 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
# mypy: allow-untyped-defs
import ast
import errno
from functools import partial
import glob
import importlib
import marshal
import os
from pathlib import Path
import py_compile
import stat
import sys
import textwrap
from typing import cast
from typing import Dict
from typing import Generator
from typing import List
from typing import Mapping
from typing import Optional
from typing import Set
from unittest import mock
import zipfile

import _pytest._code
from _pytest._io.saferepr import DEFAULT_REPR_MAX_SIZE
from _pytest.assertion import util
from _pytest.assertion.rewrite import _get_assertion_exprs
from _pytest.assertion.rewrite import _get_maxsize_for_saferepr
from _pytest.assertion.rewrite import AssertionRewritingHook
from _pytest.assertion.rewrite import get_cache_dir
from _pytest.assertion.rewrite import PYC_TAIL
from _pytest.assertion.rewrite import PYTEST_TAG
from _pytest.assertion.rewrite import rewrite_asserts
from _pytest.config import Config
from _pytest.config import ExitCode
from _pytest.pathlib import make_numbered_dir
from _pytest.pytester import Pytester
import pytest


def rewrite(src: str) -> ast.Module:
    tree = ast.parse(src)
    rewrite_asserts(tree, src.encode())
    return tree


def getmsg(
    f, extra_ns: Optional[Mapping[str, object]] = None, *, must_pass: bool = False
) -> Optional[str]:
    """Rewrite the assertions in f, run it, and get the failure message."""
    src = "\n".join(_pytest._code.Code.from_function(f).source().lines)
    mod = rewrite(src)
    code = compile(mod, "<test>", "exec")
    ns: Dict[str, object] = {}
    if extra_ns is not None:
        ns.update(extra_ns)
    exec(code, ns)
    func = ns[f.__name__]
    try:
        func()  # type: ignore[operator]
    except AssertionError:
        if must_pass:
            pytest.fail("shouldn't have raised")
        s = str(sys.exc_info()[1])
        if not s.startswith("assert"):
            return "AssertionError: " + s
        return s
    else:
        if not must_pass:
            pytest.fail("function didn't raise at all")
        return None


class TestAssertionRewrite:
    def test_place_initial_imports(self) -> None:
        s = """'Doc string'\nother = stuff"""
        m = rewrite(s)
        assert isinstance(m.body[0], ast.Expr)
        for imp in m.body[1:3]:
            assert isinstance(imp, ast.Import)
            assert imp.lineno == 2
            assert imp.col_offset == 0
        assert isinstance(m.body[3], ast.Assign)
        s = """from __future__ import division\nother_stuff"""
        m = rewrite(s)
        assert isinstance(m.body[0], ast.ImportFrom)
        for imp in m.body[1:3]:
            assert isinstance(imp, ast.Import)
            assert imp.lineno == 2
            assert imp.col_offset == 0
        assert isinstance(m.body[3], ast.Expr)
        s = """'doc string'\nfrom __future__ import division"""
        m = rewrite(s)
        assert isinstance(m.body[0], ast.Expr)
        assert isinstance(m.body[1], ast.ImportFrom)
        for imp in m.body[2:4]:
            assert isinstance(imp, ast.Import)
            assert imp.lineno == 2
            assert imp.col_offset == 0
        s = """'doc string'\nfrom __future__ import division\nother"""
        m = rewrite(s)
        assert isinstance(m.body[0], ast.Expr)
        assert isinstance(m.body[1], ast.ImportFrom)
        for imp in m.body[2:4]:
            assert isinstance(imp, ast.Import)
            assert imp.lineno == 3
            assert imp.col_offset == 0
        assert isinstance(m.body[4], ast.Expr)
        s = """from . import relative\nother_stuff"""
        m = rewrite(s)
        for imp in m.body[:2]:
            assert isinstance(imp, ast.Import)
            assert imp.lineno == 1
            assert imp.col_offset == 0
        assert isinstance(m.body[3], ast.Expr)

    def test_location_is_set(self) -> None:
        s = textwrap.dedent(
            """

        assert False, (

            "Ouch"
          )

        """
        )
        m = rewrite(s)
        for node in m.body:
            if isinstance(node, ast.Import):
                continue
            for n in [node, *ast.iter_child_nodes(node)]:
                assert n.lineno == 3
                assert n.col_offset == 0
                assert n.end_lineno == 6
                assert n.end_col_offset == 3

    def test_dont_rewrite(self) -> None:
        s = """'PYTEST_DONT_REWRITE'\nassert 14"""
        m = rewrite(s)
        assert len(m.body) == 2
        assert isinstance(m.body[1], ast.Assert)
        assert m.body[1].msg is None

    def test_dont_rewrite_plugin(self, pytester: Pytester) -> None:
        contents = {
            "conftest.py": "pytest_plugins = 'plugin'; import plugin",
            "plugin.py": "'PYTEST_DONT_REWRITE'",
            "test_foo.py": "def test_foo(): pass",
        }
        pytester.makepyfile(**contents)
        result = pytester.runpytest_subprocess()
        assert "warning" not in "".join(result.outlines)

    def test_rewrites_plugin_as_a_package(self, pytester: Pytester) -> None:
        pkgdir = pytester.mkpydir("plugin")
        pkgdir.joinpath("__init__.py").write_text(
            "import pytest\n"
            "@pytest.fixture\n"
            "def special_asserter():\n"
            "    def special_assert(x, y):\n"
            "        assert x == y\n"
            "    return special_assert\n",
            encoding="utf-8",
        )
        pytester.makeconftest('pytest_plugins = ["plugin"]')
        pytester.makepyfile("def test(special_asserter): special_asserter(1, 2)\n")
        result = pytester.runpytest()
        result.stdout.fnmatch_lines(["*assert 1 == 2*"])

    def test_honors_pep_235(self, pytester: Pytester, monkeypatch) -> None:
        # note: couldn't make it fail on macos with a single `sys.path` entry
        # note: these modules are named `test_*` to trigger rewriting
        pytester.makepyfile(test_y="x = 1")
        xdir = pytester.mkdir("x")
        pytester.mkpydir(str(xdir.joinpath("test_Y")))
        xdir.joinpath("test_Y").joinpath("__init__.py").write_text(
            "x = 2", encoding="utf-8"
        )
        pytester.makepyfile(
            "import test_y\n"
            "import test_Y\n"
            "def test():\n"
            "    assert test_y.x == 1\n"
            "    assert test_Y.x == 2\n"
        )
        monkeypatch.syspath_prepend(str(xdir))
        pytester.runpytest().assert_outcomes(passed=1)

    def test_name(self, request) -> None:
        def f1() -> None:
            assert False

        assert getmsg(f1) == "assert False"

        def f2() -> None:
            f = False
            assert f

        assert getmsg(f2) == "assert False"

        def f3() -> None:
            assert a_global  # type: ignore[name-defined] # noqa: F821

        assert getmsg(f3, {"a_global": False}) == "assert False"

        def f4() -> None:
            assert sys == 42  # type: ignore[comparison-overlap]

        msg = getmsg(f4, {"sys": sys})
        assert msg == "assert sys == 42"

        def f5() -> None:
            assert cls == 42  # type: ignore[name-defined]  # noqa: F821

        class X:
            pass

        msg = getmsg(f5, {"cls": X})
        assert msg is not None
        lines = msg.splitlines()
        assert lines == ["assert cls == 42"]

    def test_assertrepr_compare_same_width(self, request) -> None:
        """Should use same width/truncation with same initial width."""

        def f() -> None:
            assert "1234567890" * 5 + "A" == "1234567890" * 5 + "B"

        msg = getmsg(f)
        assert msg is not None
        line = msg.splitlines()[0]
        if request.config.getoption("verbose") > 1:
            assert line == (
                "assert '12345678901234567890123456789012345678901234567890A' "
                "== '12345678901234567890123456789012345678901234567890B'"
            )
        else:
            assert line == (
                "assert '123456789012...901234567890A' "
                "== '123456789012...901234567890B'"
            )

    def test_dont_rewrite_if_hasattr_fails(self, request) -> None:
        class Y:
            """A class whose getattr fails, but not with `AttributeError`."""

            def __getattr__(self, attribute_name):
                raise KeyError()

            def __repr__(self) -> str:
                return "Y"

            def __init__(self) -> None:
                self.foo = 3

        def f() -> None:
            assert cls().foo == 2  # type: ignore[name-defined] # noqa: F821

        # XXX: looks like the "where" should also be there in verbose mode?!
        msg = getmsg(f, {"cls": Y})
        assert msg is not None
        lines = msg.splitlines()
        assert lines == [
            "assert 3 == 2",
            " +  where 3 = Y.foo",
            " +    where Y = cls()",
        ]

    def test_assert_already_has_message(self) -> None:
        def f():
            assert False, "something bad!"

        assert getmsg(f) == "AssertionError: something bad!\nassert False"

    def test_assertion_message(self, pytester: Pytester) -> None:
        pytester.makepyfile(
            """
            def test_foo():
                assert 1 == 2, "The failure message"
        """
        )
        result = pytester.runpytest()
        assert result.ret == 1
        result.stdout.fnmatch_lines(
            ["*AssertionError*The failure message*", "*assert 1 == 2*"]
        )

    def test_assertion_message_multiline(self, pytester: Pytester) -> None:
        pytester.makepyfile(
            """
            def test_foo():
                assert 1 == 2, "A multiline\\nfailure message"
        """
        )
        result = pytester.runpytest()
        assert result.ret == 1
        result.stdout.fnmatch_lines(
            ["*AssertionError*A multiline*", "*failure message*", "*assert 1 == 2*"]
        )

    def test_assertion_message_tuple(self, pytester: Pytester) -> None:
        pytester.makepyfile(
            """
            def test_foo():
                assert 1 == 2, (1, 2)
        """
        )
        result = pytester.runpytest()
        assert result.ret == 1
        result.stdout.fnmatch_lines([f"*AssertionError*{(1, 2)!r}*", "*assert 1 == 2*"])

    def test_assertion_message_expr(self, pytester: Pytester) -> None:
        pytester.makepyfile(
            """
            def test_foo():
                assert 1 == 2, 1 + 2
        """
        )
        result = pytester.runpytest()
        assert result.ret == 1
        result.stdout.fnmatch_lines(["*AssertionError*3*", "*assert 1 == 2*"])

    def test_assertion_message_escape(self, pytester: Pytester) -> None:
        pytester.makepyfile(
            """
            def test_foo():
                assert 1 == 2, 'To be escaped: %'
        """
        )
        result = pytester.runpytest()
        assert result.ret == 1
        result.stdout.fnmatch_lines(
            ["*AssertionError: To be escaped: %", "*assert 1 == 2"]
        )

    def test_assertion_messages_bytes(self, pytester: Pytester) -> None:
        pytester.makepyfile("def test_bytes_assertion():\n    assert False, b'ohai!'\n")
        result = pytester.runpytest()
        assert result.ret == 1
        result.stdout.fnmatch_lines(["*AssertionError: b'ohai!'", "*assert False"])

    def test_boolop(self) -> None:
        def f1() -> None:
            f = g = False
            assert f and g

        assert getmsg(f1) == "assert (False)"

        def f2() -> None:
            f = True
            g = False
            assert f and g

        assert getmsg(f2) == "assert (True and False)"

        def f3() -> None:
            f = False
            g = True
            assert f and g

        assert getmsg(f3) == "assert (False)"

        def f4() -> None:
            f = g = False
            assert f or g

        assert getmsg(f4) == "assert (False or False)"

        def f5() -> None:
            f = g = False
            assert not f and not g

        getmsg(f5, must_pass=True)

        def x() -> bool:
            return False

        def f6() -> None:
            assert x() and x()

        assert (
            getmsg(f6, {"x": x})
            == """assert (False)
 +  where False = x()"""
        )

        def f7() -> None:
            assert False or x()

        assert (
            getmsg(f7, {"x": x})
            == """assert (False or False)
 +  where False = x()"""
        )

        def f8() -> None:
            assert 1 in {} and 2 in {}

        assert getmsg(f8) == "assert (1 in {})"

        def f9() -> None:
            x = 1
            y = 2
            assert x in {1: None} and y in {}

        assert getmsg(f9) == "assert (1 in {1: None} and 2 in {})"

        def f10() -> None:
            f = True
            g = False
            assert f or g

        getmsg(f10, must_pass=True)

        def f11() -> None:
            f = g = h = lambda: True
            assert f() and g() and h()

        getmsg(f11, must_pass=True)

    def test_short_circuit_evaluation(self) -> None:
        def f1() -> None:
            assert True or explode  # type: ignore[name-defined,unreachable] # noqa: F821

        getmsg(f1, must_pass=True)

        def f2() -> None:
            x = 1
            assert x == 1 or x == 2  # noqa: PLR1714

        getmsg(f2, must_pass=True)

    def test_unary_op(self) -> None:
        def f1() -> None:
            x = True
            assert not x

        assert getmsg(f1) == "assert not True"

        def f2() -> None:
            x = 0
            assert ~x + 1

        assert getmsg(f2) == "assert (~0 + 1)"

        def f3() -> None:
            x = 3
            assert -x + x

        assert getmsg(f3) == "assert (-3 + 3)"

        def f4() -> None:
            x = 0
            assert +x + x

        assert getmsg(f4) == "assert (+0 + 0)"

    def test_binary_op(self) -> None:
        def f1() -> None:
            x = 1
            y = -1
            assert x + y

        assert getmsg(f1) == "assert (1 + -1)"

        def f2() -> None:
            assert not 5 % 4

        assert getmsg(f2) == "assert not (5 % 4)"

    def test_boolop_percent(self) -> None:
        def f1() -> None:
            assert 3 % 2 and False

        assert getmsg(f1) == "assert ((3 % 2) and False)"

        def f2() -> None:
            assert False or 4 % 2

        assert getmsg(f2) == "assert (False or (4 % 2))"

    def test_at_operator_issue1290(self, pytester: Pytester) -> None:
        pytester.makepyfile(
            """
            class Matrix(object):
                def __init__(self, num):
                    self.num = num
                def __matmul__(self, other):
                    return self.num * other.num

            def test_multmat_operator():
                assert Matrix(2) @ Matrix(3) == 6"""
        )
        pytester.runpytest().assert_outcomes(passed=1)

    def test_starred_with_side_effect(self, pytester: Pytester) -> None:
        """See #4412"""
        pytester.makepyfile(
            """\
            def test():
                f = lambda x: x
                x = iter([1, 2, 3])
                assert 2 * next(x) == f(*[next(x)])
            """
        )
        pytester.runpytest().assert_outcomes(passed=1)

    def test_call(self) -> None:
        def g(a=42, *args, **kwargs) -> bool:
            return False

        ns = {"g": g}

        def f1() -> None:
            assert g()

        assert (
            getmsg(f1, ns)
            == """assert False
 +  where False = g()"""
        )

        def f2() -> None:
            assert g(1)

        assert (
            getmsg(f2, ns)
            == """assert False
 +  where False = g(1)"""
        )

        def f3() -> None:
            assert g(1, 2)

        assert (
            getmsg(f3, ns)
            == """assert False
 +  where False = g(1, 2)"""
        )

        def f4() -> None:
            assert g(1, g=42)

        assert (
            getmsg(f4, ns)
            == """assert False
 +  where False = g(1, g=42)"""
        )

        def f5() -> None:
            assert g(1, 3, g=23)

        assert (
            getmsg(f5, ns)
            == """assert False
 +  where False = g(1, 3, g=23)"""
        )

        def f6() -> None:
            seq = [1, 2, 3]
            assert g(*seq)

        assert (
            getmsg(f6, ns)
            == """assert False
 +  where False = g(*[1, 2, 3])"""
        )

        def f7() -> None:
            x = "a"
            assert g(**{x: 2})

        assert (
            getmsg(f7, ns)
            == """assert False
 +  where False = g(**{'a': 2})"""
        )

    def test_attribute(self) -> None:
        class X:
            g = 3

        ns = {"x": X}

        def f1() -> None:
            assert not x.g  # type: ignore[name-defined] # noqa: F821

        assert (
            getmsg(f1, ns)
            == """assert not 3
 +  where 3 = x.g"""
        )

        def f2() -> None:
            x.a = False  # type: ignore[name-defined] # noqa: F821
            assert x.a  # type: ignore[name-defined] # noqa: F821

        assert (
            getmsg(f2, ns)
            == """assert False
 +  where False = x.a"""
        )

    def test_comparisons(self) -> None:
        def f1() -> None:
            a, b = range(2)
            assert b < a

        assert getmsg(f1) == """assert 1 < 0"""

        def f2() -> None:
            a, b, c = range(3)
            assert a > b > c

        assert getmsg(f2) == """assert 0 > 1"""

        def f3() -> None:
            a, b, c = range(3)
            assert a < b > c

        assert getmsg(f3) == """assert 1 > 2"""

        def f4() -> None:
            a, b, c = range(3)
            assert a < b <= c

        getmsg(f4, must_pass=True)

        def f5() -> None:
            a, b, c = range(3)
            assert a < b
            assert b < c

        getmsg(f5, must_pass=True)

    def test_len(self, request) -> None:
        def f():
            values = list(range(10))
            assert len(values) == 11

        msg = getmsg(f)
        assert msg == "assert 10 == 11\n +  where 10 = len([0, 1, 2, 3, 4, 5, ...])"

    def test_custom_reprcompare(self, monkeypatch) -> None:
        def my_reprcompare1(op, left, right) -> str:
            return "42"

        monkeypatch.setattr(util, "_reprcompare", my_reprcompare1)

        def f1() -> None:
            assert 42 < 3

        assert getmsg(f1) == "assert 42"

        def my_reprcompare2(op, left, right) -> str:
            return f"{left} {op} {right}"

        monkeypatch.setattr(util, "_reprcompare", my_reprcompare2)

        def f2() -> None:
            assert 1 < 3 < 5 <= 4 < 7

        assert getmsg(f2) == "assert 5 <= 4"

    def test_assert_raising__bool__in_comparison(self) -> None:
        def f() -> None:
            class A:
                def __bool__(self):
                    raise ValueError(42)

                def __lt__(self, other):
                    return A()

                def __repr__(self):
                    return "<MY42 object>"

            def myany(x) -> bool:
                return False

            assert myany(A() < 0)

        msg = getmsg(f)
        assert msg is not None
        assert "<MY42 object> < 0" in msg

    def test_assert_handling_raise_in__iter__(self, pytester: Pytester) -> None:
        pytester.makepyfile(
            """\
            class A:
                def __iter__(self):
                    raise ValueError()

                def __eq__(self, o: object) -> bool:
                    return self is o

                def __repr__(self):
                    return "<A object>"

            assert A() == A()
            """
        )
        result = pytester.runpytest()
        result.stdout.fnmatch_lines(["*E*assert <A object> == <A object>"])

    def test_formatchar(self) -> None:
        def f() -> None:
            assert "%test" == "test"  # type: ignore[comparison-overlap]

        msg = getmsg(f)
        assert msg is not None
        assert msg.startswith("assert '%test' == 'test'")

    def test_custom_repr(self, request) -> None:
        def f() -> None:
            class Foo:
                a = 1

                def __repr__(self):
                    return "\n{ \n~ \n}"

            f = Foo()
            assert 0 == f.a

        msg = getmsg(f)
        assert msg is not None
        lines = util._format_lines([msg])
        assert lines == ["assert 0 == 1\n +  where 1 = \\n{ \\n~ \\n}.a"]

    def test_custom_repr_non_ascii(self) -> None:
        def f() -> None:
            class A:
                name = "ä"

                def __repr__(self):
                    return self.name.encode("UTF-8")  # only legal in python2

            a = A()
            assert not a.name

        msg = getmsg(f)
        assert msg is not None
        assert "UnicodeDecodeError" not in msg
        assert "UnicodeEncodeError" not in msg


class TestRewriteOnImport:
    def test_pycache_is_a_file(self, pytester: Pytester) -> None:
        pytester.path.joinpath("__pycache__").write_text("Hello", encoding="utf-8")
        pytester.makepyfile(
            """
            def test_rewritten():
                assert "@py_builtins" in globals()"""
        )
        assert pytester.runpytest().ret == 0

    def test_pycache_is_readonly(self, pytester: Pytester) -> None:
        cache = pytester.mkdir("__pycache__")
        old_mode = cache.stat().st_mode
        cache.chmod(old_mode ^ stat.S_IWRITE)
        pytester.makepyfile(
            """
            def test_rewritten():
                assert "@py_builtins" in globals()"""
        )
        try:
            assert pytester.runpytest().ret == 0
        finally:
            cache.chmod(old_mode)

    def test_zipfile(self, pytester: Pytester) -> None:
        z = pytester.path.joinpath("myzip.zip")
        z_fn = str(z)
        f = zipfile.ZipFile(z_fn, "w")
        try:
            f.writestr("test_gum/__init__.py", "")
            f.writestr("test_gum/test_lizard.py", "")
        finally:
            f.close()
        z.chmod(256)
        pytester.makepyfile(
            f"""
            import sys
            sys.path.append({z_fn!r})
            import test_gum.test_lizard"""
        )
        assert pytester.runpytest().ret == ExitCode.NO_TESTS_COLLECTED

    @pytest.mark.skipif(
        sys.version_info < (3, 9),
        reason="importlib.resources.files was introduced in 3.9",
    )
    def test_load_resource_via_files_with_rewrite(self, pytester: Pytester) -> None:
        example = pytester.path.joinpath("demo") / "example"
        init = pytester.path.joinpath("demo") / "__init__.py"
        pytester.makepyfile(
            **{
                "demo/__init__.py": """
                from importlib.resources import files

                def load():
                    return files(__name__)
                """,
                "test_load": f"""
                pytest_plugins = ["demo"]

                def test_load():
                    from demo import load
                    found = {{str(i) for i in load().iterdir() if i.name != "__pycache__"}}
                    assert found == {{{str(example)!r}, {str(init)!r}}}
                """,
            }
        )
        example.mkdir()

        assert pytester.runpytest("-vv").ret == ExitCode.OK

    def test_readonly(self, pytester: Pytester) -> None:
        sub = pytester.mkdir("testing")
        sub.joinpath("test_readonly.py").write_bytes(
            b"""
def test_rewritten():
    assert "@py_builtins" in globals()
            """,
        )
        old_mode = sub.stat().st_mode
        sub.chmod(320)
        try:
            assert pytester.runpytest().ret == 0
        finally:
            sub.chmod(old_mode)

    def test_dont_write_bytecode(self, pytester: Pytester, monkeypatch) -> None:
        monkeypatch.delenv("PYTHONPYCACHEPREFIX", raising=False)

        pytester.makepyfile(
            """
            import os
            def test_no_bytecode():
                assert "__pycache__" in __cached__
                assert not os.path.exists(__cached__)
                assert not os.path.exists(os.path.dirname(__cached__))"""
        )
        monkeypatch.setenv("PYTHONDONTWRITEBYTECODE", "1")
        assert pytester.runpytest_subprocess().ret == 0

    def test_orphaned_pyc_file(self, pytester: Pytester, monkeypatch) -> None:
        monkeypatch.delenv("PYTHONPYCACHEPREFIX", raising=False)
        monkeypatch.setattr(sys, "pycache_prefix", None, raising=False)

        pytester.makepyfile(
            """
            import orphan
            def test_it():
                assert orphan.value == 17
            """
        )
        pytester.makepyfile(
            orphan="""
            value = 17
            """
        )
        py_compile.compile("orphan.py")
        os.remove("orphan.py")

        # Python 3 puts the .pyc files in a __pycache__ directory, and will
        # not import from there without source.  It will import a .pyc from
        # the source location though.
        if not os.path.exists("orphan.pyc"):
            pycs = glob.glob("__pycache__/orphan.*.pyc")
            assert len(pycs) == 1
            os.rename(pycs[0], "orphan.pyc")

        assert pytester.runpytest().ret == 0

    def test_cached_pyc_includes_pytest_version(
        self, pytester: Pytester, monkeypatch
    ) -> None:
        """Avoid stale caches (#1671)"""
        monkeypatch.delenv("PYTHONDONTWRITEBYTECODE", raising=False)
        monkeypatch.delenv("PYTHONPYCACHEPREFIX", raising=False)
        pytester.makepyfile(
            test_foo="""
            def test_foo():
                assert True
            """
        )
        result = pytester.runpytest_subprocess()
        assert result.ret == 0
        found_names = glob.glob(f"__pycache__/*-pytest-{pytest.__version__}.pyc")
        assert found_names, "pyc with expected tag not found in names: {}".format(
            glob.glob("__pycache__/*.pyc")
        )

    @pytest.mark.skipif('"__pypy__" in sys.modules')
    def test_pyc_vs_pyo(
        self,
        pytester: Pytester,
        monkeypatch: pytest.MonkeyPatch,
    ) -> None:
        pytester.makepyfile(
            """
            import pytest
            def test_optimized():
                "hello"
                assert test_optimized.__doc__ is None"""
        )
        p = make_numbered_dir(root=Path(pytester.path), prefix="runpytest-")
        tmp = f"--basetemp={p}"
        with monkeypatch.context() as mp:
            mp.setenv("PYTHONOPTIMIZE", "2")
            mp.delenv("PYTHONDONTWRITEBYTECODE", raising=False)
            mp.delenv("PYTHONPYCACHEPREFIX", raising=False)
            assert pytester.runpytest_subprocess(tmp).ret == 0
            tagged = "test_pyc_vs_pyo." + PYTEST_TAG
            assert tagged + ".pyo" in os.listdir("__pycache__")
        monkeypatch.delenv("PYTHONDONTWRITEBYTECODE", raising=False)
        monkeypatch.delenv("PYTHONPYCACHEPREFIX", raising=False)
        assert pytester.runpytest_subprocess(tmp).ret == 1
        assert tagged + ".pyc" in os.listdir("__pycache__")

    def test_package(self, pytester: Pytester) -> None:
        pkg = pytester.path.joinpath("pkg")
        pkg.mkdir()
        pkg.joinpath("__init__.py")
        pkg.joinpath("test_blah.py").write_text(
            """
def test_rewritten():
    assert "@py_builtins" in globals()""",
            encoding="utf-8",
        )
        assert pytester.runpytest().ret == 0

    def test_translate_newlines(self, pytester: Pytester) -> None:
        content = "def test_rewritten():\r\n assert '@py_builtins' in globals()"
        b = content.encode("utf-8")
        pytester.path.joinpath("test_newlines.py").write_bytes(b)
        assert pytester.runpytest().ret == 0

    def test_package_without__init__py(self, pytester: Pytester) -> None:
        pkg = pytester.mkdir("a_package_without_init_py")
        pkg.joinpath("module.py").touch()
        pytester.makepyfile("import a_package_without_init_py.module")
        assert pytester.runpytest().ret == ExitCode.NO_TESTS_COLLECTED

    def test_rewrite_warning(self, pytester: Pytester) -> None:
        pytester.makeconftest(
            """
            import pytest
            pytest.register_assert_rewrite("_pytest")
        """
        )
        # needs to be a subprocess because pytester explicitly disables this warning
        result = pytester.runpytest_subprocess()
        result.stdout.fnmatch_lines(["*Module already imported*: _pytest"])

    def test_rewrite_module_imported_from_conftest(self, pytester: Pytester) -> None:
        pytester.makeconftest(
            """
            import test_rewrite_module_imported
        """
        )
        pytester.makepyfile(
            test_rewrite_module_imported="""
            def test_rewritten():
                assert "@py_builtins" in globals()
        """
        )
        assert pytester.runpytest_subprocess().ret == 0

    def test_remember_rewritten_modules(
        self, pytestconfig, pytester: Pytester, monkeypatch
    ) -> None:
        """`AssertionRewriteHook` should remember rewritten modules so it
        doesn't give false positives (#2005)."""
        monkeypatch.syspath_prepend(pytester.path)
        pytester.makepyfile(test_remember_rewritten_modules="")
        warnings = []
        hook = AssertionRewritingHook(pytestconfig)
        monkeypatch.setattr(
            hook, "_warn_already_imported", lambda code, msg: warnings.append(msg)
        )
        spec = hook.find_spec("test_remember_rewritten_modules")
        assert spec is not None
        module = importlib.util.module_from_spec(spec)
        hook.exec_module(module)
        hook.mark_rewrite("test_remember_rewritten_modules")
        hook.mark_rewrite("test_remember_rewritten_modules")
        assert warnings == []

    def test_rewrite_warning_using_pytest_plugins(self, pytester: Pytester) -> None:
        pytester.makepyfile(
            **{
                "conftest.py": "pytest_plugins = ['core', 'gui', 'sci']",
                "core.py": "",
                "gui.py": "pytest_plugins = ['core', 'sci']",
                "sci.py": "pytest_plugins = ['core']",
                "test_rewrite_warning_pytest_plugins.py": "def test(): pass",
            }
        )
        pytester.chdir()
        result = pytester.runpytest_subprocess()
        result.stdout.fnmatch_lines(["*= 1 passed in *=*"])
        result.stdout.no_fnmatch_line("*pytest-warning summary*")

    def test_rewrite_warning_using_pytest_plugins_env_var(
        self, pytester: Pytester, monkeypatch
    ) -> None:
        monkeypatch.setenv("PYTEST_PLUGINS", "plugin")
        pytester.makepyfile(
            **{
                "plugin.py": "",
                "test_rewrite_warning_using_pytest_plugins_env_var.py": """
                import plugin
                pytest_plugins = ['plugin']
                def test():
                    pass
            """,
            }
        )
        pytester.chdir()
        result = pytester.runpytest_subprocess()
        result.stdout.fnmatch_lines(["*= 1 passed in *=*"])
        result.stdout.no_fnmatch_line("*pytest-warning summary*")


class TestAssertionRewriteHookDetails:
    def test_sys_meta_path_munged(self, pytester: Pytester) -> None:
        pytester.makepyfile(
            """
            def test_meta_path():
                import sys; sys.meta_path = []"""
        )
        assert pytester.runpytest().ret == 0

    def test_write_pyc(self, pytester: Pytester, tmp_path) -> None:
        from _pytest.assertion import AssertionState
        from _pytest.assertion.rewrite import _write_pyc

        config = pytester.parseconfig()
        state = AssertionState(config, "rewrite")
        tmp_path.joinpath("source.py").touch()
        source_path = str(tmp_path)
        pycpath = tmp_path.joinpath("pyc")
        co = compile("1", "f.py", "single")
        assert _write_pyc(state, co, os.stat(source_path), pycpath)

        with mock.patch.object(os, "replace", side_effect=OSError):
            assert not _write_pyc(state, co, os.stat(source_path), pycpath)

    def test_resources_provider_for_loader(self, pytester: Pytester) -> None:
        """
        Attempts to load resources from a package should succeed normally,
        even when the AssertionRewriteHook is used to load the modules.

        See #366 for details.
        """
        pytest.importorskip("pkg_resources")

        pytester.mkpydir("testpkg")
        contents = {
            "testpkg/test_pkg": """
                import pkg_resources

                import pytest
                from _pytest.assertion.rewrite import AssertionRewritingHook

                def test_load_resource():
                    assert isinstance(__loader__, AssertionRewritingHook)
                    res = pkg_resources.resource_string(__name__, 'resource.txt')
                    res = res.decode('ascii')
                    assert res == 'Load me please.'
                """
        }
        pytester.makepyfile(**contents)
        pytester.maketxtfile(**{"testpkg/resource": "Load me please."})

        result = pytester.runpytest_subprocess()
        result.assert_outcomes(passed=1)

    def test_read_pyc(self, tmp_path: Path) -> None:
        """
        Ensure that the `_read_pyc` can properly deal with corrupted pyc files.
        In those circumstances it should just give up instead of generating
        an exception that is propagated to the caller.
        """
        import py_compile

        from _pytest.assertion.rewrite import _read_pyc

        source = tmp_path / "source.py"
        pyc = Path(str(source) + "c")

        source.write_text("def test(): pass", encoding="utf-8")
        py_compile.compile(str(source), str(pyc))

        contents = pyc.read_bytes()
        strip_bytes = 20  # header is around 16 bytes, strip a little more
        assert len(contents) > strip_bytes
        pyc.write_bytes(contents[:strip_bytes])

        assert _read_pyc(source, pyc) is None  # no error

    def test_read_pyc_success(self, tmp_path: Path, pytester: Pytester) -> None:
        """
        Ensure that the _rewrite_test() -> _write_pyc() produces a pyc file
        that can be properly read with _read_pyc()
        """
        from _pytest.assertion import AssertionState
        from _pytest.assertion.rewrite import _read_pyc
        from _pytest.assertion.rewrite import _rewrite_test
        from _pytest.assertion.rewrite import _write_pyc

        config = pytester.parseconfig()
        state = AssertionState(config, "rewrite")

        fn = tmp_path / "source.py"
        pyc = Path(str(fn) + "c")

        fn.write_text("def test(): assert True", encoding="utf-8")

        source_stat, co = _rewrite_test(fn, config)
        _write_pyc(state, co, source_stat, pyc)
        assert _read_pyc(fn, pyc, state.trace) is not None

    def test_read_pyc_more_invalid(self, tmp_path: Path) -> None:
        from _pytest.assertion.rewrite import _read_pyc

        source = tmp_path / "source.py"
        pyc = tmp_path / "source.pyc"

        source_bytes = b"def test(): pass\n"
        source.write_bytes(source_bytes)

        magic = importlib.util.MAGIC_NUMBER

        flags = b"\x00\x00\x00\x00"

        mtime = b"\x58\x3c\xb0\x5f"
        mtime_int = int.from_bytes(mtime, "little")
        os.utime(source, (mtime_int, mtime_int))

        size = len(source_bytes).to_bytes(4, "little")

        code = marshal.dumps(compile(source_bytes, str(source), "exec"))

        # Good header.
        pyc.write_bytes(magic + flags + mtime + size + code)
        assert _read_pyc(source, pyc, print) is not None

        # Too short.
        pyc.write_bytes(magic + flags + mtime)
        assert _read_pyc(source, pyc, print) is None

        # Bad magic.
        pyc.write_bytes(b"\x12\x34\x56\x78" + flags + mtime + size + code)
        assert _read_pyc(source, pyc, print) is None

        # Unsupported flags.
        pyc.write_bytes(magic + b"\x00\xff\x00\x00" + mtime + size + code)
        assert _read_pyc(source, pyc, print) is None

        # Bad mtime.
        pyc.write_bytes(magic + flags + b"\x58\x3d\xb0\x5f" + size + code)
        assert _read_pyc(source, pyc, print) is None

        # Bad size.
        pyc.write_bytes(magic + flags + mtime + b"\x99\x00\x00\x00" + code)
        assert _read_pyc(source, pyc, print) is None

    def test_reload_is_same_and_reloads(self, pytester: Pytester) -> None:
        """Reloading a (collected) module after change picks up the change."""
        pytester.makeini(
            """
            [pytest]
            python_files = *.py
            """
        )
        pytester.makepyfile(
            file="""
            def reloaded():
                return False

            def rewrite_self():
                with open(__file__, 'w', encoding='utf-8') as self:
                    self.write('def reloaded(): return True')
            """,
            test_fun="""
            import sys
            from importlib import reload

            def test_loader():
                import file
                assert not file.reloaded()
                file.rewrite_self()
                assert sys.modules["file"] is reload(file)
                assert file.reloaded()
            """,
        )
        result = pytester.runpytest()
        result.stdout.fnmatch_lines(["* 1 passed*"])

    def test_get_data_support(self, pytester: Pytester) -> None:
        """Implement optional PEP302 api (#808)."""
        path = pytester.mkpydir("foo")
        path.joinpath("test_foo.py").write_text(
            textwrap.dedent(
                """\
                class Test(object):
                    def test_foo(self):
                        import pkgutil
                        data = pkgutil.get_data('foo.test_foo', 'data.txt')
                        assert data == b'Hey'
                """
            ),
            encoding="utf-8",
        )
        path.joinpath("data.txt").write_text("Hey", encoding="utf-8")
        result = pytester.runpytest()
        result.stdout.fnmatch_lines(["*1 passed*"])


def test_issue731(pytester: Pytester) -> None:
    pytester.makepyfile(
        """
    class LongReprWithBraces(object):
        def __repr__(self):
           return 'LongReprWithBraces({' + ('a' * 80) + '}' + ('a' * 120) + ')'

        def some_method(self):
            return False

    def test_long_repr():
        obj = LongReprWithBraces()
        assert obj.some_method()
    """
    )
    result = pytester.runpytest()
    result.stdout.no_fnmatch_line("*unbalanced braces*")


class TestIssue925:
    def test_simple_case(self, pytester: Pytester) -> None:
        pytester.makepyfile(
            """
        def test_ternary_display():
            assert (False == False) == False
        """
        )
        result = pytester.runpytest()
        result.stdout.fnmatch_lines(["*E*assert (False == False) == False"])

    def test_long_case(self, pytester: Pytester) -> None:
        pytester.makepyfile(
            """
        def test_ternary_display():
             assert False == (False == True) == True
        """
        )
        result = pytester.runpytest()
        result.stdout.fnmatch_lines(["*E*assert (False == True) == True"])

    def test_many_brackets(self, pytester: Pytester) -> None:
        pytester.makepyfile(
            """
            def test_ternary_display():
                 assert True == ((False == True) == True)
            """
        )
        result = pytester.runpytest()
        result.stdout.fnmatch_lines(["*E*assert True == ((False == True) == True)"])


class TestIssue2121:
    def test_rewrite_python_files_contain_subdirs(self, pytester: Pytester) -> None:
        pytester.makepyfile(
            **{
                "tests/file.py": """
                def test_simple_failure():
                    assert 1 + 1 == 3
                """
            }
        )
        pytester.makeini(
            """
                [pytest]
                python_files = tests/**.py
            """
        )
        result = pytester.runpytest()
        result.stdout.fnmatch_lines(["*E*assert (1 + 1) == 3"])


class TestIssue10743:
    def test_assertion_walrus_operator(self, pytester: Pytester) -> None:
        pytester.makepyfile(
            """
            def my_func(before, after):
                return before == after

            def change_value(value):
                return value.lower()

            def test_walrus_conversion():
                a = "Hello"
                assert not my_func(a, a := change_value(a))
                assert a == "hello"
        """
        )
        result = pytester.runpytest()
        assert result.ret == 0

    def test_assertion_walrus_operator_dont_rewrite(self, pytester: Pytester) -> None:
        pytester.makepyfile(
            """
            'PYTEST_DONT_REWRITE'
            def my_func(before, after):
                return before == after

            def change_value(value):
                return value.lower()

            def test_walrus_conversion_dont_rewrite():
                a = "Hello"
                assert not my_func(a, a := change_value(a))
                assert a == "hello"
        """
        )
        result = pytester.runpytest()
        assert result.ret == 0

    def test_assertion_inline_walrus_operator(self, pytester: Pytester) -> None:
        pytester.makepyfile(
            """
            def my_func(before, after):
                return before == after

            def test_walrus_conversion_inline():
                a = "Hello"
                assert not my_func(a, a := a.lower())
                assert a == "hello"
        """
        )
        result = pytester.runpytest()
        assert result.ret == 0

    def test_assertion_inline_walrus_operator_reverse(self, pytester: Pytester) -> None:
        pytester.makepyfile(
            """
            def my_func(before, after):
                return before == after

            def test_walrus_conversion_reverse():
                a = "Hello"
                assert my_func(a := a.lower(), a)
                assert a == 'hello'
        """
        )
        result = pytester.runpytest()
        assert result.ret == 0

    def test_assertion_walrus_no_variable_name_conflict(
        self, pytester: Pytester
    ) -> None:
        pytester.makepyfile(
            """
            def test_walrus_conversion_no_conflict():
                a = "Hello"
                assert a == (b := a.lower())
        """
        )
        result = pytester.runpytest()
        assert result.ret == 1
        result.stdout.fnmatch_lines(["*AssertionError: assert 'Hello' == 'hello'"])

    def test_assertion_walrus_operator_true_assertion_and_changes_variable_value(
        self, pytester: Pytester
    ) -> None:
        pytester.makepyfile(
            """
            def test_walrus_conversion_succeed():
                a = "Hello"
                assert a != (a := a.lower())
                assert a == 'hello'
        """
        )
        result = pytester.runpytest()
        assert result.ret == 0

    def test_assertion_walrus_operator_fail_assertion(self, pytester: Pytester) -> None:
        pytester.makepyfile(
            """
            def test_walrus_conversion_fails():
                a = "Hello"
                assert a == (a := a.lower())
        """
        )
        result = pytester.runpytest()
        assert result.ret == 1
        result.stdout.fnmatch_lines(["*AssertionError: assert 'Hello' == 'hello'"])

    def test_assertion_walrus_operator_boolean_composite(
        self, pytester: Pytester
    ) -> None:
        pytester.makepyfile(
            """
            def test_walrus_operator_change_boolean_value():
                a = True
                assert a and True and ((a := False) is False) and (a is False) and ((a := None) is None)
                assert a is None
        """
        )
        result = pytester.runpytest()
        assert result.ret == 0

    def test_assertion_walrus_operator_compare_boolean_fails(
        self, pytester: Pytester
    ) -> None:
        pytester.makepyfile(
            """
            def test_walrus_operator_change_boolean_value():
                a = True
                assert not (a and ((a := False) is False))
        """
        )
        result = pytester.runpytest()
        assert result.ret == 1
        result.stdout.fnmatch_lines(["*assert not (True and False is False)"])

    def test_assertion_walrus_operator_boolean_none_fails(
        self, pytester: Pytester
    ) -> None:
        pytester.makepyfile(
            """
            def test_walrus_operator_change_boolean_value():
                a = True
                assert not (a and ((a := None) is None))
        """
        )
        result = pytester.runpytest()
        assert result.ret == 1
        result.stdout.fnmatch_lines(["*assert not (True and None is None)"])

    def test_assertion_walrus_operator_value_changes_cleared_after_each_test(
        self, pytester: Pytester
    ) -> None:
        pytester.makepyfile(
            """
            def test_walrus_operator_change_value():
                a = True
                assert (a := None) is None

            def test_walrus_operator_not_override_value():
                a = True
                assert a is True
        """
        )
        result = pytester.runpytest()
        assert result.ret == 0


class TestIssue11028:
    def test_assertion_walrus_operator_in_operand(self, pytester: Pytester) -> None:
        pytester.makepyfile(
            """
            def test_in_string():
              assert (obj := "foo") in obj
        """
        )
        result = pytester.runpytest()
        assert result.ret == 0

    def test_assertion_walrus_operator_in_operand_json_dumps(
        self, pytester: Pytester
    ) -> None:
        pytester.makepyfile(
            """
            import json

            def test_json_encoder():
                assert (obj := "foo") in json.dumps(obj)
        """
        )
        result = pytester.runpytest()
        assert result.ret == 0

    def test_assertion_walrus_operator_equals_operand_function(
        self, pytester: Pytester
    ) -> None:
        pytester.makepyfile(
            """
            def f(a):
                return a

            def test_call_other_function_arg():
              assert (obj := "foo") == f(obj)
        """
        )
        result = pytester.runpytest()
        assert result.ret == 0

    def test_assertion_walrus_operator_equals_operand_function_keyword_arg(
        self, pytester: Pytester
    ) -> None:
        pytester.makepyfile(
            """
            def f(a='test'):
                return a

            def test_call_other_function_k_arg():
              assert (obj := "foo") == f(a=obj)
        """
        )
        result = pytester.runpytest()
        assert result.ret == 0

    def test_assertion_walrus_operator_equals_operand_function_arg_as_function(
        self, pytester: Pytester
    ) -> None:
        pytester.makepyfile(
            """
            def f(a='test'):
                return a

            def test_function_of_function():
              assert (obj := "foo") == f(f(obj))
        """
        )
        result = pytester.runpytest()
        assert result.ret == 0

    def test_assertion_walrus_operator_gt_operand_function(
        self, pytester: Pytester
    ) -> None:
        pytester.makepyfile(
            """
            def add_one(a):
                return a + 1

            def test_gt():
              assert (obj := 4) > add_one(obj)
        """
        )
        result = pytester.runpytest()
        assert result.ret == 1
        result.stdout.fnmatch_lines(["*assert 4 > 5", "*where 5 = add_one(4)"])


class TestIssue11239:
    def test_assertion_walrus_different_test_cases(self, pytester: Pytester) -> None:
        """Regression for (#11239)

        Walrus operator rewriting would leak to separate test cases if they used the same variables.
        """
        pytester.makepyfile(
            """
            def test_1():
                state = {"x": 2}.get("x")
                assert state is not None

            def test_2():
                db = {"x": 2}
                assert (state := db.get("x")) is not None
        """
        )
        result = pytester.runpytest()
        assert result.ret == 0


@pytest.mark.skipif(
    sys.maxsize <= (2**31 - 1), reason="Causes OverflowError on 32bit systems"
)
@pytest.mark.parametrize("offset", [-1, +1])
def test_source_mtime_long_long(pytester: Pytester, offset) -> None:
    """Support modification dates after 2038 in rewritten files (#4903).

    pytest would crash with:

            fp.write(struct.pack("<ll", mtime, size))
        E   struct.error: argument out of range
    """
    p = pytester.makepyfile(
        """
        def test(): pass
    """
    )
    # use unsigned long timestamp which overflows signed long,
    # which was the cause of the bug
    # +1 offset also tests masking of 0xFFFFFFFF
    timestamp = 2**32 + offset
    os.utime(str(p), (timestamp, timestamp))
    result = pytester.runpytest()
    assert result.ret == 0


def test_rewrite_infinite_recursion(
    pytester: Pytester, pytestconfig, monkeypatch
) -> None:
    """Fix infinite recursion when writing pyc files: if an import happens to be triggered when writing the pyc
    file, this would cause another call to the hook, which would trigger another pyc writing, which could
    trigger another import, and so on. (#3506)"""
    from _pytest.assertion import rewrite as rewritemod

    pytester.syspathinsert()
    pytester.makepyfile(test_foo="def test_foo(): pass")
    pytester.makepyfile(test_bar="def test_bar(): pass")

    original_write_pyc = rewritemod._write_pyc

    write_pyc_called = []

    def spy_write_pyc(*args, **kwargs):
        # make a note that we have called _write_pyc
        write_pyc_called.append(True)
        # try to import a module at this point: we should not try to rewrite this module
        assert hook.find_spec("test_bar") is None
        return original_write_pyc(*args, **kwargs)

    monkeypatch.setattr(rewritemod, "_write_pyc", spy_write_pyc)
    monkeypatch.setattr(sys, "dont_write_bytecode", False)

    hook = AssertionRewritingHook(pytestconfig)
    spec = hook.find_spec("test_foo")
    assert spec is not None
    module = importlib.util.module_from_spec(spec)
    hook.exec_module(module)
    assert len(write_pyc_called) == 1


class TestEarlyRewriteBailout:
    @pytest.fixture
    def hook(
        self, pytestconfig, monkeypatch, pytester: Pytester
    ) -> Generator[AssertionRewritingHook, None, None]:
        """Returns a patched AssertionRewritingHook instance so we can configure its initial paths and track
        if PathFinder.find_spec has been called.
        """
        import importlib.machinery

        self.find_spec_calls: List[str] = []
        self.initial_paths: Set[Path] = set()

        class StubSession:
            _initialpaths = self.initial_paths

            def isinitpath(self, p):
                return p in self._initialpaths

        def spy_find_spec(name, path):
            self.find_spec_calls.append(name)
            return importlib.machinery.PathFinder.find_spec(name, path)

        hook = AssertionRewritingHook(pytestconfig)
        # use default patterns, otherwise we inherit pytest's testing config
        with mock.patch.object(hook, "fnpats", ["test_*.py", "*_test.py"]):
            monkeypatch.setattr(hook, "_find_spec", spy_find_spec)
            hook.set_session(StubSession())  # type: ignore[arg-type]
            pytester.syspathinsert()
            yield hook

    def test_basic(self, pytester: Pytester, hook: AssertionRewritingHook) -> None:
        """
        Ensure we avoid calling PathFinder.find_spec when we know for sure a certain
        module will not be rewritten to optimize assertion rewriting (#3918).
        """
        pytester.makeconftest(
            """
            import pytest
            @pytest.fixture
            def fix(): return 1
        """
        )
        pytester.makepyfile(test_foo="def test_foo(): pass")
        pytester.makepyfile(bar="def bar(): pass")
        foobar_path = pytester.makepyfile(foobar="def foobar(): pass")
        self.initial_paths.add(foobar_path)

        # conftest files should always be rewritten
        assert hook.find_spec("conftest") is not None
        assert self.find_spec_calls == ["conftest"]

        # files matching "python_files" mask should always be rewritten
        assert hook.find_spec("test_foo") is not None
        assert self.find_spec_calls == ["conftest", "test_foo"]

        # file does not match "python_files": early bailout
        assert hook.find_spec("bar") is None
        assert self.find_spec_calls == ["conftest", "test_foo"]

        # file is an initial path (passed on the command-line): should be rewritten
        assert hook.find_spec("foobar") is not None
        assert self.find_spec_calls == ["conftest", "test_foo", "foobar"]

    def test_pattern_contains_subdirectories(
        self, pytester: Pytester, hook: AssertionRewritingHook
    ) -> None:
        """If one of the python_files patterns contain subdirectories ("tests/**.py") we can't bailout early
        because we need to match with the full path, which can only be found by calling PathFinder.find_spec
        """
        pytester.makepyfile(
            **{
                "tests/file.py": """\
                    def test_simple_failure():
                        assert 1 + 1 == 3
                """
            }
        )
        pytester.syspathinsert("tests")
        with mock.patch.object(hook, "fnpats", ["tests/**.py"]):
            assert hook.find_spec("file") is not None
            assert self.find_spec_calls == ["file"]

    @pytest.mark.skipif(
        sys.platform.startswith("win32"), reason="cannot remove cwd on Windows"
    )
    @pytest.mark.skipif(
        sys.platform.startswith("sunos5"), reason="cannot remove cwd on Solaris"
    )
    def test_cwd_changed(self, pytester: Pytester, monkeypatch) -> None:
        # Setup conditions for py's fspath trying to import pathlib on py34
        # always (previously triggered via xdist only).
        # Ref: https://github.com/pytest-dev/py/pull/207
        monkeypatch.syspath_prepend("")
        monkeypatch.delitem(sys.modules, "pathlib", raising=False)

        pytester.makepyfile(
            **{
                "test_setup_nonexisting_cwd.py": """\
                    import os
                    import tempfile

                    with tempfile.TemporaryDirectory() as newpath:
                        os.chdir(newpath)
                """,
                "test_test.py": """\
                    def test():
                        pass
                """,
            }
        )
        result = pytester.runpytest()
        result.stdout.fnmatch_lines(["* 1 passed in *"])


class TestAssertionPass:
    def test_option_default(self, pytester: Pytester) -> None:
        config = pytester.parseconfig()
        assert config.getini("enable_assertion_pass_hook") is False

    @pytest.fixture
    def flag_on(self, pytester: Pytester):
        pytester.makeini("[pytest]\nenable_assertion_pass_hook = True\n")

    @pytest.fixture
    def hook_on(self, pytester: Pytester):
        pytester.makeconftest(
            """\
            def pytest_assertion_pass(item, lineno, orig, expl):
                raise Exception("Assertion Passed: {} {} at line {}".format(orig, expl, lineno))
            """
        )

    def test_hook_call(self, pytester: Pytester, flag_on, hook_on) -> None:
        pytester.makepyfile(
            """\
            def test_simple():
                a=1
                b=2
                c=3
                d=0

                assert a+b == c+d

            # cover failing assertions with a message
            def test_fails():
                assert False, "assert with message"
            """
        )
        result = pytester.runpytest()
        result.stdout.fnmatch_lines(
            "*Assertion Passed: a+b == c+d (1 + 2) == (3 + 0) at line 7*"
        )

    def test_hook_call_with_parens(self, pytester: Pytester, flag_on, hook_on) -> None:
        pytester.makepyfile(
            """\
            def f(): return 1
            def test():
                assert f()
            """
        )
        result = pytester.runpytest()
        result.stdout.fnmatch_lines("*Assertion Passed: f() 1")

    def test_hook_not_called_without_hookimpl(
        self, pytester: Pytester, monkeypatch, flag_on
    ) -> None:
        """Assertion pass should not be called (and hence formatting should
        not occur) if there is no hook declared for pytest_assertion_pass"""

        def raise_on_assertionpass(*_, **__):
            raise Exception("Assertion passed called when it shouldn't!")

        monkeypatch.setattr(
            _pytest.assertion.rewrite, "_call_assertion_pass", raise_on_assertionpass
        )

        pytester.makepyfile(
            """\
            def test_simple():
                a=1
                b=2
                c=3
                d=0

                assert a+b == c+d
            """
        )
        result = pytester.runpytest()
        result.assert_outcomes(passed=1)

    def test_hook_not_called_without_cmd_option(
        self, pytester: Pytester, monkeypatch
    ) -> None:
        """Assertion pass should not be called (and hence formatting should
        not occur) if there is no hook declared for pytest_assertion_pass"""

        def raise_on_assertionpass(*_, **__):
            raise Exception("Assertion passed called when it shouldn't!")

        monkeypatch.setattr(
            _pytest.assertion.rewrite, "_call_assertion_pass", raise_on_assertionpass
        )

        pytester.makeconftest(
            """\
            def pytest_assertion_pass(item, lineno, orig, expl):
                raise Exception("Assertion Passed: {} {} at line {}".format(orig, expl, lineno))
            """
        )

        pytester.makepyfile(
            """\
            def test_simple():
                a=1
                b=2
                c=3
                d=0

                assert a+b == c+d
            """
        )
        result = pytester.runpytest()
        result.assert_outcomes(passed=1)


# fmt: off
@pytest.mark.parametrize(
    ("src", "expected"),
    (
        pytest.param(b"", {}, id="trivial"),
        pytest.param(
            b"def x(): assert 1\n",
            {1: "1"},
            id="assert statement not on own line",
        ),
        pytest.param(
            b"def x():\n"
            b"    assert 1\n"
            b"    assert 1+2\n",
            {2: "1", 3: "1+2"},
            id="multiple assertions",
        ),
        pytest.param(
            # changes in encoding cause the byte offsets to be different
            "# -*- coding: latin1\n"
            "def ÀÀÀÀÀ(): assert 1\n".encode("latin1"),
            {2: "1"},
            id="latin1 encoded on first line\n",
        ),
        pytest.param(
            # using the default utf-8 encoding
            "def ÀÀÀÀÀ(): assert 1\n".encode(),
            {1: "1"},
            id="utf-8 encoded on first line",
        ),
        pytest.param(
            b"def x():\n"
            b"    assert (\n"
            b"        1 + 2  # comment\n"
            b"    )\n",
            {2: "(\n        1 + 2  # comment\n    )"},
            id="multi-line assertion",
        ),
        pytest.param(
            b"def x():\n"
            b"    assert y == [\n"
            b"        1, 2, 3\n"
            b"    ]\n",
            {2: "y == [\n        1, 2, 3\n    ]"},
            id="multi line assert with list continuation",
        ),
        pytest.param(
            b"def x():\n"
            b"    assert 1 + \\\n"
            b"        2\n",
            {2: "1 + \\\n        2"},
            id="backslash continuation",
        ),
        pytest.param(
            b"def x():\n"
            b"    assert x, y\n",
            {2: "x"},
            id="assertion with message",
        ),
        pytest.param(
            b"def x():\n"
            b"    assert (\n"
            b"        f(1, 2, 3)\n"
            b"    ),  'f did not work!'\n",
            {2: "(\n        f(1, 2, 3)\n    )"},
            id="assertion with message, test spanning multiple lines",
        ),
        pytest.param(
            b"def x():\n"
            b"    assert \\\n"
            b"        x\\\n"
            b"        , 'failure message'\n",
            {2: "x"},
            id="escaped newlines plus message",
        ),
        pytest.param(
            b"def x(): assert 5",
            {1: "5"},
            id="no newline at end of file",
        ),
    ),
)
# fmt: on
def test_get_assertion_exprs(src, expected) -> None:
    assert _get_assertion_exprs(src) == expected


def test_try_makedirs(monkeypatch, tmp_path: Path) -> None:
    from _pytest.assertion.rewrite import try_makedirs

    p = tmp_path / "foo"

    # create
    assert try_makedirs(p)
    assert p.is_dir()

    # already exist
    assert try_makedirs(p)

    # monkeypatch to simulate all error situations
    def fake_mkdir(p, exist_ok=False, *, exc):
        assert isinstance(p, Path)
        raise exc

    monkeypatch.setattr(os, "makedirs", partial(fake_mkdir, exc=FileNotFoundError()))
    assert not try_makedirs(p)

    monkeypatch.setattr(os, "makedirs", partial(fake_mkdir, exc=NotADirectoryError()))
    assert not try_makedirs(p)

    monkeypatch.setattr(os, "makedirs", partial(fake_mkdir, exc=PermissionError()))
    assert not try_makedirs(p)

    err = OSError()
    err.errno = errno.EROFS
    monkeypatch.setattr(os, "makedirs", partial(fake_mkdir, exc=err))
    assert not try_makedirs(p)

    # unhandled OSError should raise
    err = OSError()
    err.errno = errno.ECHILD
    monkeypatch.setattr(os, "makedirs", partial(fake_mkdir, exc=err))
    with pytest.raises(OSError) as exc_info:
        try_makedirs(p)
    assert exc_info.value.errno == errno.ECHILD


class TestPyCacheDir:
    @pytest.mark.parametrize(
        "prefix, source, expected",
        [
            ("c:/tmp/pycs", "d:/projects/src/foo.py", "c:/tmp/pycs/projects/src"),
            (None, "d:/projects/src/foo.py", "d:/projects/src/__pycache__"),
            ("/tmp/pycs", "/home/projects/src/foo.py", "/tmp/pycs/home/projects/src"),
            (None, "/home/projects/src/foo.py", "/home/projects/src/__pycache__"),
        ],
    )
    def test_get_cache_dir(self, monkeypatch, prefix, source, expected) -> None:
        monkeypatch.delenv("PYTHONPYCACHEPREFIX", raising=False)
        monkeypatch.setattr(sys, "pycache_prefix", prefix, raising=False)

        assert get_cache_dir(Path(source)) == Path(expected)

    @pytest.mark.skipif(
        sys.version_info[:2] == (3, 9) and sys.platform.startswith("win"),
        reason="#9298",
    )
    def test_sys_pycache_prefix_integration(
        self, tmp_path, monkeypatch, pytester: Pytester
    ) -> None:
        """Integration test for sys.pycache_prefix (#4730)."""
        pycache_prefix = tmp_path / "my/pycs"
        monkeypatch.setattr(sys, "pycache_prefix", str(pycache_prefix))
        monkeypatch.setattr(sys, "dont_write_bytecode", False)

        pytester.makepyfile(
            **{
                "src/test_foo.py": """
                import bar
                def test_foo():
                    pass
            """,
                "src/bar/__init__.py": "",
            }
        )
        result = pytester.runpytest()
        assert result.ret == 0

        test_foo = pytester.path.joinpath("src/test_foo.py")
        bar_init = pytester.path.joinpath("src/bar/__init__.py")
        assert test_foo.is_file()
        assert bar_init.is_file()

        # test file: rewritten, custom pytest cache tag
        test_foo_pyc = get_cache_dir(test_foo) / ("test_foo" + PYC_TAIL)
        assert test_foo_pyc.is_file()

        # normal file: not touched by pytest, normal cache tag
        bar_init_pyc = get_cache_dir(bar_init) / f"__init__.{sys.implementation.cache_tag}.pyc"
        assert bar_init_pyc.is_file()


class TestReprSizeVerbosity:
    """
    Check that verbosity also controls the string length threshold to shorten it using
    ellipsis.
    """

    @pytest.mark.parametrize(
        "verbose, expected_size",
        [
            (0, DEFAULT_REPR_MAX_SIZE),
            (1, DEFAULT_REPR_MAX_SIZE * 10),
            (2, None),
            (3, None),
        ],
    )
    def test_get_maxsize_for_saferepr(self, verbose: int, expected_size) -> None:
        class FakeConfig:
            def get_verbosity(self, verbosity_type: Optional[str] = None) -> int:
                return verbose

        config = FakeConfig()
        assert _get_maxsize_for_saferepr(cast(Config, config)) == expected_size

    def test_get_maxsize_for_saferepr_no_config(self) -> None:
        assert _get_maxsize_for_saferepr(None) == DEFAULT_REPR_MAX_SIZE

    def create_test_file(self, pytester: Pytester, size: int) -> None:
        pytester.makepyfile(
            f"""
            def test_very_long_string():
                text = "x" * {size}
                assert "hello world" in text
            """
        )

    def test_default_verbosity(self, pytester: Pytester) -> None:
        self.create_test_file(pytester, DEFAULT_REPR_MAX_SIZE)
        result = pytester.runpytest()
        result.stdout.fnmatch_lines(["*xxx...xxx*"])

    def test_increased_verbosity(self, pytester: Pytester) -> None:
        self.create_test_file(pytester, DEFAULT_REPR_MAX_SIZE)
        result = pytester.runpytest("-v")
        result.stdout.no_fnmatch_line("*xxx...xxx*")

    def test_max_increased_verbosity(self, pytester: Pytester) -> None:
        self.create_test_file(pytester, DEFAULT_REPR_MAX_SIZE * 10)
        result = pytester.runpytest("-vv")
        result.stdout.no_fnmatch_line("*xxx...xxx*")


class TestIssue11140:
    def test_constant_not_picked_as_module_docstring(self, pytester: Pytester) -> None:
        pytester.makepyfile(
            """\
            0

            def test_foo():
                pass
            """
        )
        result = pytester.runpytest()
        assert result.ret == 0