blob: 2afc261f16a3cecef4748687d8542624055295a9 [file] [log] [blame]
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001import unittest, test.support
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002import sys, io, os
Robert Schuppenies4d45bfe2008-06-28 23:58:47 +00003import struct
Antoine Pitrou652e7072009-03-13 19:25:20 +00004import subprocess
5import textwrap
Antoine Pitrouc3b07572009-11-13 22:19:19 +00006import warnings
Eric Smithf7bb5782010-01-27 00:44:57 +00007import operator
Victor Stinner85ca2af2010-08-19 11:23:47 +00008import codecs
Walter Dörwaldc3502462003-02-03 23:03:49 +00009
Georg Brandl03526552009-10-27 23:00:28 +000010# count the number of test runs, used to create unique
11# strings to intern in test_intern()
12numruns = 0
13
Victor Stinner45df8202010-04-28 22:31:17 +000014try:
15 import threading
16except ImportError:
17 threading = None
Georg Brandl03526552009-10-27 23:00:28 +000018
Walter Dörwaldc3502462003-02-03 23:03:49 +000019class SysModuleTest(unittest.TestCase):
20
Christian Heimesef181a72007-11-07 16:14:12 +000021 def setUp(self):
22 self.orig_stdout = sys.stdout
23 self.orig_stderr = sys.stderr
24 self.orig_displayhook = sys.displayhook
25
26 def tearDown(self):
27 sys.stdout = self.orig_stdout
28 sys.stderr = self.orig_stderr
29 sys.displayhook = self.orig_displayhook
Antoine Pitrou836f0e22009-10-27 19:25:57 +000030 test.support.reap_children()
Christian Heimesef181a72007-11-07 16:14:12 +000031
Walter Dörwaldc3502462003-02-03 23:03:49 +000032 def test_original_displayhook(self):
Georg Brandl1a3284e2007-12-02 09:40:06 +000033 import builtins
Guido van Rossum34d19282007-08-09 01:03:29 +000034 out = io.StringIO()
Walter Dörwaldc3502462003-02-03 23:03:49 +000035 sys.stdout = out
36
37 dh = sys.__displayhook__
38
39 self.assertRaises(TypeError, dh)
Georg Brandl1a3284e2007-12-02 09:40:06 +000040 if hasattr(builtins, "_"):
41 del builtins._
Walter Dörwaldc3502462003-02-03 23:03:49 +000042
43 dh(None)
44 self.assertEqual(out.getvalue(), "")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000045 self.assertTrue(not hasattr(builtins, "_"))
Walter Dörwaldc3502462003-02-03 23:03:49 +000046 dh(42)
47 self.assertEqual(out.getvalue(), "42\n")
Georg Brandl1a3284e2007-12-02 09:40:06 +000048 self.assertEqual(builtins._, 42)
Walter Dörwaldc3502462003-02-03 23:03:49 +000049
50 del sys.stdout
51 self.assertRaises(RuntimeError, dh, 42)
52
Walter Dörwaldc3502462003-02-03 23:03:49 +000053 def test_lost_displayhook(self):
Walter Dörwaldc3502462003-02-03 23:03:49 +000054 del sys.displayhook
55 code = compile("42", "<string>", "single")
56 self.assertRaises(RuntimeError, eval, code)
Walter Dörwaldc3502462003-02-03 23:03:49 +000057
58 def test_custom_displayhook(self):
Walter Dörwaldc3502462003-02-03 23:03:49 +000059 def baddisplayhook(obj):
60 raise ValueError
61 sys.displayhook = baddisplayhook
62 code = compile("42", "<string>", "single")
63 self.assertRaises(ValueError, eval, code)
Walter Dörwaldc3502462003-02-03 23:03:49 +000064
65 def test_original_excepthook(self):
Guido van Rossum34d19282007-08-09 01:03:29 +000066 err = io.StringIO()
Walter Dörwaldc3502462003-02-03 23:03:49 +000067 sys.stderr = err
68
69 eh = sys.__excepthook__
70
71 self.assertRaises(TypeError, eh)
72 try:
73 raise ValueError(42)
Guido van Rossumb940e112007-01-10 16:19:56 +000074 except ValueError as exc:
Walter Dörwaldc3502462003-02-03 23:03:49 +000075 eh(*sys.exc_info())
76
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000077 self.assertTrue(err.getvalue().endswith("ValueError: 42\n"))
Walter Dörwaldc3502462003-02-03 23:03:49 +000078
Benjamin Petersonbc74e5b2008-08-23 20:19:17 +000079 def test_excepthook(self):
80 with test.support.captured_output("stderr") as stderr:
81 sys.excepthook(1, '1', 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000082 self.assertTrue("TypeError: print_exception(): Exception expected for " \
Benjamin Petersonbc74e5b2008-08-23 20:19:17 +000083 "value, str found" in stderr.getvalue())
84
Walter Dörwalde7028ac2003-02-03 23:05:27 +000085 # FIXME: testing the code for a lost or replaced excepthook in
Walter Dörwaldc3502462003-02-03 23:03:49 +000086 # Python/pythonrun.c::PyErr_PrintEx() is tricky.
87
88 def test_exit(self):
Victor Stinnere9fb3192010-05-17 08:58:51 +000089
Walter Dörwaldc3502462003-02-03 23:03:49 +000090 self.assertRaises(TypeError, sys.exit, 42, 42)
91
92 # call without argument
93 try:
94 sys.exit(0)
Guido van Rossumb940e112007-01-10 16:19:56 +000095 except SystemExit as exc:
Ezio Melottib3aedd42010-11-20 19:04:17 +000096 self.assertEqual(exc.code, 0)
Walter Dörwaldc3502462003-02-03 23:03:49 +000097 except:
98 self.fail("wrong exception")
99 else:
100 self.fail("no exception")
101
102 # call with tuple argument with one entry
103 # entry will be unpacked
104 try:
105 sys.exit(42)
Guido van Rossumb940e112007-01-10 16:19:56 +0000106 except SystemExit as exc:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000107 self.assertEqual(exc.code, 42)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000108 except:
109 self.fail("wrong exception")
110 else:
111 self.fail("no exception")
112
113 # call with integer argument
114 try:
115 sys.exit((42,))
Guido van Rossumb940e112007-01-10 16:19:56 +0000116 except SystemExit as exc:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000117 self.assertEqual(exc.code, 42)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000118 except:
119 self.fail("wrong exception")
120 else:
121 self.fail("no exception")
122
123 # call with string argument
124 try:
125 sys.exit("exit")
Guido van Rossumb940e112007-01-10 16:19:56 +0000126 except SystemExit as exc:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000127 self.assertEqual(exc.code, "exit")
Walter Dörwaldc3502462003-02-03 23:03:49 +0000128 except:
129 self.fail("wrong exception")
130 else:
131 self.fail("no exception")
132
133 # call with tuple argument with two entries
134 try:
135 sys.exit((17, 23))
Guido van Rossumb940e112007-01-10 16:19:56 +0000136 except SystemExit as exc:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000137 self.assertEqual(exc.code, (17, 23))
Walter Dörwaldc3502462003-02-03 23:03:49 +0000138 except:
139 self.fail("wrong exception")
140 else:
141 self.fail("no exception")
142
Michael W. Hudsonf0588582005-02-15 15:26:11 +0000143 # test that the exit machinery handles SystemExits properly
Michael W. Hudsonf0588582005-02-15 15:26:11 +0000144 rc = subprocess.call([sys.executable, "-c",
145 "raise SystemExit(47)"])
146 self.assertEqual(rc, 47)
Tim Petersf0db38d2005-02-15 21:50:12 +0000147
Victor Stinner7126dbc2010-05-21 23:45:42 +0000148 def check_exit_message(code, expected, env=None):
Victor Stinnere9fb3192010-05-17 08:58:51 +0000149 process = subprocess.Popen([sys.executable, "-c", code],
Victor Stinner7126dbc2010-05-21 23:45:42 +0000150 stderr=subprocess.PIPE, env=env)
Victor Stinnere9fb3192010-05-17 08:58:51 +0000151 stdout, stderr = process.communicate()
152 self.assertEqual(process.returncode, 1)
Victor Stinner7cf7d722010-05-17 14:36:43 +0000153 self.assertTrue(stderr.startswith(expected),
Victor Stinnerc0983852010-05-17 19:57:40 +0000154 "%s doesn't start with %s" % (ascii(stderr), ascii(expected)))
Victor Stinnere9fb3192010-05-17 08:58:51 +0000155
156 # test that stderr buffer if flushed before the exit message is written
157 # into stderr
158 check_exit_message(
159 r'import sys; sys.stderr.write("unflushed,"); sys.exit("message")',
160 b"unflushed,message")
161
Victor Stinner372ac5e2010-05-17 01:26:01 +0000162 # test that the exit message is written with backslashreplace error
163 # handler to stderr
Victor Stinnere9fb3192010-05-17 08:58:51 +0000164 check_exit_message(
165 r'import sys; sys.exit("surrogates:\uDCFF")',
166 b"surrogates:\\udcff")
Victor Stinner372ac5e2010-05-17 01:26:01 +0000167
Victor Stinner7126dbc2010-05-21 23:45:42 +0000168 # test that the unicode message is encoded to the stderr encoding
169 # instead of the default encoding (utf8)
170 env = os.environ.copy()
171 env['PYTHONIOENCODING'] = 'latin-1'
172 check_exit_message(
173 r'import sys; sys.exit("h\xe9")',
174 b"h\xe9", env=env)
175
Walter Dörwaldc3502462003-02-03 23:03:49 +0000176 def test_getdefaultencoding(self):
Walter Dörwald4aeaa962007-05-22 16:13:46 +0000177 self.assertRaises(TypeError, sys.getdefaultencoding, 42)
178 # can't check more than the type, as the user might have changed it
Ezio Melottie9615932010-01-24 19:26:24 +0000179 self.assertIsInstance(sys.getdefaultencoding(), str)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000180
Alexander Belopolsky07de1652010-07-25 15:05:42 +0000181 # testing sys.settrace() is done in test_sys_settrace.py
182 # testing sys.setprofile() is done in test_sys_setprofile.py
Walter Dörwaldc3502462003-02-03 23:03:49 +0000183
184 def test_setcheckinterval(self):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000185 with warnings.catch_warnings():
186 warnings.simplefilter("ignore")
187 self.assertRaises(TypeError, sys.setcheckinterval)
188 orig = sys.getcheckinterval()
189 for n in 0, 100, 120, orig: # orig last to restore starting state
190 sys.setcheckinterval(n)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000191 self.assertEqual(sys.getcheckinterval(), n)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000192
Victor Stinner45df8202010-04-28 22:31:17 +0000193 @unittest.skipUnless(threading, 'Threading required for this test.')
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000194 def test_switchinterval(self):
195 self.assertRaises(TypeError, sys.setswitchinterval)
196 self.assertRaises(TypeError, sys.setswitchinterval, "a")
197 self.assertRaises(ValueError, sys.setswitchinterval, -1.0)
198 self.assertRaises(ValueError, sys.setswitchinterval, 0.0)
199 orig = sys.getswitchinterval()
200 # sanity check
201 self.assertTrue(orig < 0.5, orig)
202 try:
203 for n in 0.00001, 0.05, 3.0, orig:
204 sys.setswitchinterval(n)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000205 self.assertAlmostEqual(sys.getswitchinterval(), n)
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000206 finally:
207 sys.setswitchinterval(orig)
208
Walter Dörwaldc3502462003-02-03 23:03:49 +0000209 def test_recursionlimit(self):
Tim Petersf2715e02003-02-19 02:35:07 +0000210 self.assertRaises(TypeError, sys.getrecursionlimit, 42)
211 oldlimit = sys.getrecursionlimit()
212 self.assertRaises(TypeError, sys.setrecursionlimit)
213 self.assertRaises(ValueError, sys.setrecursionlimit, -42)
214 sys.setrecursionlimit(10000)
215 self.assertEqual(sys.getrecursionlimit(), 10000)
216 sys.setrecursionlimit(oldlimit)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000217
Brett Cannon5543e812011-01-25 18:26:35 +0000218 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
219 'fatal error if run with a trace function')
Antoine Pitrou652e7072009-03-13 19:25:20 +0000220 def test_recursionlimit_recovery(self):
221 # NOTE: this test is slightly fragile in that it depends on the current
222 # recursion count when executing the test being low enough so as to
223 # trigger the recursion recovery detection in the _Py_MakeEndRecCheck
224 # macro (see ceval.h).
225 oldlimit = sys.getrecursionlimit()
226 def f():
227 f()
228 try:
229 for i in (50, 1000):
230 # Issue #5392: stack overflow after hitting recursion limit twice
231 sys.setrecursionlimit(i)
232 self.assertRaises(RuntimeError, f)
233 self.assertRaises(RuntimeError, f)
234 finally:
235 sys.setrecursionlimit(oldlimit)
236
237 def test_recursionlimit_fatalerror(self):
238 # A fatal error occurs if a second recursion limit is hit when recovering
239 # from a first one.
Antoine Pitrou17dc4462009-04-04 17:36:05 +0000240 if os.name == "nt":
241 raise unittest.SkipTest(
242 "under Windows, test would generate a spurious crash dialog")
Antoine Pitrou652e7072009-03-13 19:25:20 +0000243 code = textwrap.dedent("""
244 import sys
245
246 def f():
247 try:
248 f()
249 except RuntimeError:
250 f()
251
252 sys.setrecursionlimit(%d)
253 f()""")
254 for i in (50, 1000):
255 sub = subprocess.Popen([sys.executable, '-c', code % i],
256 stderr=subprocess.PIPE)
257 err = sub.communicate()[1]
258 self.assertTrue(sub.returncode, sub.returncode)
259 self.assertTrue(
260 b"Fatal Python error: Cannot recover from stack overflow" in err,
261 err)
262
Walter Dörwaldc3502462003-02-03 23:03:49 +0000263 def test_getwindowsversion(self):
Eric Smith05f337442010-01-27 01:25:02 +0000264 # Raise SkipTest if sys doesn't have getwindowsversion attribute
Eric Smithd8aef762010-01-27 01:38:34 +0000265 test.support.get_attribute(sys, "getwindowsversion")
Eric Smith05f337442010-01-27 01:25:02 +0000266 v = sys.getwindowsversion()
Brian Curtin808e1ad2010-07-08 22:13:25 +0000267 self.assertEqual(len(v), 5)
Eric Smith05f337442010-01-27 01:25:02 +0000268 self.assertIsInstance(v[0], int)
269 self.assertIsInstance(v[1], int)
270 self.assertIsInstance(v[2], int)
271 self.assertIsInstance(v[3], int)
272 self.assertIsInstance(v[4], str)
273 self.assertRaises(IndexError, operator.getitem, v, 5)
274 self.assertIsInstance(v.major, int)
275 self.assertIsInstance(v.minor, int)
276 self.assertIsInstance(v.build, int)
277 self.assertIsInstance(v.platform, int)
278 self.assertIsInstance(v.service_pack, str)
Eric Smitha1f20b92010-01-27 02:14:26 +0000279 self.assertIsInstance(v.service_pack_minor, int)
280 self.assertIsInstance(v.service_pack_major, int)
281 self.assertIsInstance(v.suite_mask, int)
282 self.assertIsInstance(v.product_type, int)
Eric Smith05f337442010-01-27 01:25:02 +0000283 self.assertEqual(v[0], v.major)
284 self.assertEqual(v[1], v.minor)
285 self.assertEqual(v[2], v.build)
286 self.assertEqual(v[3], v.platform)
287 self.assertEqual(v[4], v.service_pack)
Eric Smithf7bb5782010-01-27 00:44:57 +0000288
Eric Smith05f337442010-01-27 01:25:02 +0000289 # This is how platform.py calls it. Make sure tuple
290 # still has 5 elements
291 maj, min, buildno, plat, csd = sys.getwindowsversion()
Walter Dörwaldc3502462003-02-03 23:03:49 +0000292
Barry Warsawe94a37f2008-10-17 01:29:56 +0000293 def test_call_tracing(self):
294 self.assertRaises(TypeError, sys.call_tracing, type, 2)
295
Walter Dörwaldc3502462003-02-03 23:03:49 +0000296 def test_dlopenflags(self):
297 if hasattr(sys, "setdlopenflags"):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000298 self.assertTrue(hasattr(sys, "getdlopenflags"))
Walter Dörwaldc3502462003-02-03 23:03:49 +0000299 self.assertRaises(TypeError, sys.getdlopenflags, 42)
300 oldflags = sys.getdlopenflags()
301 self.assertRaises(TypeError, sys.setdlopenflags)
302 sys.setdlopenflags(oldflags+1)
303 self.assertEqual(sys.getdlopenflags(), oldflags+1)
304 sys.setdlopenflags(oldflags)
305
Brett Cannon7a540732011-02-22 03:04:06 +0000306 @test.support.refcount_test
Walter Dörwaldc3502462003-02-03 23:03:49 +0000307 def test_refcount(self):
Benjamin Petersond23f8222009-04-05 19:13:16 +0000308 # n here must be a global in order for this test to pass while
309 # tracing with a python function. Tracing calls PyFrame_FastToLocals
310 # which will add a copy of any locals to the frame object, causing
311 # the reference count to increase by 2 instead of 1.
312 global n
Walter Dörwaldc3502462003-02-03 23:03:49 +0000313 self.assertRaises(TypeError, sys.getrefcount)
314 c = sys.getrefcount(None)
315 n = None
316 self.assertEqual(sys.getrefcount(None), c+1)
317 del n
318 self.assertEqual(sys.getrefcount(None), c)
319 if hasattr(sys, "gettotalrefcount"):
Ezio Melottie9615932010-01-24 19:26:24 +0000320 self.assertIsInstance(sys.gettotalrefcount(), int)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000321
322 def test_getframe(self):
323 self.assertRaises(TypeError, sys._getframe, 42, 42)
Neal Norwitzeb2a5ef2003-02-18 15:22:10 +0000324 self.assertRaises(ValueError, sys._getframe, 2000000000)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000325 self.assertTrue(
Christian Heimes4a22b5d2007-11-25 09:39:14 +0000326 SysModuleTest.test_getframe.__code__ \
Walter Dörwaldc3502462003-02-03 23:03:49 +0000327 is sys._getframe().f_code
328 )
329
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000330 # sys._current_frames() is a CPython-only gimmick.
331 def test_current_frames(self):
332 have_threads = True
333 try:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000334 import _thread
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000335 except ImportError:
336 have_threads = False
337
338 if have_threads:
339 self.current_frames_with_threads()
340 else:
341 self.current_frames_without_threads()
342
343 # Test sys._current_frames() in a WITH_THREADS build.
Antoine Pitrou836f0e22009-10-27 19:25:57 +0000344 @test.support.reap_threads
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000345 def current_frames_with_threads(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200346 import threading
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000347 import traceback
348
349 # Spawn a thread that blocks at a known place. Then the main
350 # thread does sys._current_frames(), and verifies that the frames
351 # returned make sense.
352 entered_g = threading.Event()
353 leave_g = threading.Event()
354 thread_info = [] # the thread's id
355
356 def f123():
357 g456()
358
359 def g456():
Victor Stinner2a129742011-05-30 23:02:52 +0200360 thread_info.append(threading.get_ident())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000361 entered_g.set()
362 leave_g.wait()
363
364 t = threading.Thread(target=f123)
365 t.start()
366 entered_g.wait()
367
368 # At this point, t has finished its entered_g.set(), although it's
369 # impossible to guess whether it's still on that line or has moved on
370 # to its leave_g.wait().
371 self.assertEqual(len(thread_info), 1)
372 thread_id = thread_info[0]
373
374 d = sys._current_frames()
375
Victor Stinner2a129742011-05-30 23:02:52 +0200376 main_id = threading.get_ident()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000377 self.assertIn(main_id, d)
378 self.assertIn(thread_id, d)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000379
380 # Verify that the captured main-thread frame is _this_ frame.
381 frame = d.pop(main_id)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000382 self.assertTrue(frame is sys._getframe())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000383
384 # Verify that the captured thread frame is blocked in g456, called
385 # from f123. This is a litte tricky, since various bits of
386 # threading.py are also in the thread's call stack.
387 frame = d.pop(thread_id)
388 stack = traceback.extract_stack(frame)
389 for i, (filename, lineno, funcname, sourceline) in enumerate(stack):
390 if funcname == "f123":
391 break
392 else:
393 self.fail("didn't find f123() on thread's call stack")
394
395 self.assertEqual(sourceline, "g456()")
396
397 # And the next record must be for g456().
398 filename, lineno, funcname, sourceline = stack[i+1]
399 self.assertEqual(funcname, "g456")
Benjamin Peterson577473f2010-01-19 00:09:57 +0000400 self.assertIn(sourceline, ["leave_g.wait()", "entered_g.set()"])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000401
402 # Reap the spawned thread.
403 leave_g.set()
404 t.join()
405
406 # Test sys._current_frames() when thread support doesn't exist.
407 def current_frames_without_threads(self):
408 # Not much happens here: there is only one thread, with artificial
409 # "thread id" 0.
410 d = sys._current_frames()
411 self.assertEqual(len(d), 1)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000412 self.assertIn(0, d)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000413 self.assertTrue(d[0] is sys._getframe())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000414
Walter Dörwaldc3502462003-02-03 23:03:49 +0000415 def test_attributes(self):
Ezio Melottie9615932010-01-24 19:26:24 +0000416 self.assertIsInstance(sys.api_version, int)
417 self.assertIsInstance(sys.argv, list)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000418 self.assertIn(sys.byteorder, ("little", "big"))
Ezio Melottie9615932010-01-24 19:26:24 +0000419 self.assertIsInstance(sys.builtin_module_names, tuple)
420 self.assertIsInstance(sys.copyright, str)
421 self.assertIsInstance(sys.exec_prefix, str)
422 self.assertIsInstance(sys.executable, str)
Christian Heimes93852662007-12-01 12:22:32 +0000423 self.assertEqual(len(sys.float_info), 11)
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000424 self.assertEqual(sys.float_info.radix, 2)
Mark Dickinsonbd792642009-03-18 20:06:12 +0000425 self.assertEqual(len(sys.int_info), 2)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000426 self.assertTrue(sys.int_info.bits_per_digit % 5 == 0)
427 self.assertTrue(sys.int_info.sizeof_digit >= 1)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000428 self.assertEqual(type(sys.int_info.bits_per_digit), int)
429 self.assertEqual(type(sys.int_info.sizeof_digit), int)
Ezio Melottie9615932010-01-24 19:26:24 +0000430 self.assertIsInstance(sys.hexversion, int)
Mark Dickinsondc787d22010-05-23 13:33:13 +0000431
432 self.assertEqual(len(sys.hash_info), 5)
433 self.assertLess(sys.hash_info.modulus, 2**sys.hash_info.width)
434 # sys.hash_info.modulus should be a prime; we do a quick
435 # probable primality test (doesn't exclude the possibility of
436 # a Carmichael number)
437 for x in range(1, 100):
438 self.assertEqual(
439 pow(x, sys.hash_info.modulus-1, sys.hash_info.modulus),
440 1,
441 "sys.hash_info.modulus {} is a non-prime".format(
442 sys.hash_info.modulus)
443 )
444 self.assertIsInstance(sys.hash_info.inf, int)
445 self.assertIsInstance(sys.hash_info.nan, int)
446 self.assertIsInstance(sys.hash_info.imag, int)
447
Ezio Melottie9615932010-01-24 19:26:24 +0000448 self.assertIsInstance(sys.maxsize, int)
449 self.assertIsInstance(sys.maxunicode, int)
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300450 self.assertEqual(sys.maxunicode, 0x10FFFF)
Ezio Melottie9615932010-01-24 19:26:24 +0000451 self.assertIsInstance(sys.platform, str)
452 self.assertIsInstance(sys.prefix, str)
453 self.assertIsInstance(sys.version, str)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000454 vi = sys.version_info
Ezio Melottie9615932010-01-24 19:26:24 +0000455 self.assertIsInstance(vi[:], tuple)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000456 self.assertEqual(len(vi), 5)
Ezio Melottie9615932010-01-24 19:26:24 +0000457 self.assertIsInstance(vi[0], int)
458 self.assertIsInstance(vi[1], int)
459 self.assertIsInstance(vi[2], int)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000460 self.assertIn(vi[3], ("alpha", "beta", "candidate", "final"))
Ezio Melottie9615932010-01-24 19:26:24 +0000461 self.assertIsInstance(vi[4], int)
462 self.assertIsInstance(vi.major, int)
463 self.assertIsInstance(vi.minor, int)
464 self.assertIsInstance(vi.micro, int)
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000465 self.assertIn(vi.releaselevel, ("alpha", "beta", "candidate", "final"))
Ezio Melottie9615932010-01-24 19:26:24 +0000466 self.assertIsInstance(vi.serial, int)
Eric Smith0e5b5622009-02-06 01:32:42 +0000467 self.assertEqual(vi[0], vi.major)
468 self.assertEqual(vi[1], vi.minor)
469 self.assertEqual(vi[2], vi.micro)
470 self.assertEqual(vi[3], vi.releaselevel)
471 self.assertEqual(vi[4], vi.serial)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000472 self.assertTrue(vi > (1,0,0))
Mark Dickinson55d110c2009-10-24 14:04:48 +0000473 self.assertIsInstance(sys.float_repr_style, str)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000474 self.assertIn(sys.float_repr_style, ('short', 'legacy'))
Barry Warsaw8cf4eae2010-10-16 01:04:07 +0000475 if not sys.platform.startswith('win'):
476 self.assertIsInstance(sys.abiflags, str)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000477
Victor Stinnerd5c355c2011-04-30 14:53:09 +0200478 @unittest.skipUnless(hasattr(sys, 'thread_info'),
479 'Threading required for this test.')
480 def test_thread_info(self):
481 info = sys.thread_info
Ezio Melotti48006cf2011-05-01 00:03:49 +0300482 self.assertEqual(len(info), 3)
Victor Stinnerd5c355c2011-04-30 14:53:09 +0200483 self.assertIn(info.name, ('nt', 'os2', 'pthread', 'solaris', None))
484 self.assertIn(info.lock, ('semaphore', 'mutex+cond', None))
485
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000486 def test_43581(self):
Georg Brandl03124942008-06-10 15:50:56 +0000487 # Can't use sys.stdout, as this is a StringIO object when
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000488 # the test runs under regrtest.
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000489 self.assertEqual(sys.__stdout__.encoding, sys.__stderr__.encoding)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000490
Georg Brandl66a796e2006-12-19 20:50:34 +0000491 def test_intern(self):
Georg Brandl03526552009-10-27 23:00:28 +0000492 global numruns
493 numruns += 1
Georg Brandl66a796e2006-12-19 20:50:34 +0000494 self.assertRaises(TypeError, sys.intern)
Georg Brandl03526552009-10-27 23:00:28 +0000495 s = "never interned before" + str(numruns)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000496 self.assertTrue(sys.intern(s) is s)
Georg Brandl66a796e2006-12-19 20:50:34 +0000497 s2 = s.swapcase().swapcase()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000498 self.assertTrue(sys.intern(s2) is s)
Georg Brandl66a796e2006-12-19 20:50:34 +0000499
500 # Subclasses of string can't be interned, because they
501 # provide too much opportunity for insane things to happen.
502 # We don't want them in the interned dict and if they aren't
503 # actually interned, we don't want to create the appearance
Ezio Melotti13925002011-03-16 11:05:33 +0200504 # that they are by allowing intern() to succeed.
Guido van Rossum98297ee2007-11-06 21:34:58 +0000505 class S(str):
Georg Brandl66a796e2006-12-19 20:50:34 +0000506 def __hash__(self):
507 return 123
508
Guido van Rossum98297ee2007-11-06 21:34:58 +0000509 self.assertRaises(TypeError, sys.intern, S("abc"))
Martin v. Löwis5b222132007-06-10 09:51:05 +0000510
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000511 def test_sys_flags(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000512 self.assertTrue(sys.flags)
Éric Araujobe3bd572011-03-26 01:55:15 +0100513 attrs = ("debug",
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000514 "inspect", "interactive", "optimize", "dont_write_bytecode",
Georg Brandlc5e88d52008-06-06 09:02:07 +0000515 "no_user_site", "no_site", "ignore_environment", "verbose",
Georg Brandl09a7c722012-02-20 21:31:46 +0100516 "bytes_warning", "quiet", "hash_randomization")
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000517 for attr in attrs:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000518 self.assertTrue(hasattr(sys.flags, attr), attr)
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000519 self.assertEqual(type(getattr(sys.flags, attr)), int, attr)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000520 self.assertTrue(repr(sys.flags))
Georg Brandlc5e88d52008-06-06 09:02:07 +0000521 self.assertEqual(len(sys.flags), len(attrs))
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000522
Christian Heimes15ebc882008-02-04 18:48:49 +0000523 def test_clear_type_cache(self):
524 sys._clear_type_cache()
525
Martin v. Löwis0f599892008-06-02 11:13:03 +0000526 def test_ioencoding(self):
Martin v. Löwis0f599892008-06-02 11:13:03 +0000527 env = dict(os.environ)
528
529 # Test character: cent sign, encoded as 0x4A (ASCII J) in CP424,
530 # not representable in ASCII.
531
532 env["PYTHONIOENCODING"] = "cp424"
533 p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'],
534 stdout = subprocess.PIPE, env=env)
Antoine Pitrou836f0e22009-10-27 19:25:57 +0000535 out = p.communicate()[0].strip()
Martin v. Löwis0f599892008-06-02 11:13:03 +0000536 self.assertEqual(out, "\xa2\n".encode("cp424"))
537
538 env["PYTHONIOENCODING"] = "ascii:replace"
539 p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'],
540 stdout = subprocess.PIPE, env=env)
Antoine Pitrou836f0e22009-10-27 19:25:57 +0000541 out = p.communicate()[0].strip()
Martin v. Löwis0f599892008-06-02 11:13:03 +0000542 self.assertEqual(out, b'?')
543
Victor Stinner171ba052010-03-12 14:20:59 +0000544 def test_executable(self):
Petri Lehtinen97133212012-02-02 20:59:48 +0200545 # sys.executable should be absolute
546 self.assertEqual(os.path.abspath(sys.executable), sys.executable)
547
Victor Stinner171ba052010-03-12 14:20:59 +0000548 # Issue #7774: Ensure that sys.executable is an empty string if argv[0]
549 # has been set to an non existent program name and Python is unable to
550 # retrieve the real program name
Florent Xicluna02ea12b22010-07-28 16:39:41 +0000551
Victor Stinner171ba052010-03-12 14:20:59 +0000552 # For a normal installation, it should work without 'cwd'
553 # argument. For test runs in the build directory, see #7774.
554 python_dir = os.path.dirname(os.path.realpath(sys.executable))
555 p = subprocess.Popen(
556 ["nonexistent", "-c",
557 'import sys; print(sys.executable.encode("ascii", "backslashreplace"))'],
558 executable=sys.executable, stdout=subprocess.PIPE, cwd=python_dir)
559 stdout = p.communicate()[0]
560 executable = stdout.strip().decode("ASCII")
561 p.wait()
562 self.assertIn(executable, ["b''", repr(sys.executable.encode("ascii", "backslashreplace"))])
563
Victor Stinner85ca2af2010-08-19 11:23:47 +0000564 def check_fsencoding(self, fs_encoding, expected=None):
565 self.assertIsNotNone(fs_encoding)
566 codecs.lookup(fs_encoding)
567 if expected:
568 self.assertEqual(fs_encoding, expected)
569
Victor Stinnerc732e3b2010-08-18 22:44:15 +0000570 def test_getfilesystemencoding(self):
Victor Stinnerc732e3b2010-08-18 22:44:15 +0000571 fs_encoding = sys.getfilesystemencoding()
Victor Stinner85ca2af2010-08-19 11:23:47 +0000572 if sys.platform == 'darwin':
573 expected = 'utf-8'
574 elif sys.platform == 'win32':
575 expected = 'mbcs'
576 else:
577 expected = None
Victor Stinner99435242010-08-19 11:30:09 +0000578 self.check_fsencoding(fs_encoding, expected)
Victor Stinnerc732e3b2010-08-18 22:44:15 +0000579
Martin v. Löwis0f599892008-06-02 11:13:03 +0000580
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000581class SizeofTest(unittest.TestCase):
582
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000583 TPFLAGS_HAVE_GC = 1<<14
584 TPFLAGS_HEAPTYPE = 1<<9
585
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000586 def setUp(self):
Victor Stinnerbaab9d02010-12-28 13:33:43 +0000587 self.c = len(struct.pack('c', b' '))
Robert Schuppenies4d45bfe2008-06-28 23:58:47 +0000588 self.H = len(struct.pack('H', 0))
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000589 self.i = len(struct.pack('i', 0))
590 self.l = len(struct.pack('l', 0))
Robert Schuppenies4d45bfe2008-06-28 23:58:47 +0000591 self.P = len(struct.pack('P', 0))
592 # due to missing size_t information from struct, it is assumed that
593 # sizeof(Py_ssize_t) = sizeof(void*)
594 self.header = 'PP'
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000595 self.vheader = self.header + 'P'
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000596 if hasattr(sys, "gettotalrefcount"):
Robert Schuppenies4d45bfe2008-06-28 23:58:47 +0000597 self.header += '2P'
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000598 self.vheader += '2P'
Mark Dickinsonbd792642009-03-18 20:06:12 +0000599 self.longdigit = sys.int_info.sizeof_digit
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000600 import _testcapi
601 self.gc_headsize = _testcapi.SIZEOF_PYGC_HEAD
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000602 self.file = open(test.support.TESTFN, 'wb')
603
604 def tearDown(self):
605 self.file.close()
606 test.support.unlink(test.support.TESTFN)
607
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000608 def check_sizeof(self, o, size):
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000609 result = sys.getsizeof(o)
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000610 # add GC header size
611 if ((type(o) == type) and (o.__flags__ & self.TPFLAGS_HEAPTYPE) or\
612 ((type(o) != type) and (type(o).__flags__ & self.TPFLAGS_HAVE_GC))):
613 size += self.gc_headsize
614 msg = 'wrong size for %s: got %d, expected %d' \
615 % (type(o), result, size)
616 self.assertEqual(result, size, msg)
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000617
Robert Schuppenies4d45bfe2008-06-28 23:58:47 +0000618 def calcsize(self, fmt):
619 """Wrapper around struct.calcsize which enforces the alignment of the
620 end of a structure to the alignment requirement of pointer.
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000621
Robert Schuppenies4d45bfe2008-06-28 23:58:47 +0000622 Note: This wrapper should only be used if a pointer member is included
623 and no member with a size larger than a pointer exists.
624 """
625 return struct.calcsize(fmt + '0P')
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000626
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000627 def test_gc_head_size(self):
628 # Check that the gc header size is added to objects tracked by the gc.
Robert Schuppenies4d45bfe2008-06-28 23:58:47 +0000629 h = self.header
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000630 vh = self.vheader
Robert Schuppenies4d45bfe2008-06-28 23:58:47 +0000631 size = self.calcsize
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000632 gc_header_size = self.gc_headsize
633 # bool objects are not gc tracked
Mark Dickinsonbd792642009-03-18 20:06:12 +0000634 self.assertEqual(sys.getsizeof(True), size(vh) + self.longdigit)
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000635 # but lists are
636 self.assertEqual(sys.getsizeof([]), size(vh + 'PP') + gc_header_size)
637
638 def test_default(self):
639 h = self.header
640 vh = self.vheader
641 size = self.calcsize
Mark Dickinsonbd792642009-03-18 20:06:12 +0000642 self.assertEqual(sys.getsizeof(True), size(vh) + self.longdigit)
643 self.assertEqual(sys.getsizeof(True, -1), size(vh) + self.longdigit)
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000644
645 def test_objecttypes(self):
646 # check all types defined in Objects/
647 h = self.header
648 vh = self.vheader
649 size = self.calcsize
650 check = self.check_sizeof
651 # bool
Mark Dickinsonbd792642009-03-18 20:06:12 +0000652 check(True, size(vh) + self.longdigit)
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000653 # buffer
654 # XXX
655 # builtin_function_or_method
656 check(len, size(h + '3P'))
657 # bytearray
658 samples = [b'', b'u'*100000]
659 for sample in samples:
660 x = bytearray(sample)
661 check(x, size(vh + 'iPP') + x.__alloc__() * self.c)
662 # bytearray_iterator
663 check(iter(bytearray()), size(h + 'PP'))
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000664 # cell
665 def get_cell():
666 x = 42
667 def inner():
668 return x
669 return inner
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000670 check(get_cell().__closure__[0], size(h + 'P'))
Robert Schuppenies4efb5182008-06-06 11:49:51 +0000671 # code
Benjamin Peterson90037602011-06-25 22:54:45 -0500672 check(get_cell().__code__, size(h + '5i9Pi3P'))
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000673 # complex
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000674 check(complex(0,1), size(h + '2d'))
675 # method_descriptor (descriptor object)
Antoine Pitrou9d574812011-12-12 13:47:25 +0100676 check(str.lower, size(h + '3PP'))
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000677 # classmethod_descriptor (descriptor object)
678 # XXX
679 # member_descriptor (descriptor object)
680 import datetime
Antoine Pitrou9d574812011-12-12 13:47:25 +0100681 check(datetime.timedelta.days, size(h + '3PP'))
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000682 # getset_descriptor (descriptor object)
683 import collections
Antoine Pitrou9d574812011-12-12 13:47:25 +0100684 check(collections.defaultdict.default_factory, size(h + '3PP'))
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000685 # wrapper_descriptor (descriptor object)
Antoine Pitrou9d574812011-12-12 13:47:25 +0100686 check(int.__add__, size(h + '3P2P'))
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000687 # method-wrapper (descriptor object)
688 check({}.__iter__, size(h + '2P'))
689 # dict
690 check({}, size(h + '3P2P' + 8*'P2P'))
691 longdict = {1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8}
692 check(longdict, size(h + '3P2P' + 8*'P2P') + 16*size('P2P'))
693 # dictionary-keyiterator
694 check({}.keys(), size(h + 'P'))
695 # dictionary-valueiterator
696 check({}.values(), size(h + 'P'))
697 # dictionary-itemiterator
698 check({}.items(), size(h + 'P'))
699 # dictproxy
700 class C(object): pass
701 check(C.__dict__, size(h + 'P'))
702 # BaseException
703 check(BaseException(), size(h + '5P'))
704 # UnicodeEncodeError
705 check(UnicodeEncodeError("", "", 0, 0, ""), size(h + '5P 2P2PP'))
706 # UnicodeDecodeError
707 # XXX
708# check(UnicodeDecodeError("", "", 0, 0, ""), size(h + '5P2PP'))
709 # UnicodeTranslateError
710 check(UnicodeTranslateError("", 0, 1, ""), size(h + '5P 2P2PP'))
711 # ellipses
712 check(Ellipsis, size(h + ''))
713 # EncodingMap
714 import codecs, encodings.iso8859_3
715 x = codecs.charmap_build(encodings.iso8859_3.decoding_table)
716 check(x, size(h + '32B2iB'))
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000717 # enumerate
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000718 check(enumerate([]), size(h + 'l3P'))
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000719 # reverse
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000720 check(reversed(''), size(h + 'PP'))
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000721 # float
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000722 check(float(0), size(h + 'd'))
723 # sys.floatinfo
724 check(sys.float_info, size(vh) + self.P * len(sys.float_info))
725 # frame
726 import inspect
727 CO_MAXBLOCKS = 20
728 x = inspect.currentframe()
729 ncells = len(x.f_code.co_cellvars)
730 nfrees = len(x.f_code.co_freevars)
731 extras = x.f_code.co_stacksize + x.f_code.co_nlocals +\
732 ncells + nfrees - 1
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500733 check(x, size(vh + '12P3i' + CO_MAXBLOCKS*'3i' + 'P' + extras*'P'))
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000734 # function
735 def func(): pass
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100736 check(func, size(h + '12P'))
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000737 class c():
738 @staticmethod
739 def foo():
740 pass
741 @classmethod
742 def bar(cls):
743 pass
744 # staticmethod
Benjamin Peterson85c71ae2012-02-19 19:16:47 -0500745 check(foo, size(h + 'PP'))
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000746 # classmethod
Benjamin Peterson85c71ae2012-02-19 19:16:47 -0500747 check(bar, size(h + 'PP'))
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000748 # generator
749 def get_gen(): yield 1
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000750 check(get_gen(), size(h + 'Pi2P'))
751 # iterator
752 check(iter('abc'), size(h + 'lP'))
753 # callable-iterator
754 import re
755 check(re.finditer('',''), size(h + '2P'))
756 # list
757 samples = [[], [1,2,3], ['1', '2', '3']]
758 for sample in samples:
759 check(sample, size(vh + 'PP') + len(sample)*self.P)
760 # sortwrapper (list)
761 # XXX
762 # cmpwrapper (list)
763 # XXX
764 # listiterator (list)
765 check(iter([]), size(h + 'lP'))
766 # listreverseiterator (list)
767 check(reversed([]), size(h + 'lP'))
768 # long
769 check(0, size(vh))
Mark Dickinsonbd792642009-03-18 20:06:12 +0000770 check(1, size(vh) + self.longdigit)
771 check(-1, size(vh) + self.longdigit)
772 PyLong_BASE = 2**sys.int_info.bits_per_digit
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000773 check(int(PyLong_BASE), size(vh) + 2*self.longdigit)
774 check(int(PyLong_BASE**2-1), size(vh) + 2*self.longdigit)
775 check(int(PyLong_BASE**2), size(vh) + 3*self.longdigit)
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100776 # memoryview
777 check(memoryview(b''), size(h + 'PPiP4P2i5P3cP'))
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000778 # module
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000779 check(unittest, size(h + '3P'))
780 # None
781 check(None, size(h + ''))
782 # NotImplementedType
783 check(NotImplemented, size(h))
784 # object
785 check(object(), size(h + ''))
786 # property (descriptor object)
787 class C(object):
788 def getx(self): return self.__x
789 def setx(self, value): self.__x = value
790 def delx(self): del self.__x
791 x = property(getx, setx, delx, "")
792 check(x, size(h + '4Pi'))
Benjamin Petersonb173f782009-05-05 22:31:58 +0000793 # PyCapsule
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000794 # XXX
795 # rangeiterator
796 check(iter(range(1)), size(h + '4l'))
797 # reverse
798 check(reversed(''), size(h + 'PP'))
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000799 # range
Nick Coghlan37ee8502010-12-03 14:26:13 +0000800 check(range(1), size(h + '4P'))
801 check(range(66000), size(h + '4P'))
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000802 # set
803 # frozenset
804 PySet_MINSIZE = 8
805 samples = [[], range(10), range(50)]
806 s = size(h + '3P2P' + PySet_MINSIZE*'lP' + 'lP')
807 for sample in samples:
808 minused = len(sample)
809 if minused == 0: tmp = 1
810 # the computation of minused is actually a bit more complicated
811 # but this suffices for the sizeof test
812 minused = minused*2
813 newsize = PySet_MINSIZE
814 while newsize <= minused:
815 newsize = newsize << 1
816 if newsize <= 8:
817 check(set(sample), s)
818 check(frozenset(sample), s)
819 else:
820 check(set(sample), s + newsize*struct.calcsize('lP'))
821 check(frozenset(sample), s + newsize*struct.calcsize('lP'))
822 # setiterator
823 check(iter(set()), size(h + 'P3P'))
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000824 # slice
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000825 check(slice(0), size(h + '3P'))
826 # super
827 check(super(int), size(h + '3P'))
828 # tuple
829 check((), size(vh))
830 check((1,2,3), size(vh) + 3*self.P)
831 # type
832 # (PyTypeObject + PyNumberMethods + PyMappingMethods +
833 # PySequenceMethods + PyBufferProcs)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100834 s = size(vh + 'P2P15Pl4PP9PP11PI') + size('16Pi17P 3P 10P 2P 3P')
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000835 check(int, s)
836 # class
837 class newstyleclass(object): pass
838 check(newstyleclass, s)
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000839 # unicode
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200840 # each tuple contains a string and its expected character size
841 # don't put any static strings here, as they may contain
842 # wchar_t or UTF-8 representations
843 samples = ['1'*100, '\xff'*50,
844 '\u0100'*40, '\uffff'*100,
845 '\U00010000'*30, '\U0010ffff'*100]
846 asciifields = h + "PPiP"
847 compactfields = asciifields + "PPP"
848 unicodefields = compactfields + "P"
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000849 for s in samples:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200850 maxchar = ord(max(s))
851 if maxchar < 128:
852 L = size(asciifields) + len(s) + 1
853 elif maxchar < 256:
854 L = size(compactfields) + len(s) + 1
855 elif maxchar < 65536:
856 L = size(compactfields) + 2*(len(s) + 1)
857 else:
858 L = size(compactfields) + 4*(len(s) + 1)
859 check(s, L)
860 # verify that the UTF-8 size is accounted for
861 s = chr(0x4000) # 4 bytes canonical representation
862 check(s, size(compactfields) + 4)
Martin v. Löwisf02aa652011-09-28 09:22:13 +0200863 # compile() will trigger the generation of the UTF-8
864 # representation as a side effect
865 compile(s, "<stdin>", "eval")
866 check(s, size(compactfields) + 4 + 4)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200867 # TODO: add check that forces the presence of wchar_t representation
868 # TODO: add check that forces layout of unicodefields
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000869 # weakref
870 import weakref
871 check(weakref.ref(int), size(h + '2Pl2P'))
872 # weakproxy
873 # XXX
874 # weakcallableproxy
875 check(weakref.proxy(int), size(h + '2Pl2P'))
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000876
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000877 def test_pythontypes(self):
878 # check all types defined in Python/
879 h = self.header
880 vh = self.vheader
881 size = self.calcsize
882 check = self.check_sizeof
883 # _ast.AST
884 import _ast
Benjamin Petersonf28fcff2012-03-12 11:19:19 -0700885 check(_ast.AST(), size(h + 'P'))
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000886 # imp.NullImporter
887 import imp
888 check(imp.NullImporter(self.file.name), size(h + ''))
889 try:
890 raise TypeError
891 except TypeError:
892 tb = sys.exc_info()[2]
893 # traceback
894 if tb != None:
895 check(tb, size(h + '2P2i'))
896 # symtable entry
897 # XXX
898 # sys.flags
899 check(sys.flags, size(vh) + self.P * len(sys.flags))
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000900
901
Walter Dörwaldc3502462003-02-03 23:03:49 +0000902def test_main():
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000903 test.support.run_unittest(SysModuleTest, SizeofTest)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000904
905if __name__ == "__main__":
906 test_main()