Debian Codegraph @

pypy/module/__builtin__/test/test_builtin.py

raw symbols SCIP
1 # coding: utf-8
2 import sys
3
4 from rpython.tool.udir import udir
5
6 class AppTestBuiltinApp:
7 def setup_class(cls):
8 space = cls.space
9 class X(object):
10 def __eq__(self, other):
11 raise OverflowError
12 def __hash__(self):
13 return 42
14 d = {X(): 5}
15 try:
16 d[X()]
17 except OverflowError:
18 cls.w_sane_lookup = space.wrap(True)
19 except KeyError:
20 cls.w_sane_lookup = space.wrap(False)
21 # starting with CPython 2.6, when the stack is almost out, we
22 # can get a random error, instead of just a RuntimeError.
23 # For example if an object x has a __getattr__, we can get
24 # AttributeError if attempting to call x.__getattr__ runs out
25 # of stack. That's annoying, so we just work around it.
26 if cls.runappdirect:
27 cls.w_safe_runtimerror = space.wrap(True)
28 else:
29 cls.w_safe_runtimerror = space.wrap(sys.version_info < (2, 6))
30
31 def test_builtin_names(self):
32 import builtins as __builtin__
33 assert __builtin__.bytes is bytes
34 assert __builtin__.dict is dict
35 assert __builtin__.memoryview is memoryview
36 assert not hasattr(__builtin__, 'buffer')
37
38 def test_bytes_alias(self):
39 assert bytes is not str
40 assert isinstance(eval("b'hi'"), bytes)
41
42 def test_eval_adds_builtins(self):
43 d = {}
44 eval('1', d)
45 assert "__builtins__" in d
46
47 def test_import(self):
48 m = __import__('sys')
49 assert m.__name__ == "sys"
50 raises(ImportError, __import__, 'spamspam')
51 raises(TypeError, __import__, 1, 2, 3, 4)
52 print(__import__.__doc__)
53 assert __import__.__doc__.endswith('relative to the current module.')
54
55 def test_ascii(self):
56 assert ascii('') == '\'\''
57 assert ascii(0) == '0'
58 assert ascii(()) == '()'
59 assert ascii([]) == '[]'
60 assert ascii({}) == '{}'
61 a = []
62 a.append(a)
63 assert ascii(a) == '[[...]]'
64 a = {}
65 a[0] = a
66 assert ascii(a) == '{0: {...}}'
67 # Advanced checks for unicode strings
68 def _check_uni(s):
69 assert ascii(s) == repr(s)
70 _check_uni("'")
71 _check_uni('"')
72 _check_uni('"\'')
73 _check_uni('\0')
74 _check_uni('\r\n\t .')
75 # Unprintable non-ASCII characters
76 _check_uni('\x85')
77 _check_uni('\u1fff')
78 _check_uni('\U00012fff')
79 # Lone surrogates
80 _check_uni('\ud800')
81 _check_uni('\udfff')
82 # Issue #9804: surrogates should be joined even for printable
83 # wide characters (UCS-2 builds).
84 assert ascii('\U0001d121') == "'\\U0001d121'"
85 # another buggy case
86 x = ascii("\U00012fff")
87 assert x == r"'\U00012fff'"
88 # All together
89 s = "'\0\"\n\r\t abcd\x85é\U00012fff\uD800\U0001D121xxx."
90 assert ascii(s) == \
91 r"""'\'\x00"\n\r\t abcd\x85\xe9\U00012fff\ud800\U0001d121xxx.'"""
92
93 def test_bin(self):
94 class Foo:
95 def __index__(self):
96 return 4
97 assert bin(0) == "0b0"
98 assert bin(-1) == "-0b1"
99 assert bin(2) == "0b10"
100 assert bin(-2) == "-0b10"
101 assert bin(Foo()) == "0b100"
102 raises(TypeError, bin, 0.)
103 class C(object):
104 def __index__(self):
105 return 42
106 assert bin(C()) == bin(42)
107 class D(object):
108 def __int__(self):
109 return 42
110 exc = raises(TypeError, bin, D())
111 assert "integer" in str(exc.value)
112
113 def test_oct(self):
114 class Foo:
115 def __index__(self):
116 return 4
117 assert oct(0) == "0o0"
118 assert oct(-1) == "-0o1"
119 assert oct(8) == "0o10"
120 assert oct(-8) == "-0o10"
121 assert oct(Foo()) == "0o4"
122 raises(TypeError, oct, 0.)
123
124 def test_hex(self):
125 class Foo:
126 def __index__(self):
127 return 4
128 class Bar(int):
129 def __format__(self, *args):
130 return "nope"
131 assert hex(0) == "0x0"
132 assert hex(-1) == "-0x1"
133 assert hex(16) == "0x10"
134 assert hex(-16) == "-0x10"
135 assert hex(Foo()) == "0x4"
136 assert hex(Bar(16)) == "0x10", hex(Bar(16))
137 raises(TypeError, hex, 0.)
138
139 def test_chr(self):
140 import sys
141 assert chr(65) == 'A'
142 assert type(str(65)) is str
143 assert chr(0x9876) == '\u9876'
144 if sys.maxunicode > 0xFFFF:
145 assert chr(sys.maxunicode) == '\U0010FFFF'
146 else:
147 assert chr(sys.maxunicode) == '\uFFFF'
148 assert chr(0x00010000) == '\U00010000'
149 assert chr(0x0010ffff) == '\U0010FFFF'
150 raises(ValueError, chr, -1)
151
152 def test_globals(self):
153 d = {"foo":"bar"}
154 exec("def f(): return globals()", d)
155 d2 = d["f"]()
156 assert d2 is d
157
158 def test_locals(self):
159 def f():
160 return locals()
161
162 def g(c=0, b=0, a=0):
163 return locals()
164
165 assert f() == {}
166 assert g() == {'a': 0, 'b': 0, 'c': 0}
167
168 def test_locals_deleted_local(self):
169 def f():
170 a = 3
171 locals()
172 del a
173 return locals()
174
175 assert f() == {}
176
177 def test_dir(self):
178 def f():
179 return dir()
180 def g(c=0, b=0, a=0):
181 return dir()
182 def nosp(x): return [y for y in x if y[0]!='_']
183 assert f() == []
184 assert g() == ['a', 'b', 'c']
185 class X(object): pass
186 assert nosp(dir(X)) == []
187 class X(object):
188 a = 23
189 c = 45
190 b = 67
191 assert nosp(dir(X)) == ['a', 'b', 'c']
192
193 def test_dir_in_broken_locals(self):
194 class C(object):
195 def __getitem__(self, item):
196 raise KeyError(item)
197 def keys(self):
198 return 'abcd' # not a list!
199 names = eval("dir()", {}, C())
200 assert names == ['a', 'b', 'c', 'd']
201
202 def test_dir_broken_module(self):
203 import sys
204 class Foo(type(sys)):
205 __dict__ = 8
206 raises(TypeError, dir, Foo("foo"))
207
208 def test_dir_broken_object(self):
209 class Foo(object):
210 x = 3
211 def __getattribute__(self, name):
212 return name
213 assert dir(Foo()) == []
214
215 def test_dir_custom(self):
216 class Foo(object):
217 def __dir__(self):
218 return ["1", "2", "3"]
219 f = Foo()
220 assert dir(f) == ["1", "2", "3"]
221 class Foo:
222 def __dir__(self):
223 return ["apple"]
224 assert dir(Foo()) == ["apple"]
225 class Foo(object):
226 def __dir__(self):
227 return 42
228 f = Foo()
229 raises(TypeError, dir, f)
230 import sys
231 class Foo(type(sys)):
232 def __dir__(self):
233 return ["blah"]
234 assert dir(Foo("a_mod")) == ["blah"]
235
236 def test_dir_custom_lookup(self):
237 """
238 class M(type):
239 def __dir__(self, *args): return ["14"]
240 class X(metaclass=M):
241 pass
242 x = X()
243 x.__dir__ = lambda x: ["14"]
244 assert dir(x) != ["14"]
245 """
246
247 def test_format(self):
248 assert format(4) == "4"
249 assert format(10, "o") == "12"
250 assert format(10, "#o") == "0o12"
251 assert format("hi") == "hi"
252
253 def test_vars(self):
254 def f():
255 return vars()
256 def g(c=0, b=0, a=0):
257 return vars()
258 assert f() == {}
259 assert g() == {'a':0, 'b':0, 'c':0}
260
261 def test_sum(self):
262 assert sum([]) ==0
263 assert sum([42]) ==42
264 assert sum([1,2,3]) ==6
265 assert sum([],5) ==5
266 assert sum([1,2,3],4) ==10
267 #
268 class Foo(object):
269 def __radd__(self, other):
270 assert other is None
271 return 42
272 assert sum([Foo()], None) == 42
273
274 def test_sum_fast_path(self):
275 # Fast paths for expected behaviour
276 start = []
277 assert sum([[1, 2], [3]], start) == [1, 2, 3]
278 assert start == []
279
280 start = [1, 2]
281 assert sum([[3]], start) == [1, 2, 3]
282 assert start == [1, 2]
283
284 assert sum([(1, 2), (3,)], ()) == (1, 2, 3)
285 assert sum([(3,)], (1, 2)) == (1, 2, 3)
286 assert sum(([x + 1] for x in range(3)), []) == [1, 2, 3]
287
288 def test_sum_empty_edge_cases(self):
289 assert sum([], []) == []
290 assert sum(iter([]), []) == []
291 assert sum([], ()) == ()
292 start = []
293 assert sum([], start) is start
294 assert sum([[]], start) is not start
295
296 def test_sum_type_errors(self):
297 with raises(TypeError):
298 sum([[]], ())
299 with raises(TypeError):
300 sum([()], [])
301 with raises(TypeError):
302 sum([[], [], ()], [])
303
304 def test_sum_strange_objects(self):
305 # All that follows should be rare, but needs care
306 class TupleTail(object):
307 def __radd__(self, other):
308 assert isinstance(other, tuple)
309 return other[1:]
310
311 strange_seq = [(1, 2), (3, 4), TupleTail(), (5,)]
312 assert sum(strange_seq, (2, 3, 4, 5))
313 assert sum(iter(strange_seq), (2, 3, 4, 5))
314
315 class NotAList(list):
316 def __add__(self, _):
317 return "!"
318
319 def __radd__(self, _):
320 return "?"
321
322 def __iadd__(self, _):
323 raise RuntimeError(
324 "Calling __iadd__ breaks CPython compatability"
325 )
326
327 assert sum([[1]], NotAList()) == "!"
328 assert sum([[1], NotAList()], []) == "?"
329
330 def test_sum_first_object_edge_cases(self):
331 class X(list):
332 def __radd__(self, other):
333 return Y()
334
335 class Y(object):
336 calls = []
337
338 def __add__(self, other):
339 Y.calls.append("add")
340
341 def __iadd__(self, other):
342 Y.calls.append("iadd")
343
344 assert sum([X(), []], []) is None
345 assert Y.calls == ["add"]
346
347 class Z(tuple):
348 def __radd__(self, other):
349 return Y()
350
351 assert sum([Z(), []], []) is None
352 assert Y.calls == ["add", "add"]
353
354 def test_type_selftest(self):
355 assert type(type) is type
356
357 def test_iter_sequence(self):
358 raises(TypeError,iter,3)
359 x = iter(['a','b','c'])
360 assert next(x) =='a'
361 assert next(x) =='b'
362 assert next(x) =='c'
363 raises(StopIteration, next, x)
364
365 def test_iter___iter__(self):
366 # This test assumes that dict.keys() method returns keys in
367 # the same order as dict.__iter__().
368 # Also, this test is not as explicit as the other tests;
369 # it tests 4 calls to __iter__() in one assert. It could
370 # be modified if better granularity on the assert is required.
371 mydict = {'a':1,'b':2,'c':3}
372 assert list(iter(mydict)) == list(mydict.keys())
373
374 def test_iter_callable_sentinel(self):
375 class count(object):
376 def __init__(self):
377 self.value = 0
378 def __call__(self):
379 self.value += 1
380 if self.value > 10:
381 raise StopIteration
382 return self.value
383 with raises(TypeError):
384 iter(3, 5)
385
386 x = iter(count(),3)
387 assert next(x) ==1
388 assert next(x) ==2
389 raises(StopIteration, next, x)
390
391 # a case that runs till the end
392 assert list(iter(count(), 100)) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
393
394 def test_enumerate(self):
395 import sys
396 seq = range(2,4)
397 enum = enumerate(seq)
398 assert next(enum) == (0, 2)
399 assert next(enum) == (1, 3)
400 raises(StopIteration, next, enum)
401 raises(TypeError, enumerate, 1)
402 raises(TypeError, enumerate, None)
403 enum = enumerate(range(5), 2)
404 assert list(enum) == list(zip(range(2, 7), range(5)))
405
406 enum = enumerate(range(2), 2**100)
407 assert list(enum) == [(2**100, 0), (2**100+1, 1)]
408
409 enum = enumerate(range(2), sys.maxsize)
410 assert list(enum) == [(sys.maxsize, 0), (sys.maxsize+1, 1)]
411
412 raises(TypeError, enumerate, range(2), 5.5)
413
414
415 def test_next(self):
416 x = iter(['a', 'b', 'c'])
417 assert next(x) == 'a'
418 assert next(x) == 'b'
419 assert next(x) == 'c'
420 raises(StopIteration, next, x)
421 assert next(x, 42) == 42
422
423 def test_next__next__(self):
424 class Counter:
425 def __init__(self):
426 self.count = 0
427 def __next__(self):
428 self.count += 1
429 return self.count
430 x = Counter()
431 assert next(x) == 1
432 assert next(x) == 2
433 assert next(x) == 3
434
435 def test_range_args(self):
436 raises(ValueError, range, 0, 1, 0)
437
438 def test_range_repr(self):
439 assert repr(range(1)) == 'range(0, 1)'
440 assert repr(range(1,2)) == 'range(1, 2)'
441 assert repr(range(1,2,3)) == 'range(1, 2, 3)'
442
443 def test_range_up(self):
444 x = range(2)
445 iter_x = iter(x)
446 assert next(iter_x) == 0
447 assert next(iter_x) == 1
448 raises(StopIteration, next, iter_x)
449
450 def test_range_down(self):
451 x = range(4,2,-1)
452
453 iter_x = iter(x)
454 assert next(iter_x) == 4
455 assert next(iter_x) == 3
456 raises(StopIteration, next, iter_x)
457
458 def test_range_has_type_identity(self):
459 assert type(range(1)) == type(range(1))
460
461 def test_range_len(self):
462 x = range(33)
463 assert len(x) == 33
464 exc = raises(TypeError, range, 33.2)
465 assert "integer" in str(exc.value)
466 x = range(33,0,-1)
467 assert len(x) == 33
468 x = range(33,0)
469 assert len(x) == 0
470 exc = raises(TypeError, range, 33, 0.2)
471 assert "integer" in str(exc.value)
472 x = range(0,33)
473 assert len(x) == 33
474 x = range(0,33,-1)
475 assert len(x) == 0
476 x = range(0,33,2)
477 assert len(x) == 17
478 x = range(0,32,2)
479 assert len(x) == 16
480
481 def test_range_indexing(self):
482 x = range(0,33,2)
483 assert x[7] == 14
484 assert x[-7] == 20
485 raises(IndexError, x.__getitem__, 17)
486 raises(IndexError, x.__getitem__, -18)
487 assert list(x.__getitem__(slice(0,3,1))) == [0, 2, 4]
488
489 def test_range_bad_args(self):
490 raises(TypeError, range, '1')
491 raises(TypeError, range, None)
492 raises(TypeError, range, 3+2j)
493 raises(TypeError, range, 1, '1')
494 raises(TypeError, range, 1, 3+2j)
495 raises(TypeError, range, 1, 2, '1')
496 raises(TypeError, range, 1, 2, 3+2j)
497
498 def test_range_bool(self):
499 import sys
500 a = range(-sys.maxsize, sys.maxsize)
501 assert bool(a) is True
502 b = range(10, 0)
503 assert bool(b) is False
504
505 def test_range_bool_arg(self):
506 a = range(True)
507 assert type(a.stop) is int
508
509 def test_sorted(self):
510 l = []
511 sorted_l = sorted(l)
512 assert sorted_l is not l
513 assert sorted_l == l
514 l = [1, 5, 2, 3]
515 sorted_l = sorted(l)
516 assert sorted_l == [1, 2, 3, 5]
517
518 def test_sorted_with_keywords(self):
519 l = ['a', 'C', 'b']
520 sorted_l = sorted(l, reverse = True)
521 assert sorted_l is not l
522 assert sorted_l == ['b', 'a', 'C']
523 sorted_l = sorted(l, reverse = True, key = lambda x: x.lower())
524 assert sorted_l is not l
525 assert sorted_l == ['C', 'b', 'a']
526 raises(TypeError, sorted, [], reverse=None)
527 raises(TypeError, sorted, [], None)
528
529 def test_sorted_posonlyarg(self):
530 raises(TypeError, sorted, iterable=[])
531
532 def test_reversed_simple_sequences(self):
533 l = range(5)
534 rev = reversed(l)
535 assert list(rev) == [4, 3, 2, 1, 0]
536 assert list(l.__reversed__()) == [4, 3, 2, 1, 0]
537 s = "abcd"
538 assert list(reversed(s)) == ['d', 'c', 'b', 'a']
539
540 def test_reversed_custom_objects(self):
541 """make sure __reversed__ is called when defined"""
542 class SomeClass(object):
543 def __reversed__(self):
544 return 42
545 obj = SomeClass()
546 assert reversed(obj) == 42
547
548 def test_return_None(self):
549 class X(object): pass
550 x = X()
551 assert setattr(x, 'x', 11) == None
552 assert delattr(x, 'x') == None
553
554 def test_divmod(self):
555 assert divmod(15,10) ==(1,5)
556
557 def test_callable(self):
558 class Call(object):
559 def __call__(self, a):
560 return a+2
561 assert callable(Call()), (
562 "Builtin function 'callable' misreads callable object")
563 assert callable(int), (
564 "Builtin function 'callable' misreads int")
565 class Call:
566 def __call__(self, a):
567 return a+2
568 assert callable(Call())
569
570
571 def test_uncallable(self):
572 # XXX TODO: I made the NoCall class explicitly newstyle to try and
573 # remedy the failure in this test observed when running this with
574 # the trivial objectspace, but the test _still_ fails then (it
575 # doesn't fail with the standard objectspace, though).
576 class NoCall(object):
577 pass
578 a = NoCall()
579 assert not callable(a), (
580 "Builtin function 'callable' misreads uncallable object")
581 a.__call__ = lambda: "foo"
582 assert not callable(a), (
583 "Builtin function 'callable' tricked by instance-__call__")
584 class NoCall:
585 pass
586 assert not callable(NoCall())
587
588 def test_hash(self):
589 assert hash(23) == hash(23)
590 assert hash(2.3) == hash(2.3)
591 assert hash('23') == hash("23")
592 assert hash((23,)) == hash((23,))
593 assert hash(22) != hash(23)
594 raises(TypeError, hash, [])
595 raises(TypeError, hash, {})
596
597 def test_eval(self):
598 assert eval("1+2") == 3
599 assert eval(" \t1+2\n") == 3
600 assert eval("len([])") == 0
601 assert eval("len([])", {}) == 0
602 # cpython 2.4 allows this (raises in 2.3)
603 assert eval("3", None, None) == 3
604 i = 4
605 assert eval("i", None, None) == 4
606 assert eval('a', None, dict(a=42)) == 42
607
608 def test_isinstance(self):
609 assert isinstance(5, int)
610 assert isinstance(5, object)
611 assert not isinstance(5, float)
612 assert isinstance(True, (int, float))
613 assert not isinstance(True, (type, float))
614 assert isinstance(True, ((type, float), bool))
615 raises(TypeError, isinstance, 5, 6)
616 raises(TypeError, isinstance, 5, (float, 6))
617
618 def test_issubclass(self):
619 assert issubclass(int, int)
620 assert issubclass(int, object)
621 assert not issubclass(int, float)
622 assert issubclass(bool, (int, float))
623 assert not issubclass(bool, (type, float))
624 assert issubclass(bool, ((type, float), bool))
625 raises(TypeError, issubclass, 5, int)
626 raises(TypeError, issubclass, int, 6)
627 raises(TypeError, issubclass, int, (float, 6))
628
629 def test_staticmethod(self):
630 class X(object):
631 def f(*args, **kwds): return args, kwds
632 f = staticmethod(f)
633 assert X.f() == ((), {})
634 assert X.f(42, x=43) == ((42,), {'x': 43})
635 assert X().f() == ((), {})
636 assert X().f(42, x=43) == ((42,), {'x': 43})
637
638 def test_classmethod(self):
639 class X(object):
640 def f(*args, **kwds): return args, kwds
641 f = classmethod(f)
642 class Y(X):
643 pass
644 assert X.f() == ((X,), {})
645 assert X.f(42, x=43) == ((X, 42), {'x': 43})
646 assert X().f() == ((X,), {})
647 assert X().f(42, x=43) == ((X, 42), {'x': 43})
648 assert Y.f() == ((Y,), {})
649 assert Y.f(42, x=43) == ((Y, 42), {'x': 43})
650 assert Y().f() == ((Y,), {})
651 assert Y().f(42, x=43) == ((Y, 42), {'x': 43})
652
653 def test_hasattr(self):
654 class X(object):
655 def broken(): pass # TypeError
656 abc = property(broken)
657 def broken2(): raise IOError
658 bac = property(broken2)
659 x = X()
660 x.foo = 42
661 assert hasattr(x, '__class__') is True
662 assert hasattr(x, 'foo') is True
663 assert hasattr(x, 'bar') is False
664 raises(TypeError, "hasattr(x, 'abc')")
665 raises(TypeError, "hasattr(x, 'bac')")
666 raises(TypeError, hasattr, x, None)
667 raises(TypeError, hasattr, x, 42)
668 assert hasattr(x, '\u5678') is False
669
670 def test_hasattr_exception(self):
671 class X(object):
672 def __getattr__(self, name):
673 if name == 'foo':
674 raise AttributeError
675 else:
676 raise KeyError
677 x = X()
678 assert hasattr(x, 'foo') is False
679 raises(KeyError, "hasattr(x, 'bar')")
680
681 def test_print_function(self):
682 import builtins
683 import sys
684 import _io
685 pr = getattr(builtins, "print")
686 save = sys.stdout
687 out = sys.stdout = _io.StringIO()
688 try:
689 pr("Hello,", "person!")
690 pr("2nd line", file=None)
691 sys.stdout = None
692 pr("nowhere")
693 finally:
694 sys.stdout = save
695 assert out.getvalue() == "Hello, person!\n2nd line\n"
696 out = _io.StringIO()
697 pr("Hello,", "person!", file=out)
698 assert out.getvalue() == "Hello, person!\n"
699 out = _io.StringIO()
700 pr("Hello,", "person!", file=out, end="")
701 assert out.getvalue() == "Hello, person!"
702 out = _io.StringIO()
703 pr("Hello,", "person!", file=out, sep="X")
704 assert out.getvalue() == "Hello,Xperson!\n"
705 out = _io.StringIO()
706 pr(b"Hello,", b"person!", file=out)
707 result = out.getvalue()
708 assert isinstance(result, str)
709 assert result == "b'Hello,' b'person!'\n"
710 out = _io.StringIO()
711 pr(None, file=out)
712 assert out.getvalue() == "None\n"
713 out = sys.stdout = _io.StringIO()
714 try:
715 pr("amaury", file=None)
716 finally:
717 sys.stdout = save
718 assert out.getvalue() == "amaury\n"
719
720 def test_print_function2(self):
721 import builtins
722 import _io
723 class MyStr(str):
724 def __str__(self):
725 return "sqlalchemy"
726 out = _io.StringIO()
727 s = MyStr('A')
728 pr = getattr(builtins, 'print')
729 pr(s, file=out)
730 pr(str(s), file=out)
731 assert out.getvalue() == "sqlalchemy\nsqlalchemy\n"
732
733 def test_print_exceptions(self):
734 import builtins
735 pr = getattr(builtins, "print")
736 raises(TypeError, pr, x=3)
737 raises(TypeError, pr, end=3)
738 raises(TypeError, pr, sep=42)
739
740 def test_round(self):
741 assert round(11.234) == 11
742 assert type(round(11.234)) is int
743 assert round(11.234, -1) == 10
744 assert type(round(11.234, -1)) is float
745 assert round(11.234, 0) == 11
746 assert round(11.234, 1) == 11.2
747 #
748 assert round(5e15-1) == 5e15-1
749 assert round(5e15) == 5e15
750 assert round(-(5e15-1)) == -(5e15-1)
751 assert round(-5e15) == -5e15
752 assert round(5e15/2) == 5e15/2
753 assert round((5e15+1)/2) == 5e15/2
754 assert round((5e15-1)/2) == 5e15/2
755 #
756 inf = 1e200 * 1e200
757 raises(OverflowError, round, inf)
758 raises(OverflowError, round, -inf)
759 nan = inf / inf
760 raises(ValueError, round, nan)
761 raises(OverflowError, round, 1.6e308, -308)
762 #
763 assert round(562949953421312.5, 1) == 562949953421312.5
764 assert round(56294995342131.5, 3) == 56294995342131.5
765 #
766 for i in range(-10, 10):
767 expected = i + (i % 2)
768 assert round(i + 0.5) == round(i + 0.5, 0) == expected
769 x = i * 10 + 5
770 assert round(x, -1) == round(float(x), -1) == expected * 10
771
772 assert round(0.0) == 0.0
773 assert type(round(0.0)) == int
774 assert round(1.0) == 1.0
775 assert round(10.0) == 10.0
776 assert round(1000000000.0) == 1000000000.0
777 assert round(1e20) == 1e20
778
779 assert round(-1.0) == -1.0
780 assert round(-10.0) == -10.0
781 assert round(-1000000000.0) == -1000000000.0
782 assert round(-1e20) == -1e20
783
784 assert round(0.1) == 0.0
785 assert round(1.1) == 1.0
786 assert round(10.1) == 10.0
787 assert round(1000000000.1) == 1000000000.0
788
789 assert round(-1.1) == -1.0
790 assert round(-10.1) == -10.0
791 assert round(-1000000000.1) == -1000000000.0
792
793 assert round(0.9) == 1.0
794 assert round(9.9) == 10.0
795 assert round(999999999.9) == 1000000000.0
796
797 assert round(-0.9) == -1.0
798 assert round(-9.9) == -10.0
799 assert round(-999999999.9) == -1000000000.0
800
801 assert round(-8.0, -1) == -10.0
802 assert type(round(-8.0, -1)) == float
803
804 assert type(round(-8.0, 0)) == float
805 assert type(round(-8.0, 1)) == float
806
807 # Check even / odd rounding behaviour
808 assert round(5.5) == 6
809 assert round(6.5) == 6
810 assert round(-5.5) == -6
811 assert round(-6.5) == -6
812
813 # Check behavior on ints
814 assert round(0) == 0
815 assert round(8) == 8
816 assert round(-8) == -8
817 assert type(round(0)) == int
818 assert type(round(-8, -1)) == int
819 assert type(round(-8, 0)) == int
820 assert type(round(-8, 1)) == int
821
822 assert round(number=-8.0, ndigits=-1) == -10.0
823 raises(TypeError, round)
824
825 # test generic rounding delegation for reals
826 class TestRound:
827 def __round__(self):
828 return 23
829
830 class TestNoRound:
831 pass
832
833 assert round(TestRound()) == 23
834
835 raises(TypeError, round, 1, 2, 3)
836 raises(TypeError, round, TestNoRound())
837
838 t = TestNoRound()
839 t.__round__ = lambda *args: args
840 raises(TypeError, round, t)
841 raises(TypeError, round, t, 0)
842
843 assert round(3, ndigits=None) == 3
844 assert round(3.0, ndigits=None) == 3
845 assert type(round(3.0, ndigits=None)) is int
846
847 def test_vars_obscure_case(self):
848 class C_get_vars(object):
849 def getDict(self):
850 return {'a':2}
851 __dict__ = property(fget=getDict)
852 assert vars(C_get_vars()) == {'a':2}
853
854 def test_len_negative_overflow(self):
855 import sys
856 class NegativeLen:
857 def __len__(self):
858 return -10
859 raises(ValueError, len, NegativeLen())
860 class HugeLen:
861 def __len__(self):
862 return sys.maxsize + 1
863 raises(OverflowError, len, HugeLen())
864 class HugeNegativeLen:
865 def __len__(self):
866 return -sys.maxsize-10
867 raises(ValueError, len, HugeNegativeLen())
868
869
870 class AppTestGetattr:
871 spaceconfig = {}
872
873 def test_getattr(self):
874 class a(object):
875 i = 5
876 assert getattr(a, 'i') == 5
877 raises(AttributeError, getattr, a, 'k')
878 assert getattr(a, 'k', 42) == 42
879 raises(TypeError, getattr, a, b'i')
880 raises(TypeError, getattr, a, b'k', 42)
881
882 def test_getattr_typecheck(self):
883 class A(object):
884 def __getattribute__(self, name):
885 pass
886 def __setattr__(self, name, value):
887 pass
888 def __delattr__(self, name):
889 pass
890 raises(TypeError, getattr, A(), 42)
891 raises(TypeError, setattr, A(), 42, 'x')
892 raises(TypeError, delattr, A(), 42)
893
894 def test_getattr_None(self):
895 import sys
896 if '__pypy__' not in sys.modules:
897 skip('CPython uses wrapper types for this')
898 class C:
899 def _m(self): pass
900 assert isinstance(getattr(type(None), '__eq__'), type(lambda: None))
901 assert isinstance(getattr(None, '__eq__'), type(C()._m))
902
903 def test_getattr_userobject(self):
904 class C:
905 def _m(self): pass
906 class A(object):
907 def __eq__(self, other):
908 pass
909 a = A()
910 assert isinstance(getattr(A, '__eq__'), type(lambda: None))
911 assert isinstance(getattr(a, '__eq__'), type(C()._m))
912 a.__eq__ = 42
913 assert a.__eq__ == 42
914
915 def test_pow_kwarg(self):
916 assert pow(base=5, exp=2, mod=14) == 11