blob: 28614a6f16b85477447a50ba548807a3b897ecba [file] [log] [blame]
Walter Dörwaldc3502462003-02-03 23:03:49 +00001# -*- coding: iso-8859-1 -*-
2import unittest, test.test_support
Robert Schuppenies51df0642008-06-01 16:16:17 +00003import sys, cStringIO, os
Walter Dörwaldc3502462003-02-03 23:03:49 +00004
5class SysModuleTest(unittest.TestCase):
6
7 def test_original_displayhook(self):
8 import __builtin__
9 savestdout = sys.stdout
10 out = cStringIO.StringIO()
11 sys.stdout = out
12
13 dh = sys.__displayhook__
14
15 self.assertRaises(TypeError, dh)
16 if hasattr(__builtin__, "_"):
17 del __builtin__._
18
19 dh(None)
20 self.assertEqual(out.getvalue(), "")
21 self.assert_(not hasattr(__builtin__, "_"))
22 dh(42)
23 self.assertEqual(out.getvalue(), "42\n")
24 self.assertEqual(__builtin__._, 42)
25
26 del sys.stdout
27 self.assertRaises(RuntimeError, dh, 42)
28
29 sys.stdout = savestdout
30
31 def test_lost_displayhook(self):
32 olddisplayhook = sys.displayhook
33 del sys.displayhook
34 code = compile("42", "<string>", "single")
35 self.assertRaises(RuntimeError, eval, code)
36 sys.displayhook = olddisplayhook
37
38 def test_custom_displayhook(self):
39 olddisplayhook = sys.displayhook
40 def baddisplayhook(obj):
41 raise ValueError
42 sys.displayhook = baddisplayhook
43 code = compile("42", "<string>", "single")
44 self.assertRaises(ValueError, eval, code)
45 sys.displayhook = olddisplayhook
46
47 def test_original_excepthook(self):
48 savestderr = sys.stderr
49 err = cStringIO.StringIO()
50 sys.stderr = err
51
52 eh = sys.__excepthook__
53
54 self.assertRaises(TypeError, eh)
55 try:
56 raise ValueError(42)
57 except ValueError, exc:
58 eh(*sys.exc_info())
59
60 sys.stderr = savestderr
61 self.assert_(err.getvalue().endswith("ValueError: 42\n"))
62
Walter Dörwalde7028ac2003-02-03 23:05:27 +000063 # FIXME: testing the code for a lost or replaced excepthook in
Walter Dörwaldc3502462003-02-03 23:03:49 +000064 # Python/pythonrun.c::PyErr_PrintEx() is tricky.
65
Guido van Rossum46d3dc32003-03-01 03:20:41 +000066 def test_exc_clear(self):
67 self.assertRaises(TypeError, sys.exc_clear, 42)
68
69 # Verify that exc_info is present and matches exc, then clear it, and
70 # check that it worked.
71 def clear_check(exc):
Guido van Rossumd6473d12003-03-01 03:25:41 +000072 typ, value, traceback = sys.exc_info()
73 self.assert_(typ is not None)
74 self.assert_(value is exc)
75 self.assert_(traceback is not None)
Guido van Rossum46d3dc32003-03-01 03:20:41 +000076
Guido van Rossumd6473d12003-03-01 03:25:41 +000077 sys.exc_clear()
Guido van Rossum46d3dc32003-03-01 03:20:41 +000078
Guido van Rossumd6473d12003-03-01 03:25:41 +000079 typ, value, traceback = sys.exc_info()
80 self.assert_(typ is None)
81 self.assert_(value is None)
82 self.assert_(traceback is None)
Guido van Rossum46d3dc32003-03-01 03:20:41 +000083
84 def clear():
Guido van Rossumd6473d12003-03-01 03:25:41 +000085 try:
86 raise ValueError, 42
87 except ValueError, exc:
88 clear_check(exc)
Guido van Rossum46d3dc32003-03-01 03:20:41 +000089
90 # Raise an exception and check that it can be cleared
91 clear()
92
93 # Verify that a frame currently handling an exception is
94 # unaffected by calling exc_clear in a nested frame.
95 try:
Guido van Rossumd6473d12003-03-01 03:25:41 +000096 raise ValueError, 13
Guido van Rossum46d3dc32003-03-01 03:20:41 +000097 except ValueError, exc:
Guido van Rossumd6473d12003-03-01 03:25:41 +000098 typ1, value1, traceback1 = sys.exc_info()
99 clear()
100 typ2, value2, traceback2 = sys.exc_info()
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000101
Guido van Rossumd6473d12003-03-01 03:25:41 +0000102 self.assert_(typ1 is typ2)
103 self.assert_(value1 is exc)
104 self.assert_(value1 is value2)
105 self.assert_(traceback1 is traceback2)
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000106
107 # Check that an exception can be cleared outside of an except block
108 clear_check(exc)
109
Walter Dörwaldc3502462003-02-03 23:03:49 +0000110 def test_exit(self):
111 self.assertRaises(TypeError, sys.exit, 42, 42)
112
113 # call without argument
114 try:
115 sys.exit(0)
116 except SystemExit, exc:
117 self.assertEquals(exc.code, 0)
118 except:
119 self.fail("wrong exception")
120 else:
121 self.fail("no exception")
122
123 # call with tuple argument with one entry
124 # entry will be unpacked
125 try:
126 sys.exit(42)
127 except SystemExit, exc:
128 self.assertEquals(exc.code, 42)
129 except:
130 self.fail("wrong exception")
131 else:
132 self.fail("no exception")
133
134 # call with integer argument
135 try:
136 sys.exit((42,))
137 except SystemExit, exc:
138 self.assertEquals(exc.code, 42)
139 except:
140 self.fail("wrong exception")
141 else:
142 self.fail("no exception")
143
144 # call with string argument
145 try:
146 sys.exit("exit")
147 except SystemExit, exc:
148 self.assertEquals(exc.code, "exit")
149 except:
150 self.fail("wrong exception")
151 else:
152 self.fail("no exception")
153
154 # call with tuple argument with two entries
155 try:
156 sys.exit((17, 23))
157 except SystemExit, exc:
158 self.assertEquals(exc.code, (17, 23))
159 except:
160 self.fail("wrong exception")
161 else:
162 self.fail("no exception")
163
Michael W. Hudsonf0588582005-02-15 15:26:11 +0000164 # test that the exit machinery handles SystemExits properly
165 import subprocess
166 # both unnormalized...
167 rc = subprocess.call([sys.executable, "-c",
168 "raise SystemExit, 46"])
169 self.assertEqual(rc, 46)
170 # ... and normalized
171 rc = subprocess.call([sys.executable, "-c",
172 "raise SystemExit(47)"])
173 self.assertEqual(rc, 47)
Tim Petersf0db38d2005-02-15 21:50:12 +0000174
175
Walter Dörwaldc3502462003-02-03 23:03:49 +0000176 def test_getdefaultencoding(self):
177 if test.test_support.have_unicode:
178 self.assertRaises(TypeError, sys.getdefaultencoding, 42)
179 # can't check more than the type, as the user might have changed it
180 self.assert_(isinstance(sys.getdefaultencoding(), str))
181
182 # testing sys.settrace() is done in test_trace.py
183 # testing sys.setprofile() is done in test_profile.py
184
185 def test_setcheckinterval(self):
Tim Petersf2715e02003-02-19 02:35:07 +0000186 self.assertRaises(TypeError, sys.setcheckinterval)
Tim Peterse5e065b2003-07-06 18:36:54 +0000187 orig = sys.getcheckinterval()
188 for n in 0, 100, 120, orig: # orig last to restore starting state
189 sys.setcheckinterval(n)
190 self.assertEquals(sys.getcheckinterval(), n)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000191
192 def test_recursionlimit(self):
Tim Petersf2715e02003-02-19 02:35:07 +0000193 self.assertRaises(TypeError, sys.getrecursionlimit, 42)
194 oldlimit = sys.getrecursionlimit()
195 self.assertRaises(TypeError, sys.setrecursionlimit)
196 self.assertRaises(ValueError, sys.setrecursionlimit, -42)
197 sys.setrecursionlimit(10000)
198 self.assertEqual(sys.getrecursionlimit(), 10000)
199 sys.setrecursionlimit(oldlimit)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000200
201 def test_getwindowsversion(self):
202 if hasattr(sys, "getwindowsversion"):
203 v = sys.getwindowsversion()
204 self.assert_(isinstance(v, tuple))
205 self.assertEqual(len(v), 5)
206 self.assert_(isinstance(v[0], int))
207 self.assert_(isinstance(v[1], int))
208 self.assert_(isinstance(v[2], int))
209 self.assert_(isinstance(v[3], int))
210 self.assert_(isinstance(v[4], str))
211
212 def test_dlopenflags(self):
213 if hasattr(sys, "setdlopenflags"):
214 self.assert_(hasattr(sys, "getdlopenflags"))
215 self.assertRaises(TypeError, sys.getdlopenflags, 42)
216 oldflags = sys.getdlopenflags()
217 self.assertRaises(TypeError, sys.setdlopenflags)
218 sys.setdlopenflags(oldflags+1)
219 self.assertEqual(sys.getdlopenflags(), oldflags+1)
220 sys.setdlopenflags(oldflags)
221
222 def test_refcount(self):
223 self.assertRaises(TypeError, sys.getrefcount)
224 c = sys.getrefcount(None)
225 n = None
226 self.assertEqual(sys.getrefcount(None), c+1)
227 del n
228 self.assertEqual(sys.getrefcount(None), c)
229 if hasattr(sys, "gettotalrefcount"):
230 self.assert_(isinstance(sys.gettotalrefcount(), int))
231
232 def test_getframe(self):
233 self.assertRaises(TypeError, sys._getframe, 42, 42)
Neal Norwitzeb2a5ef2003-02-18 15:22:10 +0000234 self.assertRaises(ValueError, sys._getframe, 2000000000)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000235 self.assert_(
236 SysModuleTest.test_getframe.im_func.func_code \
237 is sys._getframe().f_code
238 )
239
Tim Peters32a83612006-07-10 21:08:24 +0000240 # sys._current_frames() is a CPython-only gimmick.
241 def test_current_frames(self):
Tim Peters112aad32006-07-19 00:03:19 +0000242 have_threads = True
243 try:
244 import thread
245 except ImportError:
246 have_threads = False
247
248 if have_threads:
249 self.current_frames_with_threads()
250 else:
251 self.current_frames_without_threads()
252
253 # Test sys._current_frames() in a WITH_THREADS build.
254 def current_frames_with_threads(self):
Tim Peters32a83612006-07-10 21:08:24 +0000255 import threading, thread
256 import traceback
257
258 # Spawn a thread that blocks at a known place. Then the main
259 # thread does sys._current_frames(), and verifies that the frames
260 # returned make sense.
261 entered_g = threading.Event()
262 leave_g = threading.Event()
263 thread_info = [] # the thread's id
264
265 def f123():
266 g456()
267
268 def g456():
269 thread_info.append(thread.get_ident())
270 entered_g.set()
271 leave_g.wait()
272
273 t = threading.Thread(target=f123)
274 t.start()
275 entered_g.wait()
276
Tim Peters0c4a3b32006-07-25 04:07:22 +0000277 # At this point, t has finished its entered_g.set(), although it's
278 # impossible to guess whether it's still on that line or has moved on
279 # to its leave_g.wait().
Tim Peters32a83612006-07-10 21:08:24 +0000280 self.assertEqual(len(thread_info), 1)
281 thread_id = thread_info[0]
282
283 d = sys._current_frames()
284
285 main_id = thread.get_ident()
286 self.assert_(main_id in d)
287 self.assert_(thread_id in d)
288
289 # Verify that the captured main-thread frame is _this_ frame.
290 frame = d.pop(main_id)
291 self.assert_(frame is sys._getframe())
292
293 # Verify that the captured thread frame is blocked in g456, called
294 # from f123. This is a litte tricky, since various bits of
295 # threading.py are also in the thread's call stack.
296 frame = d.pop(thread_id)
297 stack = traceback.extract_stack(frame)
298 for i, (filename, lineno, funcname, sourceline) in enumerate(stack):
299 if funcname == "f123":
300 break
301 else:
302 self.fail("didn't find f123() on thread's call stack")
303
304 self.assertEqual(sourceline, "g456()")
305
306 # And the next record must be for g456().
307 filename, lineno, funcname, sourceline = stack[i+1]
308 self.assertEqual(funcname, "g456")
Tim Peters0c4a3b32006-07-25 04:07:22 +0000309 self.assert_(sourceline in ["leave_g.wait()", "entered_g.set()"])
Tim Peters32a83612006-07-10 21:08:24 +0000310
311 # Reap the spawned thread.
312 leave_g.set()
313 t.join()
314
Tim Peters112aad32006-07-19 00:03:19 +0000315 # Test sys._current_frames() when thread support doesn't exist.
316 def current_frames_without_threads(self):
317 # Not much happens here: there is only one thread, with artificial
318 # "thread id" 0.
319 d = sys._current_frames()
320 self.assertEqual(len(d), 1)
321 self.assert_(0 in d)
322 self.assert_(d[0] is sys._getframe())
323
Walter Dörwaldc3502462003-02-03 23:03:49 +0000324 def test_attributes(self):
325 self.assert_(isinstance(sys.api_version, int))
326 self.assert_(isinstance(sys.argv, list))
327 self.assert_(sys.byteorder in ("little", "big"))
328 self.assert_(isinstance(sys.builtin_module_names, tuple))
329 self.assert_(isinstance(sys.copyright, basestring))
330 self.assert_(isinstance(sys.exec_prefix, basestring))
331 self.assert_(isinstance(sys.executable, basestring))
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000332 self.assertEqual(len(sys.float_info), 11)
Christian Heimesc94e2b52008-01-14 04:13:37 +0000333 self.assertEqual(sys.float_info.radix, 2)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000334 self.assert_(isinstance(sys.hexversion, int))
335 self.assert_(isinstance(sys.maxint, int))
Walter Dörwald4e41a4b2005-08-03 17:09:04 +0000336 if test.test_support.have_unicode:
337 self.assert_(isinstance(sys.maxunicode, int))
Walter Dörwaldc3502462003-02-03 23:03:49 +0000338 self.assert_(isinstance(sys.platform, basestring))
339 self.assert_(isinstance(sys.prefix, basestring))
340 self.assert_(isinstance(sys.version, basestring))
341 vi = sys.version_info
342 self.assert_(isinstance(vi, tuple))
343 self.assertEqual(len(vi), 5)
344 self.assert_(isinstance(vi[0], int))
345 self.assert_(isinstance(vi[1], int))
346 self.assert_(isinstance(vi[2], int))
347 self.assert_(vi[3] in ("alpha", "beta", "candidate", "final"))
348 self.assert_(isinstance(vi[4], int))
349
Martin v. Löwisa8cd7a22006-04-03 11:05:39 +0000350 def test_43581(self):
351 # Can't use sys.stdout, as this is a cStringIO object when
352 # the test runs under regrtest.
353 self.assert_(sys.__stdout__.encoding == sys.__stderr__.encoding)
354
Christian Heimesf31b69f2008-01-14 03:42:48 +0000355 def test_sys_flags(self):
356 self.failUnless(sys.flags)
357 attrs = ("debug", "py3k_warning", "division_warning", "division_new",
358 "inspect", "interactive", "optimize", "dont_write_bytecode",
Andrew M. Kuchling7ce9b182008-01-15 01:29:16 +0000359 "no_site", "ignore_environment", "tabcheck", "verbose",
Brett Cannonbe1501b2008-05-08 20:23:06 +0000360 "unicode", "bytes_warning")
Christian Heimesf31b69f2008-01-14 03:42:48 +0000361 for attr in attrs:
362 self.assert_(hasattr(sys.flags, attr), attr)
363 self.assertEqual(type(getattr(sys.flags, attr)), int, attr)
364 self.assert_(repr(sys.flags))
365
Christian Heimes422051a2008-02-04 18:00:12 +0000366 def test_clear_type_cache(self):
367 sys._clear_type_cache()
368
369 def test_compact_freelists(self):
370 sys._compact_freelists()
371 r = sys._compact_freelists()
Raymond Hettinger8c6c12c2008-02-09 10:06:20 +0000372## # freed blocks shouldn't change
373## self.assertEqual(r[0][2], 0)
374## self.assertEqual(r[1][2], 0)
375## # fill freelists
376## ints = list(range(10000))
377## floats = [float(i) for i in ints]
378## del ints
379## del floats
380## # should free more than 200 blocks each
381## r = sys._compact_freelists()
382## self.assert_(r[0][1] > 100, r[0][1])
383## self.assert_(r[1][2] > 100, r[1][1])
384##
385## self.assert_(r[0][2] > 100, r[0][2])
386## self.assert_(r[1][2] > 100, r[1][2])
Christian Heimesf31b69f2008-01-14 03:42:48 +0000387
Martin v. Löwis99815892008-06-01 07:20:46 +0000388 def test_ioencoding(self):
389 import subprocess,os
390 env = dict(os.environ)
391
392 # Test character: cent sign, encoded as 0x4A (ASCII J) in CP424,
393 # not representable in ASCII.
394
395 env["PYTHONIOENCODING"] = "cp424"
396 p = subprocess.Popen([sys.executable, "-c", 'print unichr(0xa2)'],
397 stdout = subprocess.PIPE, env=env)
398 out = p.stdout.read().strip()
399 self.assertEqual(out, unichr(0xa2).encode("cp424"))
400
401 env["PYTHONIOENCODING"] = "ascii:replace"
402 p = subprocess.Popen([sys.executable, "-c", 'print unichr(0xa2)'],
403 stdout = subprocess.PIPE, env=env)
404 out = p.stdout.read().strip()
405 self.assertEqual(out, '?')
406
407
Robert Schuppenies51df0642008-06-01 16:16:17 +0000408class SizeofTest(unittest.TestCase):
409
410 def setUp(self):
411 import struct
412 self.i = len(struct.pack('i', 0))
413 self.l = len(struct.pack('l', 0))
414 self.p = len(struct.pack('P', 0))
415 self.headersize = self.l + self.p
416 if hasattr(sys, "gettotalrefcount"):
417 self.headersize += 2 * self.p
418 self.file = open(test.test_support.TESTFN, 'wb')
419
420 def tearDown(self):
421 self.file.close()
Georg Brandl7a6de8b2008-06-01 16:42:16 +0000422 test.test_support.unlink(test.test_support.TESTFN)
Robert Schuppenies51df0642008-06-01 16:16:17 +0000423
424 def check_sizeof(self, o, size):
425 result = sys.getsizeof(o)
426 msg = 'wrong size for %s: got %d, expected %d' \
427 % (type(o), result, size)
428 self.assertEqual(result, size, msg)
429
430 def align(self, value):
431 mod = value % self.p
432 if mod != 0:
433 return value - mod + self.p
434 else:
435 return value
436
437 def test_align(self):
Georg Brandl7a6de8b2008-06-01 16:42:16 +0000438 self.assertEqual(self.align(0) % self.p, 0)
439 self.assertEqual(self.align(1) % self.p, 0)
440 self.assertEqual(self.align(3) % self.p, 0)
441 self.assertEqual(self.align(4) % self.p, 0)
442 self.assertEqual(self.align(7) % self.p, 0)
443 self.assertEqual(self.align(8) % self.p, 0)
444 self.assertEqual(self.align(9) % self.p, 0)
Robert Schuppenies51df0642008-06-01 16:16:17 +0000445
446 def test_standardtypes(self):
447 i = self.i
448 l = self.l
449 p = self.p
450 h = self.headersize
451 # bool
452 self.check_sizeof(True, h + l)
453 # buffer
454 self.check_sizeof(buffer(''), h + 2*p + 2*l + self.align(i) +l)
455 # bytearray
456 self.check_sizeof(bytes(), h + self.align(i) + l + p)
457 # cell
458 def get_cell():
459 x = 42
460 def inner():
461 return x
462 return inner
463 self.check_sizeof(get_cell().func_closure[0], h + p)
464 # old-style class
465 class class_oldstyle():
466 def method():
467 pass
468 self.check_sizeof(class_oldstyle, h + 6*p)
469 # instance
470 self.check_sizeof(class_oldstyle(), h + 3*p)
471 # method
472 self.check_sizeof(class_oldstyle().method, h + 4*p)
473 # code
474 self.check_sizeof(get_cell().func_code, h + self.align(4*i) + 8*p +\
475 self.align(i) + 2*p)
476 # complex
477 self.check_sizeof(complex(0,1), h + 2*8)
478 # enumerate
479 self.check_sizeof(enumerate([]), h + l + 3*p)
480 # reverse
481 self.check_sizeof(reversed(''), h + l + p )
482 # file
483 self.check_sizeof(self.file, h + 4*p + self.align(2*i) + 4*p +\
484 self.align(3*i) + 3*p + self.align(i))
485 # float
486 self.check_sizeof(float(0), h + 8)
487 # function
488 def func(): pass
489 self.check_sizeof(func, h + 9 * l)
490 class c():
491 @staticmethod
492 def foo():
493 pass
494 @classmethod
495 def bar(cls):
496 pass
497 # staticmethod
498 self.check_sizeof(foo, h + l)
499 # classmethod
500 self.check_sizeof(bar, h + l)
501 # generator
502 def get_gen(): yield 1
503 self.check_sizeof(get_gen(), h + p + self.align(i) + 2*p)
504 # integer
505 self.check_sizeof(1, h + l)
506 # builtin_function_or_method
507 self.check_sizeof(abs, h + 3*p)
508 # module
509 self.check_sizeof(unittest, h + p)
Georg Brandl7a6de8b2008-06-01 16:42:16 +0000510 # xrange
Robert Schuppenies51df0642008-06-01 16:16:17 +0000511 self.check_sizeof(xrange(1), h + 3*p)
512 # slice
513 self.check_sizeof(slice(0), h + 3*p)
514
515 h += l
516 # new-style class
517 class class_newstyle(object):
518 def method():
519 pass
520 # type (PyTypeObject + PyNumberMethods + PyMappingMethods +
521 # PySequenceMethods + PyBufferProcs)
522 len_typeobject = p + 2*l + 15*p + l + 4*p + l + 9*p + l + 11*p
Georg Brandl7a6de8b2008-06-01 16:42:16 +0000523 self.check_sizeof(class_newstyle,
524 h + len_typeobject + 42*p + 10*p + 3*p + 6*p)
Robert Schuppenies51df0642008-06-01 16:16:17 +0000525
526
527 def test_specialtypes(self):
528 i = self.i
529 l = self.l
530 p = self.p
531 h = self.headersize
532 # dict
533 self.check_sizeof({}, h + 3*l + 3*p + 8*(l + 2*p))
534 longdict = {1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8}
535 self.check_sizeof(longdict, h + 3*l + 3*p + 8*(l + 2*p) + 16*(l + 2*p))
536 # list
537 self.check_sizeof([], h + l + p + l)
538 self.check_sizeof([1, 2, 3], h + l + p + l + 3*l)
539
540 h += l
541 # long
542 self.check_sizeof(0L, h + self.align(2))
543 self.check_sizeof(1L, h + self.align(2))
544 self.check_sizeof(-1L, h + self.align(2))
545 self.check_sizeof(32768L, h + self.align(2) + 2)
546 self.check_sizeof(32768L*32768L-1, h + self.align(2) + 2)
547 self.check_sizeof(32768L*32768L, h + self.align(2) + 4)
548 # string
549 self.check_sizeof('', h + l + self.align(i + 1))
550 self.check_sizeof('abc', h + l + self.align(i + 1) + 3)
551
552
Walter Dörwaldc3502462003-02-03 23:03:49 +0000553def test_main():
Robert Schuppenies51df0642008-06-01 16:16:17 +0000554 test_classes = (SysModuleTest, SizeofTest)
555
556 test.test_support.run_unittest(*test_classes)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000557
558if __name__ == "__main__":
559 test_main()