Debian Codegraph @

pypy/objspace/std/test/apptest_stringformat.py

raw symbols SCIP
1 # coding: utf-8
2 import sys
3
4 #from AppTestStringObjectWithDict
5 def test_format_item_dict():
6 d = {'i': 23}
7 assert 'a23b' == 'a%(i)sb' % d
8 assert '23b' == '%(i)sb' % d
9 assert 'a23' == 'a%(i)s' % d
10 assert '23' == '%(i)s' % d
11
12 def test_format_two_items():
13 d = {'i': 23, 'j': 42}
14 assert 'a23b42c' == 'a%(i)sb%(j)sc' % d
15 assert 'a23b23c' == 'a%(i)sb%(i)sc' % d
16
17 def test_format_percent_dict():
18 d = {}
19 assert 'a%b' == 'a%%b' % d
20
21 def test_format_empty_key():
22 d = {'':42}
23 assert '42' == '%()s' % d
24
25 def test_format_wrong_char_dict():
26 d = {'i': 23}
27 with raises(ValueError):
28 'a%(i)Zb'.__mod__(d)
29
30 def test_format_missing():
31 d = {'i': 23}
32 with raises(KeyError):
33 'a%(x)sb'.__mod__(d)
34
35 def test_format_error():
36 d = {}
37 assert '' % d == ''
38 n = 5
39 with raises(TypeError):
40 '' % n
41
42 class MyMapping(object):
43 def __getitem__(self, key):
44 py.test.fail('should not be here')
45 assert '' % MyMapping() == ''
46
47 class MyMapping2(object):
48 def __getitem__(self, key):
49 return key
50 assert '%(key)s'%MyMapping2() == 'key'
51 #assert u'%(key)s'%MyMapping2() == u'key' # no py3k
52
53 def test_format_error_complex():
54 with raises(TypeError) as e:
55 "%u" % 3j
56 assert "%u format: a real number" in str(e.value)
57
58 with raises(TypeError) as e:
59 "%i" % 3j
60 assert "%i format: a real number" in str(e.value)
61
62 def test_format_bad_class():
63 class RaisingNumber:
64 def __int__(self):
65 raise RuntimeError('int')
66 def __index__(self):
67 raise RuntimeError('index')
68
69 with raises(RuntimeError) as e:
70 "%d" % RaisingNumber()
71 assert "int" in str(e.value)
72
73
74 #from AppTestStringObject
75 def test_format_item_string():
76 n = 23
77 assert 'a23b' == 'a%sb' % n
78 assert '23b' == '%sb' % n
79 assert 'a23' == 'a%s' % n
80 assert '23' == '%s' % n
81
82 def test_format_percent_tuple():
83 t = ()
84 assert 'a%b' == 'a%%b' % t
85 assert '%b' == '%%b' % t
86 assert 'a%' == 'a%%' % t
87 assert '%' == '%%' % t
88
89 def test_format_percent_subclass_tuple_ignores_iter():
90 class t(tuple):
91 def __iter__(self):
92 yield 1
93 yield 2
94 yield 3
95 assert "%s %s %s" % t((4, 5, 6)) == "4 5 6"
96
97 def test_format_too_much():
98 raises(TypeError, '%s%s'.__mod__, ())
99 raises(TypeError, '%s%s'.__mod__, (23,))
100
101 def test_format_not_enough():
102 raises(TypeError, '%s%s'.__mod__, (23,)*3)
103 raises(TypeError, '%s%s'.__mod__, (23,)*4)
104
105 def test_format_string():
106 s = '23'
107 assert '23' == '%s' % s
108 assert "'23'" == '%r' % s
109 raises(TypeError, '%d'.__mod__, s)
110
111 def test_format_float():
112 f = -23.456
113 assert '-23' == '%d' % f
114 assert '-23' == '%i' % f
115 assert '-23' == '%u' % f
116 with raises(TypeError) as e:
117 '%x' % f
118 assert str(e.value).startswith("%x format:")
119 with raises(TypeError) as e:
120 '%X' % f
121 assert str(e.value).startswith("%X format:")
122 with raises(TypeError):
123 '%o' % f
124 assert '-23.456' == '%s' % f
125 # for 'r' use a float that has an exact decimal rep:
126 g = 23.125
127 assert '23.125' == '%r' % g
128 h = 0.0276
129 assert '0.028' == '%.3f' % h # should work on most platforms...
130 big = 1E200
131 assert ' inf' == '%6g' % (big * big)
132
133 assert '0.' == '%#.0f' % 0.0
134
135 def test_format_int():
136
137 n = 23
138 z = 0
139 assert '23' == '%d' % n
140 assert '17' == '%x' % n
141 assert '0x17' == '%#x' % n
142 assert '0x0' == '%#x' % z
143 assert '23' == '%s' % n
144 assert '23' == '%r' % n
145 assert ('%d' % (-sys.maxsize-1,) == '-' + str(sys.maxsize+1)
146 == '-%d' % (sys.maxsize+1,))
147 n = 28
148 m = 8
149 assert '1C' == '%X' % n
150 assert '0X1C' == '%#X' % n
151 assert '10' == '%o' % m
152 assert '0o10' == '%#o' % m
153 assert '-0o10' == '%#o' % -m
154 assert '0' == '%o' % z
155 assert '0o0' == '%#o' % z
156
157 n = 23
158 f = 5
159 assert '-0x017' == '%#06x' % -n
160 assert '0' == '%.0o' % z
161 assert '0o0' == '%#.0o' % z
162 assert '5' == '%.0o' % f
163 assert '0o5' == '%#.0o' % f
164 assert '000' == '%.3o' % z
165 assert '0o000' == '%#.3o' % z
166 assert '005' == '%.3o' % f
167 assert '0o005' == '%#.3o' % f
168 assert '27' == '%.2o' % n
169 assert '0o27' == '%#.2o' % n
170
171 def test_format_subclass_with_str():
172 class SubInt2(int):
173 def __str__(self):
174 assert False, "not called"
175 def __hex__(self):
176 assert False, "not called"
177 def __oct__(self):
178 assert False, "not called"
179 def __int__(self):
180 assert False, "not called"
181 def __long__(self):
182 assert False, "not called"
183 sl = SubInt2(123)
184 assert '%i' % sl == '123'
185 assert '%u' % sl == '123'
186 assert '%d' % sl == '123'
187 assert '%x' % sl == '7b'
188 assert '%X' % sl == '7B'
189 assert '%o' % sl == '173'
190
191 skip("the rest of this test is serious nonsense imho, changed "
192 "only on 2.7.13, and is different on 3.x anyway. We could "
193 "reproduce it by writing lengthy logic, then get again the "
194 "reasonable performance by special-casing the exact type "
195 "'long'. And all for 2.7.13 only. Let's give up.")
196
197 class SubLong2(long):
198 def __str__(self):
199 return extra_stuff + 'Xx'
200 def __hex__(self):
201 return extra_stuff + '0xYy' + extra_tail
202 def __oct__(self):
203 return extra_stuff + '0Zz' + extra_tail
204 def __int__(self):
205 assert False, "not called"
206 def __long__(self):
207 assert False, "not called"
208 sl = SubLong2(123)
209 for extra_stuff in ['', '-']:
210 for extra_tail in ['', 'l', 'L']:
211 m = extra_stuff
212 x = '%i' % sl
213 assert x == m+'Xx'
214 assert '%u' % sl == m+'Xx'
215 assert '%d' % sl == m+'Xx'
216 assert '%x' % sl == m+('Yyl' if extra_tail == 'l' else 'Yy')
217 assert '%X' % sl == m+('YYL' if extra_tail == 'l' else 'YY')
218 assert '%o' % sl == m+('Zzl' if extra_tail == 'l' else 'Zz')
219 extra_stuff = '??'
220 with raises(ValueError):
221 '%x' % sl
222 with raises(ValueError):
223 '%X' % sl
224 with raises(ValueError):
225 '%o' % sl
226
227 def test_format_list():
228 l = [1,2]
229 assert '<[1, 2]>' == '<%s>' % l
230 assert '<[1, 2]-[3, 4]>' == '<%s-%s>' % (l, [3,4])
231
232 def test_format_tuple():
233 t = (1,2)
234 assert '<(1, 2)>' == '<%s>' % (t,)
235 assert '<(1, 2)-(3, 4)>' == '<%s-%s>' % (t, (3,4))
236
237 def test_format_dict():
238 # I'll just note that the first of these two completely
239 # contradicts what CPython's documentation says:
240
241 # When the right argument is a dictionary (or other
242 # mapping type), then the formats in the string
243 # \emph{must} include a parenthesised mapping key into
244 # that dictionary inserted immediately after the
245 # \character{\%} character.
246
247 # It is what CPython *does*, however. All software sucks.
248
249 d = {1:2}
250 assert '<{1: 2}>' == '<%s>' % d
251 assert '<{1: 2}-{3: 4}>' == '<%s-%s>' % (d, {3:4})
252
253 def test_format_wrong_char():
254 raises(ValueError, 'a%Zb'.__mod__, ((23,),))
255 raises(ValueError, u'a%\ud800b'.__mod__, ((23,),))
256
257 def test_incomplete_format():
258 raises(ValueError, '%'.__mod__, ((23,),))
259 raises((ValueError, TypeError), '%('.__mod__, ({},))
260
261 def test_format_char():
262
263 A = 65
264 e = 'e'
265 assert '%c' % A == 'A'
266 assert '%c' % e == 'e'
267 #raises(OverflowError, '%c'.__mod__, (256,)) # py2
268 assert '%c' % 256 == '\u0100' # py3k
269 raises(OverflowError, '%c'.__mod__, (-1,))
270 raises(OverflowError, '%c'.__mod__, (sys.maxunicode+1,))
271 raises(TypeError, '%c'.__mod__, ("bla",))
272 raises(TypeError, '%c'.__mod__, ("",))
273 raises(TypeError, '%c'.__mod__, (['c'],))
274 with raises(TypeError):
275 '%c'.__mod__(b'A')
276 surrogate = 0xd800
277 assert '%c' % surrogate == '\ud800'
278
279 def test_force_unicode_uses_default_encoding():
280 if not hasattr(sys, 'setdefaultencoding'):
281 skip("no setdefaultencoding")
282 encoding = sys.getdefaultencoding()
283 try:
284 sys.setdefaultencoding("utf-8")
285 assert "ä%s" % u"ö" == "äö"
286 finally:
287 sys.setdefaultencoding(encoding)
288
289 def test_force_unicode_doesnt_force_random_objects():
290 with raises(TypeError) as info:
291 None % u"abc"
292 assert "unsupported operand type(s) for %: 'NoneType' and 'str'" in str(info.value)
293
294 def test___int__index__():
295 class MyInt(object):
296 def __init__(self, x):
297 self.x = x
298 def __int__(self):
299 return self.x
300 x = MyInt(33)
301 with raises(TypeError):
302 '%c' % x
303 MyInt.__index__ = lambda self: self.x * 2
304 assert '%c' % x == 'B'
305
306 def test_index_fails():
307 class MyException(Exception):
308 pass
309
310 class IndexFails(object):
311 def __index__(self):
312 raise MyException
313
314 exc = raises(MyException, "%x".__mod__, IndexFails())
315 raises(MyException, "%c".__mod__, IndexFails())
316
317 def test_formatting_huge_precision():
318 prec = 2**31
319 format_string = "%.{}f".format(prec)
320 with raises(ValueError) as exc:
321 format_string % 2.34
322 assert str(exc.value) == 'precision too big'
323 raises(OverflowError, lambda: u'%.*f' % (prec, 1. / 7))
324
325 def test_formatting_huge_width():
326
327 format_string = "%{}f".format(sys.maxsize + 1)
328 with raises(ValueError) as exc:
329 format_string % 2.34
330 assert str(exc.value) == 'width too big'
331
332 def test_wrong_formatchar_error_not_masked_by_not_enough_args():
333 with raises(ValueError):
334 "%?" % () # not TypeError (which would be due to lack of arguments)
335 with raises(ValueError):
336 "%?" % {} # not TypeError
337
338 #from AppTestWidthPrec
339 def test_width():
340 a = 'a'
341 assert "%3s" % a == ' a'
342 assert "%-3s"% a == 'a '
343
344 def test_no_chars_between_percent():
345 with raises(ValueError) as exc:
346 "% %" % ()
347 assert "extra character ' ' (0x20) before escaped '%' at index 1" in str(exc.value)
348
349 def test_prec_zero():
350 z = 0
351 assert "%.0x" % z == '0'
352 assert "%.0X" % z == '0'
353 assert "%.x" % z == '0'
354 assert "%.0d" % z == '0'
355 assert "%.i" % z == '0'
356 assert "%.0o" % z == '0'
357 assert "%.o" % z == '0'
358
359 def test_prec_string():
360 a = 'a'
361 abcde = 'abcde'
362 assert "%.3s"% a == 'a'
363 assert "%.3s"% abcde == 'abc'
364
365 def test_prec_width_string():
366 a = 'a'
367 abcde = 'abcde'
368 assert "%5.3s" % a == ' a'
369 assert "%5.3s" % abcde == ' abc'
370 assert "%-5.3s"% a == 'a '
371 assert "%-5.3s"% abcde == 'abc '
372
373 def test_zero_pad():
374 one = 1
375 ttf = 2.25
376 assert "%02d" % one == "01"
377 assert "%05d" % one == "00001"
378 assert "%-05d" % one == "1 "
379 assert "%04f" % ttf == "2.250000"
380 assert "%05g" % ttf == "02.25"
381 assert "%-05g" % ttf =="2.25 "
382 assert "%05s" % ttf == " 2.25"
383
384 def test_star_width():
385 f = 5
386 assert "%*s" %( f, 'abc') == ' abc'
387 assert "%*s" %(-f, 'abc') == 'abc '
388 assert "%-*s"%( f, 'abc') == 'abc '
389 assert "%-*s"%(-f, 'abc') == 'abc '
390
391 def test_star_prec():
392 t = 3
393 assert "%.*s"%( t, 'abc') == 'abc'
394 assert "%.*s"%( t, 'abcde') == 'abc'
395 assert "%.*s"%(-t, 'abc') == ''
396
397 def test_star_width_prec():
398 f = 5
399 assert "%*.*s"%( f, 3, 'abc') == ' abc'
400 assert "%*.*s"%( f, 3, 'abcde') == ' abc'
401 assert "%*.*s"%(-f, 3, 'abcde') == 'abc '
402
403 def test_long_format():
404 def f(fmt, x):
405 return fmt % x
406 assert '%.70f' % 2.0 == '2.' + '0' * 70
407 assert '%.110g' % 2.0 == '2'
408
409 def test_subnormal():
410 inf = 1e300 * 1e300
411 assert "%f" % (inf,) == 'inf'
412 assert "%E" % (inf,) == 'INF'
413 assert "%f" % (-inf,) == '-inf'
414 assert "%F" % (-inf,) == '-INF'
415 nan = inf / inf
416 assert "%f" % (nan,) == 'nan'
417 assert "%f" % (-nan,) == 'nan'
418 assert "%E" % (nan,) == 'NAN'
419 assert "%F" % (nan,) == 'NAN'
420 assert "%G" % (nan,) == 'NAN'
421
422
423 #from AppTestUnicodeObject
424
425 def test_unicode_d():
426 t = 3
427 assert "%.1d" % t == '3'
428
429 def test_unicode_overflow():
430 skip("nicely passes on top of CPython but requires > 2GB of RAM")
431
432 with raises((OverflowError, MemoryError)):
433 u"%.*d" % (sys.maxint, 1)
434
435 def test_unicode_format_a():
436 ten = 10
437 assert '%x' % ten == 'a'
438
439 def test_long_no_overflow():
440 big = 0x1234567890987654321
441 assert "%x" % big == "1234567890987654321"
442
443 def test_missing_cases():
444 big = -123456789012345678901234567890
445 assert '%032d' % big == '-0123456789012345678901234567890'
446
447 def test_invalid_char():
448 f = 4
449 with raises(ValueError):
450 "%\u1234" % (f,)
451
452 def test_invalid_b_with_unicode():
453 with raises(ValueError):
454 "%b" % b"A"
455 with raises(ValueError):
456 "%b" % 42
457
458 def test_formatting_huge_precision_u():
459 prec = 2**31
460 format_string = u"%.{}f".format(prec)
461 with raises(ValueError) as exc:
462 format_string % 2.34
463 assert str(exc.value) == 'precision too big'
464 raises(OverflowError, lambda: u'%.*f' % (prec, 1. / 7))
465
466 def test_formatting_huge_width_u():
467
468 format_string = u"%{}f".format(sys.maxsize + 1)
469 with raises(ValueError) as exc:
470 format_string % 2.34
471 assert str(exc.value) == 'width too big'
472
473 def test_unicode_error_position():
474 with raises(ValueError) as info:
475 u"\xe4\xe4\xe4%?" % {}
476 assert str(info.value) == "unsupported format character '?' (0x3f) at index 4"
477 with raises(ValueError) as info:
478 u"\xe4\xe4\xe4%\xe4" % {}
479 assert str(info.value) == "unsupported format character '\xe4' (0xe4) at index 4"
480
481 def test_g_strip_trailing_zero_bug():
482 assert "%.3g" % 1505.0 == "1.5e+03"
483 def test_ascii():
484 assert "<%a>" % "test" == "<'test'>"
485 assert "<%a>" % "\t\x80" == "<'\\t\\x80'>"
486 assert repr("\xe9") == "'\xe9'"
487 assert "<%r>" % "\xe9" == "<'\xe9'>"
488 assert "<%a>" % "\xe9" == "<'\\xe9'>"
489
490
491 #from AppTestBytes
492
493 def test_ascii_bytes():
494 assert b"<%a>" % b"test" == b"<b'test'>"
495 assert b"<%a>" % b"\t\x80" == b"<b'\\t\\x80'>"
496 assert repr(b"\xe9") == "b'\\xe9'"
497 assert b"<%a>" % b"\xe9" == b"<b'\\xe9'>"
498 assert b"<%a>" % "foo" == b"<'foo'>"
499 assert b"<%a>" % "\u1234" == b"<'\\u1234'>"
500 assert b"<%a>" % 3.14 == b"<3.14>"
501
502 def test_r_compat_bytes():
503 assert b"<%r>" % b"test" == b"<b'test'>"
504 assert b"<%r>" % b"\t\x80" == b"<b'\\t\\x80'>"
505 assert repr(b"\xe9") == "b'\\xe9'"
506 assert b"<%r>" % b"\xe9" == b"<b'\\xe9'>"
507 assert b"<%r>" % "foo" == b"<'foo'>"
508 assert b"<%r>" % "\u1234" == b"<'\\u1234'>"
509
510 def test_numeric_bytes():
511 assert b"<%4x>" % 10 == b"< a>"
512 assert b"<%#4x>" % 10 == b"< 0xa>"
513 assert b"<%04X>" % 10 == b"<000A>"
514
515 def test_char_bytes():
516 assert b"<%c>" % 48 == b"<0>"
517 assert b"<%c>" % b"?" == b"<?>"
518 with raises(TypeError):
519 b"<%c>" % "?"
520 assert b"<%c>" % bytearray(b"?") == b"<?>"
521 class X:
522 def __bytes__(self):
523 return b'5'
524 with raises(TypeError):
525 b"<%c>" % X()
526
527 def test_bytes_bytes():
528 assert b"<%b>" % b"123" == b"<123>"
529 class Foo:
530 def __bytes__(self):
531 return b"123"
532 assert b"<%b>" % Foo() == b"<123>"
533 with raises(TypeError):
534 b"<%b>" % 42
535 with raises(TypeError):
536 b"<%b>" % "?"
537
538 def test_s_compat_bytes():
539 assert b"<%s>" % b"123" == b"<123>"
540 class Foo:
541 def __bytes__(self):
542 return b"123"
543 assert b"<%s>" % Foo() == b"<123>"
544 with raises(TypeError):
545 b"<%s>" % 42
546 with raises(TypeError):
547 b"<%s>" % "?"
548 assert b"<%s>" % memoryview(b"X") == b"<X>"
549
550
551 #from AppTestBytearray
552
553 def test_ascii_bytearray():
554 assert bytearray(b"<%a>") % b"test" == bytearray(b"<b'test'>")
555 assert bytearray(b"<%a>") % b"\t\x80" == bytearray(b"<b'\\t\\x80'>")
556 assert repr(b"\xe9") == "b'\\xe9'"
557 assert bytearray(b"<%a>") % b"\xe9" == bytearray(b"<b'\\xe9'>")
558 assert bytearray(b"<%a>") % "foo" == bytearray(b"<'foo'>")
559 assert bytearray(b"<%a>") % "\u1234" == bytearray(b"<'\\u1234'>")
560
561 def test_bytearray_not_modified():
562 b1 = bytearray(b"<%a>")
563 b2 = b1 % b"test"
564 assert b1 == bytearray(b"<%a>")
565 assert b2 == bytearray(b"<b'test'>")
566
567 def test_r_compat_bytearray():
568 assert bytearray(b"<%r>") % b"test" == bytearray(b"<b'test'>")
569 assert bytearray(b"<%r>") % b"\t\x80" == bytearray(b"<b'\\t\\x80'>")
570 assert repr(b"\xe9") == "b'\\xe9'"
571 assert bytearray(b"<%r>") % b"\xe9" == bytearray(b"<b'\\xe9'>")
572 assert bytearray(b"<%r>") % "foo" == bytearray(b"<'foo'>")
573 assert bytearray(b"<%r>") % "\u1234" == bytearray(b"<'\\u1234'>")
574
575 def test_numeric_bytearray():
576 assert bytearray(b"<%4x>") % 10 == bytearray(b"< a>")
577 assert bytearray(b"<%#4x>") % 10 == bytearray(b"< 0xa>")
578 assert bytearray(b"<%04X>") % 10 == bytearray(b"<000A>")
579
580 def test_char_bytearray():
581 assert bytearray(b"<%c>") % 48 == bytearray(b"<0>")
582 assert bytearray(b"<%c>") % b"?" == bytearray(b"<?>")
583 with raises(TypeError):
584 bytearray(b"<%c>") % "?"
585 assert bytearray(b"<%c>") % bytearray(b"?") == bytearray(b"<?>")
586 with raises(TypeError):
587 bytearray(b"<%c>") % memoryview(b"X")
588
589 def test_bytes_bytearray():
590 assert bytearray(b"<%b>") % b"123" == bytearray(b"<123>")
591 class Foo:
592 def __bytes__(self):
593 return b"123"
594 assert bytearray(b"<%b>") % Foo() == bytearray(b"<123>")
595 with raises(TypeError):
596 bytearray(b"<%b>") % 42
597 with raises(TypeError):
598 bytearray(b"<%b>") % "?"
599
600 def test_s_compat_bytearray():
601 assert bytearray(b"<%s>") % b"123" == bytearray(b"<123>")
602 class Foo:
603 def __bytes__(self):
604 return b"123"
605 assert bytearray(b"<%s>") % Foo() == bytearray(b"<123>")
606 with raises(TypeError):
607 bytearray(b"<%s>") % 42
608 with raises(TypeError):
609 bytearray(b"<%s>") % "?"
610 assert bytearray(b"<%s>") % memoryview(b"X") == bytearray(b"<X>")
611
612 def test_format_better_error():
613 with raises(ValueError) as info:
614 "{a:%ЫйЯЧ}".format(a='a')
615 assert str(info.value) == "Invalid format specifier '%ЫйЯЧ' for object of type 'str'"