blob: 897c6b08d4affc82de9213bf3b3293a13a12bf02 [file] [log] [blame]
Walter Dörwaldc3502462003-02-03 23:03:49 +00001# -*- coding: iso-8859-1 -*-
2import unittest, test.test_support
3import sys, cStringIO
4
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)
Guido van Rossumb940e112007-01-10 16:19:56 +000057 except ValueError as exc:
Walter Dörwaldc3502462003-02-03 23:03:49 +000058 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
Guido van Rossumb940e112007-01-10 16:19:56 +000087 except ValueError as exc:
Guido van Rossumd6473d12003-03-01 03:25:41 +000088 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 Rossumb940e112007-01-10 16:19:56 +000097 except ValueError as 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
Walter Dörwaldc3502462003-02-03 23:03:49 +0000107 def test_exit(self):
108 self.assertRaises(TypeError, sys.exit, 42, 42)
109
110 # call without argument
111 try:
112 sys.exit(0)
Guido van Rossumb940e112007-01-10 16:19:56 +0000113 except SystemExit as exc:
Walter Dörwaldc3502462003-02-03 23:03:49 +0000114 self.assertEquals(exc.code, 0)
115 except:
116 self.fail("wrong exception")
117 else:
118 self.fail("no exception")
119
120 # call with tuple argument with one entry
121 # entry will be unpacked
122 try:
123 sys.exit(42)
Guido van Rossumb940e112007-01-10 16:19:56 +0000124 except SystemExit as exc:
Walter Dörwaldc3502462003-02-03 23:03:49 +0000125 self.assertEquals(exc.code, 42)
126 except:
127 self.fail("wrong exception")
128 else:
129 self.fail("no exception")
130
131 # call with integer argument
132 try:
133 sys.exit((42,))
Guido van Rossumb940e112007-01-10 16:19:56 +0000134 except SystemExit as exc:
Walter Dörwaldc3502462003-02-03 23:03:49 +0000135 self.assertEquals(exc.code, 42)
136 except:
137 self.fail("wrong exception")
138 else:
139 self.fail("no exception")
140
141 # call with string argument
142 try:
143 sys.exit("exit")
Guido van Rossumb940e112007-01-10 16:19:56 +0000144 except SystemExit as exc:
Walter Dörwaldc3502462003-02-03 23:03:49 +0000145 self.assertEquals(exc.code, "exit")
146 except:
147 self.fail("wrong exception")
148 else:
149 self.fail("no exception")
150
151 # call with tuple argument with two entries
152 try:
153 sys.exit((17, 23))
Guido van Rossumb940e112007-01-10 16:19:56 +0000154 except SystemExit as exc:
Walter Dörwaldc3502462003-02-03 23:03:49 +0000155 self.assertEquals(exc.code, (17, 23))
156 except:
157 self.fail("wrong exception")
158 else:
159 self.fail("no exception")
160
Michael W. Hudsonf0588582005-02-15 15:26:11 +0000161 # test that the exit machinery handles SystemExits properly
162 import subprocess
163 # both unnormalized...
164 rc = subprocess.call([sys.executable, "-c",
165 "raise SystemExit, 46"])
166 self.assertEqual(rc, 46)
167 # ... and normalized
168 rc = subprocess.call([sys.executable, "-c",
169 "raise SystemExit(47)"])
170 self.assertEqual(rc, 47)
Tim Petersf0db38d2005-02-15 21:50:12 +0000171
172
Walter Dörwaldc3502462003-02-03 23:03:49 +0000173 def test_getdefaultencoding(self):
174 if test.test_support.have_unicode:
175 self.assertRaises(TypeError, sys.getdefaultencoding, 42)
176 # can't check more than the type, as the user might have changed it
177 self.assert_(isinstance(sys.getdefaultencoding(), str))
178
179 # testing sys.settrace() is done in test_trace.py
180 # testing sys.setprofile() is done in test_profile.py
181
182 def test_setcheckinterval(self):
Tim Petersf2715e02003-02-19 02:35:07 +0000183 self.assertRaises(TypeError, sys.setcheckinterval)
Tim Peterse5e065b2003-07-06 18:36:54 +0000184 orig = sys.getcheckinterval()
185 for n in 0, 100, 120, orig: # orig last to restore starting state
186 sys.setcheckinterval(n)
187 self.assertEquals(sys.getcheckinterval(), n)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000188
189 def test_recursionlimit(self):
Tim Petersf2715e02003-02-19 02:35:07 +0000190 self.assertRaises(TypeError, sys.getrecursionlimit, 42)
191 oldlimit = sys.getrecursionlimit()
192 self.assertRaises(TypeError, sys.setrecursionlimit)
193 self.assertRaises(ValueError, sys.setrecursionlimit, -42)
194 sys.setrecursionlimit(10000)
195 self.assertEqual(sys.getrecursionlimit(), 10000)
196 sys.setrecursionlimit(oldlimit)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000197
198 def test_getwindowsversion(self):
199 if hasattr(sys, "getwindowsversion"):
200 v = sys.getwindowsversion()
201 self.assert_(isinstance(v, tuple))
202 self.assertEqual(len(v), 5)
203 self.assert_(isinstance(v[0], int))
204 self.assert_(isinstance(v[1], int))
205 self.assert_(isinstance(v[2], int))
206 self.assert_(isinstance(v[3], int))
207 self.assert_(isinstance(v[4], str))
208
209 def test_dlopenflags(self):
210 if hasattr(sys, "setdlopenflags"):
211 self.assert_(hasattr(sys, "getdlopenflags"))
212 self.assertRaises(TypeError, sys.getdlopenflags, 42)
213 oldflags = sys.getdlopenflags()
214 self.assertRaises(TypeError, sys.setdlopenflags)
215 sys.setdlopenflags(oldflags+1)
216 self.assertEqual(sys.getdlopenflags(), oldflags+1)
217 sys.setdlopenflags(oldflags)
218
219 def test_refcount(self):
220 self.assertRaises(TypeError, sys.getrefcount)
221 c = sys.getrefcount(None)
222 n = None
223 self.assertEqual(sys.getrefcount(None), c+1)
224 del n
225 self.assertEqual(sys.getrefcount(None), c)
226 if hasattr(sys, "gettotalrefcount"):
227 self.assert_(isinstance(sys.gettotalrefcount(), int))
228
229 def test_getframe(self):
230 self.assertRaises(TypeError, sys._getframe, 42, 42)
Neal Norwitzeb2a5ef2003-02-18 15:22:10 +0000231 self.assertRaises(ValueError, sys._getframe, 2000000000)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000232 self.assert_(
233 SysModuleTest.test_getframe.im_func.func_code \
234 is sys._getframe().f_code
235 )
236
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000237 # sys._current_frames() is a CPython-only gimmick.
238 def test_current_frames(self):
239 have_threads = True
240 try:
241 import thread
242 except ImportError:
243 have_threads = False
244
245 if have_threads:
246 self.current_frames_with_threads()
247 else:
248 self.current_frames_without_threads()
249
250 # Test sys._current_frames() in a WITH_THREADS build.
251 def current_frames_with_threads(self):
252 import threading, thread
253 import traceback
254
255 # Spawn a thread that blocks at a known place. Then the main
256 # thread does sys._current_frames(), and verifies that the frames
257 # returned make sense.
258 entered_g = threading.Event()
259 leave_g = threading.Event()
260 thread_info = [] # the thread's id
261
262 def f123():
263 g456()
264
265 def g456():
266 thread_info.append(thread.get_ident())
267 entered_g.set()
268 leave_g.wait()
269
270 t = threading.Thread(target=f123)
271 t.start()
272 entered_g.wait()
273
274 # At this point, t has finished its entered_g.set(), although it's
275 # impossible to guess whether it's still on that line or has moved on
276 # to its leave_g.wait().
277 self.assertEqual(len(thread_info), 1)
278 thread_id = thread_info[0]
279
280 d = sys._current_frames()
281
282 main_id = thread.get_ident()
283 self.assert_(main_id in d)
284 self.assert_(thread_id in d)
285
286 # Verify that the captured main-thread frame is _this_ frame.
287 frame = d.pop(main_id)
288 self.assert_(frame is sys._getframe())
289
290 # Verify that the captured thread frame is blocked in g456, called
291 # from f123. This is a litte tricky, since various bits of
292 # threading.py are also in the thread's call stack.
293 frame = d.pop(thread_id)
294 stack = traceback.extract_stack(frame)
295 for i, (filename, lineno, funcname, sourceline) in enumerate(stack):
296 if funcname == "f123":
297 break
298 else:
299 self.fail("didn't find f123() on thread's call stack")
300
301 self.assertEqual(sourceline, "g456()")
302
303 # And the next record must be for g456().
304 filename, lineno, funcname, sourceline = stack[i+1]
305 self.assertEqual(funcname, "g456")
306 self.assert_(sourceline in ["leave_g.wait()", "entered_g.set()"])
307
308 # Reap the spawned thread.
309 leave_g.set()
310 t.join()
311
312 # Test sys._current_frames() when thread support doesn't exist.
313 def current_frames_without_threads(self):
314 # Not much happens here: there is only one thread, with artificial
315 # "thread id" 0.
316 d = sys._current_frames()
317 self.assertEqual(len(d), 1)
318 self.assert_(0 in d)
319 self.assert_(d[0] is sys._getframe())
320
Walter Dörwaldc3502462003-02-03 23:03:49 +0000321 def test_attributes(self):
322 self.assert_(isinstance(sys.api_version, int))
323 self.assert_(isinstance(sys.argv, list))
324 self.assert_(sys.byteorder in ("little", "big"))
325 self.assert_(isinstance(sys.builtin_module_names, tuple))
326 self.assert_(isinstance(sys.copyright, basestring))
327 self.assert_(isinstance(sys.exec_prefix, basestring))
328 self.assert_(isinstance(sys.executable, basestring))
329 self.assert_(isinstance(sys.hexversion, int))
330 self.assert_(isinstance(sys.maxint, int))
Walter Dörwald4e41a4b2005-08-03 17:09:04 +0000331 if test.test_support.have_unicode:
332 self.assert_(isinstance(sys.maxunicode, int))
Walter Dörwaldc3502462003-02-03 23:03:49 +0000333 self.assert_(isinstance(sys.platform, basestring))
334 self.assert_(isinstance(sys.prefix, basestring))
335 self.assert_(isinstance(sys.version, basestring))
336 vi = sys.version_info
337 self.assert_(isinstance(vi, tuple))
338 self.assertEqual(len(vi), 5)
339 self.assert_(isinstance(vi[0], int))
340 self.assert_(isinstance(vi[1], int))
341 self.assert_(isinstance(vi[2], int))
342 self.assert_(vi[3] in ("alpha", "beta", "candidate", "final"))
343 self.assert_(isinstance(vi[4], int))
344
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000345 def test_43581(self):
346 # Can't use sys.stdout, as this is a cStringIO object when
347 # the test runs under regrtest.
348 self.assert_(sys.__stdout__.encoding == sys.__stderr__.encoding)
349
Georg Brandl66a796e2006-12-19 20:50:34 +0000350 def test_intern(self):
351 self.assertRaises(TypeError, sys.intern)
352 s = "never interned before"
353 self.assert_(sys.intern(s) is s)
354 s2 = s.swapcase().swapcase()
355 self.assert_(sys.intern(s2) is s)
356
357 # Subclasses of string can't be interned, because they
358 # provide too much opportunity for insane things to happen.
359 # We don't want them in the interned dict and if they aren't
360 # actually interned, we don't want to create the appearance
361 # that they are by allowing intern() to succeeed.
362 class S(str):
363 def __hash__(self):
364 return 123
365
366 self.assertRaises(TypeError, sys.intern, S("abc"))
367
368 # It's still safe to pass these strings to routines that
369 # call intern internally, e.g. PyObject_SetAttr().
370 s = S("abc")
371 setattr(s, s, s)
372 self.assertEqual(getattr(s, s), s)
373
374
Walter Dörwaldc3502462003-02-03 23:03:49 +0000375def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +0000376 test.test_support.run_unittest(SysModuleTest)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000377
378if __name__ == "__main__":
379 test_main()