Debian Codegraph @

pypy/objspace/std/test/apptest_fstring.py

raw symbols SCIP
1 # spaceconfig = {"usemodules" : ["unicodedata"]}
2 import ast
3 import warnings
4
5 def test_error_unknown_code():
6 def fn():
7 f'{1000:j}'
8 exc_info = raises(ValueError, fn)
9 assert str(exc_info.value).startswith("Unknown format code")
10
11 def test_ast_lineno_and_col_offset():
12 m = ast.parse("\nf'a{x}bc{y}de'")
13 x_ast = m.body[0].value.values[1].value
14 y_ast = m.body[0].value.values[3].value
15 assert x_ast.lineno == 2
16 assert x_ast.col_offset == 4
17 assert y_ast.lineno == 2
18 assert y_ast.col_offset == 9
19
20 m = ast.parse("\na + f'a{x}bc{y}de'")
21 x_ast = m.body[0].value.right.values[1].value
22 y_ast = m.body[0].value.right.values[3].value
23 assert x_ast.lineno == 2
24 assert x_ast.col_offset == 8
25 assert y_ast.lineno == 2
26 assert y_ast.col_offset == 13
27
28 def test_ast_lineno_and_col_offset_duplicate():
29 m = ast.parse("\nf'a{x}bc{x}de'")
30 x_ast = m.body[0].value.values[1].value
31 y_ast = m.body[0].value.values[3].value
32 assert x_ast.lineno == 2
33 assert x_ast.col_offset == 4
34 assert y_ast.lineno == 2
35 assert y_ast.col_offset == 9
36
37 def test_ast_lineno_and_col_offset_unicode():
38 s = "\nf'α{χ}βγ{ψ}δε'"
39 assert s.encode('utf-8') ==b"\nf'\xce\xb1{\xcf\x87}\xce\xb2\xce\xb3{\xcf\x88}\xce\xb4\xce\xb5'"
40 m = ast.parse(s)
41 x_ast = m.body[0].value.values[1].value
42 y_ast = m.body[0].value.values[3].value
43 assert x_ast.lineno == 2
44 assert x_ast.col_offset == 5
45 assert y_ast.lineno == 2
46 assert y_ast.col_offset == 13
47
48 def test_ast_mutiline_lineno_and_col_offset():
49 m = ast.parse("\n\nf'''{x}\nabc{y}\n{\nz}''' \n\n\n")
50 x_ast = m.body[0].value.values[0].value
51 y_ast = m.body[0].value.values[2].value
52 z_ast = m.body[0].value.values[4].value
53 assert x_ast.lineno == 3
54 assert x_ast.col_offset == 5
55 assert y_ast.lineno == 4
56 assert y_ast.col_offset == 4
57 assert z_ast.lineno == 6
58 assert z_ast.col_offset == 0
59
60 def test_lookeahed_cases():
61 a = 2 + 2
62 b = 4
63
64 assert f'{a==b}' == 'True'
65 assert f'{a>=b}' == 'True'
66 assert f'{a<=b!r}' == 'True'
67 assert f'{a!=b:}' == 'False'
68 assert f'{a!=b!s}' == 'False'
69
70 def test_double_braces():
71 assert f'{{' == '{'
72 assert f'a{{' == 'a{'
73 assert f'{{b' == '{b'
74 assert f'a{{b' == 'a{b'
75 assert f'}}' == '}'
76 assert f'a}}' == 'a}'
77 assert f'}}b' == '}b'
78 assert f'a}}b' == 'a}b'
79 assert f'{{}}' == '{}'
80 assert f'a{{}}' == 'a{}'
81 assert f'{{b}}' == '{b}'
82 assert f'{{}}c' == '{}c'
83 assert f'a{{b}}' == 'a{b}'
84 assert f'a{{}}c' == 'a{}c'
85 assert f'{{b}}c' == '{b}c'
86 assert f'a{{b}}c' == 'a{b}c'
87
88 assert f'{{{10}' == '{10'
89 assert f'}}{10}' == '}10'
90 assert f'}}{{{10}' == '}{10'
91 assert f'}}a{{{10}' == '}a{10'
92
93 assert f'{10}{{' == '10{'
94 assert f'{10}}}' == '10}'
95 assert f'{10}}}{{' == '10}{'
96 assert f'{10}}}a{{' '}' == '10}a{}'
97
98 # Inside of strings, don't interpret doubled brackets.
99 assert f'{"{{}}"}' == '{{}}'
100
101 exc_info = raises(TypeError, eval, "f'{ {{}} }'") # dict in a set
102 assert 'unhashable' in str(exc_info.value)
103
104 def test_backslashes_in_string_part():
105 assert f'\t' == '\t'
106 assert r'\t' == '\\t'
107 assert rf'\t' == '\\t'
108 assert f'{2}\t' == '2\t'
109 assert f'{2}\t{3}' == '2\t3'
110 assert f'\t{3}' == '\t3'
111
112 assert f'\u0394' == '\u0394'
113 assert r'\u0394' == '\\u0394'
114 assert rf'\u0394' == '\\u0394'
115 assert f'{2}\u0394' == '2\u0394'
116 assert f'{2}\u0394{3}' == '2\u03943'
117 assert f'\u0394{3}' == '\u03943'
118
119 assert f'\U00000394' == '\u0394'
120 assert r'\U00000394' == '\\U00000394'
121 assert rf'\U00000394' == '\\U00000394'
122 assert f'{2}\U00000394' == '2\u0394'
123 assert f'{2}\U00000394{3}' == '2\u03943'
124 assert f'\U00000394{3}' == '\u03943'
125
126 assert f'\N{GREEK CAPITAL LETTER DELTA}' == '\u0394'
127 assert f'{2}\N{GREEK CAPITAL LETTER DELTA}' == '2\u0394'
128 assert f'{2}\N{GREEK CAPITAL LETTER DELTA}{3}' == '2\u03943'
129 assert f'\N{GREEK CAPITAL LETTER DELTA}{3}' == '\u03943'
130 assert f'2\N{GREEK CAPITAL LETTER DELTA}' == '2\u0394'
131 assert f'2\N{GREEK CAPITAL LETTER DELTA}3' == '2\u03943'
132 assert f'\N{GREEK CAPITAL LETTER DELTA}3' == '\u03943'
133
134 assert f'\x20' == ' '
135 assert r'\x20' == '\\x20'
136 assert rf'\x20' == '\\x20'
137 assert f'{2}\x20' == '2 '
138 assert f'{2}\x20{3}' == '2 3'
139 assert f'\x20{3}' == ' 3'
140
141 assert f'2\x20' == '2 '
142 assert f'2\x203' == '2 3'
143 assert f'\x203' == ' 3'
144
145 with warnings.catch_warnings(record=True) as w: # invalid escape sequence
146 warnings.simplefilter("always", DeprecationWarning)
147 value = eval(r"f'\{6*7}'")
148 assert len(w) == 1 and w[0].category == DeprecationWarning
149 assert value == '\\42'
150 assert f'\\{6*7}' == '\\42'
151 assert fr'\{6*7}' == '\\42'
152
153 AMPERSAND = 'spam'
154 # Get the right unicode character (&), or pick up local variable
155 # depending on the number of backslashes.
156 assert f'\N{AMPERSAND}' == '&'
157 assert f'\\N{AMPERSAND}' == '\\Nspam'
158 assert fr'\N{AMPERSAND}' == '\\Nspam'
159 assert f'\\\N{AMPERSAND}' == '\\&'
160
161 def test_debug_conversion():
162 x = 'A string'
163 assert f'{x=}' == 'x=' + repr(x)
164 assert f'{x =}' == 'x =' + repr(x)
165 assert f'{x=!s}'== 'x=' + str(x)
166 assert f'{x=!r}' == 'x=' + repr(x)
167 assert f'{x=!a}' == 'x=' + ascii(x)
168
169 # conversions
170 x = 2.71828
171 assert f'{x=:.2f}' =='x=' + format(x, '.2f')
172 assert f'{x=:}' == 'x=' + format(x, '')
173 assert f'{x=!r:^20}' == 'x=' + format(repr(x), '^20')
174 assert f'{x=!s:^20}' == 'x=' + format(str(x), '^20')
175 assert f'{x=!a:^20}' == 'x=' + format(ascii(x), '^20')
176
177 # complex expr
178 x = 9
179 assert f'{3*x+15=}' == '3*x+15=42'
180
181 # unicode
182 tenπ = 31.4
183 assert f'{tenπ=:.2f}' == 'tenπ=31.40'
184 assert f'{"Σ"=}' == '"Σ"=\'Σ\''
185 assert f'{f"{3.1415=:.1f}":*^20}' == '*****3.1415=3.1*****'
186
187 # whitespace offset
188 x = 'foo'
189 pi = 'π'
190 assert f'alpha α {pi=} ω omega' == "alpha α pi='π' ω omega"
191 assert f'X{x=}Y' == 'Xx='+repr(x)+'Y'
192 assert f'X{x =}Y' == 'Xx ='+repr(x)+'Y'
193 assert f'X{x= }Y' == 'Xx= '+repr(x)+'Y'
194 assert f'X{x = }Y' == 'Xx = '+repr(x)+'Y'
195
196 # multi-line expressions.
197 assert f'''{
198 3
199 =}''' =='\n3\n=3'
200
201 # keyword arguments
202 def f(a):
203 nonlocal x
204 oldx = x
205 x = a
206 return oldx
207 x = 0
208 assert f'{f(a="3=")}' == '0'
209 assert x, '3='
210 assert f'{f(a=4)}' == '3='
211 assert x, 4
212
213 # __format__
214 class C:
215 def __format__(self, s):
216 return f'FORMAT-{s}'
217 def __repr__(self):
218 return 'REPR'
219
220 assert f'{C()=}' == 'C()=REPR'
221 assert f'{C()=!r}' == 'C()=REPR'
222 assert f'{C()=:}' == 'C()=FORMAT-'
223 assert f'{C()=: }' == 'C()=FORMAT- '
224 assert f'{C()=:x}' == 'C()=FORMAT-x'
225 assert f'{C()=!r:*^20}' == 'C()=********REPR********'
226
227 def test_crash_debugging():
228 with raises(SyntaxError):
229 eval('f"{pow(x, k, j)="')
230 with raises(SyntaxError):
231 eval('f"{pow(x, k, j)= "')
232 with raises(SyntaxError):
233 eval("f'{4:{/5}}'")
234
235 def test_parseerror_lineno():
236 with raises(SyntaxError) as excinfo:
237 eval('\n\nf"{,}"')
238 assert excinfo.value.lineno == 3
239 assert excinfo.value.offset == 4
240 assert excinfo.value.msg == "f-string: invalid syntax"
241 with raises(SyntaxError) as excinfo:
242 eval('f"\\\n\\\n{,}"')
243 assert excinfo.value.lineno == 3
244 assert excinfo.value.offset == 2
245 assert excinfo.value.text == '{,}"'
246 assert excinfo.value.msg == "f-string: invalid syntax"
247 with raises(SyntaxError) as excinfo:
248 eval('''f"""{
249 ,}"""''')
250 assert excinfo.value.lineno == 2
251 assert excinfo.value.offset == 1
252 assert excinfo.value.text == ',}"""'
253 assert excinfo.value.msg == "f-string: invalid syntax"
254
255 def test_multiline_fstring_error_lineno():
256 # An error in a multi-line f-string should report end_lineno as lineno,
257 # and text should be only the end line (not the full multi-line span).
258 with raises(SyntaxError) as excinfo:
259 eval('f"""{}\nfoo"""')
260 assert excinfo.value.lineno == 2
261 assert excinfo.value.msg == "f-string: empty expression not allowed"
262 assert excinfo.value.text is not None
263 assert '\n' not in excinfo.value.text.rstrip('\n') # single line
264
265 def test_joined_positions():
266 expr = """('a'
267 "b"
268 f"wat2"
269 )
270 """
271 t = ast.parse(expr)
272 # check the fstring
273 fstring = t.body[0].value
274 for x in fstring, fstring.values[0]:
275 assert fstring.lineno == 1
276 assert fstring.col_offset == 1
277 assert fstring.end_lineno == 3
278 assert fstring.end_col_offset == 11
279
280 def test_tokenerror_lineno():
281 with raises(SyntaxError) as excinfo:
282 eval('\n\nf"{$}"')
283 assert excinfo.value.lineno == 3
284 assert excinfo.value.offset == 4
285 with raises(SyntaxError) as excinfo:
286 eval('f"\\\n\\\n{$}"')
287 assert excinfo.value.lineno == 3
288 assert excinfo.value.offset == 2
289 assert excinfo.value.text == '{$}"'
290 with raises(SyntaxError) as excinfo:
291 eval('''f"""{
292 $}"""''')
293 assert excinfo.value.lineno == 2
294 assert excinfo.value.offset == 1
295 assert excinfo.value.text == '$}"""'
296 with raises(SyntaxError) as excinfo:
297 eval("f'''{\xa0}'''")
298 assert excinfo.value.lineno == 1
299 print(excinfo.value.offset)
300 assert excinfo.value.offset == 6
301 assert 'f-string: invalid non-printable character U+00A0' in str(excinfo.value)
302
303 def test_fstring_escape_N_bug():
304 with raises(SyntaxError) as excinfo:
305 eval(r"f'\N '")
306 with raises(SyntaxError) as excinfo:
307 eval(r"f'\N '")
308
309 def test_fstring_no_closing_brace():
310 with raises(SyntaxError) as excinfo:
311 eval(r"f'{<'")
312 assert excinfo.value.msg == "f-string: expecting '}'"
313
314 def test_fstring_triple_bug():
315 assert eval('''
316 f\'\'\'{"""
317 """}
318 \'\'\'
319 ''') == "\n\n"
320
321 def test_negative_zero():
322 ## default behavior
323 assert f"{-0.:.1f}" == "-0.0"
324 assert f"{-.01:.1f}" == "-0.0"
325 assert f"{-0:.1f}" == "0.0" # integers do not distinguish -0
326
327 ## z sign option
328 assert f"{0.:z.1f}" == "0.0"
329 assert f"{0.:z6.1f}" == " 0.0"
330 assert f"{-1.:z6.1f}" == " -1.0"
331 assert f"{-0.:z.1f}" == "0.0"
332 assert f"{.01:z.1f}" == "0.0"
333 assert f"{-0:z.1f}" == "0.0" # z is allowed for integer input
334 assert f"{-.01:z.1f}" == "0.0"
335 assert f"{0.:z.2f}" == "0.00"
336 assert f"{-0.:z.2f}" == "0.00"
337 assert f"{.001:z.2f}" == "0.00"
338 assert f"{-.001:z.2f}" == "0.00"
339
340 assert f"{0.:z.1e}" == "0.0e+00"
341 assert f"{-0.:z.1e}" == "0.0e+00"
342 assert f"{0.:z.1E}" == "0.0E+00"
343 assert f"{-0.:z.1E}" == "0.0E+00"
344
345 assert f"{-0.001:z.2e}" == "-1.00e-03" # tests for mishandled
346 # rounding
347 assert f"{-0.001:z.2g}" == "-0.001"
348 assert f"{-0.001:z.2%}" == "-0.10%"
349
350 assert f"{-00000.000001:z.1f}" == "0.0"
351 assert f"{-00000.:z.1f}" == "0.0"
352 assert f"{-.0000000000:z.1f}" == "0.0"
353
354 assert f"{-00000.000001:z.2f}" == "0.00"
355 assert f"{-00000.:z.2f}" == "0.00"
356 assert f"{-.0000000000:z.2f}" == "0.00"
357
358 assert f"{.09:z.1f}" == "0.1"
359 assert f"{-.09:z.1f}" == "-0.1"
360 assert f"{-0.: z.0f}" == " 0"
361 assert f"{-0.:+z.0f}" == "+0"
362 assert f"{-0.:-z.0f}" == "0"
363 assert f"{-1.: z.0f}" == "-1"
364 assert f"{-1.:+z.0f}" == "-1"
365 assert f"{-1.:-z.0f}" == "-1"
366
367 assert f"{0.j:z.1f}" == "0.0+0.0j"
368 assert f"{-0.j:z.1f}" == "0.0+0.0j"
369 assert f"{.01j:z.1f}" == "0.0+0.0j"
370 assert f"{-.01j:z.1f}" == "0.0+0.0j"
371
372 assert f"{-0.:z>6.1f}" == "zz-0.0" # test fill, esp. 'z' fill
373 assert f"{-0.:z>z6.1f}" == "zzz0.0"
374 assert f"{-0.:x>z6.1f}" == "xxx0.0"
375 assert f"{-0.:🖤>z6.1f}" == "🖤🖤🖤0.0" # multi-byte fill char
376
377 def test_specifier_z_error():
378 with raises(ValueError) as info:
379 f"{0:zd}" # can't apply to int presentation type
380 assert "Negative zero coercion (z) not allowed" in str(info.value)
381 with raises(ValueError) as info:
382 f"{'x':zs}" # can't apply to string
383 assert "Negative zero coercion (z) not allowed" in str(info.value)
384
385 #error_msg = re.escape("unsupported format character 'z'")
386 #with self.assertRaisesRegex(ValueError, error_msg):
387 # "%z.1f" % 0 # not allowed in old style string interpolation
388 #with self.assertRaisesRegex(ValueError, error_msg):
389 # b"%z.1f" % 0
390
391 def test_empty_expression_error():
392 s = '''f'{ !x:a}' '''
393 with raises(SyntaxError) as info:
394 eval(s)
395 assert str(info.value).startswith("f-string: expression required before '!'")
396
397 def test_empty_expression_closing_brace():
398 for s in ["f'{}'", "f'{ }'", "f' {} '"]:
399 with raises(SyntaxError) as info:
400 eval(s)
401 assert str(info.value).startswith("f-string: empty expression not allowed")
402