1 # -*- coding: iso-8859-1 -*-
2 import unittest
, test
.test_support
3 import sys
, os
, cStringIO
7 class SysModuleTest(unittest
.TestCase
):
10 test
.test_support
.reap_children()
12 def test_original_displayhook(self
):
14 savestdout
= sys
.stdout
15 out
= cStringIO
.StringIO()
18 dh
= sys
.__displayhook
__
20 self
.assertRaises(TypeError, dh
)
21 if hasattr(__builtin__
, "_"):
25 self
.assertEqual(out
.getvalue(), "")
26 self
.assertTrue(not hasattr(__builtin__
, "_"))
28 self
.assertEqual(out
.getvalue(), "42\n")
29 self
.assertEqual(__builtin__
._, 42)
32 self
.assertRaises(RuntimeError, dh
, 42)
34 sys
.stdout
= savestdout
36 def test_lost_displayhook(self
):
37 olddisplayhook
= sys
.displayhook
39 code
= compile("42", "<string>", "single")
40 self
.assertRaises(RuntimeError, eval, code
)
41 sys
.displayhook
= olddisplayhook
43 def test_custom_displayhook(self
):
44 olddisplayhook
= sys
.displayhook
45 def baddisplayhook(obj
):
47 sys
.displayhook
= baddisplayhook
48 code
= compile("42", "<string>", "single")
49 self
.assertRaises(ValueError, eval, code
)
50 sys
.displayhook
= olddisplayhook
52 def test_original_excepthook(self
):
53 savestderr
= sys
.stderr
54 err
= cStringIO
.StringIO()
57 eh
= sys
.__excepthook
__
59 self
.assertRaises(TypeError, eh
)
62 except ValueError, exc
:
65 sys
.stderr
= savestderr
66 self
.assertTrue(err
.getvalue().endswith("ValueError: 42\n"))
68 # FIXME: testing the code for a lost or replaced excepthook in
69 # Python/pythonrun.c::PyErr_PrintEx() is tricky.
71 def test_exc_clear(self
):
72 self
.assertRaises(TypeError, sys
.exc_clear
, 42)
74 # Verify that exc_info is present and matches exc, then clear it, and
75 # check that it worked.
77 typ
, value
, traceback
= sys
.exc_info()
78 self
.assertTrue(typ
is not None)
79 self
.assertTrue(value
is exc
)
80 self
.assertTrue(traceback
is not None)
82 with test
.test_support
.check_py3k_warnings():
85 typ
, value
, traceback
= sys
.exc_info()
86 self
.assertTrue(typ
is None)
87 self
.assertTrue(value
is None)
88 self
.assertTrue(traceback
is None)
93 except ValueError, exc
:
96 # Raise an exception and check that it can be cleared
99 # Verify that a frame currently handling an exception is
100 # unaffected by calling exc_clear in a nested frame.
103 except ValueError, exc
:
104 typ1
, value1
, traceback1
= sys
.exc_info()
106 typ2
, value2
, traceback2
= sys
.exc_info()
108 self
.assertTrue(typ1
is typ2
)
109 self
.assertTrue(value1
is exc
)
110 self
.assertTrue(value1
is value2
)
111 self
.assertTrue(traceback1
is traceback2
)
113 # Check that an exception can be cleared outside of an except block
117 self
.assertRaises(TypeError, sys
.exit
, 42, 42)
119 # call without argument
122 except SystemExit, exc
:
123 self
.assertEquals(exc
.code
, 0)
125 self
.fail("wrong exception")
127 self
.fail("no exception")
129 # call with tuple argument with one entry
130 # entry will be unpacked
133 except SystemExit, exc
:
134 self
.assertEquals(exc
.code
, 42)
136 self
.fail("wrong exception")
138 self
.fail("no exception")
140 # call with integer argument
143 except SystemExit, exc
:
144 self
.assertEquals(exc
.code
, 42)
146 self
.fail("wrong exception")
148 self
.fail("no exception")
150 # call with string argument
153 except SystemExit, exc
:
154 self
.assertEquals(exc
.code
, "exit")
156 self
.fail("wrong exception")
158 self
.fail("no exception")
160 # call with tuple argument with two entries
163 except SystemExit, exc
:
164 self
.assertEquals(exc
.code
, (17, 23))
166 self
.fail("wrong exception")
168 self
.fail("no exception")
170 # test that the exit machinery handles SystemExits properly
172 # both unnormalized...
173 rc
= subprocess
.call([sys
.executable
, "-c",
174 "raise SystemExit, 46"])
175 self
.assertEqual(rc
, 46)
177 rc
= subprocess
.call([sys
.executable
, "-c",
178 "raise SystemExit(47)"])
179 self
.assertEqual(rc
, 47)
181 def check_exit_message(code
, expected
, env
=None):
182 process
= subprocess
.Popen([sys
.executable
, "-c", code
],
183 stderr
=subprocess
.PIPE
, env
=env
)
184 stdout
, stderr
= process
.communicate()
185 self
.assertEqual(process
.returncode
, 1)
186 self
.assertTrue(stderr
.startswith(expected
),
187 "%s doesn't start with %s" % (repr(stderr
), repr(expected
)))
189 # test that stderr buffer if flushed before the exit message is written
192 r
'import sys; sys.stderr.write("unflushed,"); sys.exit("message")',
193 b
"unflushed,message")
195 # test that the unicode message is encoded to the stderr encoding
196 env
= os
.environ
.copy()
197 env
['PYTHONIOENCODING'] = 'latin-1'
199 r
'import sys; sys.exit(u"h\xe9")',
202 def test_getdefaultencoding(self
):
203 if test
.test_support
.have_unicode
:
204 self
.assertRaises(TypeError, sys
.getdefaultencoding
, 42)
205 # can't check more than the type, as the user might have changed it
206 self
.assertIsInstance(sys
.getdefaultencoding(), str)
208 # testing sys.settrace() is done in test_trace.py
209 # testing sys.setprofile() is done in test_profile.py
211 def test_setcheckinterval(self
):
212 self
.assertRaises(TypeError, sys
.setcheckinterval
)
213 orig
= sys
.getcheckinterval()
214 for n
in 0, 100, 120, orig
: # orig last to restore starting state
215 sys
.setcheckinterval(n
)
216 self
.assertEquals(sys
.getcheckinterval(), n
)
218 def test_recursionlimit(self
):
219 self
.assertRaises(TypeError, sys
.getrecursionlimit
, 42)
220 oldlimit
= sys
.getrecursionlimit()
221 self
.assertRaises(TypeError, sys
.setrecursionlimit
)
222 self
.assertRaises(ValueError, sys
.setrecursionlimit
, -42)
223 sys
.setrecursionlimit(10000)
224 self
.assertEqual(sys
.getrecursionlimit(), 10000)
225 sys
.setrecursionlimit(oldlimit
)
227 def test_getwindowsversion(self
):
228 # Raise SkipTest if sys doesn't have getwindowsversion attribute
229 test
.test_support
.get_attribute(sys
, "getwindowsversion")
230 v
= sys
.getwindowsversion()
231 self
.assertEqual(len(v
), 5)
232 self
.assertIsInstance(v
[0], int)
233 self
.assertIsInstance(v
[1], int)
234 self
.assertIsInstance(v
[2], int)
235 self
.assertIsInstance(v
[3], int)
236 self
.assertIsInstance(v
[4], str)
237 self
.assertRaises(IndexError, operator
.getitem
, v
, 5)
238 self
.assertIsInstance(v
.major
, int)
239 self
.assertIsInstance(v
.minor
, int)
240 self
.assertIsInstance(v
.build
, int)
241 self
.assertIsInstance(v
.platform
, int)
242 self
.assertIsInstance(v
.service_pack
, str)
243 self
.assertIsInstance(v
.service_pack_minor
, int)
244 self
.assertIsInstance(v
.service_pack_major
, int)
245 self
.assertIsInstance(v
.suite_mask
, int)
246 self
.assertIsInstance(v
.product_type
, int)
247 self
.assertEqual(v
[0], v
.major
)
248 self
.assertEqual(v
[1], v
.minor
)
249 self
.assertEqual(v
[2], v
.build
)
250 self
.assertEqual(v
[3], v
.platform
)
251 self
.assertEqual(v
[4], v
.service_pack
)
253 # This is how platform.py calls it. Make sure tuple
254 # still has 5 elements
255 maj
, min, buildno
, plat
, csd
= sys
.getwindowsversion()
257 def test_dlopenflags(self
):
258 if hasattr(sys
, "setdlopenflags"):
259 self
.assertTrue(hasattr(sys
, "getdlopenflags"))
260 self
.assertRaises(TypeError, sys
.getdlopenflags
, 42)
261 oldflags
= sys
.getdlopenflags()
262 self
.assertRaises(TypeError, sys
.setdlopenflags
)
263 sys
.setdlopenflags(oldflags
+1)
264 self
.assertEqual(sys
.getdlopenflags(), oldflags
+1)
265 sys
.setdlopenflags(oldflags
)
267 def test_refcount(self
):
268 # n here must be a global in order for this test to pass while
269 # tracing with a python function. Tracing calls PyFrame_FastToLocals
270 # which will add a copy of any locals to the frame object, causing
271 # the reference count to increase by 2 instead of 1.
273 self
.assertRaises(TypeError, sys
.getrefcount
)
274 c
= sys
.getrefcount(None)
276 self
.assertEqual(sys
.getrefcount(None), c
+1)
278 self
.assertEqual(sys
.getrefcount(None), c
)
279 if hasattr(sys
, "gettotalrefcount"):
280 self
.assertIsInstance(sys
.gettotalrefcount(), int)
282 def test_getframe(self
):
283 self
.assertRaises(TypeError, sys
._getframe
, 42, 42)
284 self
.assertRaises(ValueError, sys
._getframe
, 2000000000)
286 SysModuleTest
.test_getframe
.im_func
.func_code \
287 is sys
._getframe
().f_code
290 # sys._current_frames() is a CPython-only gimmick.
291 def test_current_frames(self
):
299 self
.current_frames_with_threads()
301 self
.current_frames_without_threads()
303 # Test sys._current_frames() in a WITH_THREADS build.
304 @test.test_support
.reap_threads
305 def current_frames_with_threads(self
):
306 import threading
, thread
309 # Spawn a thread that blocks at a known place. Then the main
310 # thread does sys._current_frames(), and verifies that the frames
311 # returned make sense.
312 entered_g
= threading
.Event()
313 leave_g
= threading
.Event()
314 thread_info
= [] # the thread's id
320 thread_info
.append(thread
.get_ident())
324 t
= threading
.Thread(target
=f123
)
328 # At this point, t has finished its entered_g.set(), although it's
329 # impossible to guess whether it's still on that line or has moved on
330 # to its leave_g.wait().
331 self
.assertEqual(len(thread_info
), 1)
332 thread_id
= thread_info
[0]
334 d
= sys
._current
_frames
()
336 main_id
= thread
.get_ident()
337 self
.assertIn(main_id
, d
)
338 self
.assertIn(thread_id
, d
)
340 # Verify that the captured main-thread frame is _this_ frame.
341 frame
= d
.pop(main_id
)
342 self
.assertTrue(frame
is sys
._getframe
())
344 # Verify that the captured thread frame is blocked in g456, called
345 # from f123. This is a litte tricky, since various bits of
346 # threading.py are also in the thread's call stack.
347 frame
= d
.pop(thread_id
)
348 stack
= traceback
.extract_stack(frame
)
349 for i
, (filename
, lineno
, funcname
, sourceline
) in enumerate(stack
):
350 if funcname
== "f123":
353 self
.fail("didn't find f123() on thread's call stack")
355 self
.assertEqual(sourceline
, "g456()")
357 # And the next record must be for g456().
358 filename
, lineno
, funcname
, sourceline
= stack
[i
+1]
359 self
.assertEqual(funcname
, "g456")
360 self
.assertIn(sourceline
, ["leave_g.wait()", "entered_g.set()"])
362 # Reap the spawned thread.
366 # Test sys._current_frames() when thread support doesn't exist.
367 def current_frames_without_threads(self
):
368 # Not much happens here: there is only one thread, with artificial
370 d
= sys
._current
_frames
()
371 self
.assertEqual(len(d
), 1)
373 self
.assertTrue(d
[0] is sys
._getframe
())
375 def test_attributes(self
):
376 self
.assertIsInstance(sys
.api_version
, int)
377 self
.assertIsInstance(sys
.argv
, list)
378 self
.assertIn(sys
.byteorder
, ("little", "big"))
379 self
.assertIsInstance(sys
.builtin_module_names
, tuple)
380 self
.assertIsInstance(sys
.copyright
, basestring
)
381 self
.assertIsInstance(sys
.exec_prefix
, basestring
)
382 self
.assertIsInstance(sys
.executable
, basestring
)
383 self
.assertEqual(len(sys
.float_info
), 11)
384 self
.assertEqual(sys
.float_info
.radix
, 2)
385 self
.assertEqual(len(sys
.long_info
), 2)
386 self
.assertTrue(sys
.long_info
.bits_per_digit
% 5 == 0)
387 self
.assertTrue(sys
.long_info
.sizeof_digit
>= 1)
388 self
.assertEqual(type(sys
.long_info
.bits_per_digit
), int)
389 self
.assertEqual(type(sys
.long_info
.sizeof_digit
), int)
390 self
.assertIsInstance(sys
.hexversion
, int)
391 self
.assertIsInstance(sys
.maxint
, int)
392 if test
.test_support
.have_unicode
:
393 self
.assertIsInstance(sys
.maxunicode
, int)
394 self
.assertIsInstance(sys
.platform
, basestring
)
395 self
.assertIsInstance(sys
.prefix
, basestring
)
396 self
.assertIsInstance(sys
.version
, basestring
)
397 vi
= sys
.version_info
398 self
.assertIsInstance(vi
[:], tuple)
399 self
.assertEqual(len(vi
), 5)
400 self
.assertIsInstance(vi
[0], int)
401 self
.assertIsInstance(vi
[1], int)
402 self
.assertIsInstance(vi
[2], int)
403 self
.assertIn(vi
[3], ("alpha", "beta", "candidate", "final"))
404 self
.assertIsInstance(vi
[4], int)
405 self
.assertIsInstance(vi
.major
, int)
406 self
.assertIsInstance(vi
.minor
, int)
407 self
.assertIsInstance(vi
.micro
, int)
408 self
.assertIn(vi
.releaselevel
, ("alpha", "beta", "candidate", "final"))
409 self
.assertIsInstance(vi
.serial
, int)
410 self
.assertEqual(vi
[0], vi
.major
)
411 self
.assertEqual(vi
[1], vi
.minor
)
412 self
.assertEqual(vi
[2], vi
.micro
)
413 self
.assertEqual(vi
[3], vi
.releaselevel
)
414 self
.assertEqual(vi
[4], vi
.serial
)
415 self
.assertTrue(vi
> (1,0,0))
416 self
.assertIsInstance(sys
.float_repr_style
, str)
417 self
.assertIn(sys
.float_repr_style
, ('short', 'legacy'))
419 def test_43581(self
):
420 # Can't use sys.stdout, as this is a cStringIO object when
421 # the test runs under regrtest.
422 self
.assertTrue(sys
.__stdout
__.encoding
== sys
.__stderr
__.encoding
)
424 def test_sys_flags(self
):
425 self
.assertTrue(sys
.flags
)
426 attrs
= ("debug", "py3k_warning", "division_warning", "division_new",
427 "inspect", "interactive", "optimize", "dont_write_bytecode",
428 "no_site", "ignore_environment", "tabcheck", "verbose",
429 "unicode", "bytes_warning")
431 self
.assertTrue(hasattr(sys
.flags
, attr
), attr
)
432 self
.assertEqual(type(getattr(sys
.flags
, attr
)), int, attr
)
433 self
.assertTrue(repr(sys
.flags
))
435 def test_clear_type_cache(self
):
436 sys
._clear
_type
_cache
()
438 def test_ioencoding(self
):
440 env
= dict(os
.environ
)
442 # Test character: cent sign, encoded as 0x4A (ASCII J) in CP424,
443 # not representable in ASCII.
445 env
["PYTHONIOENCODING"] = "cp424"
446 p
= subprocess
.Popen([sys
.executable
, "-c", 'print unichr(0xa2)'],
447 stdout
= subprocess
.PIPE
, env
=env
)
448 out
= p
.communicate()[0].strip()
449 self
.assertEqual(out
, unichr(0xa2).encode("cp424"))
451 env
["PYTHONIOENCODING"] = "ascii:replace"
452 p
= subprocess
.Popen([sys
.executable
, "-c", 'print unichr(0xa2)'],
453 stdout
= subprocess
.PIPE
, env
=env
)
454 out
= p
.communicate()[0].strip()
455 self
.assertEqual(out
, '?')
457 def test_call_tracing(self
):
458 self
.assertEqual(sys
.call_tracing(str, (2,)), "2")
459 self
.assertRaises(TypeError, sys
.call_tracing
, str, 2)
461 def test_executable(self
):
462 # Issue #7774: Ensure that sys.executable is an empty string if argv[0]
463 # has been set to an non existent program name and Python is unable to
464 # retrieve the real program name
466 # For a normal installation, it should work without 'cwd'
467 # argument. For test runs in the build directory, see #7774.
468 python_dir
= os
.path
.dirname(os
.path
.realpath(sys
.executable
))
469 p
= subprocess
.Popen(
470 ["nonexistent", "-c", 'import sys; print repr(sys.executable)'],
471 executable
=sys
.executable
, stdout
=subprocess
.PIPE
, cwd
=python_dir
)
472 executable
= p
.communicate()[0].strip()
474 self
.assertIn(executable
, ["''", repr(sys
.executable
)])
476 class SizeofTest(unittest
.TestCase
):
478 TPFLAGS_HAVE_GC
= 1<<14
479 TPFLAGS_HEAPTYPE
= 1L<<9
482 self
.c
= len(struct
.pack('c', ' '))
483 self
.H
= len(struct
.pack('H', 0))
484 self
.i
= len(struct
.pack('i', 0))
485 self
.l
= len(struct
.pack('l', 0))
486 self
.P
= len(struct
.pack('P', 0))
487 # due to missing size_t information from struct, it is assumed that
488 # sizeof(Py_ssize_t) = sizeof(void*)
490 self
.vheader
= self
.header
+ 'P'
491 if hasattr(sys
, "gettotalrefcount"):
494 self
.longdigit
= sys
.long_info
.sizeof_digit
496 self
.gc_headsize
= _testcapi
.SIZEOF_PYGC_HEAD
497 self
.file = open(test
.test_support
.TESTFN
, 'wb')
501 test
.test_support
.unlink(test
.test_support
.TESTFN
)
503 def check_sizeof(self
, o
, size
):
504 result
= sys
.getsizeof(o
)
505 if ((type(o
) == type) and (o
.__flags
__ & self
.TPFLAGS_HEAPTYPE
) or\
506 ((type(o
) != type) and (type(o
).__flags
__ & self
.TPFLAGS_HAVE_GC
))):
507 size
+= self
.gc_headsize
508 msg
= 'wrong size for %s: got %d, expected %d' \
509 % (type(o
), result
, size
)
510 self
.assertEqual(result
, size
, msg
)
512 def calcsize(self
, fmt
):
513 """Wrapper around struct.calcsize which enforces the alignment of the
514 end of a structure to the alignment requirement of pointer.
516 Note: This wrapper should only be used if a pointer member is included
517 and no member with a size larger than a pointer exists.
519 return struct
.calcsize(fmt
+ '0P')
521 def test_gc_head_size(self
):
522 # Check that the gc header size is added to objects tracked by the gc.
525 gc_header_size
= self
.gc_headsize
526 # bool objects are not gc tracked
527 self
.assertEqual(sys
.getsizeof(True), size(h
+ 'l'))
529 self
.assertEqual(sys
.getsizeof([]), size(h
+ 'P PP') + gc_header_size
)
531 def test_default(self
):
534 self
.assertEqual(sys
.getsizeof(True, -1), size(h
+ 'l'))
536 def test_objecttypes(self
):
537 # check all types defined in Objects/
541 check
= self
.check_sizeof
543 check(True, size(h
+ 'l'))
545 with test
.test_support
.check_py3k_warnings():
546 check(buffer(''), size(h
+ '2P2Pil'))
547 # builtin_function_or_method
548 check(len, size(h
+ '3P'))
550 samples
= ['', 'u'*100000]
551 for sample
in samples
:
552 x
= bytearray(sample
)
553 check(x
, size(vh
+ 'iPP') + x
.__alloc
__() * self
.c
)
555 check(iter(bytearray()), size(h
+ 'PP'))
562 check(get_cell().func_closure
[0], size(h
+ 'P'))
563 # classobj (old-style class)
564 class class_oldstyle():
567 check(class_oldstyle
, size(h
+ '7P'))
568 # instance (old-style class)
569 check(class_oldstyle(), size(h
+ '3P'))
570 # instancemethod (old-style class)
571 check(class_oldstyle().method
, size(h
+ '4P'))
573 check(complex(0,1), size(h
+ '2d'))
575 check(get_cell().func_code
, size(h
+ '4i8Pi3P'))
577 check(BaseException(), size(h
+ '3P'))
579 check(UnicodeEncodeError("", u
"", 0, 0, ""), size(h
+ '5P2PP'))
581 check(UnicodeDecodeError("", "", 0, 0, ""), size(h
+ '5P2PP'))
582 # UnicodeTranslateError
583 check(UnicodeTranslateError(u
"", 0, 1, ""), size(h
+ '5P2PP'))
584 # method_descriptor (descriptor object)
585 check(str.lower
, size(h
+ '2PP'))
586 # classmethod_descriptor (descriptor object)
588 # member_descriptor (descriptor object)
590 check(datetime
.timedelta
.days
, size(h
+ '2PP'))
591 # getset_descriptor (descriptor object)
593 check(__builtin__
.file.closed
, size(h
+ '2PP'))
594 # wrapper_descriptor (descriptor object)
595 check(int.__add
__, size(h
+ '2P2P'))
597 class C(object): pass
598 check(C
.__dict
__, size(h
+ 'P'))
599 # method-wrapper (descriptor object)
600 check({}.__iter
__, size(h
+ '2P'))
602 check({}, size(h
+ '3P2P' + 8*'P2P'))
603 x
= {1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8}
604 check(x
, size(h
+ '3P2P' + 8*'P2P') + 16*size('P2P'))
605 # dictionary-keyiterator
606 check({}.iterkeys(), size(h
+ 'P2PPP'))
607 # dictionary-valueiterator
608 check({}.itervalues(), size(h
+ 'P2PPP'))
609 # dictionary-itemiterator
610 check({}.iteritems(), size(h
+ 'P2PPP'))
612 check(Ellipsis, size(h
+ ''))
614 import codecs
, encodings
.iso8859_3
615 x
= codecs
.charmap_build(encodings
.iso8859_3
.decoding_table
)
616 check(x
, size(h
+ '32B2iB'))
618 check(enumerate([]), size(h
+ 'l3P'))
620 check(self
.file, size(h
+ '4P2i4P3i3P3i'))
622 check(float(0), size(h
+ 'd'))
624 check(sys
.float_info
, size(vh
) + self
.P
* len(sys
.float_info
))
628 x
= inspect
.currentframe()
629 ncells
= len(x
.f_code
.co_cellvars
)
630 nfrees
= len(x
.f_code
.co_freevars
)
631 extras
= x
.f_code
.co_stacksize
+ x
.f_code
.co_nlocals
+\
633 check(x
, size(vh
+ '12P3i' + CO_MAXBLOCKS
*'3i' + 'P' + extras
*'P'))
636 check(func
, size(h
+ '9P'))
645 check(foo
, size(h
+ 'P'))
647 check(bar
, size(h
+ 'P'))
649 def get_gen(): yield 1
650 check(get_gen(), size(h
+ 'Pi2P'))
652 check(1, size(h
+ 'l'))
653 check(100, size(h
+ 'l'))
655 check(iter('abc'), size(h
+ 'lP'))
658 check(re
.finditer('',''), size(h
+ '2P'))
660 samples
= [[], [1,2,3], ['1', '2', '3']]
661 for sample
in samples
:
662 check(sample
, size(vh
+ 'PP') + len(sample
)*self
.P
)
667 # listiterator (list)
668 check(iter([]), size(h
+ 'lP'))
669 # listreverseiterator (list)
670 check(reversed([]), size(h
+ 'lP'))
673 check(1L, size(vh
) + self
.longdigit
)
674 check(-1L, size(vh
) + self
.longdigit
)
675 PyLong_BASE
= 2**sys
.long_info
.bits_per_digit
676 check(long(PyLong_BASE
), size(vh
) + 2*self
.longdigit
)
677 check(long(PyLong_BASE
**2-1), size(vh
) + 2*self
.longdigit
)
678 check(long(PyLong_BASE
**2), size(vh
) + 3*self
.longdigit
)
680 check(unittest
, size(h
+ 'P'))
682 check(None, size(h
+ ''))
684 check(object(), size(h
+ ''))
685 # property (descriptor object)
687 def getx(self
): return self
.__x
688 def setx(self
, value
): self
.__x
= value
689 def delx(self
): del self
.__x
690 x
= property(getx
, setx
, delx
, "")
691 check(x
, size(h
+ '4Pi'))
696 check(iter(xrange(1)), size(h
+ '4l'))
698 check(reversed(''), size(h
+ 'PP'))
702 samples
= [[], range(10), range(50)]
703 s
= size(h
+ '3P2P' + PySet_MINSIZE
*'lP' + 'lP')
704 for sample
in samples
:
705 minused
= len(sample
)
706 if minused
== 0: tmp
= 1
707 # the computation of minused is actually a bit more complicated
708 # but this suffices for the sizeof test
710 newsize
= PySet_MINSIZE
711 while newsize
<= minused
:
712 newsize
= newsize
<< 1
714 check(set(sample
), s
)
715 check(frozenset(sample
), s
)
717 check(set(sample
), s
+ newsize
*struct
.calcsize('lP'))
718 check(frozenset(sample
), s
+ newsize
*struct
.calcsize('lP'))
720 check(iter(set()), size(h
+ 'P3P'))
722 check(slice(1), size(h
+ '3P'))
724 check('', struct
.calcsize(vh
+ 'li') + 1)
725 check('abc', struct
.calcsize(vh
+ 'li') + 1 + 3*self
.c
)
727 check(super(int), size(h
+ '3P'))
730 check((1,2,3), size(vh
) + 3*self
.P
)
732 check(iter(()), size(h
+ 'lP'))
734 # (PyTypeObject + PyNumberMethods + PyMappingMethods +
735 # PySequenceMethods + PyBufferProcs)
736 s
= size(vh
+ 'P2P15Pl4PP9PP11PI') + size('41P 10P 3P 6P')
737 class newstyleclass(object):
739 check(newstyleclass
, s
)
744 check(types
.NotImplementedType
, s
)
746 usize
= len(u
'\0'.encode('unicode-internal'))
747 samples
= [u
'', u
'1'*100]
748 # we need to test for both sizes, because we don't know if the string
751 check(s
, size(h
+ 'PPlP') + usize
* (len(s
) + 1))
754 check(weakref
.ref(int), size(h
+ '2Pl2P'))
758 check(weakref
.proxy(int), size(h
+ '2Pl2P'))
760 check(xrange(1), size(h
+ '3l'))
761 check(xrange(66000), size(h
+ '3l'))
763 def test_pythontypes(self
):
764 # check all types defined in Python/
768 check
= self
.check_sizeof
771 check(_ast
.AST(), size(h
+ ''))
774 check(imp
.NullImporter(self
.file.name
), size(h
+ ''))
778 tb
= sys
.exc_info()[2]
781 check(tb
, size(h
+ '2P2i'))
785 check(sys
.flags
, size(vh
) + self
.P
* len(sys
.flags
))
789 test_classes
= (SysModuleTest
, SizeofTest
)
791 test
.test_support
.run_unittest(*test_classes
)
793 if __name__
== "__main__":