Source

pypy / pypy / module / __builtin__ / test / test_builtin.py

Full commit
Philip Jenvey e0b22ce 
holger krekel b1f618f 
Carl Friedrich B… 5deba59 
holger krekel b1f618f 

Armin Rigo 2e07b6d 












Armin Rigo 8fbb335 




Amaury Forgeot d… a03792c 
Armin Rigo 8fbb335 


Armin Rigo 2e07b6d 
Benjamin Peterso… 0f1cc46 
Amaury Forgeot d… 22fa140 

Benjamin Peterso… 0f1cc46 
holger krekel b1f618f 






Philip Jenvey e0b22ce 





























Antonio Cuni 07761ed 


Philip Jenvey e0b22ce 



holger krekel b1f618f 
Benjamin Peterso… 76ca29a 
Antonio Cuni 9a0f439 


Benjamin Peterso… 76ca29a 

Antonio Cuni 7ca5d45 

Antonio Cuni 9a0f439 
Benjamin Peterso… 76ca29a 

Antonio Cuni 4d73687 





















Amaury Forgeot d… b42bce2 
Armin Rigo 8a199de 
Amaury Forgeot d… b42bce2 


Amaury Forgeot d… bd9c6f5 
Amaury Forgeot d… b42bce2 
Amaury Forgeot d… bd9c6f5 
Amaury Forgeot d… b42bce2 
Amaury Forgeot d… 18e23a4 

Amaury Forgeot d… b42bce2 
holger krekel b1f618f 


Amaury Forgeot d… 22fa140 
holger krekel b1f618f 


















Maciej Fijalkows… b5a2e0b 
holger krekel b1f618f 
Maciej Fijalkows… b5a2e0b 
holger krekel b1f618f 




Armin Rigo 8b2e990 
Maciej Fijalkows… b5a2e0b 
Armin Rigo 8b2e990 


Antonio Cuni 460767d 


Armin Rigo 8b2e990 
Amaury Forgeot d… 970de09 





Amaury Forgeot d… addc4bc 






Armin Rigo b30637b 


Benjamin Peterso… f3806c4 
Armin Rigo b30637b 
Benjamin Peterso… f3806c4 
Benjamin Peterso… c51441e 



Armin Rigo b30637b 




Benjamin Peterso… 7315894 




Armin Rigo b30637b 
Benjamin Peterso… 25ddcf1 








Benjamin Peterso… 7e07c00 





holger krekel b1f618f 













Armin Rigo 99f9d99 





holger krekel b1f618f 






Amaury Forgeot d… 22fa140 



holger krekel b1f618f 







Antonio Cuni 82fe081 
holger krekel b1f618f 













Amaury Forgeot d… 22fa140 


holger krekel b1f618f 



Amaury Forgeot d… 22fa140 


holger krekel b1f618f 

Benjamin Peterso… 4978db5 
Amaury Forgeot d… 77f2578 
holger krekel b1f618f 
Amaury Forgeot d… 5a3c4e2 











Amaury Forgeot d… 22fa140 
Amaury Forgeot d… 5a3c4e2 






Amaury Forgeot d… fea4448 


holger krekel b1f618f 



Amaury Forgeot d… fea4448 
holger krekel b1f618f 



Amaury Forgeot d… fea4448 
holger krekel b1f618f 



Amaury Forgeot d… fea4448 
holger krekel b1f618f 
Philip Jenvey 35eee26 
Amaury Forgeot d… 77f2578 
Amaury Forgeot d… fea4448 
Antonio Cuni fff2759 
holger krekel b1f618f 
Amaury Forgeot d… fea4448 

holger krekel b1f618f 
Amaury Forgeot d… 22fa140 


holger krekel b1f618f 
Amaury Forgeot d… fea4448 

holger krekel b1f618f 

Amaury Forgeot d… 22fa140 


holger krekel b1f618f 
Amaury Forgeot d… fea4448 

holger krekel b1f618f 
Amaury Forgeot d… fea4448 

holger krekel b1f618f 
Amaury Forgeot d… 22fa140 
Amaury Forgeot d… fea4448 
holger krekel b1f618f 
Amaury Forgeot d… fea4448 
Armin Rigo 0d404d0 
Amaury Forgeot d… 22fa140 
Armin Rigo 0d404d0 
Amaury Forgeot d… fea4448 
holger krekel b1f618f 
Amaury Forgeot d… fea4448 
holger krekel b1f618f 
Amaury Forgeot d… fea4448 
holger krekel b1f618f 
Amaury Forgeot d… fea4448 
holger krekel b1f618f 

Amaury Forgeot d… fea4448 

holger krekel b1f618f 



Antonio Cuni bbc579e 
holger krekel b1f618f 
Amaury Forgeot d… fea4448 







holger krekel b1f618f 




























Maciej Fijalkows… b5a2e0b 
holger krekel b1f618f 





Maciej Fijalkows… b5a2e0b 
holger krekel b1f618f 









Maciej Fijalkows… b5a2e0b 
holger krekel b1f618f 

























Maciej Fijalkows… b5a2e0b 
holger krekel b1f618f 















holger krekel da098d9 



Amaury Forgeot d… 8eef819 
holger krekel b1f618f 



Benjamin Peterso… f6ad098 
holger krekel b1f618f 
Amaury Forgeot d… 22fa140 
holger krekel b1f618f 
Benjamin Peterso… 4458afc 
holger krekel b1f618f 

Armin Rigo 0d404d0 
Antonio Cuni bbe53f6 
Amaury Forgeot d… 77f2578 
Antonio Cuni 0952b07 
Amaury Forgeot d… 1afdb2a 


Philip Jenvey 1df7698 




Amaury Forgeot d… 34ed915 



Amaury Forgeot d… 22fa140 
Amaury Forgeot d… 34ed915 



holger krekel b1f618f 





















Maciej Fijalkows… b5a2e0b 
holger krekel b1f618f 







Maciej Fijalkows… b5a2e0b 
holger krekel b1f618f 












Armin Rigo 9ab84bf 

Armin Rigo e43a517 
Armin Rigo 9ab84bf 
Armin Rigo e43a517 

Armin Rigo 9ab84bf 

Armin Rigo 2c9bf00 


Antonio Cuni 041810e 

Armin Rigo e43a517 

Antonio Cuni 041810e 
Armin Rigo 0d404d0 
Antonio Cuni 16ec258 









holger krekel b1f618f 
Antonio Cuni 1ecc1c4 







Benjamin Peterso… 74db835 
Amaury Forgeot d… 22fa140 
Benjamin Peterso… 74db835 
Amaury Forgeot d… 22fa140 

Benjamin Peterso… 74db835 
Amaury Forgeot d… 22fa140 
Benjamin Peterso… 74db835 




Amaury Forgeot d… 22fa140 
Benjamin Peterso… 74db835 

Amaury Forgeot d… 22fa140 
Benjamin Peterso… 74db835 

Amaury Forgeot d… 22fa140 
Benjamin Peterso… 74db835 

Amaury Forgeot d… 22fa140 
Antonio Cuni 84ac123 
Benjamin Peterso… 74db835 
Amaury Forgeot d… 22fa140 
Antonio Cuni 84ac123 

Benjamin Peterso… 74db835 
Amaury Forgeot d… 22fa140 
Benjamin Peterso… 74db835 
Benjamin Peterso… 50fe490 
Benjamin Peterso… 74db835 
Philip Jenvey c914d9d 












Benjamin Peterso… 74db835 
Amaury Forgeot d… 22fa140 

Benjamin Peterso… 74db835 



Armin Rigo bc90444 
Amaury Forgeot d… 77f2578 




Armin Rigo 2668082 

Armin Rigo bc90444 



Armin Rigo 2668082 

Amaury Forgeot d… 77f2578 

Armin Rigo 2668082 
Amaury Forgeot d… 77f2578 
Armin Rigo 2668082 
Amaury Forgeot d… 85cf8a4 


Armin Rigo bc90444 
Philip Jenvey 5460b86 






































































Philip Jenvey 1fd7920 

Armin Rigo 853fe8d 






Maciej Fijalkows… b5a2e0b 
Philip Jenvey a858967 
Amaury Forgeot d… 9fa214a 
Philip Jenvey a858967 






Philip Jenvey 35eee26 

Philip Jenvey a858967 














Amaury Forgeot d… 9fa214a 
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
# coding: utf-8
import autopath
import sys

class AppTestBuiltinApp:
    def setup_class(cls):
        class X(object):
            def __eq__(self, other):
                raise OverflowError
            def __hash__(self):
                return 42
        d = {X(): 5}
        try:
            d[X()]
        except OverflowError:
            cls.w_sane_lookup = cls.space.wrap(True)
        except KeyError:
            cls.w_sane_lookup = cls.space.wrap(False)
        # starting with CPython 2.6, when the stack is almost out, we
        # can get a random error, instead of just a RuntimeError.
        # For example if an object x has a __getattr__, we can get
        # AttributeError if attempting to call x.__getattr__ runs out
        # of stack.  That's annoying, so we just work around it.
        if cls.runappdirect:
            cls.w_safe_runtimerror = cls.space.wrap(True)
        else:
            cls.w_safe_runtimerror = cls.space.wrap(sys.version_info < (2, 6))

    def test_bytes_alias(self):
        assert bytes is not str
        assert isinstance(eval("b'hi'"), bytes)

    def test_import(self):
        m = __import__('pprint')
        assert m.pformat({}) == '{}'
        assert m.__name__ == "pprint"
        raises(ImportError, __import__, 'spamspam')
        raises(TypeError, __import__, 1, 2, 3, 4)

    def test_ascii(self):
        assert ascii('') == '\'\''
        assert ascii(0) == '0'
        assert ascii(()) == '()'
        assert ascii([]) == '[]'
        assert ascii({}) == '{}'
        a = []
        a.append(a)
        assert ascii(a) == '[[...]]'
        a = {}
        a[0] = a
        assert ascii(a) == '{0: {...}}'
        # Advanced checks for unicode strings
        def _check_uni(s):
            assert ascii(s) == repr(s)
        _check_uni("'")
        _check_uni('"')
        _check_uni('"\'')
        _check_uni('\0')
        _check_uni('\r\n\t .')
        # Unprintable non-ASCII characters
        _check_uni('\x85')
        _check_uni('\u1fff')
        _check_uni('\U00012fff')
        # Lone surrogates
        _check_uni('\ud800')
        _check_uni('\udfff')
        # Issue #9804: surrogates should be joined even for printable
        # wide characters (UCS-2 builds).
        assert ascii('\U0001d121') == "'\\U0001d121'"
        # another buggy case
        x = ascii("\U00012fff")
        assert x == r"'\U00012fff'"
        # All together
        s = "'\0\"\n\r\t abcd\x85é\U00012fff\uD800\U0001D121xxx."
        assert ascii(s) == \
            r"""'\'\x00"\n\r\t abcd\x85\xe9\U00012fff\ud800\U0001d121xxx.'"""

    def test_bin(self):
        class Foo:
            def __index__(self):
                return 4
        assert bin(0) == "0b0"
        assert bin(-1) == "-0b1"
        assert bin(2) == "0b10"
        assert bin(-2) == "-0b10"
        assert bin(Foo()) == "0b100"
        raises(TypeError, bin, 0.)

    def test_oct(self):
        class Foo:
            def __index__(self):
                return 4
        assert oct(0) == "0o0"
        assert oct(-1) == "-0o1"
        assert oct(8) == "0o10"
        assert oct(-8) == "-0o10"
        assert oct(Foo()) == "0o4"
        raises(TypeError, oct, 0.)

    def test_hex(self):
        class Foo:
            def __index__(self):
                return 4
        assert hex(0) == "0x0"
        assert hex(-1) == "-0x1"
        assert hex(16) == "0x10"
        assert hex(-16) == "-0x10"
        assert hex(Foo()) == "0x4"
        raises(TypeError, hex, 0.)

    def test_chr(self):
        import sys
        assert chr(65) == 'A'
        assert type(str(65)) is str
        assert chr(0x9876) == '\u9876'
        if sys.maxunicode > 0xFFFF:
            assert chr(sys.maxunicode) == '\U0010FFFF'
        else:
            assert chr(sys.maxunicode) == '\uFFFF'
        assert chr(0x00010000) == '\U00010000'
        assert chr(0x0010ffff) == '\U0010FFFF'
        raises(ValueError, chr, -1)

    def test_globals(self):
        d = {"foo":"bar"}
        exec("def f(): return globals()", d)
        d2 = d["f"]()
        assert d2 is d

    def test_locals(self):
        def f():
            return locals()
        def g(c=0, b=0, a=0):
            return locals()
        assert f() == {}
        assert g() == {'a':0, 'b':0, 'c':0}

    def test_dir(self):
        def f():
            return dir()
        def g(c=0, b=0, a=0):
            return dir()
        def nosp(x): return [y for y in x if y[0]!='_']
        assert f() == []
        assert g() == ['a', 'b', 'c']
        class X(object): pass
        assert nosp(dir(X)) == []
        class X(object):
            a = 23
            c = 45
            b = 67
        assert nosp(dir(X)) == ['a', 'b', 'c']

    def test_dir_in_broken_locals(self):
        class C(object):
            def __getitem__(self, item):
                raise KeyError(item)
            def keys(self):
                return 'abcd'    # not a list!
        names = eval("dir()", {}, C())
        assert names == ['a', 'b', 'c', 'd']

    def test_dir_broken_module(self):
        import types
        class Foo(types.ModuleType):
            __dict__ = 8
        raises(TypeError, dir, Foo("foo"))

    def test_dir_broken_object(self):
        class Foo(object):
            x = 3
            def __getattribute__(self, name):
                return name
        assert dir(Foo()) == []

    def test_dir_custom(self):
        class Foo(object):
            def __dir__(self):
                return ["1", "2", "3"]
        f = Foo()
        assert dir(f) == ["1", "2", "3"]
        class Foo:
            def __dir__(self):
                return ["apple"]
        assert dir(Foo()) == ["apple"]
        class Foo(object):
            def __dir__(self):
                return 42
        f = Foo()
        raises(TypeError, dir, f)
        import types
        class Foo(types.ModuleType):
            def __dir__(self):
                return ["blah"]
        assert dir(Foo("a_mod")) == ["blah"]

    def test_dir_custom_lookup(self):
        class M(type):
            def __dir__(self, *args): return ["14"]
        class X(object):
            __metaclass__ = M
        x = X()
        x.__dir__ = lambda x: ["14"]
        assert dir(x) != ["14"]

    def test_format(self):
        assert format(4) == "4"
        assert format(10, "o") == "12"
        assert format(10, "#o") == "0o12"
        assert format("hi") == "hi"

    def test_vars(self):
        def f():
            return vars()
        def g(c=0, b=0, a=0):
            return vars()
        assert f() == {}
        assert g() == {'a':0, 'b':0, 'c':0}

    def test_sum(self):
        assert sum([]) ==0
        assert sum([42]) ==42
        assert sum([1,2,3]) ==6
        assert sum([],5) ==5
        assert sum([1,2,3],4) ==10
        #
        class Foo(object):
            def __radd__(self, other):
                assert other is None
                return 42
        assert sum([Foo()], None) == 42

    def test_type_selftest(self):
        assert type(type) is type

    def test_iter_sequence(self):
        raises(TypeError,iter,3)
        x = iter(['a','b','c'])
        assert next(x) =='a'
        assert next(x) =='b'
        assert next(x) =='c'
        raises(StopIteration, next, x)

    def test_iter___iter__(self):
        # This test assumes that dict.keys() method returns keys in
        # the same order as dict.__iter__().
        # Also, this test is not as explicit as the other tests;
        # it tests 4 calls to __iter__() in one assert.  It could
        # be modified if better granularity on the assert is required.
        mydict = {'a':1,'b':2,'c':3}
        assert list(iter(mydict)) == list(mydict.keys())

    def test_iter_callable_sentinel(self):
        class count(object):
            def __init__(self):
                self.value = 0
            def __call__(self):
                self.value += 1
                return self.value
        # XXX Raising errors is quite slow --
        #            uncomment these lines when fixed
        #self.assertRaises(TypeError,iter,3,5)
        #self.assertRaises(TypeError,iter,[],5)
        #self.assertRaises(TypeError,iter,{},5)
        x = iter(count(),3)
        assert next(x) ==1
        assert next(x) ==2
        raises(StopIteration, next, x)

    def test_enumerate(self):
        seq = range(2,4)
        enum = enumerate(seq)
        assert next(enum) == (0, 2)
        assert next(enum) == (1, 3)
        raises(StopIteration, next, enum)
        raises(TypeError, enumerate, 1)
        raises(TypeError, enumerate, None)
        enum = enumerate(range(5), 2)
        assert list(enum) == list(zip(range(2, 7), range(5)))

    def test_next(self):
        x = iter(['a', 'b', 'c'])
        assert next(x) == 'a'
        assert next(x) == 'b'
        assert next(x) == 'c'
        raises(StopIteration, next, x)
        assert next(x, 42) == 42

    def test_next__next__(self):
        class Counter:
            def __init__(self):
                self.count = 0
            def __next__(self):
                self.count += 1
                return self.count
        x = Counter()
        assert next(x) == 1
        assert next(x) == 2
        assert next(x) == 3

    def test_range_args(self):
##        # range() attributes are deprecated and were removed in Python 2.3.
##        x = range(2)
##        assert x.start == 0
##        assert x.stop == 2
##        assert x.step == 1

##        x = range(2,10,2)
##        assert x.start == 2
##        assert x.stop == 10
##        assert x.step == 2

##        x = range(2.3, 10.5, 2.4)
##        assert x.start == 2
##        assert x.stop == 10
##        assert x.step == 2

        raises(ValueError, range, 0, 1, 0)

    def test_range_repr(self):
        assert repr(range(1)) == 'range(0, 1)'
        assert repr(range(1,2)) == 'range(1, 2)'
        assert repr(range(1,2,3)) == 'range(1, 2, 3)'

    def test_range_up(self):
        x = range(2)
        iter_x = iter(x)
        assert next(iter_x) == 0
        assert next(iter_x) == 1
        raises(StopIteration, next, iter_x)

    def test_range_down(self):
        x = range(4,2,-1)

        iter_x = iter(x)
        assert next(iter_x) == 4
        assert next(iter_x) == 3
        raises(StopIteration, next, iter_x)

    def test_range_has_type_identity(self):
        assert type(range(1)) == type(range(1))

    def test_range_len(self):
        x = range(33)
        assert len(x) == 33
        raises(TypeError, range, 33.2)
        x = range(33,0,-1)
        assert len(x) == 33
        x = range(33,0)
        assert len(x) == 0
        raises(TypeError, range, 33, 0.2)
        assert len(x) == 0
        x = range(0,33)
        assert len(x) == 33
        x = range(0,33,-1)
        assert len(x) == 0
        x = range(0,33,2)
        assert len(x) == 17
        x = range(0,32,2)
        assert len(x) == 16

    def test_range_indexing(self):
        x = range(0,33,2)
        assert x[7] == 14
        assert x[-7] == 20
        raises(IndexError, x.__getitem__, 17)
        raises(IndexError, x.__getitem__, -18)
        assert list(x.__getitem__(slice(0,3,1))) == [0, 2, 4]

    def test_range_bad_args(self):
        raises(TypeError, range, '1')
        raises(TypeError, range, None)
        raises(TypeError, range, 3+2j)
        raises(TypeError, range, 1, '1')
        raises(TypeError, range, 1, 3+2j)
        raises(TypeError, range, 1, 2, '1')
        raises(TypeError, range, 1, 2, 3+2j)
    
    def test_sorted(self):
        l = []
        sorted_l = sorted(l)
        assert sorted_l is not l
        assert sorted_l == l
        l = [1, 5, 2, 3]
        sorted_l = sorted(l)
        assert sorted_l == [1, 2, 3, 5]

    def test_sorted_with_keywords(self):
        l = ['a', 'C', 'b']
        sorted_l = sorted(l, reverse = True)
        assert sorted_l is not l
        assert sorted_l == ['b', 'a', 'C']
        sorted_l = sorted(l, reverse = True, key = lambda x: x.lower())
        assert sorted_l is not l
        assert sorted_l == ['C', 'b', 'a']
        
    def test_reversed_simple_sequences(self):
        l = range(5)
        rev = reversed(l)
        assert list(rev) == [4, 3, 2, 1, 0]
        assert list(l.__reversed__()) == [4, 3, 2, 1, 0]
        s = "abcd"
        assert list(reversed(s)) == ['d', 'c', 'b', 'a']

    def test_reversed_custom_objects(self):
        """make sure __reversed__ is called when defined"""
        class SomeClass(object):
            def __reversed__(self):
                return 42
        obj = SomeClass()
        assert reversed(obj) == 42
    
    def test_return_None(self):
        class X(object): pass
        x = X()
        assert setattr(x, 'x', 11) == None
        assert delattr(x, 'x') == None
        # To make this test, we need autopath to work in application space.
        #self.assertEquals(execfile('emptyfile.py'), None)

    def test_divmod(self):
        assert divmod(15,10) ==(1,5)

    def test_callable(self):
        class Call(object):
            def __call__(self, a):
                return a+2
        assert callable(Call()), (
                    "Builtin function 'callable' misreads callable object")
        assert callable(int), (
                    "Builtin function 'callable' misreads int")
        class Call:
            def __call__(self, a):
                return a+2
        assert callable(Call())


    def test_uncallable(self):
        # XXX TODO: I made the NoCall class explicitly newstyle to try and
        # remedy the failure in this test observed when running this with
        # the trivial objectspace, but the test _still_ fails then (it
        # doesn't fail with the standard objectspace, though).
        class NoCall(object):
            pass
        a = NoCall()
        assert not callable(a), (
                    "Builtin function 'callable' misreads uncallable object")
        a.__call__ = lambda: "foo"
        assert not callable(a), (
                    "Builtin function 'callable' tricked by instance-__call__")
        class NoCall:
            pass
        assert not callable(NoCall())

    def test_hash(self):
        assert hash(23) == hash(23)
        assert hash(2.3) == hash(2.3)
        assert hash('23') == hash("23")
        assert hash((23,)) == hash((23,))
        assert hash(22) != hash(23)
        raises(TypeError, hash, [])
        raises(TypeError, hash, {})

    def test_eval(self):
        assert eval("1+2") == 3
        assert eval(" \t1+2\n") == 3
        assert eval("len([])") == 0
        assert eval("len([])", {}) == 0        
        # cpython 2.4 allows this (raises in 2.3)
        assert eval("3", None, None) == 3
        i = 4
        assert eval("i", None, None) == 4
        assert eval('a', None, dict(a=42)) == 42

    def test_compile(self):
        co = compile('1+2', '?', 'eval')
        assert eval(co) == 3
        compile("from __future__ import with_statement", "<test>", "exec")
        raises(SyntaxError, compile, '-', '?', 'eval')
        raises(SyntaxError, compile, '"\\xt"', '?', 'eval')
        raises(ValueError, compile, '1+2', '?', 'maybenot')
        raises(ValueError, compile, "\n", "<string>", "exec", 0xff)
        raises(TypeError, compile, '1+2', 12, 34)

    def test_unicode_encoding_compile(self):
        code = "# -*- coding: utf-8 -*-\npass\n"
        compile(code, "tmp", "exec")

    def test_bytes_compile(self):
        code = b"# -*- coding: utf-8 -*-\npass\n"
        compile(code, "tmp", "exec")
        c = compile(b"# coding: latin1\nfoo = 'caf\xe9'\n", "<string>", "exec")
        ns = {}
        exec(c, ns)
        assert ns['foo'] == 'café'
        assert eval(b"# coding: latin1\n'caf\xe9'\n") == 'café'

    def test_recompile_ast(self):
        import _ast
        # raise exception when node type doesn't match with compile mode
        co1 = compile('print(1)', '<string>', 'exec', _ast.PyCF_ONLY_AST)
        raises(TypeError, compile, co1, '<ast>', 'eval')
        co2 = compile('1+1', '<string>', 'eval', _ast.PyCF_ONLY_AST)
        compile(co2, '<ast>', 'eval')

    def test_isinstance(self):
        assert isinstance(5, int)
        assert isinstance(5, object)
        assert not isinstance(5, float)
        assert isinstance(True, (int, float))
        assert not isinstance(True, (type, float))
        assert isinstance(True, ((type, float), bool))
        raises(TypeError, isinstance, 5, 6)
        raises(TypeError, isinstance, 5, (float, 6))

    def test_issubclass(self):
        assert issubclass(int, int)
        assert issubclass(int, object)
        assert not issubclass(int, float)
        assert issubclass(bool, (int, float))
        assert not issubclass(bool, (type, float))
        assert issubclass(bool, ((type, float), bool))
        raises(TypeError, issubclass, 5, int)
        raises(TypeError, issubclass, int, 6)
        raises(TypeError, issubclass, int, (float, 6))

    def test_staticmethod(self):
        class X(object):
            def f(*args, **kwds): return args, kwds
            f = staticmethod(f)
        assert X.f() == ((), {})
        assert X.f(42, x=43) == ((42,), {'x': 43})
        assert X().f() == ((), {})
        assert X().f(42, x=43) == ((42,), {'x': 43})

    def test_classmethod(self):
        class X(object):
            def f(*args, **kwds): return args, kwds
            f = classmethod(f)
        class Y(X):
            pass
        assert X.f() == ((X,), {})
        assert X.f(42, x=43) == ((X, 42), {'x': 43})
        assert X().f() == ((X,), {})
        assert X().f(42, x=43) == ((X, 42), {'x': 43})
        assert Y.f() == ((Y,), {})
        assert Y.f(42, x=43) == ((Y, 42), {'x': 43})
        assert Y().f() == ((Y,), {})
        assert Y().f(42, x=43) == ((Y, 42), {'x': 43})

    def test_hasattr(self):
        class X(object):
            def broken(): pass   # TypeError
            abc = property(broken)
            def broken2(): raise IOError
            bac = property(broken2)
        x = X()
        x.foo = 42
        assert hasattr(x, '__class__') is True
        assert hasattr(x, 'foo') is True
        assert hasattr(x, 'bar') is False
        raises(TypeError, "hasattr(x, 'abc')")
        raises(TypeError, "hasattr(x, 'bac')")
        raises(TypeError, hasattr, x, None)
        raises(TypeError, hasattr, x, 42)
        assert hasattr(x, '\u5678') is False

    def test_hasattr_exception(self):
        class X(object):
            def __getattr__(self, name):
                if name == 'foo':
                    raise AttributeError
                else:
                    raise KeyError
        x = X()
        assert hasattr(x, 'foo') is False
        raises(KeyError, "hasattr(x, 'bar')")

    def test_compile_leading_newlines(self):
        src = """
def fn(): pass
"""
        co = compile(src, 'mymod', 'exec')
        firstlineno = co.co_firstlineno
        assert firstlineno == 2

    def test_print_function(self):
        import builtins
        import sys
        import io
        pr = getattr(builtins, "print")
        save = sys.stdout
        out = sys.stdout = io.StringIO()
        try:
            pr("Hello,", "person!")
        finally:
            sys.stdout = save
        assert out.getvalue() == "Hello, person!\n"
        out = io.StringIO()
        pr("Hello,", "person!", file=out)
        assert out.getvalue() == "Hello, person!\n"
        out = io.StringIO()
        pr("Hello,", "person!", file=out, end="")
        assert out.getvalue() == "Hello, person!"
        out = io.StringIO()
        pr("Hello,", "person!", file=out, sep="X")
        assert out.getvalue() == "Hello,Xperson!\n"
        out = io.StringIO()
        pr(b"Hello,", b"person!", file=out)
        result = out.getvalue()
        assert isinstance(result, str)
        print('XXXXXX', result)
        assert result == "b'Hello,' b'person!'\n"
        pr("Hello", file=None) # This works.
        out = io.StringIO()
        pr(None, file=out)
        assert out.getvalue() == "None\n"

    def test_print_function2(self):
        import builtins
        import io
        class MyStr(str):
            def __str__(self):
                return "sqlalchemy"
        out = io.StringIO()
        s = MyStr('A')
        pr = getattr(builtins, 'print')
        pr(s, file=out)
        pr(str(s), file=out)
        assert out.getvalue() == "sqlalchemy\nsqlalchemy\n"

    def test_print_exceptions(self):
        import builtins
        pr = getattr(builtins, "print")
        raises(TypeError, pr, x=3)
        raises(TypeError, pr, end=3)
        raises(TypeError, pr, sep=42)

    def test_round(self):
        assert round(11.234) == 11
        assert type(round(11.234)) is int
        assert round(11.234, -1) == 10
        assert type(round(11.234, -1)) is float
        assert round(11.234, 0) == 11
        assert round(11.234, 1) == 11.2
        #
        assert round(5e15-1) == 5e15-1
        assert round(5e15) == 5e15
        assert round(-(5e15-1)) == -(5e15-1)
        assert round(-5e15) == -5e15
        #
        inf = 1e200 * 1e200
        raises(OverflowError, round, inf)
        raises(OverflowError, round, -inf)
        nan = inf / inf
        raises(ValueError, round, nan)
        raises(OverflowError, round, 1.6e308, -308)
        #
        assert round(562949953421312.5, 1) == 562949953421312.5
        assert round(56294995342131.5, 3) == 56294995342131.5

        assert round(0.0) == 0.0
        assert type(round(0.0)) == int
        assert round(1.0) == 1.0
        assert round(10.0) == 10.0
        assert round(1000000000.0) == 1000000000.0
        assert round(1e20) == 1e20

        assert round(-1.0) == -1.0
        assert round(-10.0) == -10.0
        assert round(-1000000000.0) == -1000000000.0
        assert round(-1e20) == -1e20

        assert round(0.1) == 0.0
        assert round(1.1) == 1.0
        assert round(10.1) == 10.0
        assert round(1000000000.1) == 1000000000.0

        assert round(-1.1) == -1.0
        assert round(-10.1) == -10.0
        assert round(-1000000000.1) == -1000000000.0

        assert round(0.9) == 1.0
        assert round(9.9) == 10.0
        assert round(999999999.9) == 1000000000.0

        assert round(-0.9) == -1.0
        assert round(-9.9) == -10.0
        assert round(-999999999.9) == -1000000000.0

        assert round(-8.0, -1) == -10.0
        assert type(round(-8.0, -1)) == float

        assert type(round(-8.0, 0)) == float
        assert type(round(-8.0, 1)) == float

        # Check even / odd rounding behaviour
        assert round(5.5) == 6
        assert round(6.5) == 6
        assert round(-5.5) == -6
        assert round(-6.5) == -6

        # Check behavior on ints
        assert round(0) == 0
        assert round(8) == 8
        assert round(-8) == -8
        assert type(round(0)) == int
        assert type(round(-8, -1)) == int
        assert type(round(-8, 0)) == int
        assert type(round(-8, 1)) == int

        assert round(number=-8.0, ndigits=-1) == -10.0
        raises(TypeError, round)

        # test generic rounding delegation for reals
        class TestRound:
            def __round__(self):
                return 23

        class TestNoRound:
            pass

        assert round(TestRound()) == 23

        raises(TypeError, round, 1, 2, 3)
        raises(TypeError, round, TestNoRound())

        t = TestNoRound()
        t.__round__ = lambda *args: args
        raises(TypeError, round, t)
        raises(TypeError, round, t, 0)

        raises(TypeError, round, 3, None)

    def test_vars_obscure_case(self):
        class C_get_vars(object):
            def getDict(self):
                return {'a':2}
            __dict__ = property(fget=getDict)
        assert vars(C_get_vars()) == {'a':2}


class AppTestGetattr:
    spaceconfig = {}

    def test_getattr(self):
        class a(object):
            i = 5
        assert getattr(a, 'i') == 5
        raises(AttributeError, getattr, a, 'k')
        assert getattr(a, 'k', 42) == 42
        raises(TypeError, getattr, a, b'i')
        raises(TypeError, getattr, a, b'k', 42)

    def test_getattr_typecheck(self):
        class A(object):
            def __getattribute__(self, name):
                pass
            def __setattr__(self, name, value):
                pass
            def __delattr__(self, name):
                pass
        raises(TypeError, getattr, A(), 42)
        raises(TypeError, setattr, A(), 42, 'x')
        raises(TypeError, delattr, A(), 42)


class AppTestGetattrWithGetAttributeShortcut(AppTestGetattr):
    spaceconfig = {"objspace.std.getattributeshortcut": True}