Debian Codegraph @

mypyc/test-data/run-strings.test

raw
1 # Test cases for strings (compile and run)
2
3 [case testStrBasics]
4 from typing import Tuple
5 class A:
6 def __str__(self) -> str:
7 return "A-str"
8 def __repr__(self) -> str:
9 return "A-repr"
10 def f() -> str:
11 return 'some string'
12 def g() -> str:
13 return 'some\a \v \t \x7f " \n \0string 🐍'
14 def tostr(x: int) -> str:
15 return str(x)
16 def booltostr(x: bool) -> str:
17 return str(x)
18 def clstostr(x: A) -> str:
19 return str(x)
20 def torepr(x: int) -> str:
21 return repr(x)
22 def booltorepr(x: bool) -> str:
23 return repr(x)
24 def clstorepr(x: A) -> str:
25 return repr(x)
26 def concat(x: str, y: str) -> str:
27 return x + y
28 def eq(x: str) -> int:
29 if x == 'foo':
30 return 0
31 elif x != 'bar':
32 return 1
33 return 2
34 def match(x: str, y: str) -> Tuple[bool, bool]:
35 return (x.startswith(y), x.endswith(y))
36 def match_tuple(x: str, y: Tuple[str, ...]) -> Tuple[bool, bool]:
37 return (x.startswith(y), x.endswith(y))
38 def match_tuple_literal_args(x: str, y: str, z: str) -> Tuple[bool, bool]:
39 return (x.startswith((y, z)), x.endswith((y, z)))
40 def remove_prefix_suffix(x: str, y: str) -> Tuple[str, str]:
41 return (x.removeprefix(y), x.removesuffix(y))
42
43 [file driver.py]
44 from native import (
45 f, g, A, tostr, booltostr, clstostr, concat, eq, match, match_tuple,
46 match_tuple_literal_args, remove_prefix_suffix,
47 torepr, booltorepr, clstorepr
48 )
49 import sys
50 from testutil import assertRaises
51
52 assert f() == 'some string'
53 assert f() is sys.intern('some string')
54 assert g() == 'some\a \v \t \x7f " \n \0string 🐍'
55 assert tostr(57) == '57'
56 assert concat('foo', 'bar') == 'foobar'
57 assert booltostr(True) == 'True'
58 assert booltostr(False) == 'False'
59 assert clstostr(A()) == "A-str"
60 assert eq('foo') == 0
61 assert eq('zar') == 1
62 assert eq('bar') == 2
63
64 assert torepr(57) == '57'
65 assert booltorepr(True) == 'True'
66 assert booltorepr(False) == 'False'
67 assert clstorepr(A()) == "A-repr"
68
69 assert int(tostr(0)) == 0
70 assert int(tostr(20)) == 20
71 assert int(torepr(0)) == 0
72 assert int(torepr(20)) == 20
73 assert match('', '') == (True, True)
74 assert match('abc', '') == (True, True)
75 assert match('abc', 'a') == (True, False)
76 assert match('abc', 'c') == (False, True)
77 assert match('', 'abc') == (False, False)
78 assert match_tuple('abc', ('d', 'e')) == (False, False)
79 assert match_tuple('abc', ('a', 'c')) == (True, True)
80 assert match_tuple('abc', ('a',)) == (True, False)
81 assert match_tuple('abc', ('c',)) == (False, True)
82 assert match_tuple('abc', ('x', 'y', 'z')) == (False, False)
83 assert match_tuple('abc', ('x', 'y', 'z', 'a', 'c')) == (True, True)
84 with assertRaises(TypeError, "tuple for startswith must only contain str"):
85 assert match_tuple('abc', (None,))
86 with assertRaises(TypeError, "tuple for endswith must only contain str"):
87 assert match_tuple('abc', ('a', None))
88 assert match_tuple_literal_args('abc', 'z', 'a') == (True, False)
89 assert match_tuple_literal_args('abc', 'z', 'c') == (False, True)
90
91 assert remove_prefix_suffix('', '') == ('', '')
92 assert remove_prefix_suffix('abc', 'a') == ('bc', 'abc')
93 assert remove_prefix_suffix('abc', 'c') == ('abc', 'ab')
94
95 [case testStringEquality]
96 def eq(a: str, b: str) -> bool:
97 return a == b
98 def ne(a: str, b: str) -> bool:
99 return a != b
100
101 def test_basic() -> None:
102 xy = "xy"
103 xy2 = str().join(["x", "y"])
104 xx = "xx"
105 yy = "yy"
106 xxx = "xxx"
107
108 assert eq("", str())
109 assert not ne("", str())
110
111 assert eq("x", "x" + str())
112 assert ne("x", "y")
113
114 assert eq(xy, xy)
115 assert eq(xy, xy2)
116 assert not eq(xy, yy)
117 assert ne(xy, xx)
118 assert not ne(xy, xy)
119 assert not ne(xy, xy2)
120
121 assert ne(xx, xxx)
122 assert ne(xxx, xx)
123 assert ne("x", "")
124 assert ne("", "x")
125
126 assert ne("XX", xx)
127 assert ne(yy, xy)
128
129 def test_unicode() -> None:
130 assert eq(chr(200), chr(200) + str())
131 assert ne(chr(200), chr(201))
132
133 assert eq(chr(1234), chr(1234) + str())
134 assert ne(chr(1234), chr(1235))
135
136 assert eq("\U0001f4a9", "\U0001f4a9" + str())
137 assert eq("\U0001f4a9", "\U0001F4A9" + str())
138 assert ne("\U0001f4a9", "\U0002f4a9" + str())
139 assert ne("\U0001f4a9", "\U0001f5a9" + str())
140 assert ne("\U0001f4a9", "\U0001f4a8" + str())
141
142 assert eq("foobar\u1234", "foobar\u1234" + str())
143 assert eq("\u1234foobar", "\u1234foobar" + str())
144 assert ne("foobar\uf234", "foobar\uf235")
145 assert ne("foobar\uf234", "foobar\uf334")
146 assert ne("foobar\u1234", "Foobar\u1234" + str())
147
148 assert eq("foo\U0001f4a9", "foo\U0001f4a9" + str())
149 assert eq("\U0001f4a9foo", "\U0001f4a9foo" + str())
150 assert ne("foo\U0001f4a9", "foo\U0001f4a8" + str())
151 assert ne("\U0001f4a9foo", "\U0001f4a8foo" + str())
152
153 [case testStringOps]
154 from typing import List, Optional, Tuple
155 from testutil import assertRaises
156
157 def do_split(s: str, sep: Optional[str] = None, max_split: Optional[int] = None) -> List[str]:
158 if sep is not None:
159 if max_split is not None:
160 return s.split(sep, max_split)
161 else:
162 return s.split(sep)
163 return s.split()
164
165 def do_rsplit(s: str, sep: Optional[str] = None, max_split: Optional[int] = None) -> List[str]:
166 if sep is not None:
167 if max_split is not None:
168 return s.rsplit(sep, max_split)
169 else:
170 return s.rsplit(sep)
171 return s.rsplit()
172
173 ss = "abc abcd abcde abcdef"
174
175 def test_split() -> None:
176 assert do_split(ss) == ["abc", "abcd", "abcde", "abcdef"]
177 assert do_split(ss, " ") == ["abc", "abcd", "abcde", "abcdef"]
178 assert do_split(ss, "-") == ["abc abcd abcde abcdef"]
179 assert do_split(ss, " ", -1) == ["abc", "abcd", "abcde", "abcdef"]
180 assert do_split(ss, " ", 0) == ["abc abcd abcde abcdef"]
181 assert do_split(ss, " ", 1) == ["abc", "abcd abcde abcdef"]
182 assert do_split(ss, " ", 2) == ["abc", "abcd", "abcde abcdef"]
183
184 def test_rsplit() -> None:
185 assert do_rsplit(ss) == ["abc", "abcd", "abcde", "abcdef"]
186 assert do_rsplit(ss, " ") == ["abc", "abcd", "abcde", "abcdef"]
187 assert do_rsplit(ss, "-") == ["abc abcd abcde abcdef"]
188 assert do_rsplit(ss, " ", -1) == ["abc", "abcd", "abcde", "abcdef"]
189 assert do_rsplit(ss, " ", 0) == ["abc abcd abcde abcdef"]
190 assert do_rsplit(ss, " ", 1) == ["abc abcd abcde", "abcdef"] # different to do_split
191 assert do_rsplit(ss, " ", 2) == ["abc abcd", "abcde", "abcdef"] # different to do_split
192
193 def splitlines(s: str, keepends: Optional[bool] = None) -> List[str]:
194 if keepends is not None:
195 return s.splitlines(keepends)
196 return s.splitlines()
197
198 s_text = "This\nis\n\nsome\nlong\ntext.\n"
199
200 def test_splitlines() -> None:
201 assert splitlines(s_text) == ["This", "is", "", "some", "long", "text."]
202 assert splitlines(s_text, False) == ["This", "is", "", "some", "long", "text."]
203 assert splitlines(s_text, True) == ["This\n", "is\n", "\n", "some\n", "long\n", "text.\n"]
204
205 s_partition = "Some long text"
206
207 def partition(s: str, sep: str) -> Tuple[str, str, str]:
208 return s.partition(sep)
209
210 def rpartition(s: str, sep: str) -> Tuple[str, str, str]:
211 return s.rpartition(sep)
212
213 def test_partition() -> None:
214 assert partition(s_partition, " ") == ("Some", " ", "long text")
215 assert partition(s_partition, "Hello") == ("Some long text", "", "")
216 assert rpartition(s_partition, " ") == ("Some long", " ", "text")
217 assert rpartition(s_partition, "Hello") == ("", "", "Some long text")
218 with assertRaises(ValueError, "empty separator"):
219 partition(s_partition, "")
220 with assertRaises(ValueError, "empty separator"):
221 rpartition(s_partition, "")
222
223 def contains(s: str, o: str) -> bool:
224 return o in s
225
226 def getitem(s: str, index: int) -> str:
227 return s[index]
228
229 def find(s: str, substr: str, start: Optional[int] = None, end: Optional[int] = None) -> int:
230 if start is not None:
231 if end is not None:
232 return s.find(substr, start, end)
233 return s.find(substr, start)
234 return s.find(substr)
235
236 def rfind(s: str, substr: str, start: Optional[int] = None, end: Optional[int] = None) -> int:
237 if start is not None:
238 if end is not None:
239 return s.rfind(substr, start, end)
240 return s.rfind(substr, start)
241 return s.rfind(substr)
242
243 s = "abc"
244
245 def test_contains() -> None:
246 assert contains(s, "a") is True
247 assert contains(s, "abc") is True
248 assert contains(s, "Hello") is False
249 assert contains(s, "bc") is True
250 assert contains(s, "abcd") is False
251 assert contains(s, "bb") is False
252 assert contains(s, "") is True
253 assert contains(s, " ") is False
254
255 def test_getitem() -> None:
256 assert getitem(s, 0) == "a"
257 assert getitem(s, 1) == "b"
258 assert getitem(s, 2) == "c"
259 assert getitem(s, -3) == "a"
260 assert getitem(s, -2) == "b"
261 assert getitem(s, -1) == "c"
262 with assertRaises(IndexError, "string index out of range"):
263 getitem(s, 4)
264 with assertRaises(IndexError, "string index out of range"):
265 getitem(s, -4)
266
267 def test_getitem_unicode() -> None:
268 # ASCII - cached by CPython's Latin-1 table
269 ascii_s = "Hello"
270 assert getitem(ascii_s, 0) == "H"
271 assert getitem(ascii_s, 4) == "o"
272
273 # Latin-1 (>127, <256) - also cached
274 latin1_s = "\xe9\xfc\xf1" # éüñ
275 assert getitem(latin1_s, 0) == "\xe9"
276 assert getitem(latin1_s, 1) == "\xfc"
277 assert getitem(latin1_s, 2) == "\xf1"
278
279 # BMP (>255) - not cached, allocated fresh
280 bmp_s = "\u4e2d\u6587" # δΈ­ζ–‡
281 assert getitem(bmp_s, 0) == "\u4e2d"
282 assert getitem(bmp_s, 1) == "\u6587"
283
284 # Supplementary plane (>65535)
285 emoji_s = "\U0001f600\U0001f601" # πŸ˜€πŸ˜
286 assert getitem(emoji_s, 0) == "\U0001f600"
287 assert getitem(emoji_s, 1) == "\U0001f601"
288
289 # Mixed string with all kinds
290 mixed = "A\xe9\u4e2d\U0001f600"
291 assert getitem(mixed, 0) == "A"
292 assert getitem(mixed, 1) == "\xe9"
293 assert getitem(mixed, 2) == "\u4e2d"
294 assert getitem(mixed, 3) == "\U0001f600"
295
296 # Identity check: ASCII/Latin-1 chars should return cached objects
297 a1 = getitem("abc", 0)
298 a2 = getitem("axyz", 0)
299 assert a1 is a2 # both 'a', should be same cached object
300
301 def test_find() -> None:
302 s = "abcab"
303 assert find(s, "Hello") == -1
304 assert find(s, "abc") == 0
305 assert find(s, "b") == 1
306 assert find(s, "b", 1) == 1
307 assert find(s, "b", 1, 2) == 1
308 assert find(s, "b", 3) == 4
309 assert find(s, "b", 3, 5) == 4
310 assert find(s, "b", 3, 4) == -1
311
312 assert rfind(s, "Hello") == -1
313 assert rfind(s, "abc") == 0
314 assert rfind(s, "b") == 4
315 assert rfind(s, "b", 1) == 4
316 assert rfind(s, "b", 1, 2) == 1
317 assert rfind(s, "b", 3) == 4
318 assert rfind(s, "b", 3, 5) == 4
319 assert rfind(s, "b", 3, 4) == -1
320
321 def str_to_int(s: str, base: Optional[int] = None) -> int:
322 if base:
323 return int(s, base)
324 else:
325 return int(s)
326
327 def test_str_to_int() -> None:
328 assert str_to_int("1") == 1
329 assert str_to_int("10") == 10
330 assert str_to_int("a", 16) == 10
331 assert str_to_int("1a", 16) == 26
332 with assertRaises(ValueError, "invalid literal for int() with base 10: 'xyz'"):
333 str_to_int("xyz")
334
335 def test_slicing() -> None:
336 # Use dummy adds to avoid constant folding
337 zero = int()
338 two = zero + 2
339 s = "foobar" + str()
340 assert s[two:] == "obar"
341 assert s[:two] == "fo"
342 assert s[two:-two] == "ob"
343 assert s[two:two] == ""
344 assert s[two:two + 1] == "o"
345 assert s[-two:] == "ar"
346 assert s[:-two] == "foob"
347 assert s[:] == "foobar"
348 assert s[two:333] == "obar"
349 assert s[333:two] == ""
350 assert s[two:-333] == ""
351 assert s[-333:two] == "fo"
352 big_int: int = 1000 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000
353 assert s[1:big_int] == "oobar"
354 assert s[big_int:] == ""
355 assert s[-big_int:-1] == "fooba"
356
357 def test_str_replace() -> None:
358 a = "foofoofoo"
359 assert a.replace("foo", "bar") == "barbarbar"
360 assert a.replace("foo", "bar", -1) == "barbarbar"
361 assert a.replace("foo", "bar", 1) == "barfoofoo"
362 assert a.replace("foo", "bar", 4) == "barbarbar"
363 assert a.replace("aaa", "bar") == "foofoofoo"
364 assert a.replace("ofo", "xyzw") == "foxyzwxyzwo"
365
366 def is_true(x: str) -> bool:
367 if x:
368 return True
369 else:
370 return False
371
372 def is_true2(x: str) -> bool:
373 return bool(x)
374
375 def is_false(x: str) -> bool:
376 if not x:
377 return True
378 else:
379 return False
380
381 def test_str_to_bool() -> None:
382 assert is_false('')
383 assert not is_true('')
384 assert not is_true2('')
385 for x in 'a', 'foo', 'bar', 'some string':
386 assert is_true(x)
387 assert is_true2(x)
388 assert not is_false(x)
389
390 def test_str_min_max() -> None:
391 x: str = 'aaa'
392 y: str = 'bbb'
393 z: str = 'aa'
394 assert min(x, y) == 'aaa'
395 assert min(x, z) == 'aa'
396 assert max(x, y) == 'bbb'
397 assert max(x, z) == 'aaa'
398
399 def test_multiply() -> None:
400 # Use str() and int() to avoid constant folding
401 s = 'ab' + str()
402 zero = int()
403 one = 1 + zero
404 three = 3 + zero
405 neg_one = -1 + zero
406
407 assert s * zero == ''
408 assert s * one == 'ab'
409 assert s * three == 'ababab'
410 assert s * neg_one == ''
411 assert zero * s == ''
412 assert one * s == 'ab'
413 assert three * s == 'ababab'
414 assert neg_one * s == ''
415
416 # Test with empty string
417 empty = str()
418 five = 5 + zero
419 assert empty * five == ''
420 assert five * empty == ''
421
422 # Test with single character
423 single = 'x' + str()
424 four = 4 + zero
425 assert single * four == 'xxxx'
426 assert four * single == 'xxxx'
427
428 # Test type preservation
429 two = 2 + zero
430 result = s * two
431 assert type(result) == str
432
433 [case testStringFormattingCStyle]
434 from typing import Tuple
435
436 var = 'mypyc'
437 num = 20
438
439 def test_basics() -> None:
440 assert 'Hello %s, this is a test' % var == "Hello mypyc, this is a test"
441 assert 'Hello %s %d, this is a test' % (var, num) == "Hello mypyc 20, this is a test"
442 t: Tuple[str, int] = (var, num)
443 assert 'Hello %s %d, this is a test' % t == "Hello mypyc 20, this is a test"
444
445 large_num = 2**65
446 assert 'number: %d' % large_num == 'number: 36893488147419103232'
447 neg_num = -3
448 assert 'negative integer: %d' % neg_num == 'negative integer: -3'
449 assert 'negative integer: %d' % (-large_num) == 'negative integer: -36893488147419103232'
450
451 bool_var1 = True
452 bool_var2 = False
453 assert 'bool: %s, %s' % (bool_var1, bool_var2) == 'bool: True, False'
454
455 float_num = 123.4
456 assert '%f' % float_num == '123.400000'
457 assert '%.2f' % float_num == '123.40'
458 assert '%.5f' % float_num == '123.40000'
459 assert '%10.2f' % float_num == ' 123.40'
460 assert '%10.5f' % float_num == ' 123.40000'
461 assert '%010.5f' % float_num == '0123.40000'
462 assert '%015.5f' % float_num == '000000123.40000'
463 assert '%e' % float_num == '1.234000e+02'
464 large_float = 1.23e30
465 large_float2 = 1234123412341234123400000000000000000
466 small_float = 1.23e-20
467 assert '%f, %f, %f' % (small_float, large_float, large_float2) == \
468 '0.000000, 1229999999999999959718843908096.000000, 1234123412341234169005079998930878464.000000'
469 assert '%s, %s, %s' % (small_float, large_float, large_float2) == \
470 '1.23e-20, 1.23e+30, 1234123412341234123400000000000000000'
471 assert '%d, %d, %d' % (small_float, large_float, large_float2) == \
472 '0, 1229999999999999959718843908096, 1234123412341234123400000000000000000'
473
474 nan_num = float('nan')
475 inf_num = float('inf')
476 assert '%s, %s' % (nan_num, inf_num) == 'nan, inf'
477 assert '%f, %f' % (nan_num, inf_num) == 'nan, inf'
478 [typing fixtures/typing-full.pyi]
479
480 [case testFStrings]
481 import decimal
482 from datetime import datetime
483 from typing import Final
484
485 var = 'mypyc'
486 num = 20
487 final_known_at_compile_time: Final = 'hello'
488
489 def final_value_setter() -> str:
490 return 'goodbye'
491
492 final_unknown_at_compile_time: Final = final_value_setter()
493
494 def test_fstring_basics() -> None:
495 assert f'Hello {var}, this is a test' == "Hello mypyc, this is a test"
496
497 large_num = 2**65
498 assert f'number: {large_num}' == 'number: 36893488147419103232'
499 neg_num = -3
500 assert f'negative integer: {neg_num}' == 'negative integer: -3'
501 assert f'negative integer: {-large_num}' == 'negative integer: -36893488147419103232'
502
503 bool_var1 = True
504 bool_var2 = False
505 assert f'bool: {bool_var1}, {bool_var2}' == 'bool: True, False'
506
507 x = bytes([1, 2, 3, 4])
508 # assert f'bytes: {x}' == "bytes: b'\\x01\\x02\\x03\\x04'"
509 # error: If x = b'abc' then f"{x}" or "{}".format(x) produces "b'abc'", not "abc". If this is desired behavior, use f"{x!r}" or "{!r}".format(x). Otherwise, decode the bytes
510
511 float_num = 123.4
512 assert f'{float_num}' == '123.4'
513 assert f'{float_num:.2f}' == '123.40'
514 assert f'{float_num:.5f}' == '123.40000'
515 assert f'{float_num:>10.2f}' == ' 123.40'
516 assert f'{float_num:>10.5f}' == ' 123.40000'
517 assert f'{float_num:>010.5f}' == '0123.40000'
518 assert f'{float_num:>015.5f}' == '000000123.40000'
519 assert f'{float_num:e}' == '1.234000e+02'
520
521 large_float = 1.23e30
522 large_float2 = 1234123412341234123400000000000000000
523 small_float = 1.23e-20
524 assert f'{small_float}, {large_float}, {large_float2}' == '1.23e-20, 1.23e+30, 1234123412341234123400000000000000000'
525 nan_num = float('nan')
526 inf_num = float('inf')
527 assert f'{nan_num}, {inf_num}' == 'nan, inf'
528
529 assert f'{final_known_at_compile_time} {final_unknown_at_compile_time}' == 'hello goodbye'
530
531 # F-strings would be translated into ''.join[string literals, format method call, ...] in mypy AST.
532 # Currently we are using a str.join specializer for f-string speed up. We might not cover all cases
533 # and the rest ones should fall back to a normal str.join method call.
534 # TODO: Once we have a new pipeline for f-strings, this test case can be moved to testStringOps.
535 def test_str_join() -> None:
536 var = 'mypyc'
537 num = 10
538 assert ''.join(['a', 'b', '{}'.format(var), 'c']) == 'abmypycc'
539 assert ''.join(['a', 'b', '{:{}}'.format(var, ''), 'c']) == 'abmypycc'
540 assert ''.join(['a', 'b', '{:{}}'.format(var, '>10'), 'c']) == 'ab mypycc'
541 assert ''.join(['a', 'b', '{:{}}'.format(var, '>{}'.format(num)), 'c']) == 'ab mypycc'
542 assert var.join(['a', '{:{}}'.format(var, ''), 'b']) == 'amypycmypycmypycb'
543 assert ','.join(['a', '{:{}}'.format(var, ''), 'b']) == 'a,mypyc,b'
544 assert ''.join(['x', var]) == 'xmypyc'
545
546 class A:
547 def __init__(self, name, age):
548 self.name = name
549 self.age = age
550
551 def __repr__(self):
552 return f'{self.name} is {self.age} years old.'
553
554 def test_fstring_datatype() -> None:
555 u = A('John Doe', 14)
556 assert f'{u}' == 'John Doe is 14 years old.'
557 d = {'name': 'John Doe', 'age': 14}
558 assert f'{d}' == "{'name': 'John Doe', 'age': 14}"
559
560 def test_fstring_escape() -> None:
561 assert f"{'inside'}" == 'inside'
562 assert f'{"inside"}' == 'inside'
563 assert f"""inside""" == 'inside'
564 assert f'''inside''' == 'inside'
565 assert f"\"{'inside'}\"" == '"inside"'
566 assert f'\'{"inside"}\'' == "'inside'"
567
568 assert f'{{10}}' == '{10}'
569 assert f'{{10 + 10}}' == '{10 + 10}'
570 assert f'{{{10 + 10}}}' == '{20}'
571 assert f'{{{{10 + 10}}}}' == '{{10 + 10}}'
572
573 def test_fstring_conversion() -> None:
574 assert f'Hello {var!r}' == "Hello 'mypyc'"
575 # repr() is equivalent to !r
576 assert f'Hello {repr(var)}' == "Hello 'mypyc'"
577
578 assert f'Hello {var!a}' == "Hello 'mypyc'"
579 # ascii() is equivalent to !a
580 assert f'Hello {ascii(var)}' == "Hello 'mypyc'"
581
582 tmp_str = """this
583 is a new line."""
584 assert f'Test: {tmp_str!a}' == "Test: 'this\\n is a new line.'"
585
586 s = 'test: ΔΔ€Δ“Δ’ΔΔŒ..Ε‘Ε Ε«ΕͺΕΎΕ½'
587 assert f'{s}' == 'test: ΔΔ€Δ“Δ’ΔΔŒ..Ε‘Ε Ε«ΕͺΕΎΕ½'
588 assert f'{s!a}' == "'test: \\u0101\\u0100\\u0113\\u0112\\u010d\\u010c..\\u0161\\u0160\\u016b\\u016a\\u017e\\u017d'"
589
590 assert f'Hello {var!s}' == 'Hello mypyc'
591 assert f'Hello {num!s}' == 'Hello 20'
592
593 def test_fstring_align() -> None:
594 assert f'Hello {var:>20}' == "Hello mypyc"
595 assert f'Hello {var!r:>20}' == "Hello 'mypyc'"
596 assert f'Hello {var:>{num}}' == "Hello mypyc"
597 assert f'Hello {var!r:>{num}}' == "Hello 'mypyc'"
598
599 def test_fstring_multi() -> None:
600 assert f'Hello {var}, hello again {var}' == "Hello mypyc, hello again mypyc"
601 a = 'py'
602 s = f'my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}'
603 assert s == 'mypymypymypymypymypymypymypymypymypymypymypymypymypymypymypymypymypymypymypymypymypymypymypymypy'
604
605 def test_fstring_python_doc() -> None:
606 name = 'Fred'
607 assert f"He said his name is {name!r}." == "He said his name is 'Fred'."
608 assert f"He said his name is {repr(name)}." == "He said his name is 'Fred'."
609
610 width = 10
611 precision = 4
612 value = decimal.Decimal('12.34567')
613 assert f'result: {value:{width}.{precision}}' == 'result: 12.35' # nested field
614
615 today = datetime(year=2017, month=1, day=27)
616 assert f'{today:%B %d, %Y}' == 'January 27, 2017' # using date format specifier
617
618 number = 1024
619 assert f'{number:#0x}' == '0x400' # using integer format specifier
620
621 [case testStringFormatMethod]
622 from typing import Tuple
623
624 def test_format_method_basics() -> None:
625 x = str()
626 assert 'x{}'.format(x) == 'x'
627 assert 'ā{}'.format(x) == 'ā'
628 assert 'πŸ˜€{}'.format(x) == 'πŸ˜€'
629 assert ''.format() == ''
630 assert 'abc'.format() == 'abc'
631 assert '{}{}'.format(1, 2) == '12'
632
633 name = 'Eric'
634 age = 14
635 assert "My name is {name}, I'm {age}.".format(name=name, age=age) == "My name is Eric, I'm 14."
636 assert "My name is {A}, I'm {B}.".format(A=name, B=age) == "My name is Eric, I'm 14."
637 assert "My name is {}, I'm {B}.".format(name, B=age) == "My name is Eric, I'm 14."
638
639 bool_var1 = True
640 bool_var2 = False
641 assert 'bool: {}, {}'.format(bool_var1, bool_var2) == 'bool: True, False'
642
643 def test_format_method_empty_braces() -> None:
644 name = 'Eric'
645 age = 14
646
647 assert 'Hello, {}!'.format(name) == 'Hello, Eric!'
648 assert '{}'.format(name) == 'Eric'
649 assert '{}! Hi!'.format(name) == 'Eric! Hi!'
650 assert '{}, Hi, {}'.format(name, name) == 'Eric, Hi, Eric'
651 assert 'Hi! {}'.format(name) == 'Hi! Eric'
652 assert "Hi, I'm {}. I'm {}.".format(name, age) == "Hi, I'm Eric. I'm 14."
653
654 assert '{{}}'.format() == '{}'
655 assert '{{{{}}}}'.format() == '{{}}'
656 assert '{{}}{}'.format(name) == '{}Eric'
657 assert 'Hi! {{{}}}'.format(name) == 'Hi! {Eric}'
658 assert 'Hi! {{ {}'.format(name) == 'Hi! { Eric'
659 assert 'Hi! {{ {} }}}}'.format(name) == 'Hi! { Eric }}'
660
661 def test_format_method_numbers() -> None:
662 s = 'int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}'.format(-233)
663 assert s == 'int: -233; hex: -e9; oct: -351; bin: -11101001'
664 num = 2**65
665 s = 'int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}'.format(num)
666 assert s == 'int: 36893488147419103232; hex: 20000000000000000; oct: 4000000000000000000000; bin: 100000000000000000000000000000000000000000000000000000000000000000'
667 s = 'int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}'.format(-num)
668 assert s == 'int: -36893488147419103232; hex: -20000000000000000; oct: -4000000000000000000000; bin: -100000000000000000000000000000000000000000000000000000000000000000'
669
670 large_num = 2**65
671 assert 'number: {}'.format(large_num) == 'number: 36893488147419103232'
672 neg_num = -3
673 assert 'negative integer: {}'.format(neg_num) == 'negative integer: -3'
674 assert 'negative integer: {}'.format(-large_num) == 'negative integer: -36893488147419103232'
675
676 large_float = 1.23e30
677 large_float2 = 1234123412341234123400000000000000000
678 small_float = 1.23e-20
679 assert '{}, {}, {}'.format(small_float, large_float, large_float2) == '1.23e-20, 1.23e+30, 1234123412341234123400000000000000000'
680 nan_num = float('nan')
681 inf_num = float('inf')
682 assert '{}, {}'.format(nan_num, inf_num) == 'nan, inf'
683
684 def format_args(*args: int) -> str:
685 return 'x{}y{}'.format(*args)
686 def format_kwargs(**kwargs: int) -> str:
687 return 'c{x}d{y}'.format(**kwargs)
688 def format_args_self(*args: int) -> str:
689 return '{}'.format(args)
690 def format_kwargs_self(**kwargs: int) -> str:
691 return '{}'.format(kwargs)
692
693 def test_format_method_args() -> None:
694 assert format_args(10, 2) == 'x10y2'
695 assert format_args_self(10, 2) == '(10, 2)'
696 assert format_kwargs(x=10, y=2) == 'c10d2'
697 assert format_kwargs(x=10, y=2, z=1) == 'c10d2'
698 assert format_kwargs_self(x=10, y=2, z=1) == "{'x': 10, 'y': 2, 'z': 1}"
699
700 def test_format_method_different_kind() -> None:
701 s1 = "Literal['πŸ˜€']"
702 assert 'Revealed type is {}'.format(s1) == "Revealed type is Literal['πŸ˜€']"
703 s2 = "Revealed type is"
704 assert "{} Literal['πŸ˜€']".format(s2) == "Revealed type is Literal['πŸ˜€']"
705 s3 = "ζ΅‹θ―•οΌš"
706 assert "{}{} {}".format(s3, s2, s1) == "ζ΅‹θ―•οΌšRevealed type is Literal['πŸ˜€']"
707 assert "Test: {}{}".format(s3, s1) == "Test: ζ΅‹θ―•οΌšLiteral['πŸ˜€']"
708 assert "Test: {}{}".format(s3, s2) == "Test: ζ΅‹θ―•οΌšRevealed type is"
709
710 def test_format_method_nested() -> None:
711 var = 'mypyc'
712 num = 10
713 assert '{:{}}'.format(var, '') == 'mypyc'
714 assert '{:{}}'.format(var, '>10') == ' mypyc'
715 assert '{:{}}'.format(var, '>{}'.format(num)) == ' mypyc'
716
717 class Point:
718 def __init__(self, x, y):
719 self.x, self.y = x, y
720 def __str__(self):
721 return 'Point({self.x}, {self.y})'.format(self=self)
722
723 # Format examples from Python doc
724 # https://docs.python.org/3/library/string.html#formatexamples
725 def test_format_method_python_doc() -> None:
726 # Accessing arguments by position:
727 assert '{0}, {1}, {2}'.format('a', 'b', 'c') == 'a, b, c'
728 assert '{}, {}, {}'.format('a', 'b', 'c') == 'a, b, c'
729 assert '{2}, {1}, {0}'.format('a', 'b', 'c') == 'c, b, a'
730 assert '{2}, {1}, {0}'.format(*'abc') == 'c, b, a' # unpacking argument sequence
731 # assert '{0}{1}{0}'.format('abra', 'cad') = 'abracadabra' # arguments' indices can be repeated
732
733 # Accessing arguments by name:
734 s = 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
735 assert s == 'Coordinates: 37.24N, -115.81W'
736 coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
737 assert 'Coordinates: {latitude}, {longitude}'.format(**coord) == 'Coordinates: 37.24N, -115.81W'
738
739 # Accessing arguments’ attributes:
740 assert str(Point(4, 2)) == 'Point(4, 2)'
741
742 # Accessing arguments’ items:
743 coord2 = (3, 5)
744 assert 'X: {0[0]}; Y: {0[1]}'.format(coord2) == 'X: 3; Y: 5'
745
746 # Replacing %s and %r:
747 s = "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
748 assert s == "repr() shows quotes: 'test1'; str() doesn't: test2"
749
750 # Aligning the text and specifying a width:
751 assert '{:<30}'.format('left aligned') == 'left aligned '
752 assert '{:>30}'.format('right aligned') == ' right aligned'
753 assert '{:^30}'.format('centered') == ' centered '
754 assert '{:*^30}'.format('centered') == '***********centered***********' # use '*' as a fill char
755
756 # Replacing %+f, %-f, and % f and specifying a sign:
757 assert '{:+f}; {:+f}'.format(3.14, -3.14) == '+3.140000; -3.140000' # show it always
758 assert '{: f}; {: f}'.format(3.14, -3.14) == ' 3.140000; -3.140000' # show a space for positive numbers
759 assert '{:-f}; {:-f}'.format(3.14, -3.14) == '3.140000; -3.140000' # show only the minus -- same as '{:f}; {:f}'
760
761 # Replacing %x and %o and converting the value to different bases:
762 s = 'int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}'.format(42) # format also supports binary numbers
763 assert s == 'int: 42; hex: 2a; oct: 52; bin: 101010'
764 s = 'int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}'.format(42) # with 0x, 0o, or 0b as prefix:
765 assert s == 'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
766
767 # Using the comma as a thousands separator:
768 assert '{:,}'.format(1234567890) == '1,234,567,890'
769
770 # Expressing a percentage:
771 points = 19.0
772 total = 22.0
773 assert 'Correct answers: {:.2%}'.format(points/total) == 'Correct answers: 86.36%'
774
775 # Using type-specific formatting:
776 import datetime
777 d = datetime.datetime(2010, 7, 4, 12, 15, 58)
778 assert '{:%Y-%m-%d %H:%M:%S}'.format(d) == '2010-07-04 12:15:58'
779
780 # Nesting arguments and more complex examples:
781 tmp_strs = []
782 for align, text in zip('<^>', ['left', 'center', 'right']):
783 tmp_strs.append('{0:{fill}{align}16}'.format(text, fill=align, align=align))
784 assert tmp_strs == ['left<<<<<<<<<<<<', '^^^^^center^^^^^', '>>>>>>>>>>>right']
785
786 octets = [192, 168, 0, 1]
787 assert '{:02X}{:02X}{:02X}{:02X}'.format(*octets) == 'C0A80001'
788
789 width = 5
790 tmp_strs = []
791 for num in range(5,12):
792 tmp_str = ''
793 for base in 'dXob':
794 tmp_str += ('{0:{width}{base}}'.format(num, base=base, width=width))
795 tmp_strs.append(tmp_str)
796 assert tmp_strs == [' 5 5 5 101',\
797 ' 6 6 6 110',\
798 ' 7 7 7 111',\
799 ' 8 8 10 1000',\
800 ' 9 9 11 1001',\
801 ' 10 A 12 1010',\
802 ' 11 B 13 1011']
803
804 [case testChr]
805 # Some test cases are from https://docs.python.org/3/howto/unicode.html
806
807 def try_invalid(x: int) -> bool:
808 try:
809 chr(x + int())
810 return False
811 except ValueError:
812 return True
813
814 def test_chr() -> None:
815 assert chr(57344) == '\ue000'
816 assert chr(0) == '\x00'
817 assert chr(65) == 'A'
818 assert chr(150) == '\x96'
819 try:
820 chr(-1)
821 assert False
822 except ValueError:
823 pass
824 try:
825 chr(1114112)
826 assert False
827 except ValueError:
828 pass
829 assert chr(1114111) == '\U0010ffff'
830 x = 0
831 assert chr(x + int()) == '\x00'
832 x = 100
833 assert chr(x + int()) == 'd'
834 x = 150
835 assert chr(x + int()) == '\x96'
836 x = 257
837 assert chr(x + int()) == 'ā'
838 x = 65537
839 assert chr(x + int()) == '𐀁'
840 assert try_invalid(-1)
841 assert try_invalid(1114112)
842
843 [case testOrd]
844 from testutil import assertRaises
845 from mypy_extensions import i64, i32, i16, u8
846
847 def test_ord() -> None:
848 assert ord(' ') == 32
849 assert ord(' ' + str()) == 32
850 assert ord('\x00') == 0
851 assert ord('\x00' + str()) == 0
852 assert ord('\ue000') == 57344
853 assert ord('\ue000' + str()) == 57344
854 s = "a\xac\u1234\u20ac\U00010000"
855 # ^^^^ two-digit hex escape
856 # ^^^^^^ four-digit Unicode escape
857 # ^^^^^^^^^^ eight-digit Unicode escape
858 l1 = [ord(c) for c in s]
859 assert l1 == [97, 172, 4660, 8364, 65536]
860 u = 'abcdΓ©'
861 assert ord(u[-1]) == 233
862 assert ord(b'a') == 97
863 assert ord(b'a' + bytes()) == 97
864 u2 = '\U0010ffff' + str()
865 assert ord(u2) == 1114111
866 assert ord('\U0010ffff') == 1114111
867 with assertRaises(TypeError, "ord() expected a character, but a string of length 2 found"):
868 ord('aa')
869 with assertRaises(TypeError):
870 ord('')
871
872 def test_ord_str_index() -> None:
873 # ASCII
874 s1 = "hello"
875 assert ord(s1[0 + int()]) == 104 # 'h'
876 assert ord(s1[1 + int()]) == 101 # 'e'
877 assert ord(s1[4 + int()]) == 111 # 'o'
878 assert ord(s1[-1 + int()]) == 111 # 'o'
879 assert ord(s1[-5 + int()]) == 104 # 'h'
880
881 # Latin-1 (8 bits)
882 s2 = "cafΓ©"
883 assert ord(s2[0 + int()]) == 99 # 'c'
884 assert ord(s2[3 + int()]) == 233 # 'Γ©' (U+00E9)
885 assert ord(s2[-1 + int()]) == 233
886
887 # 16-bit unicode
888 s3 = "δ½ ε₯½" # Chinese
889 assert ord(s3[0 + int()]) == 20320 # 'δ½ ' (U+4F60)
890 assert ord(s3[1 + int()]) == 22909 # 'ε₯½' (U+597D)
891 assert ord(s3[-1 + int()]) == 22909
892 assert ord(s3[-2 + int()]) == 20320
893
894 # 4-byte unicode
895 s5 = "aπŸ˜€b" # Emoji between ASCII chars
896 assert ord(s5[0 + int()]) == 97 # 'a'
897 assert ord(s5[1 + int()]) == 128512 # 'πŸ˜€' (U+1F600)
898 assert ord(s5[2 + int()]) == 98 # 'b'
899 assert ord(s5[-1 + int()]) == 98
900 assert ord(s5[-2 + int()]) == 128512
901 assert ord(s5[-3 + int()]) == 97
902
903 with assertRaises(IndexError, "index out of range"):
904 ord(s1[5 + int()])
905 with assertRaises(IndexError, "index out of range"):
906 ord(s1[100 + int()])
907 with assertRaises(IndexError, "index out of range"):
908 ord(s1[-6 + int()])
909 with assertRaises(IndexError, "index out of range"):
910 ord(s1[-100 + int()])
911
912 s_empty = ""
913 with assertRaises(IndexError, "index out of range"):
914 ord(s_empty[0 + int()])
915 with assertRaises(IndexError, "index out of range"):
916 ord(s_empty[-1 + int()])
917
918 def test_ord_str_index_i64() -> None:
919 s = "hello"
920
921 idx_i64: i64 = 2 + int()
922 assert ord(s[idx_i64]) == 108 # 'l'
923
924 idx_i64_neg: i64 = -1 + int()
925 assert ord(s[idx_i64_neg]) == 111 # 'o'
926
927 idx_overflow: i64 = 10 + int()
928 with assertRaises(IndexError, "index out of range"):
929 ord(s[idx_overflow])
930
931 idx_underflow: i64 = -10 + int()
932 with assertRaises(IndexError, "index out of range"):
933 ord(s[idx_underflow])
934
935 def test_ord_str_index_unicode_mix() -> None:
936 # Mix of 1-byte, 2-byte, 3-byte, and 4-byte characters
937 s = "a\u00e9\u4f60πŸ˜€" # 'a', 'Γ©', 'δ½ ', 'πŸ˜€'
938 assert ord(s[0 + int()]) == 97 # 1-byte
939 assert ord(s[1 + int()]) == 233 # 2-byte
940 assert ord(s[2 + int()]) == 20320 # 3-byte
941 assert ord(s[3 + int()]) == 128512 # 4-byte
942
943 def test_ord_str_index_to_fixed_width() -> None:
944 # Test i32 coercion (signed 32-bit: -2^31 to 2^31-1)
945 # All valid Unicode code points fit in i32, so test min/max boundaries
946 s_i32_min = chr(0)
947 assert i32(ord(s_i32_min[0 + int()])) == 0
948
949 s_i32_max = chr(0x10FFFF) # Max Unicode code point
950 assert i32(ord(s_i32_max[0 + int()])) == 0x10FFFF
951
952 # Test i16 coercion (signed 16-bit: -2^15 to 2^15-1, i.e., -32768 to 32767)
953 # ord() returns non-negative, so test 0 to 32767
954 s_i16_min = chr(0)
955 assert i16(ord(s_i16_min[0 + int()])) == 0
956
957 s_i16_max = chr(32767) # 2^15 - 1
958 assert i16(ord(s_i16_max[0 + int()])) == 32767
959
960 s_i16_overflow = chr(32768) # 2^15
961 with assertRaises(ValueError, "int too large to convert to i16"):
962 i16(ord(s_i16_overflow[0 + int()]))
963
964 s_i16_overflow2 = chr(32769) # 2^15 + 1
965 with assertRaises(ValueError, "int too large to convert to i16"):
966 i16(ord(s_i16_overflow2[0 + int()]))
967
968 # Test u8 coercion (unsigned 8-bit: 0 to 2^8-1, i.e., 0 to 255)
969 s_u8_min = chr(0)
970 assert u8(ord(s_u8_min[0 + int()])) == 0
971
972 s_u8_max = chr(255)
973 assert u8(ord(s_u8_max[0 + int()])) == 255
974
975 s_u8_overflow = chr(256)
976 with assertRaises(ValueError, "int too large or small to convert to u8"):
977 u8(ord(s_u8_overflow[0 + int()]))
978
979 s_u8_overflow2 = chr(257)
980 with assertRaises(ValueError, "int too large or small to convert to u8"):
981 u8(ord(s_u8_overflow2[0 + int()]))
982
983 [case testDecode]
984 from testutil import assertRaises
985
986 def test_decode() -> None:
987 assert "\N{GREEK CAPITAL LETTER DELTA}" == '\u0394'
988 assert "\u0394" == "\u0394"
989 assert "\U00000394" == '\u0394'
990 assert b'\x80abc'.decode('utf-8', 'replace') == '\ufffdabc'
991 assert b'\x80abc'.decode('utf-8', 'backslashreplace') == '\\x80abc'
992 assert b''.decode() == ''
993 assert b'a'.decode() == 'a'
994 assert b'abc'.decode() == 'abc'
995 assert b'abc'.decode('utf-8') == 'abc'
996 assert b'abc'.decode('utf-8' + str()) == 'abc'
997 assert b'abc\x00\xce'.decode('latin-1') == 'abc\x00\xce'
998 assert b'abc\x00\xce'.decode('latin-1' + str()) == 'abc\x00\xce'
999 assert b'abc\x00\x7f'.decode('ascii') == 'abc\x00\x7f'
1000 assert b'abc\x00\x7f'.decode('ascii' + str()) == 'abc\x00\x7f'
1001 assert b'\x80abc'.decode('utf-8', 'ignore') == 'abc'
1002 assert b'\x80abc'.decode('UTF-8', 'ignore') == 'abc'
1003 assert b'\x80abc'.decode('Utf-8', 'ignore') == 'abc'
1004 assert b'\x80abc'.decode('utf_8', 'ignore') == 'abc'
1005 assert b'\x80abc'.decode('latin1', 'ignore') == '\x80abc'
1006 assert b'\xd2\xbb\xb6\xfe\xc8\xfd'.decode('gbk', 'ignore') == 'δΈ€δΊŒδΈ‰'
1007 assert b'\xd2\xbb\xb6\xfe\xc8\xfd'.decode('latin1', 'ignore') == 'Γ’Β»ΒΆΓΎΓˆΓ½'
1008 assert b'Z\xc3\xbcrich'.decode("utf-8") == 'ZΓΌrich'
1009 assert b'Z\xc3\xbcrich'.decode("utf-8" + str()) == 'ZΓΌrich'
1010
1011 assert bytearray(range(5)).decode() == '\x00\x01\x02\x03\x04'
1012 b = bytearray(b'\xe4\xbd\xa0\xe5\xa5\xbd')
1013 assert b.decode() == 'δ½ ε₯½'
1014 assert b.decode('gbk') == 'ζ΅£ηŠ²γ‚½'
1015 assert b.decode('latin1') == 'À½\xa0Γ₯Β₯Β½'
1016 assert b.decode('latin1' + str()) == 'À½\xa0Γ₯Β₯Β½'
1017
1018 def test_decode_error() -> None:
1019 try:
1020 b'Z\xc3\xbcrich'.decode('ascii')
1021 assert False
1022 except UnicodeDecodeError:
1023 pass
1024 try:
1025 b'Z\xc3\xbcrich'.decode('ascii' + str())
1026 assert False
1027 except UnicodeDecodeError:
1028 pass
1029 try:
1030 b'Z\xc3y'.decode('utf8')
1031 assert False
1032 except UnicodeDecodeError:
1033 pass
1034 try:
1035 b'Z\xc3y'.decode('utf8' + str())
1036 assert False
1037 except UnicodeDecodeError:
1038 pass
1039
1040 def test_decode_bytearray() -> None:
1041 b = bytearray(b'foo\x00bar')
1042 assert b.decode() == 'foo\x00bar'
1043 assert b.decode('utf-8') == 'foo\x00bar'
1044 assert b.decode('latin-1') == 'foo\x00bar'
1045 assert b.decode('ascii') == 'foo\x00bar'
1046 assert b.decode('utf-8' + str()) == 'foo\x00bar'
1047 assert b.decode('latin-1' + str()) == 'foo\x00bar'
1048 assert b.decode('ascii' + str()) == 'foo\x00bar'
1049 b2 = bytearray(b'foo\x00bar\xbe')
1050 assert b2.decode('latin-1') == 'foo\x00bar\xbe'
1051 with assertRaises(UnicodeDecodeError):
1052 b2.decode('ascii')
1053 with assertRaises(UnicodeDecodeError):
1054 b2.decode('ascii' + str())
1055 with assertRaises(UnicodeDecodeError):
1056 b2.decode('utf-8')
1057 with assertRaises(UnicodeDecodeError):
1058 b2.decode('utf-8' + str())
1059 b3 = bytearray(b'Z\xc3\xbcrich')
1060 assert b3.decode("utf-8") == 'ZΓΌrich'
1061
1062 def test_invalid_encoding() -> None:
1063 try:
1064 b"foo".decode("ut-f-8")
1065 assert False
1066 except Exception as e:
1067 assert repr(e).startswith("LookupError")
1068 try:
1069 encoding = "ut-f-8"
1070 b"foo".decode(encoding)
1071 assert False
1072 except Exception as e:
1073 assert repr(e).startswith("LookupError")
1074
1075 [case testEncode]
1076 from testutil import assertRaises
1077
1078 def test_encode() -> None:
1079 u = chr(40960) + 'abcd' + chr(1972)
1080 assert u.encode() == b'\xea\x80\x80abcd\xde\xb4'
1081 assert u.encode('utf-8') == b'\xea\x80\x80abcd\xde\xb4'
1082 with assertRaises(UnicodeEncodeError):
1083 u.encode('ascii')
1084 with assertRaises(LookupError):
1085 u.encode('aaa')
1086 assert u.encode('utf-8', 'aaaaaa') == b'\xea\x80\x80abcd\xde\xb4'
1087 assert u.encode('ascii', 'ignore') == b'abcd'
1088 assert u.encode('ASCII', 'ignore') == b'abcd'
1089 assert u.encode('ascii', 'replace') == b'?abcd?'
1090 assert u.encode('ascii', 'xmlcharrefreplace') == b'&#40960;abcd&#1972;'
1091 assert u.encode('ascii', 'backslashreplace') == b'\\ua000abcd\\u07b4'
1092 assert u.encode('ascii', 'namereplace') == b'\\N{YI SYLLABLE IT}abcd\\u07b4'
1093 assert 'pythΓΆn!'.encode() == b'pyth\xc3\xb6n!'
1094 assert 'δΈ€δΊŒδΈ‰'.encode('gbk') == b'\xd2\xbb\xb6\xfe\xc8\xfd'
1095 assert u.encode('UTF-8', 'ignore') == b'\xea\x80\x80abcd\xde\xb4'
1096 assert u.encode('Utf_8') == b'\xea\x80\x80abcd\xde\xb4'
1097 assert u.encode('UTF_8') == b'\xea\x80\x80abcd\xde\xb4'
1098 assert u'\u00E1'.encode('latin1') == b'\xe1'
1099 with assertRaises(UnicodeEncodeError):
1100 u.encode('latin1')
1101
1102 [case testUnicodeSurrogate]
1103 def f() -> str:
1104 return "\ud800"
1105
1106 def test_surrogate() -> None:
1107 assert ord(f()) == 0xd800
1108 assert ord("\udfff") == 0xdfff
1109 assert repr("foobar\x00\xab\ud912\U00012345") == r"'foobar\x00Β«\ud912𒍅'"
1110
1111 [case testStrip]
1112 def test_all_strips_default() -> None:
1113 s = " a1\t"
1114 assert s.lstrip() == "a1\t"
1115 assert s.strip() == "a1"
1116 assert s.rstrip() == " a1"
1117 def test_all_strips() -> None:
1118 s = "xxb2yy"
1119 assert s.lstrip("xy") == "b2yy"
1120 assert s.strip("xy") == "b2"
1121 assert s.rstrip("xy") == "xxb2"
1122 def test_unicode_whitespace() -> None:
1123 assert "\u200A\u000D\u2009\u2020\u000Dtt\u0085\u000A".strip() == "\u2020\u000Dtt"
1124 def test_unicode_range() -> None:
1125 assert "\u2029 \U00107581 ".lstrip() == "\U00107581 "
1126 assert "\u2029 \U0010AAAA\U00104444B\u205F ".strip() == "\U0010AAAA\U00104444B"
1127 assert " \u3000\u205F ".strip() == ""
1128 assert "\u2029 \U00102865\u205F ".rstrip() == "\u2029 \U00102865"
1129
1130 [case testCount]
1131 # mypy: disable-error-code="attr-defined"
1132 def test_count() -> None:
1133 string = "abcbcb"
1134 assert string.count("a") == 1
1135 assert string.count("b") == 3
1136 assert string.count("c") == 2
1137 def test_count_start() -> None:
1138 string = "abcbcb"
1139 assert string.count("a", 2) == string.count("a", -4) == 0, (string.count("a", 2), string.count("a", -4))
1140 assert string.count("b", 2) == string.count("b", -4) == 2, (string.count("b", 2), string.count("b", -4))
1141 assert string.count("c", 2) == string.count("c", -4) == 2, (string.count("c", 2), string.count("c", -4))
1142 # out of bounds
1143 assert string.count("a", 8) == 0
1144 assert string.count("a", -8) == 1
1145 assert string.count("b", 8) == 0
1146 assert string.count("b", -8) == 3
1147 assert string.count("c", 8) == 0
1148 assert string.count("c", -8) == 2
1149 def test_count_start_end() -> None:
1150 string = "abcbcb"
1151 assert string.count("a", 0, 4) == 1, string.count("a", 0, 4)
1152 assert string.count("b", 0, 4) == 2, string.count("b", 0, 4)
1153 assert string.count("c", 0, 4) == 1, string.count("c", 0, 4)
1154 def test_count_multi() -> None:
1155 string = "aaabbbcccbbbcccbbb"
1156 assert string.count("aaa") == 1, string.count("aaa")
1157 assert string.count("bbb") == 3, string.count("bbb")
1158 assert string.count("ccc") == 2, string.count("ccc")
1159 def test_count_multi_start() -> None:
1160 string = "aaabbbcccbbbcccbbb"
1161 assert string.count("aaa", 6) == string.count("aaa", -12) == 0, (string.count("aaa", 6), string.count("aaa", -12))
1162 assert string.count("bbb", 6) == string.count("bbb", -12) == 2, (string.count("bbb", 6), string.count("bbb", -12))
1163 assert string.count("ccc", 6) == string.count("ccc", -12) == 2, (string.count("ccc", 6), string.count("ccc", -12))
1164 # out of bounds
1165 assert string.count("aaa", 20) == 0
1166 assert string.count("aaa", -20) == 1
1167 assert string.count("bbb", 20) == 0
1168 assert string.count("bbb", -20) == 3
1169 assert string.count("ccc", 20) == 0
1170 assert string.count("ccc", -20) == 2
1171 def test_count_multi_start_end() -> None:
1172 string = "aaabbbcccbbbcccbbb"
1173 assert string.count("aaa", 0, 12) == 1, string.count("aaa", 0, 12)
1174 assert string.count("bbb", 0, 12) == 2, string.count("bbb", 0, 12)
1175 assert string.count("ccc", 0, 12) == 1, string.count("ccc", 0, 12)
1176 def test_count_emoji() -> None:
1177 string = "πŸ˜΄πŸš€Γ±πŸš€Γ±πŸš€"
1178 assert string.count("😴") == 1, string.count("😴")
1179 assert string.count("πŸš€") == 3, string.count("πŸš€")
1180 assert string.count("Γ±") == 2, string.count("Γ±")
1181 def test_count_start_emoji() -> None:
1182 string = "πŸ˜΄πŸš€Γ±πŸš€Γ±πŸš€"
1183 assert string.count("😴", 2) == string.count("😴", -4) == 0, (string.count("😴", 2), string.count("😴", -4))
1184 assert string.count("πŸš€", 2) == string.count("πŸš€", -4) == 2, (string.count("πŸš€", 2), string.count("πŸš€", -4))
1185 assert string.count("Γ±", 2) == string.count("Γ±", -4) == 2, (string.count("Γ±", 2), string.count("Γ±", -4))
1186 # Out of bounds
1187 assert string.count("😴", 8) == 0, string.count("😴", 8)
1188 assert string.count("😴", -8) == 1, string.count("😴", -8)
1189 assert string.count("πŸš€", 8) == 0, string.count("πŸš€", 8)
1190 assert string.count("πŸš€", -8) == 3, string.count("πŸš€", -8)
1191 assert string.count("Γ±", 8) == 0, string.count("Γ±", 8)
1192 assert string.count("Γ±", -8) == 2, string.count("Γ±", -8)
1193 def test_count_start_end_emoji() -> None:
1194 string = "πŸ˜΄πŸš€Γ±πŸš€Γ±πŸš€"
1195 assert string.count("😴", 0, 4) == 1, string.count("😴", 0, 4)
1196 assert string.count("πŸš€", 0, 4) == 2, string.count("πŸš€", 0, 4)
1197 assert string.count("Γ±", 0, 4) == 1, string.count("Γ±", 0, 4)
1198 def test_count_multi_emoji() -> None:
1199 string = "πŸ˜΄πŸ˜΄πŸ˜΄πŸš€πŸš€πŸš€Γ±Γ±Γ±πŸš€πŸš€πŸš€Γ±Γ±Γ±πŸš€πŸš€πŸš€"
1200 assert string.count("😴😴😴") == 1, string.count("😴😴😴")
1201 assert string.count("πŸš€πŸš€πŸš€") == 3, string.count("πŸš€πŸš€πŸš€")
1202 assert string.count("Γ±Γ±Γ±") == 2, string.count("Γ±Γ±Γ±")
1203 def test_count_multi_start_emoji() -> None:
1204 string = "πŸ˜΄πŸ˜΄πŸ˜΄πŸš€πŸš€πŸš€Γ±Γ±Γ±πŸš€πŸš€πŸš€Γ±Γ±Γ±πŸš€πŸš€πŸš€"
1205 assert string.count("😴😴😴", 6) == string.count("😴😴😴", -12) == 0, (string.count("😴😴😴", 6), string.count("😴😴😴", -12))
1206 assert string.count("πŸš€πŸš€πŸš€", 6) == string.count("πŸš€πŸš€πŸš€", -12) == 2, (string.count("πŸš€πŸš€πŸš€", 6), string.count("πŸš€πŸš€πŸš€", -12))
1207 assert string.count("Γ±Γ±Γ±", 6) == string.count("Γ±Γ±Γ±", -12) == 2, (string.count("Γ±Γ±Γ±", 6), string.count("Γ±Γ±Γ±", -12))
1208 # Out of bounds
1209 assert string.count("😴😴😴", 20) == 0, string.count("😴😴😴", 20)
1210 assert string.count("😴😴😴", -20) == 1, string.count("😴😴😴", -20)
1211 assert string.count("πŸš€πŸš€πŸš€", 20) == 0, string.count("πŸš€πŸš€πŸš€", 20)
1212 assert string.count("πŸš€πŸš€πŸš€", -20) == 3, string.count("πŸš€πŸš€πŸš€", -20)
1213 assert string.count("Γ±Γ±Γ±", 20) == 0, string.count("Γ±Γ±Γ±", 20)
1214 assert string.count("Γ±Γ±Γ±", -20) == 2, string.count("Γ±Γ±Γ±", -20)
1215 def test_count_multi_start_end_emoji() -> None:
1216 string = "πŸ˜΄πŸ˜΄πŸ˜΄πŸš€πŸš€πŸš€Γ±Γ±Γ±πŸš€πŸš€πŸš€Γ±Γ±Γ±πŸš€πŸš€πŸš€"
1217 assert string.count("😴😴😴", 0, 12) == 1, string.count("😴😴😴", 0, 12)
1218 assert string.count("πŸš€πŸš€πŸš€", 0, 12) == 2, string.count("πŸš€πŸš€πŸš€", 0, 12)
1219 assert string.count("Γ±Γ±Γ±", 0, 12) == 1, string.count("Γ±Γ±Γ±", 0, 12)
1220
1221 [case testIsInstance]
1222 from copysubclass import subc
1223 from typing import Any
1224 def test_built_in() -> None:
1225 s: Any = str()
1226 assert isinstance(s, str)
1227 assert isinstance(s + "test", str)
1228 assert isinstance(s + "Γ±Γ±Γ±", str)
1229 assert isinstance(subc(), str)
1230 assert isinstance(subc("test"), str)
1231 assert isinstance(subc("Γ±Γ±Γ±"), str)
1232
1233 assert not isinstance(set(), str)
1234 assert not isinstance((), str)
1235 assert not isinstance(('a','b'), str)
1236 assert not isinstance({'a','b'}, str)
1237 assert not isinstance(int() + 1, str)
1238 assert not isinstance(['a','b'], str)
1239
1240 def test_user_defined() -> None:
1241 from userdefinedstr import str
1242
1243 s: Any = "str"
1244 assert isinstance(str(), str)
1245 assert not isinstance(s, str)
1246
1247 [file copysubclass.py]
1248 from typing import Any
1249 class subc(str):
1250 pass
1251
1252 [file userdefinedstr.py]
1253 class str:
1254 pass
1255
1256 [case testStrOptionalEquality]
1257 from __future__ import annotations
1258
1259 def eq_s_opt_s_opt(x: str | None, y: str | None) -> bool:
1260 return x == y
1261
1262 def ne_s_opt_s_opt(x: str | None, y: str | None) -> bool:
1263 return x != y
1264
1265 def test_optional_eq() -> None:
1266 s = 'x'
1267 assert eq_s_opt_s_opt(s, s)
1268 assert eq_s_opt_s_opt(s + str(int()), s + str(int()))
1269 assert eq_s_opt_s_opt(None, None)
1270
1271 assert not eq_s_opt_s_opt('x', 'y')
1272 assert not eq_s_opt_s_opt('y', 'x')
1273 assert not eq_s_opt_s_opt(None, 'x')
1274 assert not eq_s_opt_s_opt('x', None)
1275
1276 def test_optional_ne() -> None:
1277 s = 'x'
1278 assert not ne_s_opt_s_opt(s, s)
1279 assert not ne_s_opt_s_opt(s + str(int()), s+ str(int()))
1280 assert not ne_s_opt_s_opt(None, None)
1281
1282 assert ne_s_opt_s_opt('x', 'y')
1283 assert ne_s_opt_s_opt('y', 'x')
1284 assert ne_s_opt_s_opt(None, 'x')
1285 assert ne_s_opt_s_opt('x', None)
1286
1287 [case testConstantFoldFormatArgs]
1288 from typing import Final
1289
1290 FMT: Final = "{} {}"
1291
1292 def test_format() -> None:
1293 assert FMT.format(400 + 20, "roll" + "up") == "420 rollup"
1294
1295 [case testLowerAndUpper]
1296 from typing import Any
1297
1298 def test_lower_basic() -> None:
1299 assert "".lower() == ""
1300 assert "hello".lower() == "hello"
1301 assert "HELLO".lower() == "hello"
1302 assert "Hello World".lower() == "hello world"
1303 assert "123".lower() == "123"
1304 assert "ABC123".lower() == "abc123"
1305
1306 def test_upper_basic() -> None:
1307 assert "".upper() == ""
1308 assert "HELLO".upper() == "HELLO"
1309 assert "hello".upper() == "HELLO"
1310 assert "Hello World".upper() == "HELLO WORLD"
1311 assert "123".upper() == "123"
1312 assert "abc123".upper() == "ABC123"
1313
1314 def test_lower_unicode() -> None:
1315 assert "\u00C9".lower() == "\u00E9" # Γ‰ -> Γ©
1316 assert "\u0391\u0392".lower() == "\u03B1\u03B2" # ΑΒ -> Ξ±Ξ²
1317 assert "\u4E2D\u6587".lower() == "\u4E2D\u6587" # CJK (no case)
1318 assert "\U0001F600".lower() == "\U0001F600" # Emoji (no case)
1319
1320 def test_upper_unicode() -> None:
1321 assert "\u00E9".upper() == "\u00C9" # Γ© -> Γ‰
1322 assert "\u03B1\u03B2".upper() == "\u0391\u0392" # Ξ±Ξ² -> ΑΒ
1323 assert "\u4E2D\u6587".upper() == "\u4E2D\u6587" # CJK (no case)
1324 assert "\U0001F600".upper() == "\U0001F600" # Emoji (no case)
1325
1326 def test_expansion() -> None:
1327 # 1-to-N expansion cases
1328 assert "\u0130".lower() == "\u0069\u0307" # Δ° -> i + combining dot above
1329 assert "\uFB03".lower() == "\uFB03" # ffi ligature stays lowercase
1330 assert "\u00DF".upper() == "SS" # ß -> SS
1331 assert "\uFB03".upper() == "FFI" # ffi ligature -> FFI
1332
1333 def test_comprehensive() -> None:
1334 for i in range(0x110000):
1335 c = chr(i)
1336 a: Any = c
1337 assert c.lower() == a.lower(), f"lower mismatch at U+{i:04X}"
1338 assert c.upper() == a.upper(), f"upper mismatch at U+{i:04X}"
1339
1340 [case testIsSpace]
1341 from typing import Any
1342
1343 def test_isspace() -> None:
1344 # Verify correctness across all Unicode codepoints.
1345 # Exercises UCS-1 (0x00-0xFF), UCS-2 (0x100-0xFFFF), and UCS-4 (0x10000-x10FFFF inclusive) string kinds.
1346 # Any forces generic dispatch so we compare our primitive against stdlib's
1347 for i in range(0x110000):
1348 c = chr(i)
1349 a: Any = c
1350 assert c.isspace() == a.isspace()
1351
1352 [case testIsAlnum]
1353 def test_isalnum_basic() -> None:
1354 assert "abc".isalnum()
1355 assert "ABC".isalnum()
1356 assert "abc123".isalnum()
1357 assert "123".isalnum()
1358 assert not "".isalnum()
1359 assert not " ".isalnum()
1360 assert not "abc!".isalnum()
1361 assert not "hello world".isalnum()
1362 assert not "abc-123".isalnum()
1363
1364 def test_isalnum_unicode() -> None:
1365 # Single chars: letters and digits from various scripts
1366 assert "\u00E9".isalnum() # Γ© (UCS-1 Latin letter)
1367 assert "\u0660".isalnum() # Ω  (UCS-2 Arabic-Indic digit)
1368 assert "\u4E2D".isalnum() # δΈ­ (UCS-2 CJK ideograph)
1369 assert "\U00010400".isalnum() # 𐐀 (UCS-4 Deseret capital letter long I)
1370 assert not "\u2000".isalnum() # EN QUAD (whitespace)
1371 assert not "\u0021".isalnum() # !
1372 assert not "\u00B6".isalnum() # ΒΆ (pilcrow sign, punctuation)
1373
1374 # Mixed Unicode letters and digits β€” all alnum
1375 assert "\u00E9\u0660".isalnum() # Γ©Ω 
1376 assert "\u4E2D\u0041\u0660".isalnum() # δΈ­AΩ 
1377
1378 # Unicode letter/digit mixed with punctuation β€” not alnum
1379 assert not "\u00E9!".isalnum()
1380 assert not "\u4E2D\u2000".isalnum() # CJK + whitespace
1381
1382 [case testIsDigit]
1383 from typing import Any
1384
1385 def test_isdigit() -> None:
1386 for i in range(0x110000):
1387 c = chr(i)
1388 a: Any = c
1389 assert c.isdigit() == a.isdigit()
1390
1391 def test_isdigit_strings() -> None:
1392 # ASCII digits
1393 assert "0123456789".isdigit()
1394 assert not "".isdigit()
1395 assert not " ".isdigit()
1396 assert not "a".isdigit()
1397 assert not "abc".isdigit()
1398 assert not "!@#".isdigit()
1399
1400 # Mixed ASCII
1401 assert not "123abc".isdigit()
1402 assert not "abc123".isdigit()
1403 assert not "12 34".isdigit()
1404 assert not "123!".isdigit()
1405
1406 # Unicode digits
1407 assert "\u0660\u0661\u0662".isdigit()
1408 assert "\u00b2\u00b3".isdigit()
1409 assert "123\U0001d7ce\U0001d7cf\U0001d7d0".isdigit()
1410
1411 # Mixed digits and Unicode non-digits
1412 assert not "\u00e9\u00e8".isdigit()
1413 assert not "123\u00e9".isdigit()
1414 assert not "\U0001d7ce!".isdigit()
1415
1416 [case testStrIndexEqLiteralSpecialize]
1417 from testutil import assertRaises
1418
1419 # The specializer fires on the AST shape `IndexExpr == StrLiteral` (or the
1420 # symmetric swap, and `!=`). The literal has to be a real source-level
1421 # string literal (can't be passed in as a parameter), so each test
1422 # function pins one distinct shape.
1423
1424 def eq_comma(s: str, i: int) -> bool:
1425 # Specialized: s[i] == "x".
1426 return s[i] == ","
1427
1428 def ne_comma(s: str, i: int) -> bool:
1429 # Specialized: s[i] != "x".
1430 return s[i] != ","
1431
1432 def comma_eq(s: str, i: int) -> bool:
1433 # Specialized: "x" == s[i]. Operand-swap is normalized.
1434 return "," == s[i]
1435
1436 def eq_two_chars(s: str, i: int) -> bool:
1437 # Not specialized: literal isn't 1 char. Falls through to the generic
1438 # str compare, which returns False since s[i] is always 1 codepoint.
1439 return s[i] == "ab"
1440
1441 def eq_empty(s: str, i: int) -> bool:
1442 # Not specialized: empty literal. Same fall-through.
1443 return s[i] == ""
1444
1445 def test_specialized_path() -> None:
1446 s = "a,b" # comma at index 1
1447 assert eq_comma(s, 1)
1448 assert not eq_comma(s, 0)
1449 assert not eq_comma(s, 2)
1450 # != inverts.
1451 assert ne_comma(s, 0)
1452 assert not ne_comma(s, 1)
1453 # Literal on the LHS is normalized to the same shape.
1454 assert comma_eq(s, 1)
1455 assert not comma_eq(s, 0)
1456
1457 def test_negative_index_is_adjusted() -> None:
1458 s = "a,b"
1459 assert eq_comma(s, -2) # -2 -> 1 (',')
1460 assert not eq_comma(s, -1) # -1 -> 2 ('b')
1461
1462 def test_non_1char_literal_falls_through() -> None:
1463 s = "a,b"
1464 # Generic str compare answers False because s[i] has length 1.
1465 assert not eq_two_chars(s, 0)
1466 assert not eq_two_chars(s, 1)
1467 assert not eq_empty(s, 0)
1468
1469 def test_out_of_range_raises_indexerror() -> None:
1470 # Bounds-check semantics match the unspecialized s[i] path.
1471 s = "a,b"
1472 with assertRaises(IndexError):
1473 eq_comma(s, 3)
1474 with assertRaises(IndexError):
1475 eq_comma(s, -4)