Debian Codegraph @

tests/test_trans.py

raw
1 from black.trans import iter_fexpr_spans
2
3
4 def test_fexpr_spans() -> None:
5 def check(
6 string: str, expected_spans: list[tuple[int, int]], expected_slices: list[str]
7 ) -> None:
8 spans = list(iter_fexpr_spans(string))
9
10 # Checking slices isn't strictly necessary, but it's easier to verify at
11 # a glance than only spans
12 assert len(spans) == len(expected_slices)
13 for (i, j), slice in zip(spans, expected_slices, strict=True):
14 assert 0 <= i <= j <= len(string)
15 assert string[i:j] == slice
16
17 assert spans == expected_spans
18
19 # Most of these test cases omit the leading 'f' and leading / closing quotes
20 # for convenience
21 # Some additional property-based tests can be found in
22 # https://github.com/psf/black/pull/2654#issuecomment-981411748
23 check("""{var}""", [(0, 5)], ["{var}"])
24 check("""f'{var}'""", [(2, 7)], ["{var}"])
25 check("""f'{1 + f() + 2 + "asdf"}'""", [(2, 24)], ["""{1 + f() + 2 + "asdf"}"""])
26 check("""text {var} text""", [(5, 10)], ["{var}"])
27 check("""text {{ {var} }} text""", [(8, 13)], ["{var}"])
28 check("""{a} {b} {c}""", [(0, 3), (4, 7), (8, 11)], ["{a}", "{b}", "{c}"])
29 check("""f'{a} {b} {c}'""", [(2, 5), (6, 9), (10, 13)], ["{a}", "{b}", "{c}"])
30 check("""{ {} }""", [(0, 6)], ["{ {} }"])
31 check("""{ {{}} }""", [(0, 8)], ["{ {{}} }"])
32 check("""{ {{{}}} }""", [(0, 10)], ["{ {{{}}} }"])
33 check("""{{ {{{}}} }}""", [(5, 7)], ["{}"])
34 check("""{{ {{{var}}} }}""", [(5, 10)], ["{var}"])
35 check("""{f"{0}"}""", [(0, 8)], ["""{f"{0}"}"""])
36 check("""{"'"}""", [(0, 5)], ["""{"'"}"""])
37 check("""{"{"}""", [(0, 5)], ["""{"{"}"""])
38 check("""{"}"}""", [(0, 5)], ["""{"}"}"""])
39 check("""{"{{"}""", [(0, 6)], ["""{"{{"}"""])
40 check("""{''' '''}""", [(0, 9)], ["""{''' '''}"""])
41 check("""{'''{'''}""", [(0, 9)], ["""{'''{'''}"""])
42 check("""{''' {'{ '''}""", [(0, 13)], ["""{''' {'{ '''}"""])
43 check(
44 '''f\'\'\'-{f"""*{f"+{f'.{x}.'}+"}*"""}-'y\\'\'\'\'''',
45 [(5, 33)],
46 ['''{f"""*{f"+{f'.{x}.'}+"}*"""}'''],
47 )
48 check(r"""{}{""", [(0, 2)], ["{}"])
49 check("""f"{'{'''''''''}\"""", [(2, 15)], ["{'{'''''''''}"])