Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 1 | # -*- coding: iso-8859-1 -*- |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 2 | import unittest, test.support |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 3 | import sys, io, os |
Robert Schuppenies | 4d45bfe | 2008-06-28 23:58:47 +0000 | [diff] [blame] | 4 | import struct |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 5 | |
| 6 | class SysModuleTest(unittest.TestCase): |
| 7 | |
Christian Heimes | ef181a7 | 2007-11-07 16:14:12 +0000 | [diff] [blame] | 8 | def setUp(self): |
| 9 | self.orig_stdout = sys.stdout |
| 10 | self.orig_stderr = sys.stderr |
| 11 | self.orig_displayhook = sys.displayhook |
| 12 | |
| 13 | def tearDown(self): |
| 14 | sys.stdout = self.orig_stdout |
| 15 | sys.stderr = self.orig_stderr |
| 16 | sys.displayhook = self.orig_displayhook |
| 17 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 18 | def test_original_displayhook(self): |
Georg Brandl | 1a3284e | 2007-12-02 09:40:06 +0000 | [diff] [blame] | 19 | import builtins |
Guido van Rossum | 34d1928 | 2007-08-09 01:03:29 +0000 | [diff] [blame] | 20 | out = io.StringIO() |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 21 | sys.stdout = out |
| 22 | |
| 23 | dh = sys.__displayhook__ |
| 24 | |
| 25 | self.assertRaises(TypeError, dh) |
Georg Brandl | 1a3284e | 2007-12-02 09:40:06 +0000 | [diff] [blame] | 26 | if hasattr(builtins, "_"): |
| 27 | del builtins._ |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 28 | |
| 29 | dh(None) |
| 30 | self.assertEqual(out.getvalue(), "") |
Georg Brandl | 1a3284e | 2007-12-02 09:40:06 +0000 | [diff] [blame] | 31 | self.assert_(not hasattr(builtins, "_")) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 32 | dh(42) |
| 33 | self.assertEqual(out.getvalue(), "42\n") |
Georg Brandl | 1a3284e | 2007-12-02 09:40:06 +0000 | [diff] [blame] | 34 | self.assertEqual(builtins._, 42) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 35 | |
| 36 | del sys.stdout |
| 37 | self.assertRaises(RuntimeError, dh, 42) |
| 38 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 39 | def test_lost_displayhook(self): |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 40 | del sys.displayhook |
| 41 | code = compile("42", "<string>", "single") |
| 42 | self.assertRaises(RuntimeError, eval, code) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 43 | |
| 44 | def test_custom_displayhook(self): |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 45 | def baddisplayhook(obj): |
| 46 | raise ValueError |
| 47 | sys.displayhook = baddisplayhook |
| 48 | code = compile("42", "<string>", "single") |
| 49 | self.assertRaises(ValueError, eval, code) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 50 | |
| 51 | def test_original_excepthook(self): |
Guido van Rossum | 34d1928 | 2007-08-09 01:03:29 +0000 | [diff] [blame] | 52 | err = io.StringIO() |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 53 | sys.stderr = err |
| 54 | |
| 55 | eh = sys.__excepthook__ |
| 56 | |
| 57 | self.assertRaises(TypeError, eh) |
| 58 | try: |
| 59 | raise ValueError(42) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 60 | except ValueError as exc: |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 61 | eh(*sys.exc_info()) |
| 62 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 63 | self.assert_(err.getvalue().endswith("ValueError: 42\n")) |
| 64 | |
Benjamin Peterson | bc74e5b | 2008-08-23 20:19:17 +0000 | [diff] [blame] | 65 | def test_excepthook(self): |
| 66 | with test.support.captured_output("stderr") as stderr: |
| 67 | sys.excepthook(1, '1', 1) |
| 68 | self.assert_("TypeError: print_exception(): Exception expected for " \ |
| 69 | "value, str found" in stderr.getvalue()) |
| 70 | |
Walter Dörwald | e7028ac | 2003-02-03 23:05:27 +0000 | [diff] [blame] | 71 | # FIXME: testing the code for a lost or replaced excepthook in |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 72 | # Python/pythonrun.c::PyErr_PrintEx() is tricky. |
| 73 | |
| 74 | def test_exit(self): |
| 75 | self.assertRaises(TypeError, sys.exit, 42, 42) |
| 76 | |
| 77 | # call without argument |
| 78 | try: |
| 79 | sys.exit(0) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 80 | except SystemExit as exc: |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 81 | self.assertEquals(exc.code, 0) |
| 82 | except: |
| 83 | self.fail("wrong exception") |
| 84 | else: |
| 85 | self.fail("no exception") |
| 86 | |
| 87 | # call with tuple argument with one entry |
| 88 | # entry will be unpacked |
| 89 | try: |
| 90 | sys.exit(42) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 91 | except SystemExit as exc: |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 92 | self.assertEquals(exc.code, 42) |
| 93 | except: |
| 94 | self.fail("wrong exception") |
| 95 | else: |
| 96 | self.fail("no exception") |
| 97 | |
| 98 | # call with integer argument |
| 99 | try: |
| 100 | sys.exit((42,)) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 101 | except SystemExit as exc: |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 102 | self.assertEquals(exc.code, 42) |
| 103 | except: |
| 104 | self.fail("wrong exception") |
| 105 | else: |
| 106 | self.fail("no exception") |
| 107 | |
| 108 | # call with string argument |
| 109 | try: |
| 110 | sys.exit("exit") |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 111 | except SystemExit as exc: |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 112 | self.assertEquals(exc.code, "exit") |
| 113 | except: |
| 114 | self.fail("wrong exception") |
| 115 | else: |
| 116 | self.fail("no exception") |
| 117 | |
| 118 | # call with tuple argument with two entries |
| 119 | try: |
| 120 | sys.exit((17, 23)) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 121 | except SystemExit as exc: |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 122 | self.assertEquals(exc.code, (17, 23)) |
| 123 | except: |
| 124 | self.fail("wrong exception") |
| 125 | else: |
| 126 | self.fail("no exception") |
| 127 | |
Michael W. Hudson | f058858 | 2005-02-15 15:26:11 +0000 | [diff] [blame] | 128 | # test that the exit machinery handles SystemExits properly |
| 129 | import subprocess |
Michael W. Hudson | f058858 | 2005-02-15 15:26:11 +0000 | [diff] [blame] | 130 | rc = subprocess.call([sys.executable, "-c", |
| 131 | "raise SystemExit(47)"]) |
| 132 | self.assertEqual(rc, 47) |
Tim Peters | f0db38d | 2005-02-15 21:50:12 +0000 | [diff] [blame] | 133 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 134 | def test_getdefaultencoding(self): |
Walter Dörwald | 4aeaa96 | 2007-05-22 16:13:46 +0000 | [diff] [blame] | 135 | self.assertRaises(TypeError, sys.getdefaultencoding, 42) |
| 136 | # can't check more than the type, as the user might have changed it |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 137 | self.assert_(isinstance(sys.getdefaultencoding(), str)) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 138 | |
| 139 | # testing sys.settrace() is done in test_trace.py |
| 140 | # testing sys.setprofile() is done in test_profile.py |
| 141 | |
| 142 | def test_setcheckinterval(self): |
Tim Peters | f2715e0 | 2003-02-19 02:35:07 +0000 | [diff] [blame] | 143 | self.assertRaises(TypeError, sys.setcheckinterval) |
Tim Peters | e5e065b | 2003-07-06 18:36:54 +0000 | [diff] [blame] | 144 | orig = sys.getcheckinterval() |
| 145 | for n in 0, 100, 120, orig: # orig last to restore starting state |
| 146 | sys.setcheckinterval(n) |
| 147 | self.assertEquals(sys.getcheckinterval(), n) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 148 | |
| 149 | def test_recursionlimit(self): |
Tim Peters | f2715e0 | 2003-02-19 02:35:07 +0000 | [diff] [blame] | 150 | self.assertRaises(TypeError, sys.getrecursionlimit, 42) |
| 151 | oldlimit = sys.getrecursionlimit() |
| 152 | self.assertRaises(TypeError, sys.setrecursionlimit) |
| 153 | self.assertRaises(ValueError, sys.setrecursionlimit, -42) |
| 154 | sys.setrecursionlimit(10000) |
| 155 | self.assertEqual(sys.getrecursionlimit(), 10000) |
| 156 | sys.setrecursionlimit(oldlimit) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 157 | |
| 158 | def test_getwindowsversion(self): |
| 159 | if hasattr(sys, "getwindowsversion"): |
| 160 | v = sys.getwindowsversion() |
| 161 | self.assert_(isinstance(v, tuple)) |
| 162 | self.assertEqual(len(v), 5) |
| 163 | self.assert_(isinstance(v[0], int)) |
| 164 | self.assert_(isinstance(v[1], int)) |
| 165 | self.assert_(isinstance(v[2], int)) |
| 166 | self.assert_(isinstance(v[3], int)) |
| 167 | self.assert_(isinstance(v[4], str)) |
| 168 | |
Barry Warsaw | e94a37f | 2008-10-17 01:29:56 +0000 | [diff] [blame] | 169 | def test_call_tracing(self): |
| 170 | self.assertRaises(TypeError, sys.call_tracing, type, 2) |
| 171 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 172 | def test_dlopenflags(self): |
| 173 | if hasattr(sys, "setdlopenflags"): |
| 174 | self.assert_(hasattr(sys, "getdlopenflags")) |
| 175 | self.assertRaises(TypeError, sys.getdlopenflags, 42) |
| 176 | oldflags = sys.getdlopenflags() |
| 177 | self.assertRaises(TypeError, sys.setdlopenflags) |
| 178 | sys.setdlopenflags(oldflags+1) |
| 179 | self.assertEqual(sys.getdlopenflags(), oldflags+1) |
| 180 | sys.setdlopenflags(oldflags) |
| 181 | |
| 182 | def test_refcount(self): |
| 183 | self.assertRaises(TypeError, sys.getrefcount) |
| 184 | c = sys.getrefcount(None) |
| 185 | n = None |
| 186 | self.assertEqual(sys.getrefcount(None), c+1) |
| 187 | del n |
| 188 | self.assertEqual(sys.getrefcount(None), c) |
| 189 | if hasattr(sys, "gettotalrefcount"): |
| 190 | self.assert_(isinstance(sys.gettotalrefcount(), int)) |
| 191 | |
| 192 | def test_getframe(self): |
| 193 | self.assertRaises(TypeError, sys._getframe, 42, 42) |
Neal Norwitz | eb2a5ef | 2003-02-18 15:22:10 +0000 | [diff] [blame] | 194 | self.assertRaises(ValueError, sys._getframe, 2000000000) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 195 | self.assert_( |
Christian Heimes | 4a22b5d | 2007-11-25 09:39:14 +0000 | [diff] [blame] | 196 | SysModuleTest.test_getframe.__code__ \ |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 197 | is sys._getframe().f_code |
| 198 | ) |
| 199 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 200 | # sys._current_frames() is a CPython-only gimmick. |
| 201 | def test_current_frames(self): |
| 202 | have_threads = True |
| 203 | try: |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 204 | import _thread |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 205 | except ImportError: |
| 206 | have_threads = False |
| 207 | |
| 208 | if have_threads: |
| 209 | self.current_frames_with_threads() |
| 210 | else: |
| 211 | self.current_frames_without_threads() |
| 212 | |
| 213 | # Test sys._current_frames() in a WITH_THREADS build. |
| 214 | def current_frames_with_threads(self): |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 215 | import threading, _thread |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 216 | import traceback |
| 217 | |
| 218 | # Spawn a thread that blocks at a known place. Then the main |
| 219 | # thread does sys._current_frames(), and verifies that the frames |
| 220 | # returned make sense. |
| 221 | entered_g = threading.Event() |
| 222 | leave_g = threading.Event() |
| 223 | thread_info = [] # the thread's id |
| 224 | |
| 225 | def f123(): |
| 226 | g456() |
| 227 | |
| 228 | def g456(): |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 229 | thread_info.append(_thread.get_ident()) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 230 | entered_g.set() |
| 231 | leave_g.wait() |
| 232 | |
| 233 | t = threading.Thread(target=f123) |
| 234 | t.start() |
| 235 | entered_g.wait() |
| 236 | |
| 237 | # At this point, t has finished its entered_g.set(), although it's |
| 238 | # impossible to guess whether it's still on that line or has moved on |
| 239 | # to its leave_g.wait(). |
| 240 | self.assertEqual(len(thread_info), 1) |
| 241 | thread_id = thread_info[0] |
| 242 | |
| 243 | d = sys._current_frames() |
| 244 | |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 245 | main_id = _thread.get_ident() |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 246 | self.assert_(main_id in d) |
| 247 | self.assert_(thread_id in d) |
| 248 | |
| 249 | # Verify that the captured main-thread frame is _this_ frame. |
| 250 | frame = d.pop(main_id) |
| 251 | self.assert_(frame is sys._getframe()) |
| 252 | |
| 253 | # Verify that the captured thread frame is blocked in g456, called |
| 254 | # from f123. This is a litte tricky, since various bits of |
| 255 | # threading.py are also in the thread's call stack. |
| 256 | frame = d.pop(thread_id) |
| 257 | stack = traceback.extract_stack(frame) |
| 258 | for i, (filename, lineno, funcname, sourceline) in enumerate(stack): |
| 259 | if funcname == "f123": |
| 260 | break |
| 261 | else: |
| 262 | self.fail("didn't find f123() on thread's call stack") |
| 263 | |
| 264 | self.assertEqual(sourceline, "g456()") |
| 265 | |
| 266 | # And the next record must be for g456(). |
| 267 | filename, lineno, funcname, sourceline = stack[i+1] |
| 268 | self.assertEqual(funcname, "g456") |
| 269 | self.assert_(sourceline in ["leave_g.wait()", "entered_g.set()"]) |
| 270 | |
| 271 | # Reap the spawned thread. |
| 272 | leave_g.set() |
| 273 | t.join() |
| 274 | |
| 275 | # Test sys._current_frames() when thread support doesn't exist. |
| 276 | def current_frames_without_threads(self): |
| 277 | # Not much happens here: there is only one thread, with artificial |
| 278 | # "thread id" 0. |
| 279 | d = sys._current_frames() |
| 280 | self.assertEqual(len(d), 1) |
| 281 | self.assert_(0 in d) |
| 282 | self.assert_(d[0] is sys._getframe()) |
| 283 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 284 | def test_attributes(self): |
| 285 | self.assert_(isinstance(sys.api_version, int)) |
| 286 | self.assert_(isinstance(sys.argv, list)) |
| 287 | self.assert_(sys.byteorder in ("little", "big")) |
| 288 | self.assert_(isinstance(sys.builtin_module_names, tuple)) |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 289 | self.assert_(isinstance(sys.copyright, str)) |
| 290 | self.assert_(isinstance(sys.exec_prefix, str)) |
| 291 | self.assert_(isinstance(sys.executable, str)) |
Christian Heimes | 9385266 | 2007-12-01 12:22:32 +0000 | [diff] [blame] | 292 | self.assertEqual(len(sys.float_info), 11) |
Christian Heimes | d32ed6f | 2008-01-14 18:49:24 +0000 | [diff] [blame] | 293 | self.assertEqual(sys.float_info.radix, 2) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 294 | self.assert_(isinstance(sys.hexversion, int)) |
Christian Heimes | a37d4c6 | 2007-12-04 23:02:19 +0000 | [diff] [blame] | 295 | self.assert_(isinstance(sys.maxsize, int)) |
Walter Dörwald | 4aeaa96 | 2007-05-22 16:13:46 +0000 | [diff] [blame] | 296 | self.assert_(isinstance(sys.maxunicode, int)) |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 297 | self.assert_(isinstance(sys.platform, str)) |
| 298 | self.assert_(isinstance(sys.prefix, str)) |
| 299 | self.assert_(isinstance(sys.version, str)) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 300 | vi = sys.version_info |
Eric Smith | 0e5b562 | 2009-02-06 01:32:42 +0000 | [diff] [blame^] | 301 | self.assert_(isinstance(vi[:], tuple)) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 302 | self.assertEqual(len(vi), 5) |
| 303 | self.assert_(isinstance(vi[0], int)) |
| 304 | self.assert_(isinstance(vi[1], int)) |
| 305 | self.assert_(isinstance(vi[2], int)) |
| 306 | self.assert_(vi[3] in ("alpha", "beta", "candidate", "final")) |
| 307 | self.assert_(isinstance(vi[4], int)) |
Eric Smith | 0e5b562 | 2009-02-06 01:32:42 +0000 | [diff] [blame^] | 308 | self.assert_(isinstance(vi.major, int)) |
| 309 | self.assert_(isinstance(vi.minor, int)) |
| 310 | self.assert_(isinstance(vi.micro, int)) |
| 311 | self.assert_(vi.releaselevel in |
| 312 | ("alpha", "beta", "candidate", "final")) |
| 313 | self.assert_(isinstance(vi.serial, int)) |
| 314 | self.assertEqual(vi[0], vi.major) |
| 315 | self.assertEqual(vi[1], vi.minor) |
| 316 | self.assertEqual(vi[2], vi.micro) |
| 317 | self.assertEqual(vi[3], vi.releaselevel) |
| 318 | self.assertEqual(vi[4], vi.serial) |
| 319 | self.assert_(vi > (1,0,0)) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 320 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 321 | def test_43581(self): |
Georg Brandl | 0312494 | 2008-06-10 15:50:56 +0000 | [diff] [blame] | 322 | # Can't use sys.stdout, as this is a StringIO object when |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 323 | # the test runs under regrtest. |
Guido van Rossum | e61fd5b | 2007-07-11 12:20:59 +0000 | [diff] [blame] | 324 | self.assertEqual(sys.__stdout__.encoding, sys.__stderr__.encoding) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 325 | |
Georg Brandl | 66a796e | 2006-12-19 20:50:34 +0000 | [diff] [blame] | 326 | def test_intern(self): |
| 327 | self.assertRaises(TypeError, sys.intern) |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 328 | s = "never interned before" |
Georg Brandl | 66a796e | 2006-12-19 20:50:34 +0000 | [diff] [blame] | 329 | self.assert_(sys.intern(s) is s) |
| 330 | s2 = s.swapcase().swapcase() |
| 331 | self.assert_(sys.intern(s2) is s) |
| 332 | |
| 333 | # Subclasses of string can't be interned, because they |
| 334 | # provide too much opportunity for insane things to happen. |
| 335 | # We don't want them in the interned dict and if they aren't |
| 336 | # actually interned, we don't want to create the appearance |
| 337 | # that they are by allowing intern() to succeeed. |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 338 | class S(str): |
Georg Brandl | 66a796e | 2006-12-19 20:50:34 +0000 | [diff] [blame] | 339 | def __hash__(self): |
| 340 | return 123 |
| 341 | |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 342 | self.assertRaises(TypeError, sys.intern, S("abc")) |
Martin v. Löwis | 5b22213 | 2007-06-10 09:51:05 +0000 | [diff] [blame] | 343 | |
Georg Brandl | 66a796e | 2006-12-19 20:50:34 +0000 | [diff] [blame] | 344 | |
Christian Heimes | d32ed6f | 2008-01-14 18:49:24 +0000 | [diff] [blame] | 345 | def test_sys_flags(self): |
| 346 | self.failUnless(sys.flags) |
| 347 | attrs = ("debug", "division_warning", |
| 348 | "inspect", "interactive", "optimize", "dont_write_bytecode", |
Georg Brandl | c5e88d5 | 2008-06-06 09:02:07 +0000 | [diff] [blame] | 349 | "no_user_site", "no_site", "ignore_environment", "verbose", |
Benjamin Peterson | 699adb9 | 2008-05-08 22:27:58 +0000 | [diff] [blame] | 350 | "bytes_warning") |
Christian Heimes | d32ed6f | 2008-01-14 18:49:24 +0000 | [diff] [blame] | 351 | for attr in attrs: |
| 352 | self.assert_(hasattr(sys.flags, attr), attr) |
| 353 | self.assertEqual(type(getattr(sys.flags, attr)), int, attr) |
| 354 | self.assert_(repr(sys.flags)) |
Georg Brandl | c5e88d5 | 2008-06-06 09:02:07 +0000 | [diff] [blame] | 355 | self.assertEqual(len(sys.flags), len(attrs)) |
Christian Heimes | d32ed6f | 2008-01-14 18:49:24 +0000 | [diff] [blame] | 356 | |
Christian Heimes | 15ebc88 | 2008-02-04 18:48:49 +0000 | [diff] [blame] | 357 | def test_clear_type_cache(self): |
| 358 | sys._clear_type_cache() |
| 359 | |
Martin v. Löwis | 0f59989 | 2008-06-02 11:13:03 +0000 | [diff] [blame] | 360 | def test_ioencoding(self): |
| 361 | import subprocess,os |
| 362 | env = dict(os.environ) |
| 363 | |
| 364 | # Test character: cent sign, encoded as 0x4A (ASCII J) in CP424, |
| 365 | # not representable in ASCII. |
| 366 | |
| 367 | env["PYTHONIOENCODING"] = "cp424" |
| 368 | p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'], |
| 369 | stdout = subprocess.PIPE, env=env) |
| 370 | out = p.stdout.read() |
| 371 | self.assertEqual(out, "\xa2\n".encode("cp424")) |
| 372 | |
| 373 | env["PYTHONIOENCODING"] = "ascii:replace" |
| 374 | p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'], |
| 375 | stdout = subprocess.PIPE, env=env) |
| 376 | out = p.stdout.read().strip() |
| 377 | self.assertEqual(out, b'?') |
| 378 | |
| 379 | |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 380 | class SizeofTest(unittest.TestCase): |
| 381 | |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 382 | TPFLAGS_HAVE_GC = 1<<14 |
| 383 | TPFLAGS_HEAPTYPE = 1<<9 |
| 384 | |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 385 | def setUp(self): |
Robert Schuppenies | 4d45bfe | 2008-06-28 23:58:47 +0000 | [diff] [blame] | 386 | self.c = len(struct.pack('c', ' ')) |
| 387 | self.H = len(struct.pack('H', 0)) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 388 | self.i = len(struct.pack('i', 0)) |
| 389 | self.l = len(struct.pack('l', 0)) |
Robert Schuppenies | 4d45bfe | 2008-06-28 23:58:47 +0000 | [diff] [blame] | 390 | self.P = len(struct.pack('P', 0)) |
| 391 | # due to missing size_t information from struct, it is assumed that |
| 392 | # sizeof(Py_ssize_t) = sizeof(void*) |
| 393 | self.header = 'PP' |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 394 | self.vheader = self.header + 'P' |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 395 | if hasattr(sys, "gettotalrefcount"): |
Robert Schuppenies | 4d45bfe | 2008-06-28 23:58:47 +0000 | [diff] [blame] | 396 | self.header += '2P' |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 397 | self.vheader += '2P' |
| 398 | import _testcapi |
| 399 | self.gc_headsize = _testcapi.SIZEOF_PYGC_HEAD |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 400 | self.file = open(test.support.TESTFN, 'wb') |
| 401 | |
| 402 | def tearDown(self): |
| 403 | self.file.close() |
| 404 | test.support.unlink(test.support.TESTFN) |
| 405 | |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 406 | def check_sizeof(self, o, size): |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 407 | result = sys.getsizeof(o) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 408 | # add GC header size |
| 409 | if ((type(o) == type) and (o.__flags__ & self.TPFLAGS_HEAPTYPE) or\ |
| 410 | ((type(o) != type) and (type(o).__flags__ & self.TPFLAGS_HAVE_GC))): |
| 411 | size += self.gc_headsize |
| 412 | msg = 'wrong size for %s: got %d, expected %d' \ |
| 413 | % (type(o), result, size) |
| 414 | self.assertEqual(result, size, msg) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 415 | |
Robert Schuppenies | 4d45bfe | 2008-06-28 23:58:47 +0000 | [diff] [blame] | 416 | def calcsize(self, fmt): |
| 417 | """Wrapper around struct.calcsize which enforces the alignment of the |
| 418 | end of a structure to the alignment requirement of pointer. |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 419 | |
Robert Schuppenies | 4d45bfe | 2008-06-28 23:58:47 +0000 | [diff] [blame] | 420 | Note: This wrapper should only be used if a pointer member is included |
| 421 | and no member with a size larger than a pointer exists. |
| 422 | """ |
| 423 | return struct.calcsize(fmt + '0P') |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 424 | |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 425 | def test_gc_head_size(self): |
| 426 | # Check that the gc header size is added to objects tracked by the gc. |
Robert Schuppenies | 4d45bfe | 2008-06-28 23:58:47 +0000 | [diff] [blame] | 427 | h = self.header |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 428 | vh = self.vheader |
Robert Schuppenies | 4d45bfe | 2008-06-28 23:58:47 +0000 | [diff] [blame] | 429 | size = self.calcsize |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 430 | gc_header_size = self.gc_headsize |
| 431 | # bool objects are not gc tracked |
| 432 | self.assertEqual(sys.getsizeof(True), size(vh) + self.H) |
| 433 | # but lists are |
| 434 | self.assertEqual(sys.getsizeof([]), size(vh + 'PP') + gc_header_size) |
| 435 | |
| 436 | def test_default(self): |
| 437 | h = self.header |
| 438 | vh = self.vheader |
| 439 | size = self.calcsize |
| 440 | self.assertEqual(sys.getsizeof(True), size(vh) + self.H) |
| 441 | self.assertEqual(sys.getsizeof(True, -1), size(vh) + self.H) |
| 442 | |
| 443 | def test_objecttypes(self): |
| 444 | # check all types defined in Objects/ |
| 445 | h = self.header |
| 446 | vh = self.vheader |
| 447 | size = self.calcsize |
| 448 | check = self.check_sizeof |
| 449 | # bool |
| 450 | check(True, size(vh) + self.H) |
| 451 | # buffer |
| 452 | # XXX |
| 453 | # builtin_function_or_method |
| 454 | check(len, size(h + '3P')) |
| 455 | # bytearray |
| 456 | samples = [b'', b'u'*100000] |
| 457 | for sample in samples: |
| 458 | x = bytearray(sample) |
| 459 | check(x, size(vh + 'iPP') + x.__alloc__() * self.c) |
| 460 | # bytearray_iterator |
| 461 | check(iter(bytearray()), size(h + 'PP')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 462 | # cell |
| 463 | def get_cell(): |
| 464 | x = 42 |
| 465 | def inner(): |
| 466 | return x |
| 467 | return inner |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 468 | check(get_cell().__closure__[0], size(h + 'P')) |
Robert Schuppenies | 4efb518 | 2008-06-06 11:49:51 +0000 | [diff] [blame] | 469 | # code |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 470 | check(get_cell().__code__, size(h + '5i8Pi2P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 471 | # complex |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 472 | check(complex(0,1), size(h + '2d')) |
| 473 | # method_descriptor (descriptor object) |
| 474 | check(str.lower, size(h + '2PP')) |
| 475 | # classmethod_descriptor (descriptor object) |
| 476 | # XXX |
| 477 | # member_descriptor (descriptor object) |
| 478 | import datetime |
| 479 | check(datetime.timedelta.days, size(h + '2PP')) |
| 480 | # getset_descriptor (descriptor object) |
| 481 | import collections |
| 482 | check(collections.defaultdict.default_factory, size(h + '2PP')) |
| 483 | # wrapper_descriptor (descriptor object) |
| 484 | check(int.__add__, size(h + '2P2P')) |
| 485 | # method-wrapper (descriptor object) |
| 486 | check({}.__iter__, size(h + '2P')) |
| 487 | # dict |
| 488 | check({}, size(h + '3P2P' + 8*'P2P')) |
| 489 | longdict = {1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8} |
| 490 | check(longdict, size(h + '3P2P' + 8*'P2P') + 16*size('P2P')) |
| 491 | # dictionary-keyiterator |
| 492 | check({}.keys(), size(h + 'P')) |
| 493 | # dictionary-valueiterator |
| 494 | check({}.values(), size(h + 'P')) |
| 495 | # dictionary-itemiterator |
| 496 | check({}.items(), size(h + 'P')) |
| 497 | # dictproxy |
| 498 | class C(object): pass |
| 499 | check(C.__dict__, size(h + 'P')) |
| 500 | # BaseException |
| 501 | check(BaseException(), size(h + '5P')) |
| 502 | # UnicodeEncodeError |
| 503 | check(UnicodeEncodeError("", "", 0, 0, ""), size(h + '5P 2P2PP')) |
| 504 | # UnicodeDecodeError |
| 505 | # XXX |
| 506 | # check(UnicodeDecodeError("", "", 0, 0, ""), size(h + '5P2PP')) |
| 507 | # UnicodeTranslateError |
| 508 | check(UnicodeTranslateError("", 0, 1, ""), size(h + '5P 2P2PP')) |
| 509 | # ellipses |
| 510 | check(Ellipsis, size(h + '')) |
| 511 | # EncodingMap |
| 512 | import codecs, encodings.iso8859_3 |
| 513 | x = codecs.charmap_build(encodings.iso8859_3.decoding_table) |
| 514 | check(x, size(h + '32B2iB')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 515 | # enumerate |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 516 | check(enumerate([]), size(h + 'l3P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 517 | # reverse |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 518 | check(reversed(''), size(h + 'PP')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 519 | # float |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 520 | check(float(0), size(h + 'd')) |
| 521 | # sys.floatinfo |
| 522 | check(sys.float_info, size(vh) + self.P * len(sys.float_info)) |
| 523 | # frame |
| 524 | import inspect |
| 525 | CO_MAXBLOCKS = 20 |
| 526 | x = inspect.currentframe() |
| 527 | ncells = len(x.f_code.co_cellvars) |
| 528 | nfrees = len(x.f_code.co_freevars) |
| 529 | extras = x.f_code.co_stacksize + x.f_code.co_nlocals +\ |
| 530 | ncells + nfrees - 1 |
| 531 | check(x, size(vh + '12P3i' + CO_MAXBLOCKS*'3i' + 'P' + extras*'P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 532 | # function |
| 533 | def func(): pass |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 534 | check(func, size(h + '11P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 535 | class c(): |
| 536 | @staticmethod |
| 537 | def foo(): |
| 538 | pass |
| 539 | @classmethod |
| 540 | def bar(cls): |
| 541 | pass |
| 542 | # staticmethod |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 543 | check(foo, size(h + 'P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 544 | # classmethod |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 545 | check(bar, size(h + 'P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 546 | # generator |
| 547 | def get_gen(): yield 1 |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 548 | check(get_gen(), size(h + 'Pi2P')) |
| 549 | # iterator |
| 550 | check(iter('abc'), size(h + 'lP')) |
| 551 | # callable-iterator |
| 552 | import re |
| 553 | check(re.finditer('',''), size(h + '2P')) |
| 554 | # list |
| 555 | samples = [[], [1,2,3], ['1', '2', '3']] |
| 556 | for sample in samples: |
| 557 | check(sample, size(vh + 'PP') + len(sample)*self.P) |
| 558 | # sortwrapper (list) |
| 559 | # XXX |
| 560 | # cmpwrapper (list) |
| 561 | # XXX |
| 562 | # listiterator (list) |
| 563 | check(iter([]), size(h + 'lP')) |
| 564 | # listreverseiterator (list) |
| 565 | check(reversed([]), size(h + 'lP')) |
| 566 | # long |
| 567 | check(0, size(vh)) |
| 568 | check(1, size(vh) + self.H) |
| 569 | check(-1, size(vh) + self.H) |
| 570 | check(32768, size(vh) + 2*self.H) |
| 571 | check(32768*32768-1, size(vh) + 2*self.H) |
| 572 | check(32768*32768, size(vh) + 3*self.H) |
| 573 | # memory |
Antoine Pitrou | c3b3924 | 2009-01-03 16:59:18 +0000 | [diff] [blame] | 574 | check(memoryview(b''), size(h + 'P PP2P2i7P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 575 | # module |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 576 | check(unittest, size(h + '3P')) |
| 577 | # None |
| 578 | check(None, size(h + '')) |
| 579 | # NotImplementedType |
| 580 | check(NotImplemented, size(h)) |
| 581 | # object |
| 582 | check(object(), size(h + '')) |
| 583 | # property (descriptor object) |
| 584 | class C(object): |
| 585 | def getx(self): return self.__x |
| 586 | def setx(self, value): self.__x = value |
| 587 | def delx(self): del self.__x |
| 588 | x = property(getx, setx, delx, "") |
| 589 | check(x, size(h + '4Pi')) |
| 590 | # PyCObject |
| 591 | # XXX |
| 592 | # rangeiterator |
| 593 | check(iter(range(1)), size(h + '4l')) |
| 594 | # reverse |
| 595 | check(reversed(''), size(h + 'PP')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 596 | # range |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 597 | check(range(1), size(h + '3P')) |
Robert Schuppenies | 357877c | 2008-09-16 07:21:01 +0000 | [diff] [blame] | 598 | check(range(66000), size(h + '3P')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 599 | # set |
| 600 | # frozenset |
| 601 | PySet_MINSIZE = 8 |
| 602 | samples = [[], range(10), range(50)] |
| 603 | s = size(h + '3P2P' + PySet_MINSIZE*'lP' + 'lP') |
| 604 | for sample in samples: |
| 605 | minused = len(sample) |
| 606 | if minused == 0: tmp = 1 |
| 607 | # the computation of minused is actually a bit more complicated |
| 608 | # but this suffices for the sizeof test |
| 609 | minused = minused*2 |
| 610 | newsize = PySet_MINSIZE |
| 611 | while newsize <= minused: |
| 612 | newsize = newsize << 1 |
| 613 | if newsize <= 8: |
| 614 | check(set(sample), s) |
| 615 | check(frozenset(sample), s) |
| 616 | else: |
| 617 | check(set(sample), s + newsize*struct.calcsize('lP')) |
| 618 | check(frozenset(sample), s + newsize*struct.calcsize('lP')) |
| 619 | # setiterator |
| 620 | check(iter(set()), size(h + 'P3P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 621 | # slice |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 622 | check(slice(0), size(h + '3P')) |
| 623 | # super |
| 624 | check(super(int), size(h + '3P')) |
| 625 | # tuple |
| 626 | check((), size(vh)) |
| 627 | check((1,2,3), size(vh) + 3*self.P) |
| 628 | # type |
| 629 | # (PyTypeObject + PyNumberMethods + PyMappingMethods + |
| 630 | # PySequenceMethods + PyBufferProcs) |
| 631 | s = size(vh + 'P2P15Pl4PP9PP11PI') + size('16Pi17P 3P 10P 2P 2P') |
| 632 | check(int, s) |
| 633 | # class |
| 634 | class newstyleclass(object): pass |
| 635 | check(newstyleclass, s) |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 636 | # unicode |
Benjamin Peterson | b49d994 | 2008-06-17 12:44:04 +0000 | [diff] [blame] | 637 | usize = len('\0'.encode('unicode-internal')) |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 638 | samples = ['', '1'*100] |
| 639 | # we need to test for both sizes, because we don't know if the string |
| 640 | # has been cached |
| 641 | for s in samples: |
Robert Schuppenies | 4d45bfe | 2008-06-28 23:58:47 +0000 | [diff] [blame] | 642 | basicsize = size(h + 'PPliP') + usize * (len(s) + 1) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 643 | check(s, basicsize) |
| 644 | # weakref |
| 645 | import weakref |
| 646 | check(weakref.ref(int), size(h + '2Pl2P')) |
| 647 | # weakproxy |
| 648 | # XXX |
| 649 | # weakcallableproxy |
| 650 | check(weakref.proxy(int), size(h + '2Pl2P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 651 | |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 652 | def test_pythontypes(self): |
| 653 | # check all types defined in Python/ |
| 654 | h = self.header |
| 655 | vh = self.vheader |
| 656 | size = self.calcsize |
| 657 | check = self.check_sizeof |
| 658 | # _ast.AST |
| 659 | import _ast |
| 660 | check(_ast.AST(), size(h + '')) |
| 661 | # imp.NullImporter |
| 662 | import imp |
| 663 | check(imp.NullImporter(self.file.name), size(h + '')) |
| 664 | try: |
| 665 | raise TypeError |
| 666 | except TypeError: |
| 667 | tb = sys.exc_info()[2] |
| 668 | # traceback |
| 669 | if tb != None: |
| 670 | check(tb, size(h + '2P2i')) |
| 671 | # symtable entry |
| 672 | # XXX |
| 673 | # sys.flags |
| 674 | check(sys.flags, size(vh) + self.P * len(sys.flags)) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 675 | |
Martin v. Löwis | 04dc25c | 2008-10-03 16:09:28 +0000 | [diff] [blame] | 676 | def test_setfilesystemencoding(self): |
| 677 | old = sys.getfilesystemencoding() |
| 678 | sys.setfilesystemencoding("iso-8859-1") |
| 679 | self.assertEqual(sys.getfilesystemencoding(), "iso-8859-1") |
| 680 | sys.setfilesystemencoding(old) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 681 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 682 | def test_main(): |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 683 | test.support.run_unittest(SysModuleTest, SizeofTest) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 684 | |
| 685 | if __name__ == "__main__": |
| 686 | test_main() |