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 |
Antoine Pitrou | 652e707 | 2009-03-13 19:25:20 +0000 | [diff] [blame] | 5 | import subprocess |
| 6 | import textwrap |
Antoine Pitrou | c3b0757 | 2009-11-13 22:19:19 +0000 | [diff] [blame] | 7 | import warnings |
Eric Smith | f7bb578 | 2010-01-27 00:44:57 +0000 | [diff] [blame] | 8 | import operator |
Victor Stinner | 85ca2af | 2010-08-19 11:23:47 +0000 | [diff] [blame] | 9 | import codecs |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 10 | |
Georg Brandl | 0352655 | 2009-10-27 23:00:28 +0000 | [diff] [blame] | 11 | # count the number of test runs, used to create unique |
| 12 | # strings to intern in test_intern() |
| 13 | numruns = 0 |
| 14 | |
Victor Stinner | 45df820 | 2010-04-28 22:31:17 +0000 | [diff] [blame] | 15 | try: |
| 16 | import threading |
| 17 | except ImportError: |
| 18 | threading = None |
Georg Brandl | 0352655 | 2009-10-27 23:00:28 +0000 | [diff] [blame] | 19 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 20 | class SysModuleTest(unittest.TestCase): |
| 21 | |
Christian Heimes | ef181a7 | 2007-11-07 16:14:12 +0000 | [diff] [blame] | 22 | def setUp(self): |
| 23 | self.orig_stdout = sys.stdout |
| 24 | self.orig_stderr = sys.stderr |
| 25 | self.orig_displayhook = sys.displayhook |
| 26 | |
| 27 | def tearDown(self): |
| 28 | sys.stdout = self.orig_stdout |
| 29 | sys.stderr = self.orig_stderr |
| 30 | sys.displayhook = self.orig_displayhook |
Antoine Pitrou | 836f0e2 | 2009-10-27 19:25:57 +0000 | [diff] [blame] | 31 | test.support.reap_children() |
Christian Heimes | ef181a7 | 2007-11-07 16:14:12 +0000 | [diff] [blame] | 32 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 33 | def test_original_displayhook(self): |
Georg Brandl | 1a3284e | 2007-12-02 09:40:06 +0000 | [diff] [blame] | 34 | import builtins |
Guido van Rossum | 34d1928 | 2007-08-09 01:03:29 +0000 | [diff] [blame] | 35 | out = io.StringIO() |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 36 | sys.stdout = out |
| 37 | |
| 38 | dh = sys.__displayhook__ |
| 39 | |
| 40 | self.assertRaises(TypeError, dh) |
Georg Brandl | 1a3284e | 2007-12-02 09:40:06 +0000 | [diff] [blame] | 41 | if hasattr(builtins, "_"): |
| 42 | del builtins._ |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 43 | |
| 44 | dh(None) |
| 45 | self.assertEqual(out.getvalue(), "") |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 46 | self.assertTrue(not hasattr(builtins, "_")) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 47 | dh(42) |
| 48 | self.assertEqual(out.getvalue(), "42\n") |
Georg Brandl | 1a3284e | 2007-12-02 09:40:06 +0000 | [diff] [blame] | 49 | self.assertEqual(builtins._, 42) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 50 | |
| 51 | del sys.stdout |
| 52 | self.assertRaises(RuntimeError, dh, 42) |
| 53 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 54 | def test_lost_displayhook(self): |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 55 | del sys.displayhook |
| 56 | code = compile("42", "<string>", "single") |
| 57 | self.assertRaises(RuntimeError, eval, code) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 58 | |
| 59 | def test_custom_displayhook(self): |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 60 | def baddisplayhook(obj): |
| 61 | raise ValueError |
| 62 | sys.displayhook = baddisplayhook |
| 63 | code = compile("42", "<string>", "single") |
| 64 | self.assertRaises(ValueError, eval, code) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 65 | |
| 66 | def test_original_excepthook(self): |
Guido van Rossum | 34d1928 | 2007-08-09 01:03:29 +0000 | [diff] [blame] | 67 | err = io.StringIO() |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 68 | sys.stderr = err |
| 69 | |
| 70 | eh = sys.__excepthook__ |
| 71 | |
| 72 | self.assertRaises(TypeError, eh) |
| 73 | try: |
| 74 | raise ValueError(42) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 75 | except ValueError as exc: |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 76 | eh(*sys.exc_info()) |
| 77 | |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 78 | self.assertTrue(err.getvalue().endswith("ValueError: 42\n")) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 79 | |
Benjamin Peterson | bc74e5b | 2008-08-23 20:19:17 +0000 | [diff] [blame] | 80 | def test_excepthook(self): |
| 81 | with test.support.captured_output("stderr") as stderr: |
| 82 | sys.excepthook(1, '1', 1) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 83 | self.assertTrue("TypeError: print_exception(): Exception expected for " \ |
Benjamin Peterson | bc74e5b | 2008-08-23 20:19:17 +0000 | [diff] [blame] | 84 | "value, str found" in stderr.getvalue()) |
| 85 | |
Walter Dörwald | e7028ac | 2003-02-03 23:05:27 +0000 | [diff] [blame] | 86 | # FIXME: testing the code for a lost or replaced excepthook in |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 87 | # Python/pythonrun.c::PyErr_PrintEx() is tricky. |
| 88 | |
| 89 | def test_exit(self): |
Victor Stinner | e9fb319 | 2010-05-17 08:58:51 +0000 | [diff] [blame] | 90 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 91 | self.assertRaises(TypeError, sys.exit, 42, 42) |
| 92 | |
| 93 | # call without argument |
| 94 | try: |
| 95 | sys.exit(0) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 96 | except SystemExit as exc: |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 97 | self.assertEquals(exc.code, 0) |
| 98 | except: |
| 99 | self.fail("wrong exception") |
| 100 | else: |
| 101 | self.fail("no exception") |
| 102 | |
| 103 | # call with tuple argument with one entry |
| 104 | # entry will be unpacked |
| 105 | try: |
| 106 | sys.exit(42) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 107 | except SystemExit as exc: |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 108 | self.assertEquals(exc.code, 42) |
| 109 | except: |
| 110 | self.fail("wrong exception") |
| 111 | else: |
| 112 | self.fail("no exception") |
| 113 | |
| 114 | # call with integer argument |
| 115 | try: |
| 116 | sys.exit((42,)) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 117 | except SystemExit as exc: |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 118 | self.assertEquals(exc.code, 42) |
| 119 | except: |
| 120 | self.fail("wrong exception") |
| 121 | else: |
| 122 | self.fail("no exception") |
| 123 | |
| 124 | # call with string argument |
| 125 | try: |
| 126 | sys.exit("exit") |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 127 | except SystemExit as exc: |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 128 | self.assertEquals(exc.code, "exit") |
| 129 | except: |
| 130 | self.fail("wrong exception") |
| 131 | else: |
| 132 | self.fail("no exception") |
| 133 | |
| 134 | # call with tuple argument with two entries |
| 135 | try: |
| 136 | sys.exit((17, 23)) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 137 | except SystemExit as exc: |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 138 | self.assertEquals(exc.code, (17, 23)) |
| 139 | except: |
| 140 | self.fail("wrong exception") |
| 141 | else: |
| 142 | self.fail("no exception") |
| 143 | |
Michael W. Hudson | f058858 | 2005-02-15 15:26:11 +0000 | [diff] [blame] | 144 | # test that the exit machinery handles SystemExits properly |
Michael W. Hudson | f058858 | 2005-02-15 15:26:11 +0000 | [diff] [blame] | 145 | rc = subprocess.call([sys.executable, "-c", |
| 146 | "raise SystemExit(47)"]) |
| 147 | self.assertEqual(rc, 47) |
Tim Peters | f0db38d | 2005-02-15 21:50:12 +0000 | [diff] [blame] | 148 | |
Victor Stinner | 7126dbc | 2010-05-21 23:45:42 +0000 | [diff] [blame] | 149 | def check_exit_message(code, expected, env=None): |
Victor Stinner | e9fb319 | 2010-05-17 08:58:51 +0000 | [diff] [blame] | 150 | process = subprocess.Popen([sys.executable, "-c", code], |
Victor Stinner | 7126dbc | 2010-05-21 23:45:42 +0000 | [diff] [blame] | 151 | stderr=subprocess.PIPE, env=env) |
Victor Stinner | e9fb319 | 2010-05-17 08:58:51 +0000 | [diff] [blame] | 152 | stdout, stderr = process.communicate() |
| 153 | self.assertEqual(process.returncode, 1) |
Victor Stinner | 7cf7d72 | 2010-05-17 14:36:43 +0000 | [diff] [blame] | 154 | self.assertTrue(stderr.startswith(expected), |
Victor Stinner | c098385 | 2010-05-17 19:57:40 +0000 | [diff] [blame] | 155 | "%s doesn't start with %s" % (ascii(stderr), ascii(expected))) |
Victor Stinner | e9fb319 | 2010-05-17 08:58:51 +0000 | [diff] [blame] | 156 | |
| 157 | # test that stderr buffer if flushed before the exit message is written |
| 158 | # into stderr |
| 159 | check_exit_message( |
| 160 | r'import sys; sys.stderr.write("unflushed,"); sys.exit("message")', |
| 161 | b"unflushed,message") |
| 162 | |
Victor Stinner | 372ac5e | 2010-05-17 01:26:01 +0000 | [diff] [blame] | 163 | # test that the exit message is written with backslashreplace error |
| 164 | # handler to stderr |
Victor Stinner | e9fb319 | 2010-05-17 08:58:51 +0000 | [diff] [blame] | 165 | check_exit_message( |
| 166 | r'import sys; sys.exit("surrogates:\uDCFF")', |
| 167 | b"surrogates:\\udcff") |
Victor Stinner | 372ac5e | 2010-05-17 01:26:01 +0000 | [diff] [blame] | 168 | |
Victor Stinner | 7126dbc | 2010-05-21 23:45:42 +0000 | [diff] [blame] | 169 | # test that the unicode message is encoded to the stderr encoding |
| 170 | # instead of the default encoding (utf8) |
| 171 | env = os.environ.copy() |
| 172 | env['PYTHONIOENCODING'] = 'latin-1' |
| 173 | check_exit_message( |
| 174 | r'import sys; sys.exit("h\xe9")', |
| 175 | b"h\xe9", env=env) |
| 176 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 177 | def test_getdefaultencoding(self): |
Walter Dörwald | 4aeaa96 | 2007-05-22 16:13:46 +0000 | [diff] [blame] | 178 | self.assertRaises(TypeError, sys.getdefaultencoding, 42) |
| 179 | # 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] | 180 | self.assertIsInstance(sys.getdefaultencoding(), str) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 181 | |
Alexander Belopolsky | 07de165 | 2010-07-25 15:05:42 +0000 | [diff] [blame] | 182 | # testing sys.settrace() is done in test_sys_settrace.py |
| 183 | # testing sys.setprofile() is done in test_sys_setprofile.py |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 184 | |
| 185 | def test_setcheckinterval(self): |
Antoine Pitrou | c3b0757 | 2009-11-13 22:19:19 +0000 | [diff] [blame] | 186 | with warnings.catch_warnings(): |
| 187 | warnings.simplefilter("ignore") |
| 188 | self.assertRaises(TypeError, sys.setcheckinterval) |
| 189 | orig = sys.getcheckinterval() |
| 190 | for n in 0, 100, 120, orig: # orig last to restore starting state |
| 191 | sys.setcheckinterval(n) |
| 192 | self.assertEquals(sys.getcheckinterval(), n) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 193 | |
Victor Stinner | 45df820 | 2010-04-28 22:31:17 +0000 | [diff] [blame] | 194 | @unittest.skipUnless(threading, 'Threading required for this test.') |
Antoine Pitrou | 074e5ed | 2009-11-10 19:50:40 +0000 | [diff] [blame] | 195 | def test_switchinterval(self): |
| 196 | self.assertRaises(TypeError, sys.setswitchinterval) |
| 197 | self.assertRaises(TypeError, sys.setswitchinterval, "a") |
| 198 | self.assertRaises(ValueError, sys.setswitchinterval, -1.0) |
| 199 | self.assertRaises(ValueError, sys.setswitchinterval, 0.0) |
| 200 | orig = sys.getswitchinterval() |
| 201 | # sanity check |
| 202 | self.assertTrue(orig < 0.5, orig) |
| 203 | try: |
| 204 | for n in 0.00001, 0.05, 3.0, orig: |
| 205 | sys.setswitchinterval(n) |
| 206 | self.assertAlmostEquals(sys.getswitchinterval(), n) |
| 207 | finally: |
| 208 | sys.setswitchinterval(orig) |
| 209 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 210 | def test_recursionlimit(self): |
Tim Peters | f2715e0 | 2003-02-19 02:35:07 +0000 | [diff] [blame] | 211 | self.assertRaises(TypeError, sys.getrecursionlimit, 42) |
| 212 | oldlimit = sys.getrecursionlimit() |
| 213 | self.assertRaises(TypeError, sys.setrecursionlimit) |
| 214 | self.assertRaises(ValueError, sys.setrecursionlimit, -42) |
| 215 | sys.setrecursionlimit(10000) |
| 216 | self.assertEqual(sys.getrecursionlimit(), 10000) |
| 217 | sys.setrecursionlimit(oldlimit) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 218 | |
Antoine Pitrou | 652e707 | 2009-03-13 19:25:20 +0000 | [diff] [blame] | 219 | def test_recursionlimit_recovery(self): |
| 220 | # NOTE: this test is slightly fragile in that it depends on the current |
| 221 | # recursion count when executing the test being low enough so as to |
| 222 | # trigger the recursion recovery detection in the _Py_MakeEndRecCheck |
| 223 | # macro (see ceval.h). |
| 224 | oldlimit = sys.getrecursionlimit() |
| 225 | def f(): |
| 226 | f() |
| 227 | try: |
| 228 | for i in (50, 1000): |
| 229 | # Issue #5392: stack overflow after hitting recursion limit twice |
| 230 | sys.setrecursionlimit(i) |
| 231 | self.assertRaises(RuntimeError, f) |
| 232 | self.assertRaises(RuntimeError, f) |
| 233 | finally: |
| 234 | sys.setrecursionlimit(oldlimit) |
| 235 | |
| 236 | def test_recursionlimit_fatalerror(self): |
| 237 | # A fatal error occurs if a second recursion limit is hit when recovering |
| 238 | # from a first one. |
Antoine Pitrou | 17dc446 | 2009-04-04 17:36:05 +0000 | [diff] [blame] | 239 | if os.name == "nt": |
| 240 | raise unittest.SkipTest( |
| 241 | "under Windows, test would generate a spurious crash dialog") |
Antoine Pitrou | 652e707 | 2009-03-13 19:25:20 +0000 | [diff] [blame] | 242 | code = textwrap.dedent(""" |
| 243 | import sys |
| 244 | |
| 245 | def f(): |
| 246 | try: |
| 247 | f() |
| 248 | except RuntimeError: |
| 249 | f() |
| 250 | |
| 251 | sys.setrecursionlimit(%d) |
| 252 | f()""") |
| 253 | for i in (50, 1000): |
| 254 | sub = subprocess.Popen([sys.executable, '-c', code % i], |
| 255 | stderr=subprocess.PIPE) |
| 256 | err = sub.communicate()[1] |
| 257 | self.assertTrue(sub.returncode, sub.returncode) |
| 258 | self.assertTrue( |
| 259 | b"Fatal Python error: Cannot recover from stack overflow" in err, |
| 260 | err) |
| 261 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 262 | def test_getwindowsversion(self): |
Eric Smith | 05f33744 | 2010-01-27 01:25:02 +0000 | [diff] [blame] | 263 | # Raise SkipTest if sys doesn't have getwindowsversion attribute |
Eric Smith | d8aef76 | 2010-01-27 01:38:34 +0000 | [diff] [blame] | 264 | test.support.get_attribute(sys, "getwindowsversion") |
Eric Smith | 05f33744 | 2010-01-27 01:25:02 +0000 | [diff] [blame] | 265 | v = sys.getwindowsversion() |
Brian Curtin | 808e1ad | 2010-07-08 22:13:25 +0000 | [diff] [blame] | 266 | self.assertEqual(len(v), 5) |
Eric Smith | 05f33744 | 2010-01-27 01:25:02 +0000 | [diff] [blame] | 267 | self.assertIsInstance(v[0], int) |
| 268 | self.assertIsInstance(v[1], int) |
| 269 | self.assertIsInstance(v[2], int) |
| 270 | self.assertIsInstance(v[3], int) |
| 271 | self.assertIsInstance(v[4], str) |
| 272 | self.assertRaises(IndexError, operator.getitem, v, 5) |
| 273 | self.assertIsInstance(v.major, int) |
| 274 | self.assertIsInstance(v.minor, int) |
| 275 | self.assertIsInstance(v.build, int) |
| 276 | self.assertIsInstance(v.platform, int) |
| 277 | self.assertIsInstance(v.service_pack, str) |
Eric Smith | a1f20b9 | 2010-01-27 02:14:26 +0000 | [diff] [blame] | 278 | self.assertIsInstance(v.service_pack_minor, int) |
| 279 | self.assertIsInstance(v.service_pack_major, int) |
| 280 | self.assertIsInstance(v.suite_mask, int) |
| 281 | self.assertIsInstance(v.product_type, int) |
Eric Smith | 05f33744 | 2010-01-27 01:25:02 +0000 | [diff] [blame] | 282 | self.assertEqual(v[0], v.major) |
| 283 | self.assertEqual(v[1], v.minor) |
| 284 | self.assertEqual(v[2], v.build) |
| 285 | self.assertEqual(v[3], v.platform) |
| 286 | self.assertEqual(v[4], v.service_pack) |
Eric Smith | f7bb578 | 2010-01-27 00:44:57 +0000 | [diff] [blame] | 287 | |
Eric Smith | 05f33744 | 2010-01-27 01:25:02 +0000 | [diff] [blame] | 288 | # This is how platform.py calls it. Make sure tuple |
| 289 | # still has 5 elements |
| 290 | maj, min, buildno, plat, csd = sys.getwindowsversion() |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 291 | |
Barry Warsaw | e94a37f | 2008-10-17 01:29:56 +0000 | [diff] [blame] | 292 | def test_call_tracing(self): |
| 293 | self.assertRaises(TypeError, sys.call_tracing, type, 2) |
| 294 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 295 | def test_dlopenflags(self): |
| 296 | if hasattr(sys, "setdlopenflags"): |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 297 | self.assertTrue(hasattr(sys, "getdlopenflags")) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 298 | self.assertRaises(TypeError, sys.getdlopenflags, 42) |
| 299 | oldflags = sys.getdlopenflags() |
| 300 | self.assertRaises(TypeError, sys.setdlopenflags) |
| 301 | sys.setdlopenflags(oldflags+1) |
| 302 | self.assertEqual(sys.getdlopenflags(), oldflags+1) |
| 303 | sys.setdlopenflags(oldflags) |
| 304 | |
| 305 | def test_refcount(self): |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 306 | # n here must be a global in order for this test to pass while |
| 307 | # tracing with a python function. Tracing calls PyFrame_FastToLocals |
| 308 | # which will add a copy of any locals to the frame object, causing |
| 309 | # the reference count to increase by 2 instead of 1. |
| 310 | global n |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 311 | self.assertRaises(TypeError, sys.getrefcount) |
| 312 | c = sys.getrefcount(None) |
| 313 | n = None |
| 314 | self.assertEqual(sys.getrefcount(None), c+1) |
| 315 | del n |
| 316 | self.assertEqual(sys.getrefcount(None), c) |
| 317 | if hasattr(sys, "gettotalrefcount"): |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 318 | self.assertIsInstance(sys.gettotalrefcount(), int) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 319 | |
| 320 | def test_getframe(self): |
| 321 | self.assertRaises(TypeError, sys._getframe, 42, 42) |
Neal Norwitz | eb2a5ef | 2003-02-18 15:22:10 +0000 | [diff] [blame] | 322 | self.assertRaises(ValueError, sys._getframe, 2000000000) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 323 | self.assertTrue( |
Christian Heimes | 4a22b5d | 2007-11-25 09:39:14 +0000 | [diff] [blame] | 324 | SysModuleTest.test_getframe.__code__ \ |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 325 | is sys._getframe().f_code |
| 326 | ) |
| 327 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 328 | # sys._current_frames() is a CPython-only gimmick. |
| 329 | def test_current_frames(self): |
| 330 | have_threads = True |
| 331 | try: |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 332 | import _thread |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 333 | except ImportError: |
| 334 | have_threads = False |
| 335 | |
| 336 | if have_threads: |
| 337 | self.current_frames_with_threads() |
| 338 | else: |
| 339 | self.current_frames_without_threads() |
| 340 | |
| 341 | # Test sys._current_frames() in a WITH_THREADS build. |
Antoine Pitrou | 836f0e2 | 2009-10-27 19:25:57 +0000 | [diff] [blame] | 342 | @test.support.reap_threads |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 343 | def current_frames_with_threads(self): |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 344 | import threading, _thread |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 345 | import traceback |
| 346 | |
| 347 | # Spawn a thread that blocks at a known place. Then the main |
| 348 | # thread does sys._current_frames(), and verifies that the frames |
| 349 | # returned make sense. |
| 350 | entered_g = threading.Event() |
| 351 | leave_g = threading.Event() |
| 352 | thread_info = [] # the thread's id |
| 353 | |
| 354 | def f123(): |
| 355 | g456() |
| 356 | |
| 357 | def g456(): |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 358 | thread_info.append(_thread.get_ident()) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 359 | entered_g.set() |
| 360 | leave_g.wait() |
| 361 | |
| 362 | t = threading.Thread(target=f123) |
| 363 | t.start() |
| 364 | entered_g.wait() |
| 365 | |
| 366 | # At this point, t has finished its entered_g.set(), although it's |
| 367 | # impossible to guess whether it's still on that line or has moved on |
| 368 | # to its leave_g.wait(). |
| 369 | self.assertEqual(len(thread_info), 1) |
| 370 | thread_id = thread_info[0] |
| 371 | |
| 372 | d = sys._current_frames() |
| 373 | |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 374 | main_id = _thread.get_ident() |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 375 | self.assertIn(main_id, d) |
| 376 | self.assertIn(thread_id, d) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 377 | |
| 378 | # Verify that the captured main-thread frame is _this_ frame. |
| 379 | frame = d.pop(main_id) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 380 | self.assertTrue(frame is sys._getframe()) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 381 | |
| 382 | # Verify that the captured thread frame is blocked in g456, called |
| 383 | # from f123. This is a litte tricky, since various bits of |
| 384 | # threading.py are also in the thread's call stack. |
| 385 | frame = d.pop(thread_id) |
| 386 | stack = traceback.extract_stack(frame) |
| 387 | for i, (filename, lineno, funcname, sourceline) in enumerate(stack): |
| 388 | if funcname == "f123": |
| 389 | break |
| 390 | else: |
| 391 | self.fail("didn't find f123() on thread's call stack") |
| 392 | |
| 393 | self.assertEqual(sourceline, "g456()") |
| 394 | |
| 395 | # And the next record must be for g456(). |
| 396 | filename, lineno, funcname, sourceline = stack[i+1] |
| 397 | self.assertEqual(funcname, "g456") |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 398 | self.assertIn(sourceline, ["leave_g.wait()", "entered_g.set()"]) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 399 | |
| 400 | # Reap the spawned thread. |
| 401 | leave_g.set() |
| 402 | t.join() |
| 403 | |
| 404 | # Test sys._current_frames() when thread support doesn't exist. |
| 405 | def current_frames_without_threads(self): |
| 406 | # Not much happens here: there is only one thread, with artificial |
| 407 | # "thread id" 0. |
| 408 | d = sys._current_frames() |
| 409 | self.assertEqual(len(d), 1) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 410 | self.assertIn(0, d) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 411 | self.assertTrue(d[0] is sys._getframe()) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 412 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 413 | def test_attributes(self): |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 414 | self.assertIsInstance(sys.api_version, int) |
| 415 | self.assertIsInstance(sys.argv, list) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 416 | self.assertIn(sys.byteorder, ("little", "big")) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 417 | self.assertIsInstance(sys.builtin_module_names, tuple) |
| 418 | self.assertIsInstance(sys.copyright, str) |
| 419 | self.assertIsInstance(sys.exec_prefix, str) |
| 420 | self.assertIsInstance(sys.executable, str) |
Christian Heimes | 9385266 | 2007-12-01 12:22:32 +0000 | [diff] [blame] | 421 | self.assertEqual(len(sys.float_info), 11) |
Christian Heimes | d32ed6f | 2008-01-14 18:49:24 +0000 | [diff] [blame] | 422 | self.assertEqual(sys.float_info.radix, 2) |
Mark Dickinson | bd79264 | 2009-03-18 20:06:12 +0000 | [diff] [blame] | 423 | self.assertEqual(len(sys.int_info), 2) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 424 | self.assertTrue(sys.int_info.bits_per_digit % 5 == 0) |
| 425 | self.assertTrue(sys.int_info.sizeof_digit >= 1) |
Benjamin Peterson | ef3e4c2 | 2009-04-11 19:48:14 +0000 | [diff] [blame] | 426 | self.assertEqual(type(sys.int_info.bits_per_digit), int) |
| 427 | self.assertEqual(type(sys.int_info.sizeof_digit), int) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 428 | self.assertIsInstance(sys.hexversion, int) |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 429 | |
| 430 | self.assertEqual(len(sys.hash_info), 5) |
| 431 | self.assertLess(sys.hash_info.modulus, 2**sys.hash_info.width) |
| 432 | # sys.hash_info.modulus should be a prime; we do a quick |
| 433 | # probable primality test (doesn't exclude the possibility of |
| 434 | # a Carmichael number) |
| 435 | for x in range(1, 100): |
| 436 | self.assertEqual( |
| 437 | pow(x, sys.hash_info.modulus-1, sys.hash_info.modulus), |
| 438 | 1, |
| 439 | "sys.hash_info.modulus {} is a non-prime".format( |
| 440 | sys.hash_info.modulus) |
| 441 | ) |
| 442 | self.assertIsInstance(sys.hash_info.inf, int) |
| 443 | self.assertIsInstance(sys.hash_info.nan, int) |
| 444 | self.assertIsInstance(sys.hash_info.imag, int) |
| 445 | |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 446 | self.assertIsInstance(sys.maxsize, int) |
| 447 | self.assertIsInstance(sys.maxunicode, int) |
| 448 | self.assertIsInstance(sys.platform, str) |
| 449 | self.assertIsInstance(sys.prefix, str) |
| 450 | self.assertIsInstance(sys.version, str) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 451 | vi = sys.version_info |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 452 | self.assertIsInstance(vi[:], tuple) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 453 | self.assertEqual(len(vi), 5) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 454 | self.assertIsInstance(vi[0], int) |
| 455 | self.assertIsInstance(vi[1], int) |
| 456 | self.assertIsInstance(vi[2], int) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 457 | self.assertIn(vi[3], ("alpha", "beta", "candidate", "final")) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 458 | self.assertIsInstance(vi[4], int) |
| 459 | self.assertIsInstance(vi.major, int) |
| 460 | self.assertIsInstance(vi.minor, int) |
| 461 | self.assertIsInstance(vi.micro, int) |
Ezio Melotti | b58e0bd | 2010-01-23 15:40:09 +0000 | [diff] [blame] | 462 | self.assertIn(vi.releaselevel, ("alpha", "beta", "candidate", "final")) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 463 | self.assertIsInstance(vi.serial, int) |
Eric Smith | 0e5b562 | 2009-02-06 01:32:42 +0000 | [diff] [blame] | 464 | self.assertEqual(vi[0], vi.major) |
| 465 | self.assertEqual(vi[1], vi.minor) |
| 466 | self.assertEqual(vi[2], vi.micro) |
| 467 | self.assertEqual(vi[3], vi.releaselevel) |
| 468 | self.assertEqual(vi[4], vi.serial) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 469 | self.assertTrue(vi > (1,0,0)) |
Mark Dickinson | 55d110c | 2009-10-24 14:04:48 +0000 | [diff] [blame] | 470 | self.assertIsInstance(sys.float_repr_style, str) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 471 | self.assertIn(sys.float_repr_style, ('short', 'legacy')) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 472 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 473 | def test_43581(self): |
Georg Brandl | 0312494 | 2008-06-10 15:50:56 +0000 | [diff] [blame] | 474 | # Can't use sys.stdout, as this is a StringIO object when |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 475 | # the test runs under regrtest. |
Guido van Rossum | e61fd5b | 2007-07-11 12:20:59 +0000 | [diff] [blame] | 476 | self.assertEqual(sys.__stdout__.encoding, sys.__stderr__.encoding) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 477 | |
Georg Brandl | 66a796e | 2006-12-19 20:50:34 +0000 | [diff] [blame] | 478 | def test_intern(self): |
Georg Brandl | 0352655 | 2009-10-27 23:00:28 +0000 | [diff] [blame] | 479 | global numruns |
| 480 | numruns += 1 |
Georg Brandl | 66a796e | 2006-12-19 20:50:34 +0000 | [diff] [blame] | 481 | self.assertRaises(TypeError, sys.intern) |
Georg Brandl | 0352655 | 2009-10-27 23:00:28 +0000 | [diff] [blame] | 482 | s = "never interned before" + str(numruns) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 483 | self.assertTrue(sys.intern(s) is s) |
Georg Brandl | 66a796e | 2006-12-19 20:50:34 +0000 | [diff] [blame] | 484 | s2 = s.swapcase().swapcase() |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 485 | self.assertTrue(sys.intern(s2) is s) |
Georg Brandl | 66a796e | 2006-12-19 20:50:34 +0000 | [diff] [blame] | 486 | |
| 487 | # Subclasses of string can't be interned, because they |
| 488 | # provide too much opportunity for insane things to happen. |
| 489 | # We don't want them in the interned dict and if they aren't |
| 490 | # actually interned, we don't want to create the appearance |
| 491 | # that they are by allowing intern() to succeeed. |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 492 | class S(str): |
Georg Brandl | 66a796e | 2006-12-19 20:50:34 +0000 | [diff] [blame] | 493 | def __hash__(self): |
| 494 | return 123 |
| 495 | |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 496 | self.assertRaises(TypeError, sys.intern, S("abc")) |
Martin v. Löwis | 5b22213 | 2007-06-10 09:51:05 +0000 | [diff] [blame] | 497 | |
Victor Stinner | 6baded4 | 2010-05-17 01:13:37 +0000 | [diff] [blame] | 498 | def test_main_invalid_unicode(self): |
| 499 | import locale |
| 500 | non_decodable = b"\xff" |
| 501 | encoding = locale.getpreferredencoding() |
| 502 | try: |
| 503 | non_decodable.decode(encoding) |
| 504 | except UnicodeDecodeError: |
| 505 | pass |
| 506 | else: |
| 507 | self.skipTest('%r is decodable with encoding %s' |
| 508 | % (non_decodable, encoding)) |
| 509 | code = b'print("' + non_decodable + b'")' |
| 510 | p = subprocess.Popen([sys.executable, "-c", code], stderr=subprocess.PIPE) |
| 511 | stdout, stderr = p.communicate() |
| 512 | self.assertEqual(p.returncode, 1) |
Victor Stinner | 398356b | 2010-08-18 22:23:22 +0000 | [diff] [blame] | 513 | lines = stderr.splitlines() |
| 514 | self.assertGreaterEqual(len(lines), 2) |
| 515 | self.assertEqual(b"Unable to decode the command from the command line:", lines[0]) |
| 516 | self.assertIn(br"UnicodeEncodeError:", lines[1]) |
Georg Brandl | 66a796e | 2006-12-19 20:50:34 +0000 | [diff] [blame] | 517 | |
Christian Heimes | d32ed6f | 2008-01-14 18:49:24 +0000 | [diff] [blame] | 518 | def test_sys_flags(self): |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 519 | self.assertTrue(sys.flags) |
Christian Heimes | d32ed6f | 2008-01-14 18:49:24 +0000 | [diff] [blame] | 520 | attrs = ("debug", "division_warning", |
| 521 | "inspect", "interactive", "optimize", "dont_write_bytecode", |
Georg Brandl | c5e88d5 | 2008-06-06 09:02:07 +0000 | [diff] [blame] | 522 | "no_user_site", "no_site", "ignore_environment", "verbose", |
Benjamin Peterson | 699adb9 | 2008-05-08 22:27:58 +0000 | [diff] [blame] | 523 | "bytes_warning") |
Christian Heimes | d32ed6f | 2008-01-14 18:49:24 +0000 | [diff] [blame] | 524 | for attr in attrs: |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 525 | self.assertTrue(hasattr(sys.flags, attr), attr) |
Christian Heimes | d32ed6f | 2008-01-14 18:49:24 +0000 | [diff] [blame] | 526 | self.assertEqual(type(getattr(sys.flags, attr)), int, attr) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 527 | self.assertTrue(repr(sys.flags)) |
Georg Brandl | c5e88d5 | 2008-06-06 09:02:07 +0000 | [diff] [blame] | 528 | self.assertEqual(len(sys.flags), len(attrs)) |
Christian Heimes | d32ed6f | 2008-01-14 18:49:24 +0000 | [diff] [blame] | 529 | |
Christian Heimes | 15ebc88 | 2008-02-04 18:48:49 +0000 | [diff] [blame] | 530 | def test_clear_type_cache(self): |
| 531 | sys._clear_type_cache() |
| 532 | |
Martin v. Löwis | 0f59989 | 2008-06-02 11:13:03 +0000 | [diff] [blame] | 533 | def test_ioencoding(self): |
Martin v. Löwis | 0f59989 | 2008-06-02 11:13:03 +0000 | [diff] [blame] | 534 | env = dict(os.environ) |
| 535 | |
| 536 | # Test character: cent sign, encoded as 0x4A (ASCII J) in CP424, |
| 537 | # not representable in ASCII. |
| 538 | |
| 539 | env["PYTHONIOENCODING"] = "cp424" |
| 540 | p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'], |
| 541 | stdout = subprocess.PIPE, env=env) |
Antoine Pitrou | 836f0e2 | 2009-10-27 19:25:57 +0000 | [diff] [blame] | 542 | out = p.communicate()[0].strip() |
Martin v. Löwis | 0f59989 | 2008-06-02 11:13:03 +0000 | [diff] [blame] | 543 | self.assertEqual(out, "\xa2\n".encode("cp424")) |
| 544 | |
| 545 | env["PYTHONIOENCODING"] = "ascii:replace" |
| 546 | p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'], |
| 547 | stdout = subprocess.PIPE, env=env) |
Antoine Pitrou | 836f0e2 | 2009-10-27 19:25:57 +0000 | [diff] [blame] | 548 | out = p.communicate()[0].strip() |
Martin v. Löwis | 0f59989 | 2008-06-02 11:13:03 +0000 | [diff] [blame] | 549 | self.assertEqual(out, b'?') |
| 550 | |
Victor Stinner | 171ba05 | 2010-03-12 14:20:59 +0000 | [diff] [blame] | 551 | def test_executable(self): |
| 552 | # Issue #7774: Ensure that sys.executable is an empty string if argv[0] |
| 553 | # has been set to an non existent program name and Python is unable to |
| 554 | # retrieve the real program name |
Florent Xicluna | 02ea12b2 | 2010-07-28 16:39:41 +0000 | [diff] [blame] | 555 | |
Victor Stinner | 171ba05 | 2010-03-12 14:20:59 +0000 | [diff] [blame] | 556 | # For a normal installation, it should work without 'cwd' |
| 557 | # argument. For test runs in the build directory, see #7774. |
| 558 | python_dir = os.path.dirname(os.path.realpath(sys.executable)) |
| 559 | p = subprocess.Popen( |
| 560 | ["nonexistent", "-c", |
| 561 | 'import sys; print(sys.executable.encode("ascii", "backslashreplace"))'], |
| 562 | executable=sys.executable, stdout=subprocess.PIPE, cwd=python_dir) |
| 563 | stdout = p.communicate()[0] |
| 564 | executable = stdout.strip().decode("ASCII") |
| 565 | p.wait() |
| 566 | self.assertIn(executable, ["b''", repr(sys.executable.encode("ascii", "backslashreplace"))]) |
| 567 | |
Victor Stinner | 85ca2af | 2010-08-19 11:23:47 +0000 | [diff] [blame] | 568 | def check_fsencoding(self, fs_encoding, expected=None): |
| 569 | self.assertIsNotNone(fs_encoding) |
| 570 | codecs.lookup(fs_encoding) |
| 571 | if expected: |
| 572 | self.assertEqual(fs_encoding, expected) |
| 573 | |
Victor Stinner | c732e3b | 2010-08-18 22:44:15 +0000 | [diff] [blame] | 574 | def test_getfilesystemencoding(self): |
Victor Stinner | c732e3b | 2010-08-18 22:44:15 +0000 | [diff] [blame] | 575 | fs_encoding = sys.getfilesystemencoding() |
Victor Stinner | 85ca2af | 2010-08-19 11:23:47 +0000 | [diff] [blame] | 576 | if sys.platform == 'darwin': |
| 577 | expected = 'utf-8' |
| 578 | elif sys.platform == 'win32': |
| 579 | expected = 'mbcs' |
| 580 | else: |
| 581 | expected = None |
Victor Stinner | 9943524 | 2010-08-19 11:30:09 +0000 | [diff] [blame^] | 582 | self.check_fsencoding(fs_encoding, expected) |
Victor Stinner | c732e3b | 2010-08-18 22:44:15 +0000 | [diff] [blame] | 583 | |
Victor Stinner | 85ca2af | 2010-08-19 11:23:47 +0000 | [diff] [blame] | 584 | @unittest.skipIf(sys.platform in ('win32', 'darwin'), |
| 585 | 'PYTHONFSENCODING is ignored on Windows and Mac OS X') |
| 586 | def test_pythonfsencoding(self): |
Victor Stinner | c732e3b | 2010-08-18 22:44:15 +0000 | [diff] [blame] | 587 | def get_fsencoding(env): |
| 588 | output = subprocess.check_output( |
| 589 | [sys.executable, "-c", |
| 590 | "import sys; print(sys.getfilesystemencoding())"], |
| 591 | env=env) |
| 592 | return output.rstrip().decode('ascii') |
| 593 | |
| 594 | try: |
| 595 | sys.executable.encode('ascii') |
| 596 | except UnicodeEncodeError: |
| 597 | # Python doesn't start with ASCII locale if its path is not ASCII, |
| 598 | # see issue #8611 |
| 599 | pass |
| 600 | else: |
| 601 | # Even in C locale |
| 602 | env = os.environ.copy() |
| 603 | env['LANG'] = 'C' |
| 604 | try: |
| 605 | del env['PYTHONFSENCODING'] |
| 606 | except KeyError: |
| 607 | pass |
Victor Stinner | 85ca2af | 2010-08-19 11:23:47 +0000 | [diff] [blame] | 608 | self.check_fsencoding(get_fsencoding(env), 'ascii') |
Victor Stinner | c732e3b | 2010-08-18 22:44:15 +0000 | [diff] [blame] | 609 | |
| 610 | # Filesystem encoding is hardcoded on Windows and Mac OS X |
Victor Stinner | 85ca2af | 2010-08-19 11:23:47 +0000 | [diff] [blame] | 611 | for encoding in ('ascii', 'cp850', 'iso8859-1', 'utf-8'): |
| 612 | env = os.environ.copy() |
| 613 | env['PYTHONFSENCODING'] = encoding |
| 614 | self.check_fsencoding(get_fsencoding(env), encoding) |
Victor Stinner | c732e3b | 2010-08-18 22:44:15 +0000 | [diff] [blame] | 615 | |
| 616 | |
| 617 | def test_setfilesystemencoding(self): |
| 618 | old = sys.getfilesystemencoding() |
| 619 | try: |
| 620 | sys.setfilesystemencoding("iso-8859-1") |
| 621 | self.assertEqual(sys.getfilesystemencoding(), "iso-8859-1") |
| 622 | finally: |
| 623 | sys.setfilesystemencoding(old) |
| 624 | try: |
| 625 | self.assertRaises(LookupError, sys.setfilesystemencoding, "xxx") |
| 626 | finally: |
| 627 | sys.setfilesystemencoding(old) |
| 628 | |
Martin v. Löwis | 0f59989 | 2008-06-02 11:13:03 +0000 | [diff] [blame] | 629 | |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 630 | class SizeofTest(unittest.TestCase): |
| 631 | |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 632 | TPFLAGS_HAVE_GC = 1<<14 |
| 633 | TPFLAGS_HEAPTYPE = 1<<9 |
| 634 | |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 635 | def setUp(self): |
Robert Schuppenies | 4d45bfe | 2008-06-28 23:58:47 +0000 | [diff] [blame] | 636 | self.c = len(struct.pack('c', ' ')) |
| 637 | self.H = len(struct.pack('H', 0)) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 638 | self.i = len(struct.pack('i', 0)) |
| 639 | self.l = len(struct.pack('l', 0)) |
Robert Schuppenies | 4d45bfe | 2008-06-28 23:58:47 +0000 | [diff] [blame] | 640 | self.P = len(struct.pack('P', 0)) |
| 641 | # due to missing size_t information from struct, it is assumed that |
| 642 | # sizeof(Py_ssize_t) = sizeof(void*) |
| 643 | self.header = 'PP' |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 644 | self.vheader = self.header + 'P' |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 645 | if hasattr(sys, "gettotalrefcount"): |
Robert Schuppenies | 4d45bfe | 2008-06-28 23:58:47 +0000 | [diff] [blame] | 646 | self.header += '2P' |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 647 | self.vheader += '2P' |
Mark Dickinson | bd79264 | 2009-03-18 20:06:12 +0000 | [diff] [blame] | 648 | self.longdigit = sys.int_info.sizeof_digit |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 649 | import _testcapi |
| 650 | self.gc_headsize = _testcapi.SIZEOF_PYGC_HEAD |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 651 | self.file = open(test.support.TESTFN, 'wb') |
| 652 | |
| 653 | def tearDown(self): |
| 654 | self.file.close() |
| 655 | test.support.unlink(test.support.TESTFN) |
| 656 | |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 657 | def check_sizeof(self, o, size): |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 658 | result = sys.getsizeof(o) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 659 | # add GC header size |
| 660 | if ((type(o) == type) and (o.__flags__ & self.TPFLAGS_HEAPTYPE) or\ |
| 661 | ((type(o) != type) and (type(o).__flags__ & self.TPFLAGS_HAVE_GC))): |
| 662 | size += self.gc_headsize |
| 663 | msg = 'wrong size for %s: got %d, expected %d' \ |
| 664 | % (type(o), result, size) |
| 665 | self.assertEqual(result, size, msg) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 666 | |
Robert Schuppenies | 4d45bfe | 2008-06-28 23:58:47 +0000 | [diff] [blame] | 667 | def calcsize(self, fmt): |
| 668 | """Wrapper around struct.calcsize which enforces the alignment of the |
| 669 | end of a structure to the alignment requirement of pointer. |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 670 | |
Robert Schuppenies | 4d45bfe | 2008-06-28 23:58:47 +0000 | [diff] [blame] | 671 | Note: This wrapper should only be used if a pointer member is included |
| 672 | and no member with a size larger than a pointer exists. |
| 673 | """ |
| 674 | return struct.calcsize(fmt + '0P') |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 675 | |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 676 | def test_gc_head_size(self): |
| 677 | # 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] | 678 | h = self.header |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 679 | vh = self.vheader |
Robert Schuppenies | 4d45bfe | 2008-06-28 23:58:47 +0000 | [diff] [blame] | 680 | size = self.calcsize |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 681 | gc_header_size = self.gc_headsize |
| 682 | # bool objects are not gc tracked |
Mark Dickinson | bd79264 | 2009-03-18 20:06:12 +0000 | [diff] [blame] | 683 | self.assertEqual(sys.getsizeof(True), size(vh) + self.longdigit) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 684 | # but lists are |
| 685 | self.assertEqual(sys.getsizeof([]), size(vh + 'PP') + gc_header_size) |
| 686 | |
| 687 | def test_default(self): |
| 688 | h = self.header |
| 689 | vh = self.vheader |
| 690 | size = self.calcsize |
Mark Dickinson | bd79264 | 2009-03-18 20:06:12 +0000 | [diff] [blame] | 691 | self.assertEqual(sys.getsizeof(True), size(vh) + self.longdigit) |
| 692 | self.assertEqual(sys.getsizeof(True, -1), size(vh) + self.longdigit) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 693 | |
| 694 | def test_objecttypes(self): |
| 695 | # check all types defined in Objects/ |
| 696 | h = self.header |
| 697 | vh = self.vheader |
| 698 | size = self.calcsize |
| 699 | check = self.check_sizeof |
| 700 | # bool |
Mark Dickinson | bd79264 | 2009-03-18 20:06:12 +0000 | [diff] [blame] | 701 | check(True, size(vh) + self.longdigit) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 702 | # buffer |
| 703 | # XXX |
| 704 | # builtin_function_or_method |
| 705 | check(len, size(h + '3P')) |
| 706 | # bytearray |
| 707 | samples = [b'', b'u'*100000] |
| 708 | for sample in samples: |
| 709 | x = bytearray(sample) |
| 710 | check(x, size(vh + 'iPP') + x.__alloc__() * self.c) |
| 711 | # bytearray_iterator |
| 712 | check(iter(bytearray()), size(h + 'PP')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 713 | # cell |
| 714 | def get_cell(): |
| 715 | x = 42 |
| 716 | def inner(): |
| 717 | return x |
| 718 | return inner |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 719 | check(get_cell().__closure__[0], size(h + 'P')) |
Robert Schuppenies | 4efb518 | 2008-06-06 11:49:51 +0000 | [diff] [blame] | 720 | # code |
Collin Winter | 4222e9c | 2010-03-18 22:46:40 +0000 | [diff] [blame] | 721 | check(get_cell().__code__, size(h + '5i8Pi3P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 722 | # complex |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 723 | check(complex(0,1), size(h + '2d')) |
| 724 | # method_descriptor (descriptor object) |
| 725 | check(str.lower, size(h + '2PP')) |
| 726 | # classmethod_descriptor (descriptor object) |
| 727 | # XXX |
| 728 | # member_descriptor (descriptor object) |
| 729 | import datetime |
| 730 | check(datetime.timedelta.days, size(h + '2PP')) |
| 731 | # getset_descriptor (descriptor object) |
| 732 | import collections |
| 733 | check(collections.defaultdict.default_factory, size(h + '2PP')) |
| 734 | # wrapper_descriptor (descriptor object) |
| 735 | check(int.__add__, size(h + '2P2P')) |
| 736 | # method-wrapper (descriptor object) |
| 737 | check({}.__iter__, size(h + '2P')) |
| 738 | # dict |
| 739 | check({}, size(h + '3P2P' + 8*'P2P')) |
| 740 | longdict = {1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8} |
| 741 | check(longdict, size(h + '3P2P' + 8*'P2P') + 16*size('P2P')) |
| 742 | # dictionary-keyiterator |
| 743 | check({}.keys(), size(h + 'P')) |
| 744 | # dictionary-valueiterator |
| 745 | check({}.values(), size(h + 'P')) |
| 746 | # dictionary-itemiterator |
| 747 | check({}.items(), size(h + 'P')) |
| 748 | # dictproxy |
| 749 | class C(object): pass |
| 750 | check(C.__dict__, size(h + 'P')) |
| 751 | # BaseException |
| 752 | check(BaseException(), size(h + '5P')) |
| 753 | # UnicodeEncodeError |
| 754 | check(UnicodeEncodeError("", "", 0, 0, ""), size(h + '5P 2P2PP')) |
| 755 | # UnicodeDecodeError |
| 756 | # XXX |
| 757 | # check(UnicodeDecodeError("", "", 0, 0, ""), size(h + '5P2PP')) |
| 758 | # UnicodeTranslateError |
| 759 | check(UnicodeTranslateError("", 0, 1, ""), size(h + '5P 2P2PP')) |
| 760 | # ellipses |
| 761 | check(Ellipsis, size(h + '')) |
| 762 | # EncodingMap |
| 763 | import codecs, encodings.iso8859_3 |
| 764 | x = codecs.charmap_build(encodings.iso8859_3.decoding_table) |
| 765 | check(x, size(h + '32B2iB')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 766 | # enumerate |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 767 | check(enumerate([]), size(h + 'l3P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 768 | # reverse |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 769 | check(reversed(''), size(h + 'PP')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 770 | # float |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 771 | check(float(0), size(h + 'd')) |
| 772 | # sys.floatinfo |
| 773 | check(sys.float_info, size(vh) + self.P * len(sys.float_info)) |
| 774 | # frame |
| 775 | import inspect |
| 776 | CO_MAXBLOCKS = 20 |
| 777 | x = inspect.currentframe() |
| 778 | ncells = len(x.f_code.co_cellvars) |
| 779 | nfrees = len(x.f_code.co_freevars) |
| 780 | extras = x.f_code.co_stacksize + x.f_code.co_nlocals +\ |
| 781 | ncells + nfrees - 1 |
| 782 | 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] | 783 | # function |
| 784 | def func(): pass |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 785 | check(func, size(h + '11P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 786 | class c(): |
| 787 | @staticmethod |
| 788 | def foo(): |
| 789 | pass |
| 790 | @classmethod |
| 791 | def bar(cls): |
| 792 | pass |
| 793 | # staticmethod |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 794 | check(foo, size(h + 'P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 795 | # classmethod |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 796 | check(bar, size(h + 'P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 797 | # generator |
| 798 | def get_gen(): yield 1 |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 799 | check(get_gen(), size(h + 'Pi2P')) |
| 800 | # iterator |
| 801 | check(iter('abc'), size(h + 'lP')) |
| 802 | # callable-iterator |
| 803 | import re |
| 804 | check(re.finditer('',''), size(h + '2P')) |
| 805 | # list |
| 806 | samples = [[], [1,2,3], ['1', '2', '3']] |
| 807 | for sample in samples: |
| 808 | check(sample, size(vh + 'PP') + len(sample)*self.P) |
| 809 | # sortwrapper (list) |
| 810 | # XXX |
| 811 | # cmpwrapper (list) |
| 812 | # XXX |
| 813 | # listiterator (list) |
| 814 | check(iter([]), size(h + 'lP')) |
| 815 | # listreverseiterator (list) |
| 816 | check(reversed([]), size(h + 'lP')) |
| 817 | # long |
| 818 | check(0, size(vh)) |
Mark Dickinson | bd79264 | 2009-03-18 20:06:12 +0000 | [diff] [blame] | 819 | check(1, size(vh) + self.longdigit) |
| 820 | check(-1, size(vh) + self.longdigit) |
| 821 | PyLong_BASE = 2**sys.int_info.bits_per_digit |
Benjamin Peterson | ef3e4c2 | 2009-04-11 19:48:14 +0000 | [diff] [blame] | 822 | check(int(PyLong_BASE), size(vh) + 2*self.longdigit) |
| 823 | check(int(PyLong_BASE**2-1), size(vh) + 2*self.longdigit) |
| 824 | check(int(PyLong_BASE**2), size(vh) + 3*self.longdigit) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 825 | # memory |
Antoine Pitrou | c3b3924 | 2009-01-03 16:59:18 +0000 | [diff] [blame] | 826 | check(memoryview(b''), size(h + 'P PP2P2i7P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 827 | # module |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 828 | check(unittest, size(h + '3P')) |
| 829 | # None |
| 830 | check(None, size(h + '')) |
| 831 | # NotImplementedType |
| 832 | check(NotImplemented, size(h)) |
| 833 | # object |
| 834 | check(object(), size(h + '')) |
| 835 | # property (descriptor object) |
| 836 | class C(object): |
| 837 | def getx(self): return self.__x |
| 838 | def setx(self, value): self.__x = value |
| 839 | def delx(self): del self.__x |
| 840 | x = property(getx, setx, delx, "") |
| 841 | check(x, size(h + '4Pi')) |
Benjamin Peterson | b173f78 | 2009-05-05 22:31:58 +0000 | [diff] [blame] | 842 | # PyCapsule |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 843 | # XXX |
| 844 | # rangeiterator |
| 845 | check(iter(range(1)), size(h + '4l')) |
| 846 | # reverse |
| 847 | check(reversed(''), size(h + 'PP')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 848 | # range |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 849 | check(range(1), size(h + '3P')) |
Robert Schuppenies | 357877c | 2008-09-16 07:21:01 +0000 | [diff] [blame] | 850 | check(range(66000), size(h + '3P')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 851 | # set |
| 852 | # frozenset |
| 853 | PySet_MINSIZE = 8 |
| 854 | samples = [[], range(10), range(50)] |
| 855 | s = size(h + '3P2P' + PySet_MINSIZE*'lP' + 'lP') |
| 856 | for sample in samples: |
| 857 | minused = len(sample) |
| 858 | if minused == 0: tmp = 1 |
| 859 | # the computation of minused is actually a bit more complicated |
| 860 | # but this suffices for the sizeof test |
| 861 | minused = minused*2 |
| 862 | newsize = PySet_MINSIZE |
| 863 | while newsize <= minused: |
| 864 | newsize = newsize << 1 |
| 865 | if newsize <= 8: |
| 866 | check(set(sample), s) |
| 867 | check(frozenset(sample), s) |
| 868 | else: |
| 869 | check(set(sample), s + newsize*struct.calcsize('lP')) |
| 870 | check(frozenset(sample), s + newsize*struct.calcsize('lP')) |
| 871 | # setiterator |
| 872 | check(iter(set()), size(h + 'P3P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 873 | # slice |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 874 | check(slice(0), size(h + '3P')) |
| 875 | # super |
| 876 | check(super(int), size(h + '3P')) |
| 877 | # tuple |
| 878 | check((), size(vh)) |
| 879 | check((1,2,3), size(vh) + 3*self.P) |
| 880 | # type |
| 881 | # (PyTypeObject + PyNumberMethods + PyMappingMethods + |
| 882 | # PySequenceMethods + PyBufferProcs) |
| 883 | s = size(vh + 'P2P15Pl4PP9PP11PI') + size('16Pi17P 3P 10P 2P 2P') |
| 884 | check(int, s) |
| 885 | # class |
| 886 | class newstyleclass(object): pass |
| 887 | check(newstyleclass, s) |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 888 | # unicode |
Benjamin Peterson | b49d994 | 2008-06-17 12:44:04 +0000 | [diff] [blame] | 889 | usize = len('\0'.encode('unicode-internal')) |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 890 | samples = ['', '1'*100] |
| 891 | # we need to test for both sizes, because we don't know if the string |
| 892 | # has been cached |
| 893 | for s in samples: |
Robert Schuppenies | 4d45bfe | 2008-06-28 23:58:47 +0000 | [diff] [blame] | 894 | basicsize = size(h + 'PPliP') + usize * (len(s) + 1) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 895 | check(s, basicsize) |
| 896 | # weakref |
| 897 | import weakref |
| 898 | check(weakref.ref(int), size(h + '2Pl2P')) |
| 899 | # weakproxy |
| 900 | # XXX |
| 901 | # weakcallableproxy |
| 902 | check(weakref.proxy(int), size(h + '2Pl2P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 903 | |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 904 | def test_pythontypes(self): |
| 905 | # check all types defined in Python/ |
| 906 | h = self.header |
| 907 | vh = self.vheader |
| 908 | size = self.calcsize |
| 909 | check = self.check_sizeof |
| 910 | # _ast.AST |
| 911 | import _ast |
| 912 | check(_ast.AST(), size(h + '')) |
| 913 | # imp.NullImporter |
| 914 | import imp |
| 915 | check(imp.NullImporter(self.file.name), size(h + '')) |
| 916 | try: |
| 917 | raise TypeError |
| 918 | except TypeError: |
| 919 | tb = sys.exc_info()[2] |
| 920 | # traceback |
| 921 | if tb != None: |
| 922 | check(tb, size(h + '2P2i')) |
| 923 | # symtable entry |
| 924 | # XXX |
| 925 | # sys.flags |
| 926 | check(sys.flags, size(vh) + self.P * len(sys.flags)) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 927 | |
| 928 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 929 | def test_main(): |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 930 | test.support.run_unittest(SysModuleTest, SizeofTest) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 931 | |
| 932 | if __name__ == "__main__": |
| 933 | test_main() |