Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1 | import unittest, test.support |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 2 | import sys, io, os |
Robert Schuppenies | 4d45bfe | 2008-06-28 23:58:47 +0000 | [diff] [blame] | 3 | import struct |
Antoine Pitrou | 652e707 | 2009-03-13 19:25:20 +0000 | [diff] [blame] | 4 | import subprocess |
| 5 | import textwrap |
Antoine Pitrou | c3b0757 | 2009-11-13 22:19:19 +0000 | [diff] [blame] | 6 | import warnings |
Eric Smith | f7bb578 | 2010-01-27 00:44:57 +0000 | [diff] [blame] | 7 | import operator |
Victor Stinner | 85ca2af | 2010-08-19 11:23:47 +0000 | [diff] [blame] | 8 | import codecs |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 9 | |
Georg Brandl | 0352655 | 2009-10-27 23:00:28 +0000 | [diff] [blame] | 10 | # count the number of test runs, used to create unique |
| 11 | # strings to intern in test_intern() |
| 12 | numruns = 0 |
| 13 | |
Victor Stinner | 45df820 | 2010-04-28 22:31:17 +0000 | [diff] [blame] | 14 | try: |
| 15 | import threading |
| 16 | except ImportError: |
| 17 | threading = None |
Georg Brandl | 0352655 | 2009-10-27 23:00:28 +0000 | [diff] [blame] | 18 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 19 | class SysModuleTest(unittest.TestCase): |
| 20 | |
Christian Heimes | ef181a7 | 2007-11-07 16:14:12 +0000 | [diff] [blame] | 21 | 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 Pitrou | 836f0e2 | 2009-10-27 19:25:57 +0000 | [diff] [blame] | 30 | test.support.reap_children() |
Christian Heimes | ef181a7 | 2007-11-07 16:14:12 +0000 | [diff] [blame] | 31 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 32 | def test_original_displayhook(self): |
Georg Brandl | 1a3284e | 2007-12-02 09:40:06 +0000 | [diff] [blame] | 33 | import builtins |
Guido van Rossum | 34d1928 | 2007-08-09 01:03:29 +0000 | [diff] [blame] | 34 | out = io.StringIO() |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 35 | sys.stdout = out |
| 36 | |
| 37 | dh = sys.__displayhook__ |
| 38 | |
| 39 | self.assertRaises(TypeError, dh) |
Georg Brandl | 1a3284e | 2007-12-02 09:40:06 +0000 | [diff] [blame] | 40 | if hasattr(builtins, "_"): |
| 41 | del builtins._ |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 42 | |
| 43 | dh(None) |
| 44 | self.assertEqual(out.getvalue(), "") |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 45 | self.assertTrue(not hasattr(builtins, "_")) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 46 | dh(42) |
| 47 | self.assertEqual(out.getvalue(), "42\n") |
Georg Brandl | 1a3284e | 2007-12-02 09:40:06 +0000 | [diff] [blame] | 48 | self.assertEqual(builtins._, 42) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 49 | |
| 50 | del sys.stdout |
| 51 | self.assertRaises(RuntimeError, dh, 42) |
| 52 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 53 | def test_lost_displayhook(self): |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 54 | del sys.displayhook |
| 55 | code = compile("42", "<string>", "single") |
| 56 | self.assertRaises(RuntimeError, eval, code) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 57 | |
| 58 | def test_custom_displayhook(self): |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 59 | def baddisplayhook(obj): |
| 60 | raise ValueError |
| 61 | sys.displayhook = baddisplayhook |
| 62 | code = compile("42", "<string>", "single") |
| 63 | self.assertRaises(ValueError, eval, code) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 64 | |
| 65 | def test_original_excepthook(self): |
Guido van Rossum | 34d1928 | 2007-08-09 01:03:29 +0000 | [diff] [blame] | 66 | err = io.StringIO() |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 67 | sys.stderr = err |
| 68 | |
| 69 | eh = sys.__excepthook__ |
| 70 | |
| 71 | self.assertRaises(TypeError, eh) |
| 72 | try: |
| 73 | raise ValueError(42) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 74 | except ValueError as exc: |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 75 | eh(*sys.exc_info()) |
| 76 | |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 77 | self.assertTrue(err.getvalue().endswith("ValueError: 42\n")) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 78 | |
Benjamin Peterson | bc74e5b | 2008-08-23 20:19:17 +0000 | [diff] [blame] | 79 | def test_excepthook(self): |
| 80 | with test.support.captured_output("stderr") as stderr: |
| 81 | sys.excepthook(1, '1', 1) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 82 | self.assertTrue("TypeError: print_exception(): Exception expected for " \ |
Benjamin Peterson | bc74e5b | 2008-08-23 20:19:17 +0000 | [diff] [blame] | 83 | "value, str found" in stderr.getvalue()) |
| 84 | |
Walter Dörwald | e7028ac | 2003-02-03 23:05:27 +0000 | [diff] [blame] | 85 | # FIXME: testing the code for a lost or replaced excepthook in |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 86 | # Python/pythonrun.c::PyErr_PrintEx() is tricky. |
| 87 | |
| 88 | def test_exit(self): |
Victor Stinner | e9fb319 | 2010-05-17 08:58:51 +0000 | [diff] [blame] | 89 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 90 | self.assertRaises(TypeError, sys.exit, 42, 42) |
| 91 | |
| 92 | # call without argument |
| 93 | try: |
| 94 | sys.exit(0) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 95 | except SystemExit as exc: |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 96 | self.assertEqual(exc.code, 0) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 97 | 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 Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 106 | except SystemExit as exc: |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 107 | self.assertEqual(exc.code, 42) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 108 | 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 Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 116 | except SystemExit as exc: |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 117 | self.assertEqual(exc.code, 42) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 118 | 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 Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 126 | except SystemExit as exc: |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 127 | self.assertEqual(exc.code, "exit") |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 128 | 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 Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 136 | except SystemExit as exc: |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 137 | self.assertEqual(exc.code, (17, 23)) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 138 | except: |
| 139 | self.fail("wrong exception") |
| 140 | else: |
| 141 | self.fail("no exception") |
| 142 | |
Michael W. Hudson | f058858 | 2005-02-15 15:26:11 +0000 | [diff] [blame] | 143 | # test that the exit machinery handles SystemExits properly |
Michael W. Hudson | f058858 | 2005-02-15 15:26:11 +0000 | [diff] [blame] | 144 | rc = subprocess.call([sys.executable, "-c", |
| 145 | "raise SystemExit(47)"]) |
| 146 | self.assertEqual(rc, 47) |
Tim Peters | f0db38d | 2005-02-15 21:50:12 +0000 | [diff] [blame] | 147 | |
Victor Stinner | 7126dbc | 2010-05-21 23:45:42 +0000 | [diff] [blame] | 148 | def check_exit_message(code, expected, env=None): |
Victor Stinner | e9fb319 | 2010-05-17 08:58:51 +0000 | [diff] [blame] | 149 | process = subprocess.Popen([sys.executable, "-c", code], |
Victor Stinner | 7126dbc | 2010-05-21 23:45:42 +0000 | [diff] [blame] | 150 | stderr=subprocess.PIPE, env=env) |
Victor Stinner | e9fb319 | 2010-05-17 08:58:51 +0000 | [diff] [blame] | 151 | stdout, stderr = process.communicate() |
| 152 | self.assertEqual(process.returncode, 1) |
Victor Stinner | 7cf7d72 | 2010-05-17 14:36:43 +0000 | [diff] [blame] | 153 | self.assertTrue(stderr.startswith(expected), |
Victor Stinner | c098385 | 2010-05-17 19:57:40 +0000 | [diff] [blame] | 154 | "%s doesn't start with %s" % (ascii(stderr), ascii(expected))) |
Victor Stinner | e9fb319 | 2010-05-17 08:58:51 +0000 | [diff] [blame] | 155 | |
| 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 Stinner | 372ac5e | 2010-05-17 01:26:01 +0000 | [diff] [blame] | 162 | # test that the exit message is written with backslashreplace error |
| 163 | # handler to stderr |
Victor Stinner | e9fb319 | 2010-05-17 08:58:51 +0000 | [diff] [blame] | 164 | check_exit_message( |
| 165 | r'import sys; sys.exit("surrogates:\uDCFF")', |
| 166 | b"surrogates:\\udcff") |
Victor Stinner | 372ac5e | 2010-05-17 01:26:01 +0000 | [diff] [blame] | 167 | |
Victor Stinner | 7126dbc | 2010-05-21 23:45:42 +0000 | [diff] [blame] | 168 | # 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örwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 176 | def test_getdefaultencoding(self): |
Walter Dörwald | 4aeaa96 | 2007-05-22 16:13:46 +0000 | [diff] [blame] | 177 | self.assertRaises(TypeError, sys.getdefaultencoding, 42) |
| 178 | # can't check more than the type, as the user might have changed it |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 179 | self.assertIsInstance(sys.getdefaultencoding(), str) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 180 | |
Alexander Belopolsky | 07de165 | 2010-07-25 15:05:42 +0000 | [diff] [blame] | 181 | # testing sys.settrace() is done in test_sys_settrace.py |
| 182 | # testing sys.setprofile() is done in test_sys_setprofile.py |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 183 | |
| 184 | def test_setcheckinterval(self): |
Antoine Pitrou | c3b0757 | 2009-11-13 22:19:19 +0000 | [diff] [blame] | 185 | 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 Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 191 | self.assertEqual(sys.getcheckinterval(), n) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 192 | |
Victor Stinner | 45df820 | 2010-04-28 22:31:17 +0000 | [diff] [blame] | 193 | @unittest.skipUnless(threading, 'Threading required for this test.') |
Antoine Pitrou | 074e5ed | 2009-11-10 19:50:40 +0000 | [diff] [blame] | 194 | 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 Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 205 | self.assertAlmostEqual(sys.getswitchinterval(), n) |
Antoine Pitrou | 074e5ed | 2009-11-10 19:50:40 +0000 | [diff] [blame] | 206 | finally: |
| 207 | sys.setswitchinterval(orig) |
| 208 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 209 | def test_recursionlimit(self): |
Tim Peters | f2715e0 | 2003-02-19 02:35:07 +0000 | [diff] [blame] | 210 | 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örwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 217 | |
Brett Cannon | 5543e81 | 2011-01-25 18:26:35 +0000 | [diff] [blame] | 218 | @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(), |
| 219 | 'fatal error if run with a trace function') |
Antoine Pitrou | 652e707 | 2009-03-13 19:25:20 +0000 | [diff] [blame] | 220 | 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 Pitrou | 17dc446 | 2009-04-04 17:36:05 +0000 | [diff] [blame] | 240 | if os.name == "nt": |
| 241 | raise unittest.SkipTest( |
| 242 | "under Windows, test would generate a spurious crash dialog") |
Antoine Pitrou | 652e707 | 2009-03-13 19:25:20 +0000 | [diff] [blame] | 243 | 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örwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 263 | def test_getwindowsversion(self): |
Eric Smith | 05f33744 | 2010-01-27 01:25:02 +0000 | [diff] [blame] | 264 | # Raise SkipTest if sys doesn't have getwindowsversion attribute |
Eric Smith | d8aef76 | 2010-01-27 01:38:34 +0000 | [diff] [blame] | 265 | test.support.get_attribute(sys, "getwindowsversion") |
Eric Smith | 05f33744 | 2010-01-27 01:25:02 +0000 | [diff] [blame] | 266 | v = sys.getwindowsversion() |
Brian Curtin | 808e1ad | 2010-07-08 22:13:25 +0000 | [diff] [blame] | 267 | self.assertEqual(len(v), 5) |
Eric Smith | 05f33744 | 2010-01-27 01:25:02 +0000 | [diff] [blame] | 268 | 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 Smith | a1f20b9 | 2010-01-27 02:14:26 +0000 | [diff] [blame] | 279 | 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 Smith | 05f33744 | 2010-01-27 01:25:02 +0000 | [diff] [blame] | 283 | 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 Smith | f7bb578 | 2010-01-27 00:44:57 +0000 | [diff] [blame] | 288 | |
Eric Smith | 05f33744 | 2010-01-27 01:25:02 +0000 | [diff] [blame] | 289 | # 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örwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 292 | |
Barry Warsaw | e94a37f | 2008-10-17 01:29:56 +0000 | [diff] [blame] | 293 | def test_call_tracing(self): |
| 294 | self.assertRaises(TypeError, sys.call_tracing, type, 2) |
| 295 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 296 | def test_dlopenflags(self): |
| 297 | if hasattr(sys, "setdlopenflags"): |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 298 | self.assertTrue(hasattr(sys, "getdlopenflags")) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 299 | 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 Cannon | 7a54073 | 2011-02-22 03:04:06 +0000 | [diff] [blame^] | 306 | @test.support.refcount_test |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 307 | def test_refcount(self): |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 308 | # 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örwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 313 | 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 Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 320 | self.assertIsInstance(sys.gettotalrefcount(), int) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 321 | |
| 322 | def test_getframe(self): |
| 323 | self.assertRaises(TypeError, sys._getframe, 42, 42) |
Neal Norwitz | eb2a5ef | 2003-02-18 15:22:10 +0000 | [diff] [blame] | 324 | self.assertRaises(ValueError, sys._getframe, 2000000000) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 325 | self.assertTrue( |
Christian Heimes | 4a22b5d | 2007-11-25 09:39:14 +0000 | [diff] [blame] | 326 | SysModuleTest.test_getframe.__code__ \ |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 327 | is sys._getframe().f_code |
| 328 | ) |
| 329 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 330 | # sys._current_frames() is a CPython-only gimmick. |
| 331 | def test_current_frames(self): |
| 332 | have_threads = True |
| 333 | try: |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 334 | import _thread |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 335 | 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 Pitrou | 836f0e2 | 2009-10-27 19:25:57 +0000 | [diff] [blame] | 344 | @test.support.reap_threads |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 345 | def current_frames_with_threads(self): |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 346 | import threading, _thread |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 347 | 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(): |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 360 | thread_info.append(_thread.get_ident()) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 361 | 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 | |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 376 | main_id = _thread.get_ident() |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 377 | self.assertIn(main_id, d) |
| 378 | self.assertIn(thread_id, d) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 379 | |
| 380 | # Verify that the captured main-thread frame is _this_ frame. |
| 381 | frame = d.pop(main_id) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 382 | self.assertTrue(frame is sys._getframe()) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 383 | |
| 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 Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 400 | self.assertIn(sourceline, ["leave_g.wait()", "entered_g.set()"]) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 401 | |
| 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 Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 412 | self.assertIn(0, d) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 413 | self.assertTrue(d[0] is sys._getframe()) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 414 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 415 | def test_attributes(self): |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 416 | self.assertIsInstance(sys.api_version, int) |
| 417 | self.assertIsInstance(sys.argv, list) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 418 | self.assertIn(sys.byteorder, ("little", "big")) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 419 | 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 Heimes | 9385266 | 2007-12-01 12:22:32 +0000 | [diff] [blame] | 423 | self.assertEqual(len(sys.float_info), 11) |
Christian Heimes | d32ed6f | 2008-01-14 18:49:24 +0000 | [diff] [blame] | 424 | self.assertEqual(sys.float_info.radix, 2) |
Mark Dickinson | bd79264 | 2009-03-18 20:06:12 +0000 | [diff] [blame] | 425 | self.assertEqual(len(sys.int_info), 2) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 426 | self.assertTrue(sys.int_info.bits_per_digit % 5 == 0) |
| 427 | self.assertTrue(sys.int_info.sizeof_digit >= 1) |
Benjamin Peterson | ef3e4c2 | 2009-04-11 19:48:14 +0000 | [diff] [blame] | 428 | self.assertEqual(type(sys.int_info.bits_per_digit), int) |
| 429 | self.assertEqual(type(sys.int_info.sizeof_digit), int) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 430 | self.assertIsInstance(sys.hexversion, int) |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 431 | |
| 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 Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 448 | self.assertIsInstance(sys.maxsize, int) |
| 449 | self.assertIsInstance(sys.maxunicode, int) |
| 450 | self.assertIsInstance(sys.platform, str) |
| 451 | self.assertIsInstance(sys.prefix, str) |
| 452 | self.assertIsInstance(sys.version, str) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 453 | vi = sys.version_info |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 454 | self.assertIsInstance(vi[:], tuple) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 455 | self.assertEqual(len(vi), 5) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 456 | self.assertIsInstance(vi[0], int) |
| 457 | self.assertIsInstance(vi[1], int) |
| 458 | self.assertIsInstance(vi[2], int) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 459 | self.assertIn(vi[3], ("alpha", "beta", "candidate", "final")) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 460 | self.assertIsInstance(vi[4], int) |
| 461 | self.assertIsInstance(vi.major, int) |
| 462 | self.assertIsInstance(vi.minor, int) |
| 463 | self.assertIsInstance(vi.micro, int) |
Ezio Melotti | b58e0bd | 2010-01-23 15:40:09 +0000 | [diff] [blame] | 464 | self.assertIn(vi.releaselevel, ("alpha", "beta", "candidate", "final")) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 465 | self.assertIsInstance(vi.serial, int) |
Eric Smith | 0e5b562 | 2009-02-06 01:32:42 +0000 | [diff] [blame] | 466 | self.assertEqual(vi[0], vi.major) |
| 467 | self.assertEqual(vi[1], vi.minor) |
| 468 | self.assertEqual(vi[2], vi.micro) |
| 469 | self.assertEqual(vi[3], vi.releaselevel) |
| 470 | self.assertEqual(vi[4], vi.serial) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 471 | self.assertTrue(vi > (1,0,0)) |
Mark Dickinson | 55d110c | 2009-10-24 14:04:48 +0000 | [diff] [blame] | 472 | self.assertIsInstance(sys.float_repr_style, str) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 473 | self.assertIn(sys.float_repr_style, ('short', 'legacy')) |
Barry Warsaw | 8cf4eae | 2010-10-16 01:04:07 +0000 | [diff] [blame] | 474 | if not sys.platform.startswith('win'): |
| 475 | self.assertIsInstance(sys.abiflags, str) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 476 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 477 | def test_43581(self): |
Georg Brandl | 0312494 | 2008-06-10 15:50:56 +0000 | [diff] [blame] | 478 | # Can't use sys.stdout, as this is a StringIO object when |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 479 | # the test runs under regrtest. |
Guido van Rossum | e61fd5b | 2007-07-11 12:20:59 +0000 | [diff] [blame] | 480 | self.assertEqual(sys.__stdout__.encoding, sys.__stderr__.encoding) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 481 | |
Georg Brandl | 66a796e | 2006-12-19 20:50:34 +0000 | [diff] [blame] | 482 | def test_intern(self): |
Georg Brandl | 0352655 | 2009-10-27 23:00:28 +0000 | [diff] [blame] | 483 | global numruns |
| 484 | numruns += 1 |
Georg Brandl | 66a796e | 2006-12-19 20:50:34 +0000 | [diff] [blame] | 485 | self.assertRaises(TypeError, sys.intern) |
Georg Brandl | 0352655 | 2009-10-27 23:00:28 +0000 | [diff] [blame] | 486 | s = "never interned before" + str(numruns) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 487 | self.assertTrue(sys.intern(s) is s) |
Georg Brandl | 66a796e | 2006-12-19 20:50:34 +0000 | [diff] [blame] | 488 | s2 = s.swapcase().swapcase() |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 489 | self.assertTrue(sys.intern(s2) is s) |
Georg Brandl | 66a796e | 2006-12-19 20:50:34 +0000 | [diff] [blame] | 490 | |
| 491 | # Subclasses of string can't be interned, because they |
| 492 | # provide too much opportunity for insane things to happen. |
| 493 | # We don't want them in the interned dict and if they aren't |
| 494 | # actually interned, we don't want to create the appearance |
| 495 | # that they are by allowing intern() to succeeed. |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 496 | class S(str): |
Georg Brandl | 66a796e | 2006-12-19 20:50:34 +0000 | [diff] [blame] | 497 | def __hash__(self): |
| 498 | return 123 |
| 499 | |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 500 | self.assertRaises(TypeError, sys.intern, S("abc")) |
Martin v. Löwis | 5b22213 | 2007-06-10 09:51:05 +0000 | [diff] [blame] | 501 | |
Christian Heimes | d32ed6f | 2008-01-14 18:49:24 +0000 | [diff] [blame] | 502 | def test_sys_flags(self): |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 503 | self.assertTrue(sys.flags) |
Christian Heimes | d32ed6f | 2008-01-14 18:49:24 +0000 | [diff] [blame] | 504 | attrs = ("debug", "division_warning", |
| 505 | "inspect", "interactive", "optimize", "dont_write_bytecode", |
Georg Brandl | c5e88d5 | 2008-06-06 09:02:07 +0000 | [diff] [blame] | 506 | "no_user_site", "no_site", "ignore_environment", "verbose", |
Raymond Hettinger | 7d96771 | 2011-01-05 20:24:08 +0000 | [diff] [blame] | 507 | "bytes_warning", "quiet") |
Christian Heimes | d32ed6f | 2008-01-14 18:49:24 +0000 | [diff] [blame] | 508 | for attr in attrs: |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 509 | self.assertTrue(hasattr(sys.flags, attr), attr) |
Christian Heimes | d32ed6f | 2008-01-14 18:49:24 +0000 | [diff] [blame] | 510 | self.assertEqual(type(getattr(sys.flags, attr)), int, attr) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 511 | self.assertTrue(repr(sys.flags)) |
Georg Brandl | c5e88d5 | 2008-06-06 09:02:07 +0000 | [diff] [blame] | 512 | self.assertEqual(len(sys.flags), len(attrs)) |
Christian Heimes | d32ed6f | 2008-01-14 18:49:24 +0000 | [diff] [blame] | 513 | |
Christian Heimes | 15ebc88 | 2008-02-04 18:48:49 +0000 | [diff] [blame] | 514 | def test_clear_type_cache(self): |
| 515 | sys._clear_type_cache() |
| 516 | |
Martin v. Löwis | 0f59989 | 2008-06-02 11:13:03 +0000 | [diff] [blame] | 517 | def test_ioencoding(self): |
Martin v. Löwis | 0f59989 | 2008-06-02 11:13:03 +0000 | [diff] [blame] | 518 | env = dict(os.environ) |
| 519 | |
| 520 | # Test character: cent sign, encoded as 0x4A (ASCII J) in CP424, |
| 521 | # not representable in ASCII. |
| 522 | |
| 523 | env["PYTHONIOENCODING"] = "cp424" |
| 524 | p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'], |
| 525 | stdout = subprocess.PIPE, env=env) |
Antoine Pitrou | 836f0e2 | 2009-10-27 19:25:57 +0000 | [diff] [blame] | 526 | out = p.communicate()[0].strip() |
Martin v. Löwis | 0f59989 | 2008-06-02 11:13:03 +0000 | [diff] [blame] | 527 | self.assertEqual(out, "\xa2\n".encode("cp424")) |
| 528 | |
| 529 | env["PYTHONIOENCODING"] = "ascii:replace" |
| 530 | p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'], |
| 531 | stdout = subprocess.PIPE, env=env) |
Antoine Pitrou | 836f0e2 | 2009-10-27 19:25:57 +0000 | [diff] [blame] | 532 | out = p.communicate()[0].strip() |
Martin v. Löwis | 0f59989 | 2008-06-02 11:13:03 +0000 | [diff] [blame] | 533 | self.assertEqual(out, b'?') |
| 534 | |
Victor Stinner | 171ba05 | 2010-03-12 14:20:59 +0000 | [diff] [blame] | 535 | def test_executable(self): |
| 536 | # Issue #7774: Ensure that sys.executable is an empty string if argv[0] |
| 537 | # has been set to an non existent program name and Python is unable to |
| 538 | # retrieve the real program name |
Florent Xicluna | 02ea12b2 | 2010-07-28 16:39:41 +0000 | [diff] [blame] | 539 | |
Victor Stinner | 171ba05 | 2010-03-12 14:20:59 +0000 | [diff] [blame] | 540 | # For a normal installation, it should work without 'cwd' |
| 541 | # argument. For test runs in the build directory, see #7774. |
| 542 | python_dir = os.path.dirname(os.path.realpath(sys.executable)) |
| 543 | p = subprocess.Popen( |
| 544 | ["nonexistent", "-c", |
| 545 | 'import sys; print(sys.executable.encode("ascii", "backslashreplace"))'], |
| 546 | executable=sys.executable, stdout=subprocess.PIPE, cwd=python_dir) |
| 547 | stdout = p.communicate()[0] |
| 548 | executable = stdout.strip().decode("ASCII") |
| 549 | p.wait() |
| 550 | self.assertIn(executable, ["b''", repr(sys.executable.encode("ascii", "backslashreplace"))]) |
| 551 | |
Victor Stinner | 85ca2af | 2010-08-19 11:23:47 +0000 | [diff] [blame] | 552 | def check_fsencoding(self, fs_encoding, expected=None): |
| 553 | self.assertIsNotNone(fs_encoding) |
| 554 | codecs.lookup(fs_encoding) |
| 555 | if expected: |
| 556 | self.assertEqual(fs_encoding, expected) |
| 557 | |
Victor Stinner | c732e3b | 2010-08-18 22:44:15 +0000 | [diff] [blame] | 558 | def test_getfilesystemencoding(self): |
Victor Stinner | c732e3b | 2010-08-18 22:44:15 +0000 | [diff] [blame] | 559 | fs_encoding = sys.getfilesystemencoding() |
Victor Stinner | 85ca2af | 2010-08-19 11:23:47 +0000 | [diff] [blame] | 560 | if sys.platform == 'darwin': |
| 561 | expected = 'utf-8' |
| 562 | elif sys.platform == 'win32': |
| 563 | expected = 'mbcs' |
| 564 | else: |
| 565 | expected = None |
Victor Stinner | 9943524 | 2010-08-19 11:30:09 +0000 | [diff] [blame] | 566 | self.check_fsencoding(fs_encoding, expected) |
Victor Stinner | c732e3b | 2010-08-18 22:44:15 +0000 | [diff] [blame] | 567 | |
Martin v. Löwis | 0f59989 | 2008-06-02 11:13:03 +0000 | [diff] [blame] | 568 | |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 569 | class SizeofTest(unittest.TestCase): |
| 570 | |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 571 | TPFLAGS_HAVE_GC = 1<<14 |
| 572 | TPFLAGS_HEAPTYPE = 1<<9 |
| 573 | |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 574 | def setUp(self): |
Victor Stinner | baab9d0 | 2010-12-28 13:33:43 +0000 | [diff] [blame] | 575 | self.c = len(struct.pack('c', b' ')) |
Robert Schuppenies | 4d45bfe | 2008-06-28 23:58:47 +0000 | [diff] [blame] | 576 | self.H = len(struct.pack('H', 0)) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 577 | self.i = len(struct.pack('i', 0)) |
| 578 | self.l = len(struct.pack('l', 0)) |
Robert Schuppenies | 4d45bfe | 2008-06-28 23:58:47 +0000 | [diff] [blame] | 579 | self.P = len(struct.pack('P', 0)) |
| 580 | # due to missing size_t information from struct, it is assumed that |
| 581 | # sizeof(Py_ssize_t) = sizeof(void*) |
| 582 | self.header = 'PP' |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 583 | self.vheader = self.header + 'P' |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 584 | if hasattr(sys, "gettotalrefcount"): |
Robert Schuppenies | 4d45bfe | 2008-06-28 23:58:47 +0000 | [diff] [blame] | 585 | self.header += '2P' |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 586 | self.vheader += '2P' |
Mark Dickinson | bd79264 | 2009-03-18 20:06:12 +0000 | [diff] [blame] | 587 | self.longdigit = sys.int_info.sizeof_digit |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 588 | import _testcapi |
| 589 | self.gc_headsize = _testcapi.SIZEOF_PYGC_HEAD |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 590 | self.file = open(test.support.TESTFN, 'wb') |
| 591 | |
| 592 | def tearDown(self): |
| 593 | self.file.close() |
| 594 | test.support.unlink(test.support.TESTFN) |
| 595 | |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 596 | def check_sizeof(self, o, size): |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 597 | result = sys.getsizeof(o) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 598 | # add GC header size |
| 599 | if ((type(o) == type) and (o.__flags__ & self.TPFLAGS_HEAPTYPE) or\ |
| 600 | ((type(o) != type) and (type(o).__flags__ & self.TPFLAGS_HAVE_GC))): |
| 601 | size += self.gc_headsize |
| 602 | msg = 'wrong size for %s: got %d, expected %d' \ |
| 603 | % (type(o), result, size) |
| 604 | self.assertEqual(result, size, msg) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 605 | |
Robert Schuppenies | 4d45bfe | 2008-06-28 23:58:47 +0000 | [diff] [blame] | 606 | def calcsize(self, fmt): |
| 607 | """Wrapper around struct.calcsize which enforces the alignment of the |
| 608 | end of a structure to the alignment requirement of pointer. |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 609 | |
Robert Schuppenies | 4d45bfe | 2008-06-28 23:58:47 +0000 | [diff] [blame] | 610 | Note: This wrapper should only be used if a pointer member is included |
| 611 | and no member with a size larger than a pointer exists. |
| 612 | """ |
| 613 | return struct.calcsize(fmt + '0P') |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 614 | |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 615 | def test_gc_head_size(self): |
| 616 | # 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] | 617 | h = self.header |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 618 | vh = self.vheader |
Robert Schuppenies | 4d45bfe | 2008-06-28 23:58:47 +0000 | [diff] [blame] | 619 | size = self.calcsize |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 620 | gc_header_size = self.gc_headsize |
| 621 | # bool objects are not gc tracked |
Mark Dickinson | bd79264 | 2009-03-18 20:06:12 +0000 | [diff] [blame] | 622 | self.assertEqual(sys.getsizeof(True), size(vh) + self.longdigit) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 623 | # but lists are |
| 624 | self.assertEqual(sys.getsizeof([]), size(vh + 'PP') + gc_header_size) |
| 625 | |
| 626 | def test_default(self): |
| 627 | h = self.header |
| 628 | vh = self.vheader |
| 629 | size = self.calcsize |
Mark Dickinson | bd79264 | 2009-03-18 20:06:12 +0000 | [diff] [blame] | 630 | self.assertEqual(sys.getsizeof(True), size(vh) + self.longdigit) |
| 631 | self.assertEqual(sys.getsizeof(True, -1), size(vh) + self.longdigit) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 632 | |
| 633 | def test_objecttypes(self): |
| 634 | # check all types defined in Objects/ |
| 635 | h = self.header |
| 636 | vh = self.vheader |
| 637 | size = self.calcsize |
| 638 | check = self.check_sizeof |
| 639 | # bool |
Mark Dickinson | bd79264 | 2009-03-18 20:06:12 +0000 | [diff] [blame] | 640 | check(True, size(vh) + self.longdigit) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 641 | # buffer |
| 642 | # XXX |
| 643 | # builtin_function_or_method |
| 644 | check(len, size(h + '3P')) |
| 645 | # bytearray |
| 646 | samples = [b'', b'u'*100000] |
| 647 | for sample in samples: |
| 648 | x = bytearray(sample) |
| 649 | check(x, size(vh + 'iPP') + x.__alloc__() * self.c) |
| 650 | # bytearray_iterator |
| 651 | check(iter(bytearray()), size(h + 'PP')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 652 | # cell |
| 653 | def get_cell(): |
| 654 | x = 42 |
| 655 | def inner(): |
| 656 | return x |
| 657 | return inner |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 658 | check(get_cell().__closure__[0], size(h + 'P')) |
Robert Schuppenies | 4efb518 | 2008-06-06 11:49:51 +0000 | [diff] [blame] | 659 | # code |
Collin Winter | 4222e9c | 2010-03-18 22:46:40 +0000 | [diff] [blame] | 660 | check(get_cell().__code__, size(h + '5i8Pi3P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 661 | # complex |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 662 | check(complex(0,1), size(h + '2d')) |
| 663 | # method_descriptor (descriptor object) |
| 664 | check(str.lower, size(h + '2PP')) |
| 665 | # classmethod_descriptor (descriptor object) |
| 666 | # XXX |
| 667 | # member_descriptor (descriptor object) |
| 668 | import datetime |
| 669 | check(datetime.timedelta.days, size(h + '2PP')) |
| 670 | # getset_descriptor (descriptor object) |
| 671 | import collections |
| 672 | check(collections.defaultdict.default_factory, size(h + '2PP')) |
| 673 | # wrapper_descriptor (descriptor object) |
| 674 | check(int.__add__, size(h + '2P2P')) |
| 675 | # method-wrapper (descriptor object) |
| 676 | check({}.__iter__, size(h + '2P')) |
| 677 | # dict |
| 678 | check({}, size(h + '3P2P' + 8*'P2P')) |
| 679 | longdict = {1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8} |
| 680 | check(longdict, size(h + '3P2P' + 8*'P2P') + 16*size('P2P')) |
| 681 | # dictionary-keyiterator |
| 682 | check({}.keys(), size(h + 'P')) |
| 683 | # dictionary-valueiterator |
| 684 | check({}.values(), size(h + 'P')) |
| 685 | # dictionary-itemiterator |
| 686 | check({}.items(), size(h + 'P')) |
| 687 | # dictproxy |
| 688 | class C(object): pass |
| 689 | check(C.__dict__, size(h + 'P')) |
| 690 | # BaseException |
| 691 | check(BaseException(), size(h + '5P')) |
| 692 | # UnicodeEncodeError |
| 693 | check(UnicodeEncodeError("", "", 0, 0, ""), size(h + '5P 2P2PP')) |
| 694 | # UnicodeDecodeError |
| 695 | # XXX |
| 696 | # check(UnicodeDecodeError("", "", 0, 0, ""), size(h + '5P2PP')) |
| 697 | # UnicodeTranslateError |
| 698 | check(UnicodeTranslateError("", 0, 1, ""), size(h + '5P 2P2PP')) |
| 699 | # ellipses |
| 700 | check(Ellipsis, size(h + '')) |
| 701 | # EncodingMap |
| 702 | import codecs, encodings.iso8859_3 |
| 703 | x = codecs.charmap_build(encodings.iso8859_3.decoding_table) |
| 704 | check(x, size(h + '32B2iB')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 705 | # enumerate |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 706 | check(enumerate([]), size(h + 'l3P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 707 | # reverse |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 708 | check(reversed(''), size(h + 'PP')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 709 | # float |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 710 | check(float(0), size(h + 'd')) |
| 711 | # sys.floatinfo |
| 712 | check(sys.float_info, size(vh) + self.P * len(sys.float_info)) |
| 713 | # frame |
| 714 | import inspect |
| 715 | CO_MAXBLOCKS = 20 |
| 716 | x = inspect.currentframe() |
| 717 | ncells = len(x.f_code.co_cellvars) |
| 718 | nfrees = len(x.f_code.co_freevars) |
| 719 | extras = x.f_code.co_stacksize + x.f_code.co_nlocals +\ |
| 720 | ncells + nfrees - 1 |
| 721 | 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] | 722 | # function |
| 723 | def func(): pass |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 724 | check(func, size(h + '11P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 725 | class c(): |
| 726 | @staticmethod |
| 727 | def foo(): |
| 728 | pass |
| 729 | @classmethod |
| 730 | def bar(cls): |
| 731 | pass |
| 732 | # staticmethod |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 733 | check(foo, size(h + 'P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 734 | # classmethod |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 735 | check(bar, size(h + 'P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 736 | # generator |
| 737 | def get_gen(): yield 1 |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 738 | check(get_gen(), size(h + 'Pi2P')) |
| 739 | # iterator |
| 740 | check(iter('abc'), size(h + 'lP')) |
| 741 | # callable-iterator |
| 742 | import re |
| 743 | check(re.finditer('',''), size(h + '2P')) |
| 744 | # list |
| 745 | samples = [[], [1,2,3], ['1', '2', '3']] |
| 746 | for sample in samples: |
| 747 | check(sample, size(vh + 'PP') + len(sample)*self.P) |
| 748 | # sortwrapper (list) |
| 749 | # XXX |
| 750 | # cmpwrapper (list) |
| 751 | # XXX |
| 752 | # listiterator (list) |
| 753 | check(iter([]), size(h + 'lP')) |
| 754 | # listreverseiterator (list) |
| 755 | check(reversed([]), size(h + 'lP')) |
| 756 | # long |
| 757 | check(0, size(vh)) |
Mark Dickinson | bd79264 | 2009-03-18 20:06:12 +0000 | [diff] [blame] | 758 | check(1, size(vh) + self.longdigit) |
| 759 | check(-1, size(vh) + self.longdigit) |
| 760 | PyLong_BASE = 2**sys.int_info.bits_per_digit |
Benjamin Peterson | ef3e4c2 | 2009-04-11 19:48:14 +0000 | [diff] [blame] | 761 | check(int(PyLong_BASE), size(vh) + 2*self.longdigit) |
| 762 | check(int(PyLong_BASE**2-1), size(vh) + 2*self.longdigit) |
| 763 | check(int(PyLong_BASE**2), size(vh) + 3*self.longdigit) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 764 | # memory |
Antoine Pitrou | aeb6cee | 2010-11-04 20:30:33 +0000 | [diff] [blame] | 765 | check(memoryview(b''), size(h + 'PP2P2i7P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 766 | # module |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 767 | check(unittest, size(h + '3P')) |
| 768 | # None |
| 769 | check(None, size(h + '')) |
| 770 | # NotImplementedType |
| 771 | check(NotImplemented, size(h)) |
| 772 | # object |
| 773 | check(object(), size(h + '')) |
| 774 | # property (descriptor object) |
| 775 | class C(object): |
| 776 | def getx(self): return self.__x |
| 777 | def setx(self, value): self.__x = value |
| 778 | def delx(self): del self.__x |
| 779 | x = property(getx, setx, delx, "") |
| 780 | check(x, size(h + '4Pi')) |
Benjamin Peterson | b173f78 | 2009-05-05 22:31:58 +0000 | [diff] [blame] | 781 | # PyCapsule |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 782 | # XXX |
| 783 | # rangeiterator |
| 784 | check(iter(range(1)), size(h + '4l')) |
| 785 | # reverse |
| 786 | check(reversed(''), size(h + 'PP')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 787 | # range |
Nick Coghlan | 37ee850 | 2010-12-03 14:26:13 +0000 | [diff] [blame] | 788 | check(range(1), size(h + '4P')) |
| 789 | check(range(66000), size(h + '4P')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 790 | # set |
| 791 | # frozenset |
| 792 | PySet_MINSIZE = 8 |
| 793 | samples = [[], range(10), range(50)] |
| 794 | s = size(h + '3P2P' + PySet_MINSIZE*'lP' + 'lP') |
| 795 | for sample in samples: |
| 796 | minused = len(sample) |
| 797 | if minused == 0: tmp = 1 |
| 798 | # the computation of minused is actually a bit more complicated |
| 799 | # but this suffices for the sizeof test |
| 800 | minused = minused*2 |
| 801 | newsize = PySet_MINSIZE |
| 802 | while newsize <= minused: |
| 803 | newsize = newsize << 1 |
| 804 | if newsize <= 8: |
| 805 | check(set(sample), s) |
| 806 | check(frozenset(sample), s) |
| 807 | else: |
| 808 | check(set(sample), s + newsize*struct.calcsize('lP')) |
| 809 | check(frozenset(sample), s + newsize*struct.calcsize('lP')) |
| 810 | # setiterator |
| 811 | check(iter(set()), size(h + 'P3P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 812 | # slice |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 813 | check(slice(0), size(h + '3P')) |
| 814 | # super |
| 815 | check(super(int), size(h + '3P')) |
| 816 | # tuple |
| 817 | check((), size(vh)) |
| 818 | check((1,2,3), size(vh) + 3*self.P) |
| 819 | # type |
| 820 | # (PyTypeObject + PyNumberMethods + PyMappingMethods + |
| 821 | # PySequenceMethods + PyBufferProcs) |
| 822 | s = size(vh + 'P2P15Pl4PP9PP11PI') + size('16Pi17P 3P 10P 2P 2P') |
| 823 | check(int, s) |
| 824 | # class |
| 825 | class newstyleclass(object): pass |
| 826 | check(newstyleclass, s) |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 827 | # unicode |
Benjamin Peterson | b49d994 | 2008-06-17 12:44:04 +0000 | [diff] [blame] | 828 | usize = len('\0'.encode('unicode-internal')) |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 829 | samples = ['', '1'*100] |
| 830 | # we need to test for both sizes, because we don't know if the string |
| 831 | # has been cached |
| 832 | for s in samples: |
Antoine Pitrou | fbb1c61 | 2010-10-23 17:37:54 +0000 | [diff] [blame] | 833 | basicsize = size(h + 'PPPiP') + usize * (len(s) + 1) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 834 | check(s, basicsize) |
| 835 | # weakref |
| 836 | import weakref |
| 837 | check(weakref.ref(int), size(h + '2Pl2P')) |
| 838 | # weakproxy |
| 839 | # XXX |
| 840 | # weakcallableproxy |
| 841 | check(weakref.proxy(int), size(h + '2Pl2P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 842 | |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 843 | def test_pythontypes(self): |
| 844 | # check all types defined in Python/ |
| 845 | h = self.header |
| 846 | vh = self.vheader |
| 847 | size = self.calcsize |
| 848 | check = self.check_sizeof |
| 849 | # _ast.AST |
| 850 | import _ast |
| 851 | check(_ast.AST(), size(h + '')) |
| 852 | # imp.NullImporter |
| 853 | import imp |
| 854 | check(imp.NullImporter(self.file.name), size(h + '')) |
| 855 | try: |
| 856 | raise TypeError |
| 857 | except TypeError: |
| 858 | tb = sys.exc_info()[2] |
| 859 | # traceback |
| 860 | if tb != None: |
| 861 | check(tb, size(h + '2P2i')) |
| 862 | # symtable entry |
| 863 | # XXX |
| 864 | # sys.flags |
| 865 | check(sys.flags, size(vh) + self.P * len(sys.flags)) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 866 | |
| 867 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 868 | def test_main(): |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 869 | test.support.run_unittest(SysModuleTest, SizeofTest) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 870 | |
| 871 | if __name__ == "__main__": |
| 872 | test_main() |