• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# -*- coding: iso-8859-1 -*-
2import unittest, test.test_support
3from test.script_helper import assert_python_ok, assert_python_failure
4import cStringIO
5import gc
6import operator
7import os
8import struct
9import sys
10
11class SysModuleTest(unittest.TestCase):
12
13    def tearDown(self):
14        test.test_support.reap_children()
15
16    def test_original_displayhook(self):
17        import __builtin__
18        savestdout = sys.stdout
19        out = cStringIO.StringIO()
20        sys.stdout = out
21
22        dh = sys.__displayhook__
23
24        self.assertRaises(TypeError, dh)
25        if hasattr(__builtin__, "_"):
26            del __builtin__._
27
28        dh(None)
29        self.assertEqual(out.getvalue(), "")
30        self.assertTrue(not hasattr(__builtin__, "_"))
31        dh(42)
32        self.assertEqual(out.getvalue(), "42\n")
33        self.assertEqual(__builtin__._, 42)
34
35        del sys.stdout
36        self.assertRaises(RuntimeError, dh, 42)
37
38        sys.stdout = savestdout
39
40    def test_lost_displayhook(self):
41        olddisplayhook = sys.displayhook
42        del sys.displayhook
43        code = compile("42", "<string>", "single")
44        self.assertRaises(RuntimeError, eval, code)
45        sys.displayhook = olddisplayhook
46
47    def test_custom_displayhook(self):
48        olddisplayhook = sys.displayhook
49        def baddisplayhook(obj):
50            raise ValueError
51        sys.displayhook = baddisplayhook
52        code = compile("42", "<string>", "single")
53        self.assertRaises(ValueError, eval, code)
54        sys.displayhook = olddisplayhook
55
56    def test_original_excepthook(self):
57        savestderr = sys.stderr
58        err = cStringIO.StringIO()
59        sys.stderr = err
60
61        eh = sys.__excepthook__
62
63        self.assertRaises(TypeError, eh)
64        try:
65            raise ValueError(42)
66        except ValueError, exc:
67            eh(*sys.exc_info())
68
69        sys.stderr = savestderr
70        self.assertTrue(err.getvalue().endswith("ValueError: 42\n"))
71
72    # FIXME: testing the code for a lost or replaced excepthook in
73    # Python/pythonrun.c::PyErr_PrintEx() is tricky.
74
75    def test_exc_clear(self):
76        self.assertRaises(TypeError, sys.exc_clear, 42)
77
78        # Verify that exc_info is present and matches exc, then clear it, and
79        # check that it worked.
80        def clear_check(exc):
81            typ, value, traceback = sys.exc_info()
82            self.assertTrue(typ is not None)
83            self.assertTrue(value is exc)
84            self.assertTrue(traceback is not None)
85
86            with test.test_support.check_py3k_warnings():
87                sys.exc_clear()
88
89            typ, value, traceback = sys.exc_info()
90            self.assertTrue(typ is None)
91            self.assertTrue(value is None)
92            self.assertTrue(traceback is None)
93
94        def clear():
95            try:
96                raise ValueError, 42
97            except ValueError, exc:
98                clear_check(exc)
99
100        # Raise an exception and check that it can be cleared
101        clear()
102
103        # Verify that a frame currently handling an exception is
104        # unaffected by calling exc_clear in a nested frame.
105        try:
106            raise ValueError, 13
107        except ValueError, exc:
108            typ1, value1, traceback1 = sys.exc_info()
109            clear()
110            typ2, value2, traceback2 = sys.exc_info()
111
112            self.assertTrue(typ1 is typ2)
113            self.assertTrue(value1 is exc)
114            self.assertTrue(value1 is value2)
115            self.assertTrue(traceback1 is traceback2)
116
117        # Check that an exception can be cleared outside of an except block
118        clear_check(exc)
119
120    def test_exit(self):
121        # call with two arguments
122        self.assertRaises(TypeError, sys.exit, 42, 42)
123
124        # call without argument
125        with self.assertRaises(SystemExit) as cm:
126            sys.exit()
127        self.assertIsNone(cm.exception.code)
128
129        rc, out, err = assert_python_ok('-c', 'import sys; sys.exit()')
130        self.assertEqual(rc, 0)
131        self.assertEqual(out, b'')
132        self.assertEqual(err, b'')
133
134        # call with integer argument
135        with self.assertRaises(SystemExit) as cm:
136            sys.exit(42)
137        self.assertEqual(cm.exception.code, 42)
138
139        # call with tuple argument with one entry
140        # entry will be unpacked
141        with self.assertRaises(SystemExit) as cm:
142            sys.exit((42,))
143        self.assertEqual(cm.exception.code, 42)
144
145        # call with string argument
146        with self.assertRaises(SystemExit) as cm:
147            sys.exit("exit")
148        self.assertEqual(cm.exception.code, "exit")
149
150        # call with tuple argument with two entries
151        with self.assertRaises(SystemExit) as cm:
152            sys.exit((17, 23))
153        self.assertEqual(cm.exception.code, (17, 23))
154
155        # test that the exit machinery handles SystemExits properly
156        # both unnormalized...
157        rc, out, err = assert_python_failure('-c', 'raise SystemExit, 46')
158        self.assertEqual(rc, 46)
159        self.assertEqual(out, b'')
160        self.assertEqual(err, b'')
161        # ... and normalized
162        rc, out, err = assert_python_failure('-c', 'raise SystemExit(47)')
163        self.assertEqual(rc, 47)
164        self.assertEqual(out, b'')
165        self.assertEqual(err, b'')
166
167        # test that the exit machinery handles long exit codes
168        rc, out, err = assert_python_failure('-c', 'raise SystemExit(47L)')
169        self.assertEqual(rc, 47)
170        self.assertEqual(out, b'')
171        self.assertEqual(err, b'')
172
173        rc, out, err = assert_python_ok('-c', 'raise SystemExit(0L)')
174        self.assertEqual(rc, 0)
175        self.assertEqual(out, b'')
176        self.assertEqual(err, b'')
177
178        def check_exit_message(code, expected, **env_vars):
179            rc, out, err = assert_python_failure('-c', code, **env_vars)
180            self.assertEqual(rc, 1)
181            self.assertEqual(out, b'')
182            self.assertTrue(err.startswith(expected),
183                "%s doesn't start with %s" % (repr(err), repr(expected)))
184
185        # test that stderr buffer is flushed before the exit message is written
186        # into stderr
187        check_exit_message(
188            r'import sys; sys.stderr.write("unflushed,"); sys.exit("message")',
189            b"unflushed,message")
190
191        # test that the unicode message is encoded to the stderr encoding
192        check_exit_message(
193            r'import sys; sys.exit(u"h\xe9")',
194            b"h\xe9", PYTHONIOENCODING='latin-1')
195
196    def test_getdefaultencoding(self):
197        if test.test_support.have_unicode:
198            self.assertRaises(TypeError, sys.getdefaultencoding, 42)
199            # can't check more than the type, as the user might have changed it
200            self.assertIsInstance(sys.getdefaultencoding(), str)
201
202    # testing sys.settrace() is done in test_sys_settrace.py
203    # testing sys.setprofile() is done in test_sys_setprofile.py
204
205    def test_setcheckinterval(self):
206        self.assertRaises(TypeError, sys.setcheckinterval)
207        orig = sys.getcheckinterval()
208        for n in 0, 100, 120, orig: # orig last to restore starting state
209            sys.setcheckinterval(n)
210            self.assertEqual(sys.getcheckinterval(), n)
211
212    def test_recursionlimit(self):
213        self.assertRaises(TypeError, sys.getrecursionlimit, 42)
214        oldlimit = sys.getrecursionlimit()
215        self.assertRaises(TypeError, sys.setrecursionlimit)
216        self.assertRaises(ValueError, sys.setrecursionlimit, -42)
217        sys.setrecursionlimit(10000)
218        self.assertEqual(sys.getrecursionlimit(), 10000)
219        sys.setrecursionlimit(oldlimit)
220
221        self.assertRaises(OverflowError, sys.setrecursionlimit, 1 << 31)
222        try:
223            sys.setrecursionlimit((1 << 31) - 5)
224            try:
225                # issue13546: isinstance(e, ValueError) used to fail
226                # when the recursion limit is close to 1<<31
227                raise ValueError()
228            except ValueError, e:
229                pass
230        finally:
231            sys.setrecursionlimit(oldlimit)
232
233    def test_getwindowsversion(self):
234        # Raise SkipTest if sys doesn't have getwindowsversion attribute
235        test.test_support.get_attribute(sys, "getwindowsversion")
236        v = sys.getwindowsversion()
237        self.assertEqual(len(v), 5)
238        self.assertIsInstance(v[0], int)
239        self.assertIsInstance(v[1], int)
240        self.assertIsInstance(v[2], int)
241        self.assertIsInstance(v[3], int)
242        self.assertIsInstance(v[4], str)
243        self.assertRaises(IndexError, operator.getitem, v, 5)
244        self.assertIsInstance(v.major, int)
245        self.assertIsInstance(v.minor, int)
246        self.assertIsInstance(v.build, int)
247        self.assertIsInstance(v.platform, int)
248        self.assertIsInstance(v.service_pack, str)
249        self.assertIsInstance(v.service_pack_minor, int)
250        self.assertIsInstance(v.service_pack_major, int)
251        self.assertIsInstance(v.suite_mask, int)
252        self.assertIsInstance(v.product_type, int)
253        self.assertEqual(v[0], v.major)
254        self.assertEqual(v[1], v.minor)
255        self.assertEqual(v[2], v.build)
256        self.assertEqual(v[3], v.platform)
257        self.assertEqual(v[4], v.service_pack)
258
259        # This is how platform.py calls it. Make sure tuple
260        #  still has 5 elements
261        maj, min, buildno, plat, csd = sys.getwindowsversion()
262
263    @unittest.skipUnless(hasattr(sys, "setdlopenflags"),
264                         'test needs sys.setdlopenflags()')
265    def test_dlopenflags(self):
266        self.assertTrue(hasattr(sys, "getdlopenflags"))
267        self.assertRaises(TypeError, sys.getdlopenflags, 42)
268        oldflags = sys.getdlopenflags()
269        self.assertRaises(TypeError, sys.setdlopenflags)
270        sys.setdlopenflags(oldflags+1)
271        self.assertEqual(sys.getdlopenflags(), oldflags+1)
272        sys.setdlopenflags(oldflags)
273
274    def test_refcount(self):
275        # n here must be a global in order for this test to pass while
276        # tracing with a python function.  Tracing calls PyFrame_FastToLocals
277        # which will add a copy of any locals to the frame object, causing
278        # the reference count to increase by 2 instead of 1.
279        global n
280        self.assertRaises(TypeError, sys.getrefcount)
281        c = sys.getrefcount(None)
282        n = None
283        self.assertEqual(sys.getrefcount(None), c+1)
284        del n
285        self.assertEqual(sys.getrefcount(None), c)
286        if hasattr(sys, "gettotalrefcount"):
287            self.assertIsInstance(sys.gettotalrefcount(), int)
288
289    def test_getframe(self):
290        self.assertRaises(TypeError, sys._getframe, 42, 42)
291        self.assertRaises(ValueError, sys._getframe, 2000000000)
292        self.assertTrue(
293            SysModuleTest.test_getframe.im_func.func_code \
294            is sys._getframe().f_code
295        )
296
297    # sys._current_frames() is a CPython-only gimmick.
298    def test_current_frames(self):
299        have_threads = True
300        try:
301            import thread
302        except ImportError:
303            have_threads = False
304
305        if have_threads:
306            self.current_frames_with_threads()
307        else:
308            self.current_frames_without_threads()
309
310    # Test sys._current_frames() in a WITH_THREADS build.
311    @test.test_support.reap_threads
312    def current_frames_with_threads(self):
313        import threading, thread
314        import traceback
315
316        # Spawn a thread that blocks at a known place.  Then the main
317        # thread does sys._current_frames(), and verifies that the frames
318        # returned make sense.
319        entered_g = threading.Event()
320        leave_g = threading.Event()
321        thread_info = []  # the thread's id
322
323        def f123():
324            g456()
325
326        def g456():
327            thread_info.append(thread.get_ident())
328            entered_g.set()
329            leave_g.wait()
330
331        t = threading.Thread(target=f123)
332        t.start()
333        entered_g.wait()
334
335        # At this point, t has finished its entered_g.set(), although it's
336        # impossible to guess whether it's still on that line or has moved on
337        # to its leave_g.wait().
338        self.assertEqual(len(thread_info), 1)
339        thread_id = thread_info[0]
340
341        d = sys._current_frames()
342
343        main_id = thread.get_ident()
344        self.assertIn(main_id, d)
345        self.assertIn(thread_id, d)
346
347        # Verify that the captured main-thread frame is _this_ frame.
348        frame = d.pop(main_id)
349        self.assertTrue(frame is sys._getframe())
350
351        # Verify that the captured thread frame is blocked in g456, called
352        # from f123.  This is a litte tricky, since various bits of
353        # threading.py are also in the thread's call stack.
354        frame = d.pop(thread_id)
355        stack = traceback.extract_stack(frame)
356        for i, (filename, lineno, funcname, sourceline) in enumerate(stack):
357            if funcname == "f123":
358                break
359        else:
360            self.fail("didn't find f123() on thread's call stack")
361
362        self.assertEqual(sourceline, "g456()")
363
364        # And the next record must be for g456().
365        filename, lineno, funcname, sourceline = stack[i+1]
366        self.assertEqual(funcname, "g456")
367        self.assertIn(sourceline, ["leave_g.wait()", "entered_g.set()"])
368
369        # Reap the spawned thread.
370        leave_g.set()
371        t.join()
372
373    # Test sys._current_frames() when thread support doesn't exist.
374    def current_frames_without_threads(self):
375        # Not much happens here:  there is only one thread, with artificial
376        # "thread id" 0.
377        d = sys._current_frames()
378        self.assertEqual(len(d), 1)
379        self.assertIn(0, d)
380        self.assertTrue(d[0] is sys._getframe())
381
382    def test_attributes(self):
383        self.assertIsInstance(sys.api_version, int)
384        self.assertIsInstance(sys.argv, list)
385        self.assertIn(sys.byteorder, ("little", "big"))
386        self.assertIsInstance(sys.builtin_module_names, tuple)
387        self.assertIsInstance(sys.copyright, basestring)
388        self.assertIsInstance(sys.exec_prefix, basestring)
389        self.assertIsInstance(sys.executable, basestring)
390        self.assertEqual(len(sys.float_info), 11)
391        self.assertEqual(sys.float_info.radix, 2)
392        self.assertEqual(len(sys.long_info), 2)
393        self.assertTrue(sys.long_info.bits_per_digit % 5 == 0)
394        self.assertTrue(sys.long_info.sizeof_digit >= 1)
395        self.assertEqual(type(sys.long_info.bits_per_digit), int)
396        self.assertEqual(type(sys.long_info.sizeof_digit), int)
397        self.assertIsInstance(sys.hexversion, int)
398        self.assertIsInstance(sys.maxint, int)
399        if test.test_support.have_unicode:
400            self.assertIsInstance(sys.maxunicode, int)
401        self.assertIsInstance(sys.platform, basestring)
402        self.assertIsInstance(sys.prefix, basestring)
403        self.assertIsInstance(sys.version, basestring)
404        vi = sys.version_info
405        self.assertIsInstance(vi[:], tuple)
406        self.assertEqual(len(vi), 5)
407        self.assertIsInstance(vi[0], int)
408        self.assertIsInstance(vi[1], int)
409        self.assertIsInstance(vi[2], int)
410        self.assertIn(vi[3], ("alpha", "beta", "candidate", "final"))
411        self.assertIsInstance(vi[4], int)
412        self.assertIsInstance(vi.major, int)
413        self.assertIsInstance(vi.minor, int)
414        self.assertIsInstance(vi.micro, int)
415        self.assertIn(vi.releaselevel, ("alpha", "beta", "candidate", "final"))
416        self.assertIsInstance(vi.serial, int)
417        self.assertEqual(vi[0], vi.major)
418        self.assertEqual(vi[1], vi.minor)
419        self.assertEqual(vi[2], vi.micro)
420        self.assertEqual(vi[3], vi.releaselevel)
421        self.assertEqual(vi[4], vi.serial)
422        self.assertTrue(vi > (1,0,0))
423        self.assertIsInstance(sys.float_repr_style, str)
424        self.assertIn(sys.float_repr_style, ('short', 'legacy'))
425
426    def test_43581(self):
427        # Can't use sys.stdout, as this is a cStringIO object when
428        # the test runs under regrtest.
429        if not (os.environ.get('PYTHONIOENCODING') or
430                (sys.__stdout__.isatty() and sys.__stderr__.isatty())):
431            self.skipTest('stdout/stderr encoding is not set')
432        self.assertEqual(sys.__stdout__.encoding, sys.__stderr__.encoding)
433
434    def test_sys_flags(self):
435        self.assertTrue(sys.flags)
436        attrs = ("debug", "py3k_warning", "division_warning", "division_new",
437                 "inspect", "interactive", "optimize", "dont_write_bytecode",
438                 "no_site", "ignore_environment", "tabcheck", "verbose",
439                 "unicode", "bytes_warning", "hash_randomization")
440        for attr in attrs:
441            self.assertTrue(hasattr(sys.flags, attr), attr)
442            self.assertEqual(type(getattr(sys.flags, attr)), int, attr)
443        self.assertTrue(repr(sys.flags))
444
445    @test.test_support.cpython_only
446    def test_clear_type_cache(self):
447        sys._clear_type_cache()
448
449    def test_ioencoding(self):
450        import subprocess
451        env = dict(os.environ)
452
453        # Test character: cent sign, encoded as 0x4A (ASCII J) in CP424,
454        # not representable in ASCII.
455
456        env["PYTHONIOENCODING"] = "cp424"
457        p = subprocess.Popen([sys.executable, "-c", 'print unichr(0xa2)'],
458                             stdout = subprocess.PIPE, env=env)
459        out = p.communicate()[0].strip()
460        self.assertEqual(out, unichr(0xa2).encode("cp424"))
461
462        env["PYTHONIOENCODING"] = "ascii:replace"
463        p = subprocess.Popen([sys.executable, "-c", 'print unichr(0xa2)'],
464                             stdout = subprocess.PIPE, env=env)
465        out = p.communicate()[0].strip()
466        self.assertEqual(out, '?')
467
468    def test_call_tracing(self):
469        self.assertEqual(sys.call_tracing(str, (2,)), "2")
470        self.assertRaises(TypeError, sys.call_tracing, str, 2)
471
472    def test_executable(self):
473        # sys.executable should be absolute
474        self.assertEqual(os.path.abspath(sys.executable), sys.executable)
475
476        # Issue #7774: Ensure that sys.executable is an empty string if argv[0]
477        # has been set to a non existent program name and Python is unable to
478        # retrieve the real program name
479        import subprocess
480        # For a normal installation, it should work without 'cwd'
481        # argument. For test runs in the build directory, see #7774.
482        python_dir = os.path.dirname(os.path.realpath(sys.executable))
483        p = subprocess.Popen(
484            ["nonexistent", "-c", 'import sys; print repr(sys.executable)'],
485            executable=sys.executable, stdout=subprocess.PIPE, cwd=python_dir)
486        executable = p.communicate()[0].strip()
487        p.wait()
488        self.assertIn(executable, ["''", repr(sys.executable)])
489
490@test.test_support.cpython_only
491class SizeofTest(unittest.TestCase):
492
493    def setUp(self):
494        self.P = struct.calcsize('P')
495        self.longdigit = sys.long_info.sizeof_digit
496        import _testcapi
497        self.gc_headsize = _testcapi.SIZEOF_PYGC_HEAD
498
499    check_sizeof = test.test_support.check_sizeof
500
501    def test_gc_head_size(self):
502        # Check that the gc header size is added to objects tracked by the gc.
503        size = test.test_support.calcobjsize
504        gc_header_size = self.gc_headsize
505        # bool objects are not gc tracked
506        self.assertEqual(sys.getsizeof(True), size('l'))
507        # but lists are
508        self.assertEqual(sys.getsizeof([]), size('P PP') + gc_header_size)
509
510    def test_errors(self):
511        class BadSizeof(object):
512            def __sizeof__(self):
513                raise ValueError
514        self.assertRaises(ValueError, sys.getsizeof, BadSizeof())
515
516        class InvalidSizeof(object):
517            def __sizeof__(self):
518                return None
519        self.assertRaises(TypeError, sys.getsizeof, InvalidSizeof())
520        sentinel = ["sentinel"]
521        self.assertIs(sys.getsizeof(InvalidSizeof(), sentinel), sentinel)
522
523        class OverflowSizeof(long):
524            def __sizeof__(self):
525                return int(self)
526        self.assertEqual(sys.getsizeof(OverflowSizeof(sys.maxsize)),
527                         sys.maxsize + self.gc_headsize)
528        with self.assertRaises(OverflowError):
529            sys.getsizeof(OverflowSizeof(sys.maxsize + 1))
530        with self.assertRaises(ValueError):
531            sys.getsizeof(OverflowSizeof(-1))
532        with self.assertRaises((ValueError, OverflowError)):
533            sys.getsizeof(OverflowSizeof(-sys.maxsize - 1))
534
535    def test_default(self):
536        size = test.test_support.calcobjsize
537        self.assertEqual(sys.getsizeof(True, -1), size('l'))
538
539    def test_objecttypes(self):
540        # check all types defined in Objects/
541        calcsize = struct.calcsize
542        size = test.test_support.calcobjsize
543        vsize = test.test_support.calcvobjsize
544        check = self.check_sizeof
545        # bool
546        check(True, size('l'))
547        # buffer
548        with test.test_support.check_py3k_warnings():
549            check(buffer(''), size('2P2Pil'))
550        # builtin_function_or_method
551        check(len, size('3P'))
552        # bytearray
553        samples = ['', 'u'*100000]
554        for sample in samples:
555            x = bytearray(sample)
556            check(x, vsize('iPP') + x.__alloc__())
557        # bytearray_iterator
558        check(iter(bytearray()), size('PP'))
559        # cell
560        def get_cell():
561            x = 42
562            def inner():
563                return x
564            return inner
565        check(get_cell().func_closure[0], size('P'))
566        # classobj (old-style class)
567        class class_oldstyle():
568            def method():
569                pass
570        check(class_oldstyle, size('7P'))
571        # instance (old-style class)
572        check(class_oldstyle(), size('3P'))
573        # instancemethod (old-style class)
574        check(class_oldstyle().method, size('4P'))
575        # complex
576        check(complex(0,1), size('2d'))
577        # code
578        check(get_cell().func_code, size('4i8Pi3P'))
579        # BaseException
580        check(BaseException(), size('3P'))
581        # UnicodeEncodeError
582        check(UnicodeEncodeError("", u"", 0, 0, ""), size('5P2PP'))
583        # UnicodeDecodeError
584        check(UnicodeDecodeError("", "", 0, 0, ""), size('5P2PP'))
585        # UnicodeTranslateError
586        check(UnicodeTranslateError(u"", 0, 1, ""), size('5P2PP'))
587        # method_descriptor (descriptor object)
588        check(str.lower, size('2PP'))
589        # classmethod_descriptor (descriptor object)
590        # XXX
591        # member_descriptor (descriptor object)
592        import datetime
593        check(datetime.timedelta.days, size('2PP'))
594        # getset_descriptor (descriptor object)
595        import __builtin__
596        check(__builtin__.file.closed, size('2PP'))
597        # wrapper_descriptor (descriptor object)
598        check(int.__add__, size('2P2P'))
599        # dictproxy
600        class C(object): pass
601        check(C.__dict__, size('P'))
602        # method-wrapper (descriptor object)
603        check({}.__iter__, size('2P'))
604        # dict
605        check({}, size('3P2P') + 8*calcsize('P2P'))
606        x = {1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8}
607        check(x, size('3P2P') + 8*calcsize('P2P') + 16*calcsize('P2P'))
608        # dictionary-keyview
609        check({}.viewkeys(), size('P'))
610        # dictionary-valueview
611        check({}.viewvalues(), size('P'))
612        # dictionary-itemview
613        check({}.viewitems(), size('P'))
614        # dictionary iterator
615        check(iter({}), size('P2PPP'))
616        # dictionary-keyiterator
617        check({}.iterkeys(), size('P2PPP'))
618        # dictionary-valueiterator
619        check({}.itervalues(), size('P2PPP'))
620        # dictionary-itemiterator
621        check({}.iteritems(), size('P2PPP'))
622        # ellipses
623        check(Ellipsis, size(''))
624        # EncodingMap
625        import codecs, encodings.iso8859_3
626        x = codecs.charmap_build(encodings.iso8859_3.decoding_table)
627        check(x, size('32B2iB'))
628        # enumerate
629        check(enumerate([]), size('l3P'))
630        # file
631        f = file(test.test_support.TESTFN, 'wb')
632        try:
633            check(f, size('4P2i4P3i3P3i'))
634        finally:
635            f.close()
636            test.test_support.unlink(test.test_support.TESTFN)
637        # float
638        check(float(0), size('d'))
639        # sys.floatinfo
640        check(sys.float_info, vsize('') + self.P * len(sys.float_info))
641        # frame
642        import inspect
643        CO_MAXBLOCKS = 20
644        x = inspect.currentframe()
645        ncells = len(x.f_code.co_cellvars)
646        nfrees = len(x.f_code.co_freevars)
647        extras = x.f_code.co_stacksize + x.f_code.co_nlocals +\
648                 ncells + nfrees - 1
649        check(x, vsize('12P3i' + CO_MAXBLOCKS*'3i' + 'P' + extras*'P'))
650        # function
651        def func(): pass
652        check(func, size('9P'))
653        class c():
654            @staticmethod
655            def foo():
656                pass
657            @classmethod
658            def bar(cls):
659                pass
660            # staticmethod
661            check(foo, size('P'))
662            # classmethod
663            check(bar, size('P'))
664        # generator
665        def get_gen(): yield 1
666        check(get_gen(), size('Pi2P'))
667        # integer
668        check(1, size('l'))
669        check(100, size('l'))
670        # iterator
671        check(iter('abc'), size('lP'))
672        # callable-iterator
673        import re
674        check(re.finditer('',''), size('2P'))
675        # list
676        samples = [[], [1,2,3], ['1', '2', '3']]
677        for sample in samples:
678            check(sample, vsize('PP') + len(sample)*self.P)
679        # sortwrapper (list)
680        # XXX
681        # cmpwrapper (list)
682        # XXX
683        # listiterator (list)
684        check(iter([]), size('lP'))
685        # listreverseiterator (list)
686        check(reversed([]), size('lP'))
687        # long
688        check(0L, vsize(''))
689        check(1L, vsize('') + self.longdigit)
690        check(-1L, vsize('') + self.longdigit)
691        PyLong_BASE = 2**sys.long_info.bits_per_digit
692        check(long(PyLong_BASE), vsize('') + 2*self.longdigit)
693        check(long(PyLong_BASE**2-1), vsize('') + 2*self.longdigit)
694        check(long(PyLong_BASE**2), vsize('') + 3*self.longdigit)
695        # module
696        check(unittest, size('P'))
697        # None
698        check(None, size(''))
699        # object
700        check(object(), size(''))
701        # property (descriptor object)
702        class C(object):
703            def getx(self): return self.__x
704            def setx(self, value): self.__x = value
705            def delx(self): del self.__x
706            x = property(getx, setx, delx, "")
707            check(x, size('4Pi'))
708        # PyCObject
709        # PyCapsule
710        # XXX
711        # rangeiterator
712        check(iter(xrange(1)), size('4l'))
713        # reverse
714        check(reversed(''), size('PP'))
715        # set
716        # frozenset
717        PySet_MINSIZE = 8
718        samples = [[], range(10), range(50)]
719        s = size('3P2P' + PySet_MINSIZE*'lP' + 'lP')
720        for sample in samples:
721            minused = len(sample)
722            if minused == 0: tmp = 1
723            # the computation of minused is actually a bit more complicated
724            # but this suffices for the sizeof test
725            minused = minused*2
726            newsize = PySet_MINSIZE
727            while newsize <= minused:
728                newsize = newsize << 1
729            if newsize <= 8:
730                check(set(sample), s)
731                check(frozenset(sample), s)
732            else:
733                check(set(sample), s + newsize*calcsize('lP'))
734                check(frozenset(sample), s + newsize*calcsize('lP'))
735        # setiterator
736        check(iter(set()), size('P3P'))
737        # slice
738        check(slice(1), size('3P'))
739        # str
740        vh = test.test_support._vheader
741        check('', calcsize(vh + 'lic'))
742        check('abc', calcsize(vh + 'lic') + 3)
743        # super
744        check(super(int), size('3P'))
745        # tuple
746        check((), vsize(''))
747        check((1,2,3), vsize('') + 3*self.P)
748        # tupleiterator
749        check(iter(()), size('lP'))
750        # type
751        fmt = 'P2P15Pl4PP9PP11PI'
752        if hasattr(sys, 'getcounts'):
753            fmt += '3P2P'
754        s = vsize(fmt +                 # PyTypeObject
755                  '39P'                 # PyNumberMethods
756                  '3P'                  # PyMappingMethods
757                  '10P'                 # PySequenceMethods
758                  '6P'                  # PyBufferProcs
759                  '2P')
760        class newstyleclass(object):
761            pass
762        check(newstyleclass, s)
763        # builtin type
764        check(int, s)
765        # NotImplementedType
766        import types
767        check(types.NotImplementedType, s)
768        # unicode
769        usize = len(u'\0'.encode('unicode-internal'))
770        samples = [u'', u'1'*100]
771        # we need to test for both sizes, because we don't know if the string
772        # has been cached
773        for s in samples:
774            check(s, size('PPlP') + usize * (len(s) + 1))
775        # weakref
776        import weakref
777        check(weakref.ref(int), size('2Pl2P'))
778        # weakproxy
779        # XXX
780        # weakcallableproxy
781        check(weakref.proxy(int), size('2Pl2P'))
782        # xrange
783        check(xrange(1), size('3l'))
784        check(xrange(66000), size('3l'))
785
786    def check_slots(self, obj, base, extra):
787        expected = sys.getsizeof(base) + struct.calcsize(extra)
788        if gc.is_tracked(obj) and not gc.is_tracked(base):
789            expected += self.gc_headsize
790        self.assertEqual(sys.getsizeof(obj), expected)
791
792    def test_slots(self):
793        # check all subclassable types defined in Objects/ that allow
794        # non-empty __slots__
795        check = self.check_slots
796        class BA(bytearray):
797            __slots__ = 'a', 'b', 'c'
798        check(BA(), bytearray(), '3P')
799        class D(dict):
800            __slots__ = 'a', 'b', 'c'
801        check(D(x=[]), {'x': []}, '3P')
802        class L(list):
803            __slots__ = 'a', 'b', 'c'
804        check(L(), [], '3P')
805        class S(set):
806            __slots__ = 'a', 'b', 'c'
807        check(S(), set(), '3P')
808        class FS(frozenset):
809            __slots__ = 'a', 'b', 'c'
810        check(FS(), frozenset(), '3P')
811
812    def test_pythontypes(self):
813        # check all types defined in Python/
814        size = test.test_support.calcobjsize
815        vsize = test.test_support.calcvobjsize
816        check = self.check_sizeof
817        # _ast.AST
818        import _ast
819        check(_ast.AST(), size(''))
820        # imp.NullImporter
821        import imp
822        f = open(test.test_support.TESTFN, 'wb')
823        try:
824            check(imp.NullImporter(f.name), size(''))
825        finally:
826            f.close()
827            test.test_support.unlink(test.test_support.TESTFN)
828        try:
829            raise TypeError
830        except TypeError:
831            tb = sys.exc_info()[2]
832            # traceback
833            if tb != None:
834                check(tb, size('2P2i'))
835        # symtable entry
836        # XXX
837        # sys.flags
838        check(sys.flags, vsize('') + self.P * len(sys.flags))
839
840
841def test_main():
842    test_classes = (SysModuleTest, SizeofTest)
843
844    test.test_support.run_unittest(*test_classes)
845
846if __name__ == "__main__":
847    test_main()
848