Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1 | import unittest, test.support |
Berker Peksag | ce64391 | 2015-05-06 06:33:17 +0300 | [diff] [blame] | 2 | from test.support.script_helper import assert_python_ok, assert_python_failure |
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 |
Antoine Pitrou | f9d0b12 | 2012-12-09 14:28:26 +0100 | [diff] [blame] | 10 | import gc |
Antoine Pitrou | 9284053 | 2012-12-17 23:05:59 +0100 | [diff] [blame] | 11 | import sysconfig |
Christian Heimes | 985ecdc | 2013-11-20 11:46:18 +0100 | [diff] [blame] | 12 | import platform |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 13 | |
Georg Brandl | 0352655 | 2009-10-27 23:00:28 +0000 | [diff] [blame] | 14 | # count the number of test runs, used to create unique |
| 15 | # strings to intern in test_intern() |
| 16 | numruns = 0 |
| 17 | |
Victor Stinner | 45df820 | 2010-04-28 22:31:17 +0000 | [diff] [blame] | 18 | try: |
| 19 | import threading |
| 20 | except ImportError: |
| 21 | threading = None |
Georg Brandl | 0352655 | 2009-10-27 23:00:28 +0000 | [diff] [blame] | 22 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 23 | class SysModuleTest(unittest.TestCase): |
| 24 | |
Christian Heimes | ef181a7 | 2007-11-07 16:14:12 +0000 | [diff] [blame] | 25 | def setUp(self): |
| 26 | self.orig_stdout = sys.stdout |
| 27 | self.orig_stderr = sys.stderr |
| 28 | self.orig_displayhook = sys.displayhook |
| 29 | |
| 30 | def tearDown(self): |
| 31 | sys.stdout = self.orig_stdout |
| 32 | sys.stderr = self.orig_stderr |
| 33 | sys.displayhook = self.orig_displayhook |
Antoine Pitrou | 836f0e2 | 2009-10-27 19:25:57 +0000 | [diff] [blame] | 34 | test.support.reap_children() |
Christian Heimes | ef181a7 | 2007-11-07 16:14:12 +0000 | [diff] [blame] | 35 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 36 | def test_original_displayhook(self): |
Georg Brandl | 1a3284e | 2007-12-02 09:40:06 +0000 | [diff] [blame] | 37 | import builtins |
Guido van Rossum | 34d1928 | 2007-08-09 01:03:29 +0000 | [diff] [blame] | 38 | out = io.StringIO() |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 39 | sys.stdout = out |
| 40 | |
| 41 | dh = sys.__displayhook__ |
| 42 | |
| 43 | self.assertRaises(TypeError, dh) |
Georg Brandl | 1a3284e | 2007-12-02 09:40:06 +0000 | [diff] [blame] | 44 | if hasattr(builtins, "_"): |
| 45 | del builtins._ |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 46 | |
| 47 | dh(None) |
| 48 | self.assertEqual(out.getvalue(), "") |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 49 | self.assertTrue(not hasattr(builtins, "_")) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 50 | dh(42) |
| 51 | self.assertEqual(out.getvalue(), "42\n") |
Georg Brandl | 1a3284e | 2007-12-02 09:40:06 +0000 | [diff] [blame] | 52 | self.assertEqual(builtins._, 42) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 53 | |
| 54 | del sys.stdout |
| 55 | self.assertRaises(RuntimeError, dh, 42) |
| 56 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 57 | def test_lost_displayhook(self): |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 58 | del sys.displayhook |
| 59 | code = compile("42", "<string>", "single") |
| 60 | self.assertRaises(RuntimeError, eval, code) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 61 | |
| 62 | def test_custom_displayhook(self): |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 63 | def baddisplayhook(obj): |
| 64 | raise ValueError |
| 65 | sys.displayhook = baddisplayhook |
| 66 | code = compile("42", "<string>", "single") |
| 67 | self.assertRaises(ValueError, eval, code) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 68 | |
| 69 | def test_original_excepthook(self): |
Guido van Rossum | 34d1928 | 2007-08-09 01:03:29 +0000 | [diff] [blame] | 70 | err = io.StringIO() |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 71 | sys.stderr = err |
| 72 | |
| 73 | eh = sys.__excepthook__ |
| 74 | |
| 75 | self.assertRaises(TypeError, eh) |
| 76 | try: |
| 77 | raise ValueError(42) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 78 | except ValueError as exc: |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 79 | eh(*sys.exc_info()) |
| 80 | |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 81 | self.assertTrue(err.getvalue().endswith("ValueError: 42\n")) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 82 | |
Benjamin Peterson | bc74e5b | 2008-08-23 20:19:17 +0000 | [diff] [blame] | 83 | def test_excepthook(self): |
| 84 | with test.support.captured_output("stderr") as stderr: |
| 85 | sys.excepthook(1, '1', 1) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 86 | self.assertTrue("TypeError: print_exception(): Exception expected for " \ |
Benjamin Peterson | bc74e5b | 2008-08-23 20:19:17 +0000 | [diff] [blame] | 87 | "value, str found" in stderr.getvalue()) |
| 88 | |
Walter Dörwald | e7028ac | 2003-02-03 23:05:27 +0000 | [diff] [blame] | 89 | # FIXME: testing the code for a lost or replaced excepthook in |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 90 | # Python/pythonrun.c::PyErr_PrintEx() is tricky. |
| 91 | |
| 92 | def test_exit(self): |
Zachary Ware | cefe6b3 | 2014-02-18 08:39:04 -0600 | [diff] [blame] | 93 | # call with two arguments |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 94 | self.assertRaises(TypeError, sys.exit, 42, 42) |
| 95 | |
| 96 | # call without argument |
Zachary Ware | 1f9e601 | 2014-02-19 10:44:47 -0600 | [diff] [blame] | 97 | with self.assertRaises(SystemExit) as cm: |
| 98 | sys.exit() |
| 99 | self.assertIsNone(cm.exception.code) |
| 100 | |
Zachary Ware | cefe6b3 | 2014-02-18 08:39:04 -0600 | [diff] [blame] | 101 | rc, out, err = assert_python_ok('-c', 'import sys; sys.exit()') |
| 102 | self.assertEqual(rc, 0) |
| 103 | self.assertEqual(out, b'') |
| 104 | self.assertEqual(err, b'') |
| 105 | |
| 106 | # call with integer argument |
| 107 | with self.assertRaises(SystemExit) as cm: |
| 108 | sys.exit(42) |
| 109 | self.assertEqual(cm.exception.code, 42) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 110 | |
| 111 | # call with tuple argument with one entry |
| 112 | # entry will be unpacked |
Zachary Ware | cefe6b3 | 2014-02-18 08:39:04 -0600 | [diff] [blame] | 113 | with self.assertRaises(SystemExit) as cm: |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 114 | sys.exit((42,)) |
Zachary Ware | cefe6b3 | 2014-02-18 08:39:04 -0600 | [diff] [blame] | 115 | self.assertEqual(cm.exception.code, 42) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 116 | |
| 117 | # call with string argument |
Zachary Ware | cefe6b3 | 2014-02-18 08:39:04 -0600 | [diff] [blame] | 118 | with self.assertRaises(SystemExit) as cm: |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 119 | sys.exit("exit") |
Zachary Ware | cefe6b3 | 2014-02-18 08:39:04 -0600 | [diff] [blame] | 120 | self.assertEqual(cm.exception.code, "exit") |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 121 | |
| 122 | # call with tuple argument with two entries |
Zachary Ware | cefe6b3 | 2014-02-18 08:39:04 -0600 | [diff] [blame] | 123 | with self.assertRaises(SystemExit) as cm: |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 124 | sys.exit((17, 23)) |
Zachary Ware | cefe6b3 | 2014-02-18 08:39:04 -0600 | [diff] [blame] | 125 | self.assertEqual(cm.exception.code, (17, 23)) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 126 | |
Michael W. Hudson | f058858 | 2005-02-15 15:26:11 +0000 | [diff] [blame] | 127 | # test that the exit machinery handles SystemExits properly |
Zachary Ware | cefe6b3 | 2014-02-18 08:39:04 -0600 | [diff] [blame] | 128 | rc, out, err = assert_python_failure('-c', 'raise SystemExit(47)') |
Michael W. Hudson | f058858 | 2005-02-15 15:26:11 +0000 | [diff] [blame] | 129 | self.assertEqual(rc, 47) |
Zachary Ware | cefe6b3 | 2014-02-18 08:39:04 -0600 | [diff] [blame] | 130 | self.assertEqual(out, b'') |
| 131 | self.assertEqual(err, b'') |
Tim Peters | f0db38d | 2005-02-15 21:50:12 +0000 | [diff] [blame] | 132 | |
Zachary Ware | cefe6b3 | 2014-02-18 08:39:04 -0600 | [diff] [blame] | 133 | def check_exit_message(code, expected, **env_vars): |
| 134 | rc, out, err = assert_python_failure('-c', code, **env_vars) |
| 135 | self.assertEqual(rc, 1) |
| 136 | self.assertEqual(out, b'') |
| 137 | self.assertTrue(err.startswith(expected), |
| 138 | "%s doesn't start with %s" % (ascii(err), ascii(expected))) |
Victor Stinner | e9fb319 | 2010-05-17 08:58:51 +0000 | [diff] [blame] | 139 | |
Zachary Ware | cefe6b3 | 2014-02-18 08:39:04 -0600 | [diff] [blame] | 140 | # test that stderr buffer is flushed before the exit message is written |
Victor Stinner | e9fb319 | 2010-05-17 08:58:51 +0000 | [diff] [blame] | 141 | # into stderr |
| 142 | check_exit_message( |
| 143 | r'import sys; sys.stderr.write("unflushed,"); sys.exit("message")', |
| 144 | b"unflushed,message") |
| 145 | |
Victor Stinner | 372ac5e | 2010-05-17 01:26:01 +0000 | [diff] [blame] | 146 | # test that the exit message is written with backslashreplace error |
| 147 | # handler to stderr |
Victor Stinner | e9fb319 | 2010-05-17 08:58:51 +0000 | [diff] [blame] | 148 | check_exit_message( |
| 149 | r'import sys; sys.exit("surrogates:\uDCFF")', |
| 150 | b"surrogates:\\udcff") |
Victor Stinner | 372ac5e | 2010-05-17 01:26:01 +0000 | [diff] [blame] | 151 | |
Victor Stinner | 7126dbc | 2010-05-21 23:45:42 +0000 | [diff] [blame] | 152 | # test that the unicode message is encoded to the stderr encoding |
| 153 | # instead of the default encoding (utf8) |
Victor Stinner | 7126dbc | 2010-05-21 23:45:42 +0000 | [diff] [blame] | 154 | check_exit_message( |
| 155 | r'import sys; sys.exit("h\xe9")', |
Zachary Ware | cefe6b3 | 2014-02-18 08:39:04 -0600 | [diff] [blame] | 156 | b"h\xe9", PYTHONIOENCODING='latin-1') |
Victor Stinner | 7126dbc | 2010-05-21 23:45:42 +0000 | [diff] [blame] | 157 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 158 | def test_getdefaultencoding(self): |
Walter Dörwald | 4aeaa96 | 2007-05-22 16:13:46 +0000 | [diff] [blame] | 159 | self.assertRaises(TypeError, sys.getdefaultencoding, 42) |
| 160 | # 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] | 161 | self.assertIsInstance(sys.getdefaultencoding(), str) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 162 | |
Alexander Belopolsky | 07de165 | 2010-07-25 15:05:42 +0000 | [diff] [blame] | 163 | # testing sys.settrace() is done in test_sys_settrace.py |
| 164 | # testing sys.setprofile() is done in test_sys_setprofile.py |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 165 | |
| 166 | def test_setcheckinterval(self): |
Antoine Pitrou | c3b0757 | 2009-11-13 22:19:19 +0000 | [diff] [blame] | 167 | with warnings.catch_warnings(): |
| 168 | warnings.simplefilter("ignore") |
| 169 | self.assertRaises(TypeError, sys.setcheckinterval) |
| 170 | orig = sys.getcheckinterval() |
| 171 | for n in 0, 100, 120, orig: # orig last to restore starting state |
| 172 | sys.setcheckinterval(n) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 173 | self.assertEqual(sys.getcheckinterval(), n) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 174 | |
Victor Stinner | 45df820 | 2010-04-28 22:31:17 +0000 | [diff] [blame] | 175 | @unittest.skipUnless(threading, 'Threading required for this test.') |
Antoine Pitrou | 074e5ed | 2009-11-10 19:50:40 +0000 | [diff] [blame] | 176 | def test_switchinterval(self): |
| 177 | self.assertRaises(TypeError, sys.setswitchinterval) |
| 178 | self.assertRaises(TypeError, sys.setswitchinterval, "a") |
| 179 | self.assertRaises(ValueError, sys.setswitchinterval, -1.0) |
| 180 | self.assertRaises(ValueError, sys.setswitchinterval, 0.0) |
| 181 | orig = sys.getswitchinterval() |
| 182 | # sanity check |
| 183 | self.assertTrue(orig < 0.5, orig) |
| 184 | try: |
| 185 | for n in 0.00001, 0.05, 3.0, orig: |
| 186 | sys.setswitchinterval(n) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 187 | self.assertAlmostEqual(sys.getswitchinterval(), n) |
Antoine Pitrou | 074e5ed | 2009-11-10 19:50:40 +0000 | [diff] [blame] | 188 | finally: |
| 189 | sys.setswitchinterval(orig) |
| 190 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 191 | def test_recursionlimit(self): |
Tim Peters | f2715e0 | 2003-02-19 02:35:07 +0000 | [diff] [blame] | 192 | self.assertRaises(TypeError, sys.getrecursionlimit, 42) |
| 193 | oldlimit = sys.getrecursionlimit() |
| 194 | self.assertRaises(TypeError, sys.setrecursionlimit) |
| 195 | self.assertRaises(ValueError, sys.setrecursionlimit, -42) |
| 196 | sys.setrecursionlimit(10000) |
| 197 | self.assertEqual(sys.getrecursionlimit(), 10000) |
| 198 | sys.setrecursionlimit(oldlimit) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 199 | |
Antoine Pitrou | 652e707 | 2009-03-13 19:25:20 +0000 | [diff] [blame] | 200 | def test_recursionlimit_recovery(self): |
Victor Stinner | 3f18f10 | 2015-10-01 08:55:33 +0200 | [diff] [blame] | 201 | if hasattr(sys, 'gettrace') and sys.gettrace(): |
| 202 | self.skipTest('fatal error if run with a trace function') |
| 203 | |
Antoine Pitrou | 652e707 | 2009-03-13 19:25:20 +0000 | [diff] [blame] | 204 | oldlimit = sys.getrecursionlimit() |
| 205 | def f(): |
| 206 | f() |
| 207 | try: |
Victor Stinner | 50856d5 | 2015-10-13 00:11:21 +0200 | [diff] [blame] | 208 | for depth in (10, 25, 50, 75, 100, 250, 1000): |
| 209 | try: |
| 210 | sys.setrecursionlimit(depth) |
| 211 | except RecursionError: |
| 212 | # Issue #25274: The recursion limit is too low at the |
| 213 | # current recursion depth |
| 214 | continue |
| 215 | |
| 216 | # Issue #5392: test stack overflow after hitting recursion |
| 217 | # limit twice |
Yury Selivanov | f488fb4 | 2015-07-03 01:04:23 -0400 | [diff] [blame] | 218 | self.assertRaises(RecursionError, f) |
| 219 | self.assertRaises(RecursionError, f) |
Antoine Pitrou | 652e707 | 2009-03-13 19:25:20 +0000 | [diff] [blame] | 220 | finally: |
| 221 | sys.setrecursionlimit(oldlimit) |
| 222 | |
Victor Stinner | 50856d5 | 2015-10-13 00:11:21 +0200 | [diff] [blame] | 223 | @test.support.cpython_only |
| 224 | def test_setrecursionlimit_recursion_depth(self): |
| 225 | # Issue #25274: Setting a low recursion limit must be blocked if the |
| 226 | # current recursion depth is already higher than the "lower-water |
| 227 | # mark". Otherwise, it may not be possible anymore to |
| 228 | # reset the overflowed flag to 0. |
| 229 | |
| 230 | from _testcapi import get_recursion_depth |
| 231 | |
| 232 | def set_recursion_limit_at_depth(depth, limit): |
| 233 | recursion_depth = get_recursion_depth() |
| 234 | if recursion_depth >= depth: |
| 235 | with self.assertRaises(RecursionError) as cm: |
| 236 | sys.setrecursionlimit(limit) |
| 237 | self.assertRegex(str(cm.exception), |
| 238 | "cannot set the recursion limit to [0-9]+ " |
| 239 | "at the recursion depth [0-9]+: " |
| 240 | "the limit is too low") |
| 241 | else: |
| 242 | set_recursion_limit_at_depth(depth, limit) |
| 243 | |
| 244 | oldlimit = sys.getrecursionlimit() |
| 245 | try: |
| 246 | sys.setrecursionlimit(1000) |
| 247 | |
| 248 | for limit in (10, 25, 50, 75, 100, 150, 200): |
| 249 | # formula extracted from _Py_RecursionLimitLowerWaterMark() |
| 250 | if limit > 200: |
| 251 | depth = limit - 50 |
| 252 | else: |
| 253 | depth = limit * 3 // 4 |
| 254 | set_recursion_limit_at_depth(depth, limit) |
| 255 | finally: |
| 256 | sys.setrecursionlimit(oldlimit) |
| 257 | |
Antoine Pitrou | 652e707 | 2009-03-13 19:25:20 +0000 | [diff] [blame] | 258 | def test_recursionlimit_fatalerror(self): |
| 259 | # A fatal error occurs if a second recursion limit is hit when recovering |
| 260 | # from a first one. |
| 261 | code = textwrap.dedent(""" |
| 262 | import sys |
| 263 | |
| 264 | def f(): |
| 265 | try: |
| 266 | f() |
Yury Selivanov | f488fb4 | 2015-07-03 01:04:23 -0400 | [diff] [blame] | 267 | except RecursionError: |
Antoine Pitrou | 652e707 | 2009-03-13 19:25:20 +0000 | [diff] [blame] | 268 | f() |
| 269 | |
| 270 | sys.setrecursionlimit(%d) |
| 271 | f()""") |
Antoine Pitrou | 77e904e | 2013-10-08 23:04:32 +0200 | [diff] [blame] | 272 | with test.support.SuppressCrashReport(): |
Ezio Melotti | 958f7ae | 2013-03-20 18:14:48 +0200 | [diff] [blame] | 273 | for i in (50, 1000): |
| 274 | sub = subprocess.Popen([sys.executable, '-c', code % i], |
| 275 | stderr=subprocess.PIPE) |
| 276 | err = sub.communicate()[1] |
| 277 | self.assertTrue(sub.returncode, sub.returncode) |
| 278 | self.assertIn( |
| 279 | b"Fatal Python error: Cannot recover from stack overflow", |
| 280 | err) |
Antoine Pitrou | 652e707 | 2009-03-13 19:25:20 +0000 | [diff] [blame] | 281 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 282 | def test_getwindowsversion(self): |
Eric Smith | 05f33744 | 2010-01-27 01:25:02 +0000 | [diff] [blame] | 283 | # Raise SkipTest if sys doesn't have getwindowsversion attribute |
Eric Smith | d8aef76 | 2010-01-27 01:38:34 +0000 | [diff] [blame] | 284 | test.support.get_attribute(sys, "getwindowsversion") |
Eric Smith | 05f33744 | 2010-01-27 01:25:02 +0000 | [diff] [blame] | 285 | v = sys.getwindowsversion() |
Brian Curtin | 808e1ad | 2010-07-08 22:13:25 +0000 | [diff] [blame] | 286 | self.assertEqual(len(v), 5) |
Eric Smith | 05f33744 | 2010-01-27 01:25:02 +0000 | [diff] [blame] | 287 | self.assertIsInstance(v[0], int) |
| 288 | self.assertIsInstance(v[1], int) |
| 289 | self.assertIsInstance(v[2], int) |
| 290 | self.assertIsInstance(v[3], int) |
| 291 | self.assertIsInstance(v[4], str) |
| 292 | self.assertRaises(IndexError, operator.getitem, v, 5) |
| 293 | self.assertIsInstance(v.major, int) |
| 294 | self.assertIsInstance(v.minor, int) |
| 295 | self.assertIsInstance(v.build, int) |
| 296 | self.assertIsInstance(v.platform, int) |
| 297 | self.assertIsInstance(v.service_pack, str) |
Eric Smith | a1f20b9 | 2010-01-27 02:14:26 +0000 | [diff] [blame] | 298 | self.assertIsInstance(v.service_pack_minor, int) |
| 299 | self.assertIsInstance(v.service_pack_major, int) |
| 300 | self.assertIsInstance(v.suite_mask, int) |
| 301 | self.assertIsInstance(v.product_type, int) |
Eric Smith | 05f33744 | 2010-01-27 01:25:02 +0000 | [diff] [blame] | 302 | self.assertEqual(v[0], v.major) |
| 303 | self.assertEqual(v[1], v.minor) |
| 304 | self.assertEqual(v[2], v.build) |
| 305 | self.assertEqual(v[3], v.platform) |
| 306 | self.assertEqual(v[4], v.service_pack) |
Eric Smith | f7bb578 | 2010-01-27 00:44:57 +0000 | [diff] [blame] | 307 | |
Eric Smith | 05f33744 | 2010-01-27 01:25:02 +0000 | [diff] [blame] | 308 | # This is how platform.py calls it. Make sure tuple |
| 309 | # still has 5 elements |
| 310 | maj, min, buildno, plat, csd = sys.getwindowsversion() |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 311 | |
Barry Warsaw | e94a37f | 2008-10-17 01:29:56 +0000 | [diff] [blame] | 312 | def test_call_tracing(self): |
| 313 | self.assertRaises(TypeError, sys.call_tracing, type, 2) |
| 314 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 315 | @unittest.skipUnless(hasattr(sys, "setdlopenflags"), |
| 316 | 'test needs sys.setdlopenflags()') |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 317 | def test_dlopenflags(self): |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 318 | self.assertTrue(hasattr(sys, "getdlopenflags")) |
| 319 | self.assertRaises(TypeError, sys.getdlopenflags, 42) |
| 320 | oldflags = sys.getdlopenflags() |
| 321 | self.assertRaises(TypeError, sys.setdlopenflags) |
| 322 | sys.setdlopenflags(oldflags+1) |
| 323 | self.assertEqual(sys.getdlopenflags(), oldflags+1) |
| 324 | sys.setdlopenflags(oldflags) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 325 | |
Brett Cannon | 7a54073 | 2011-02-22 03:04:06 +0000 | [diff] [blame] | 326 | @test.support.refcount_test |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 327 | def test_refcount(self): |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 328 | # n here must be a global in order for this test to pass while |
| 329 | # tracing with a python function. Tracing calls PyFrame_FastToLocals |
| 330 | # which will add a copy of any locals to the frame object, causing |
| 331 | # the reference count to increase by 2 instead of 1. |
| 332 | global n |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 333 | self.assertRaises(TypeError, sys.getrefcount) |
| 334 | c = sys.getrefcount(None) |
| 335 | n = None |
| 336 | self.assertEqual(sys.getrefcount(None), c+1) |
| 337 | del n |
| 338 | self.assertEqual(sys.getrefcount(None), c) |
| 339 | if hasattr(sys, "gettotalrefcount"): |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 340 | self.assertIsInstance(sys.gettotalrefcount(), int) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 341 | |
| 342 | def test_getframe(self): |
| 343 | self.assertRaises(TypeError, sys._getframe, 42, 42) |
Neal Norwitz | eb2a5ef | 2003-02-18 15:22:10 +0000 | [diff] [blame] | 344 | self.assertRaises(ValueError, sys._getframe, 2000000000) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 345 | self.assertTrue( |
Christian Heimes | 4a22b5d | 2007-11-25 09:39:14 +0000 | [diff] [blame] | 346 | SysModuleTest.test_getframe.__code__ \ |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 347 | is sys._getframe().f_code |
| 348 | ) |
| 349 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 350 | # sys._current_frames() is a CPython-only gimmick. |
| 351 | def test_current_frames(self): |
| 352 | have_threads = True |
| 353 | try: |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 354 | import _thread |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 355 | except ImportError: |
| 356 | have_threads = False |
| 357 | |
| 358 | if have_threads: |
| 359 | self.current_frames_with_threads() |
| 360 | else: |
| 361 | self.current_frames_without_threads() |
| 362 | |
| 363 | # Test sys._current_frames() in a WITH_THREADS build. |
Antoine Pitrou | 836f0e2 | 2009-10-27 19:25:57 +0000 | [diff] [blame] | 364 | @test.support.reap_threads |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 365 | def current_frames_with_threads(self): |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 366 | import threading |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 367 | import traceback |
| 368 | |
| 369 | # Spawn a thread that blocks at a known place. Then the main |
| 370 | # thread does sys._current_frames(), and verifies that the frames |
| 371 | # returned make sense. |
| 372 | entered_g = threading.Event() |
| 373 | leave_g = threading.Event() |
| 374 | thread_info = [] # the thread's id |
| 375 | |
| 376 | def f123(): |
| 377 | g456() |
| 378 | |
| 379 | def g456(): |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 380 | thread_info.append(threading.get_ident()) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 381 | entered_g.set() |
| 382 | leave_g.wait() |
| 383 | |
| 384 | t = threading.Thread(target=f123) |
| 385 | t.start() |
| 386 | entered_g.wait() |
| 387 | |
| 388 | # At this point, t has finished its entered_g.set(), although it's |
| 389 | # impossible to guess whether it's still on that line or has moved on |
| 390 | # to its leave_g.wait(). |
| 391 | self.assertEqual(len(thread_info), 1) |
| 392 | thread_id = thread_info[0] |
| 393 | |
| 394 | d = sys._current_frames() |
| 395 | |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 396 | main_id = threading.get_ident() |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 397 | self.assertIn(main_id, d) |
| 398 | self.assertIn(thread_id, d) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 399 | |
| 400 | # Verify that the captured main-thread frame is _this_ frame. |
| 401 | frame = d.pop(main_id) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 402 | self.assertTrue(frame is sys._getframe()) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 403 | |
| 404 | # Verify that the captured thread frame is blocked in g456, called |
| 405 | # from f123. This is a litte tricky, since various bits of |
| 406 | # threading.py are also in the thread's call stack. |
| 407 | frame = d.pop(thread_id) |
| 408 | stack = traceback.extract_stack(frame) |
| 409 | for i, (filename, lineno, funcname, sourceline) in enumerate(stack): |
| 410 | if funcname == "f123": |
| 411 | break |
| 412 | else: |
| 413 | self.fail("didn't find f123() on thread's call stack") |
| 414 | |
| 415 | self.assertEqual(sourceline, "g456()") |
| 416 | |
| 417 | # And the next record must be for g456(). |
| 418 | filename, lineno, funcname, sourceline = stack[i+1] |
| 419 | self.assertEqual(funcname, "g456") |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 420 | self.assertIn(sourceline, ["leave_g.wait()", "entered_g.set()"]) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 421 | |
| 422 | # Reap the spawned thread. |
| 423 | leave_g.set() |
| 424 | t.join() |
| 425 | |
| 426 | # Test sys._current_frames() when thread support doesn't exist. |
| 427 | def current_frames_without_threads(self): |
| 428 | # Not much happens here: there is only one thread, with artificial |
| 429 | # "thread id" 0. |
| 430 | d = sys._current_frames() |
| 431 | self.assertEqual(len(d), 1) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 432 | self.assertIn(0, d) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 433 | self.assertTrue(d[0] is sys._getframe()) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 434 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 435 | def test_attributes(self): |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 436 | self.assertIsInstance(sys.api_version, int) |
| 437 | self.assertIsInstance(sys.argv, list) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 438 | self.assertIn(sys.byteorder, ("little", "big")) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 439 | self.assertIsInstance(sys.builtin_module_names, tuple) |
| 440 | self.assertIsInstance(sys.copyright, str) |
| 441 | self.assertIsInstance(sys.exec_prefix, str) |
Vinay Sajip | 7ded1f0 | 2012-05-26 03:45:29 +0100 | [diff] [blame] | 442 | self.assertIsInstance(sys.base_exec_prefix, str) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 443 | self.assertIsInstance(sys.executable, str) |
Christian Heimes | 9385266 | 2007-12-01 12:22:32 +0000 | [diff] [blame] | 444 | self.assertEqual(len(sys.float_info), 11) |
Christian Heimes | d32ed6f | 2008-01-14 18:49:24 +0000 | [diff] [blame] | 445 | self.assertEqual(sys.float_info.radix, 2) |
Mark Dickinson | bd79264 | 2009-03-18 20:06:12 +0000 | [diff] [blame] | 446 | self.assertEqual(len(sys.int_info), 2) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 447 | self.assertTrue(sys.int_info.bits_per_digit % 5 == 0) |
| 448 | self.assertTrue(sys.int_info.sizeof_digit >= 1) |
Benjamin Peterson | ef3e4c2 | 2009-04-11 19:48:14 +0000 | [diff] [blame] | 449 | self.assertEqual(type(sys.int_info.bits_per_digit), int) |
| 450 | self.assertEqual(type(sys.int_info.sizeof_digit), int) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 451 | self.assertIsInstance(sys.hexversion, int) |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 452 | |
Christian Heimes | 985ecdc | 2013-11-20 11:46:18 +0100 | [diff] [blame] | 453 | self.assertEqual(len(sys.hash_info), 9) |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 454 | self.assertLess(sys.hash_info.modulus, 2**sys.hash_info.width) |
| 455 | # sys.hash_info.modulus should be a prime; we do a quick |
| 456 | # probable primality test (doesn't exclude the possibility of |
| 457 | # a Carmichael number) |
| 458 | for x in range(1, 100): |
| 459 | self.assertEqual( |
| 460 | pow(x, sys.hash_info.modulus-1, sys.hash_info.modulus), |
| 461 | 1, |
| 462 | "sys.hash_info.modulus {} is a non-prime".format( |
| 463 | sys.hash_info.modulus) |
| 464 | ) |
| 465 | self.assertIsInstance(sys.hash_info.inf, int) |
| 466 | self.assertIsInstance(sys.hash_info.nan, int) |
| 467 | self.assertIsInstance(sys.hash_info.imag, int) |
Victor Stinner | 4b6d4b5 | 2013-12-12 23:06:07 +0100 | [diff] [blame] | 468 | algo = sysconfig.get_config_var("Py_HASH_ALGORITHM") |
Christian Heimes | 985ecdc | 2013-11-20 11:46:18 +0100 | [diff] [blame] | 469 | if sys.hash_info.algorithm in {"fnv", "siphash24"}: |
| 470 | self.assertIn(sys.hash_info.hash_bits, {32, 64}) |
| 471 | self.assertIn(sys.hash_info.seed_bits, {32, 64, 128}) |
| 472 | |
| 473 | if algo == 1: |
| 474 | self.assertEqual(sys.hash_info.algorithm, "siphash24") |
| 475 | elif algo == 2: |
| 476 | self.assertEqual(sys.hash_info.algorithm, "fnv") |
| 477 | else: |
Victor Stinner | 56668dc | 2013-12-12 23:07:40 +0100 | [diff] [blame] | 478 | self.assertIn(sys.hash_info.algorithm, {"fnv", "siphash24"}) |
Christian Heimes | 985ecdc | 2013-11-20 11:46:18 +0100 | [diff] [blame] | 479 | else: |
| 480 | # PY_HASH_EXTERNAL |
| 481 | self.assertEqual(algo, 0) |
| 482 | self.assertGreaterEqual(sys.hash_info.cutoff, 0) |
| 483 | self.assertLess(sys.hash_info.cutoff, 8) |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 484 | |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 485 | self.assertIsInstance(sys.maxsize, int) |
| 486 | self.assertIsInstance(sys.maxunicode, int) |
Ezio Melotti | 48a2f8f | 2011-09-29 00:18:19 +0300 | [diff] [blame] | 487 | self.assertEqual(sys.maxunicode, 0x10FFFF) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 488 | self.assertIsInstance(sys.platform, str) |
| 489 | self.assertIsInstance(sys.prefix, str) |
Vinay Sajip | 7ded1f0 | 2012-05-26 03:45:29 +0100 | [diff] [blame] | 490 | self.assertIsInstance(sys.base_prefix, str) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 491 | self.assertIsInstance(sys.version, str) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 492 | vi = sys.version_info |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 493 | self.assertIsInstance(vi[:], tuple) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 494 | self.assertEqual(len(vi), 5) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 495 | self.assertIsInstance(vi[0], int) |
| 496 | self.assertIsInstance(vi[1], int) |
| 497 | self.assertIsInstance(vi[2], int) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 498 | self.assertIn(vi[3], ("alpha", "beta", "candidate", "final")) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 499 | self.assertIsInstance(vi[4], int) |
| 500 | self.assertIsInstance(vi.major, int) |
| 501 | self.assertIsInstance(vi.minor, int) |
| 502 | self.assertIsInstance(vi.micro, int) |
Ezio Melotti | b58e0bd | 2010-01-23 15:40:09 +0000 | [diff] [blame] | 503 | self.assertIn(vi.releaselevel, ("alpha", "beta", "candidate", "final")) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 504 | self.assertIsInstance(vi.serial, int) |
Eric Smith | 0e5b562 | 2009-02-06 01:32:42 +0000 | [diff] [blame] | 505 | self.assertEqual(vi[0], vi.major) |
| 506 | self.assertEqual(vi[1], vi.minor) |
| 507 | self.assertEqual(vi[2], vi.micro) |
| 508 | self.assertEqual(vi[3], vi.releaselevel) |
| 509 | self.assertEqual(vi[4], vi.serial) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 510 | self.assertTrue(vi > (1,0,0)) |
Mark Dickinson | 55d110c | 2009-10-24 14:04:48 +0000 | [diff] [blame] | 511 | self.assertIsInstance(sys.float_repr_style, str) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 512 | self.assertIn(sys.float_repr_style, ('short', 'legacy')) |
Barry Warsaw | 8cf4eae | 2010-10-16 01:04:07 +0000 | [diff] [blame] | 513 | if not sys.platform.startswith('win'): |
| 514 | self.assertIsInstance(sys.abiflags, str) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 515 | |
Victor Stinner | d5c355c | 2011-04-30 14:53:09 +0200 | [diff] [blame] | 516 | @unittest.skipUnless(hasattr(sys, 'thread_info'), |
| 517 | 'Threading required for this test.') |
| 518 | def test_thread_info(self): |
| 519 | info = sys.thread_info |
Ezio Melotti | 48006cf | 2011-05-01 00:03:49 +0300 | [diff] [blame] | 520 | self.assertEqual(len(info), 3) |
Jesus Cea | f01d695 | 2012-10-05 03:36:11 +0200 | [diff] [blame] | 521 | self.assertIn(info.name, ('nt', 'pthread', 'solaris', None)) |
Victor Stinner | d5c355c | 2011-04-30 14:53:09 +0200 | [diff] [blame] | 522 | self.assertIn(info.lock, ('semaphore', 'mutex+cond', None)) |
| 523 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 524 | def test_43581(self): |
Georg Brandl | 0312494 | 2008-06-10 15:50:56 +0000 | [diff] [blame] | 525 | # Can't use sys.stdout, as this is a StringIO object when |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 526 | # the test runs under regrtest. |
Guido van Rossum | e61fd5b | 2007-07-11 12:20:59 +0000 | [diff] [blame] | 527 | self.assertEqual(sys.__stdout__.encoding, sys.__stderr__.encoding) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 528 | |
Georg Brandl | 66a796e | 2006-12-19 20:50:34 +0000 | [diff] [blame] | 529 | def test_intern(self): |
Georg Brandl | 0352655 | 2009-10-27 23:00:28 +0000 | [diff] [blame] | 530 | global numruns |
| 531 | numruns += 1 |
Georg Brandl | 66a796e | 2006-12-19 20:50:34 +0000 | [diff] [blame] | 532 | self.assertRaises(TypeError, sys.intern) |
Georg Brandl | 0352655 | 2009-10-27 23:00:28 +0000 | [diff] [blame] | 533 | s = "never interned before" + str(numruns) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 534 | self.assertTrue(sys.intern(s) is s) |
Georg Brandl | 66a796e | 2006-12-19 20:50:34 +0000 | [diff] [blame] | 535 | s2 = s.swapcase().swapcase() |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 536 | self.assertTrue(sys.intern(s2) is s) |
Georg Brandl | 66a796e | 2006-12-19 20:50:34 +0000 | [diff] [blame] | 537 | |
| 538 | # Subclasses of string can't be interned, because they |
| 539 | # provide too much opportunity for insane things to happen. |
| 540 | # We don't want them in the interned dict and if they aren't |
| 541 | # actually interned, we don't want to create the appearance |
Ezio Melotti | 1392500 | 2011-03-16 11:05:33 +0200 | [diff] [blame] | 542 | # that they are by allowing intern() to succeed. |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 543 | class S(str): |
Georg Brandl | 66a796e | 2006-12-19 20:50:34 +0000 | [diff] [blame] | 544 | def __hash__(self): |
| 545 | return 123 |
| 546 | |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 547 | self.assertRaises(TypeError, sys.intern, S("abc")) |
Martin v. Löwis | 5b22213 | 2007-06-10 09:51:05 +0000 | [diff] [blame] | 548 | |
Christian Heimes | d32ed6f | 2008-01-14 18:49:24 +0000 | [diff] [blame] | 549 | def test_sys_flags(self): |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 550 | self.assertTrue(sys.flags) |
Éric Araujo | be3bd57 | 2011-03-26 01:55:15 +0100 | [diff] [blame] | 551 | attrs = ("debug", |
Christian Heimes | d32ed6f | 2008-01-14 18:49:24 +0000 | [diff] [blame] | 552 | "inspect", "interactive", "optimize", "dont_write_bytecode", |
Georg Brandl | c5e88d5 | 2008-06-06 09:02:07 +0000 | [diff] [blame] | 553 | "no_user_site", "no_site", "ignore_environment", "verbose", |
Christian Heimes | ad73a9c | 2013-08-10 16:36:18 +0200 | [diff] [blame] | 554 | "bytes_warning", "quiet", "hash_randomization", "isolated") |
Christian Heimes | d32ed6f | 2008-01-14 18:49:24 +0000 | [diff] [blame] | 555 | for attr in attrs: |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 556 | self.assertTrue(hasattr(sys.flags, attr), attr) |
Christian Heimes | d32ed6f | 2008-01-14 18:49:24 +0000 | [diff] [blame] | 557 | self.assertEqual(type(getattr(sys.flags, attr)), int, attr) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 558 | self.assertTrue(repr(sys.flags)) |
Georg Brandl | c5e88d5 | 2008-06-06 09:02:07 +0000 | [diff] [blame] | 559 | self.assertEqual(len(sys.flags), len(attrs)) |
Christian Heimes | d32ed6f | 2008-01-14 18:49:24 +0000 | [diff] [blame] | 560 | |
Antoine Pitrou | 871dfc4 | 2014-04-28 13:07:06 +0200 | [diff] [blame] | 561 | def assert_raise_on_new_sys_type(self, sys_attr): |
| 562 | # Users are intentionally prevented from creating new instances of |
| 563 | # sys.flags, sys.version_info, and sys.getwindowsversion. |
| 564 | attr_type = type(sys_attr) |
| 565 | with self.assertRaises(TypeError): |
| 566 | attr_type() |
| 567 | with self.assertRaises(TypeError): |
| 568 | attr_type.__new__(attr_type) |
| 569 | |
| 570 | def test_sys_flags_no_instantiation(self): |
| 571 | self.assert_raise_on_new_sys_type(sys.flags) |
| 572 | |
| 573 | def test_sys_version_info_no_instantiation(self): |
| 574 | self.assert_raise_on_new_sys_type(sys.version_info) |
| 575 | |
| 576 | def test_sys_getwindowsversion_no_instantiation(self): |
| 577 | # Skip if not being run on Windows. |
| 578 | test.support.get_attribute(sys, "getwindowsversion") |
| 579 | self.assert_raise_on_new_sys_type(sys.getwindowsversion()) |
| 580 | |
Benjamin Peterson | f5f9c13 | 2015-02-02 14:22:13 -0500 | [diff] [blame] | 581 | @test.support.cpython_only |
Christian Heimes | 15ebc88 | 2008-02-04 18:48:49 +0000 | [diff] [blame] | 582 | def test_clear_type_cache(self): |
| 583 | sys._clear_type_cache() |
| 584 | |
Martin v. Löwis | 0f59989 | 2008-06-02 11:13:03 +0000 | [diff] [blame] | 585 | def test_ioencoding(self): |
Martin v. Löwis | 0f59989 | 2008-06-02 11:13:03 +0000 | [diff] [blame] | 586 | env = dict(os.environ) |
| 587 | |
| 588 | # Test character: cent sign, encoded as 0x4A (ASCII J) in CP424, |
| 589 | # not representable in ASCII. |
| 590 | |
| 591 | env["PYTHONIOENCODING"] = "cp424" |
| 592 | p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'], |
| 593 | stdout = subprocess.PIPE, env=env) |
Antoine Pitrou | 836f0e2 | 2009-10-27 19:25:57 +0000 | [diff] [blame] | 594 | out = p.communicate()[0].strip() |
Antoine Pitrou | 894375a | 2012-08-05 00:15:06 +0200 | [diff] [blame] | 595 | expected = ("\xa2" + os.linesep).encode("cp424") |
| 596 | self.assertEqual(out, expected) |
Martin v. Löwis | 0f59989 | 2008-06-02 11:13:03 +0000 | [diff] [blame] | 597 | |
| 598 | env["PYTHONIOENCODING"] = "ascii:replace" |
| 599 | p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'], |
| 600 | stdout = subprocess.PIPE, env=env) |
Antoine Pitrou | 836f0e2 | 2009-10-27 19:25:57 +0000 | [diff] [blame] | 601 | out = p.communicate()[0].strip() |
Martin v. Löwis | 0f59989 | 2008-06-02 11:13:03 +0000 | [diff] [blame] | 602 | self.assertEqual(out, b'?') |
| 603 | |
Serhiy Storchaka | bf28d2d | 2013-09-13 11:46:24 +0300 | [diff] [blame] | 604 | env["PYTHONIOENCODING"] = "ascii" |
| 605 | p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'], |
| 606 | stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
| 607 | env=env) |
| 608 | out, err = p.communicate() |
| 609 | self.assertEqual(out, b'') |
| 610 | self.assertIn(b'UnicodeEncodeError:', err) |
| 611 | self.assertIn(rb"'\xa2'", err) |
| 612 | |
| 613 | env["PYTHONIOENCODING"] = "ascii:" |
| 614 | p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'], |
| 615 | stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
| 616 | env=env) |
| 617 | out, err = p.communicate() |
| 618 | self.assertEqual(out, b'') |
| 619 | self.assertIn(b'UnicodeEncodeError:', err) |
| 620 | self.assertIn(rb"'\xa2'", err) |
| 621 | |
| 622 | env["PYTHONIOENCODING"] = ":surrogateescape" |
| 623 | p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xdcbd))'], |
| 624 | stdout=subprocess.PIPE, env=env) |
| 625 | out = p.communicate()[0].strip() |
| 626 | self.assertEqual(out, b'\xbd') |
| 627 | |
| 628 | @unittest.skipUnless(test.support.FS_NONASCII, |
| 629 | 'requires OS support of non-ASCII encodings') |
| 630 | def test_ioencoding_nonascii(self): |
| 631 | env = dict(os.environ) |
| 632 | |
| 633 | env["PYTHONIOENCODING"] = "" |
| 634 | p = subprocess.Popen([sys.executable, "-c", |
| 635 | 'print(%a)' % test.support.FS_NONASCII], |
| 636 | stdout=subprocess.PIPE, env=env) |
| 637 | out = p.communicate()[0].strip() |
| 638 | self.assertEqual(out, os.fsencode(test.support.FS_NONASCII)) |
| 639 | |
Vinay Sajip | 7ded1f0 | 2012-05-26 03:45:29 +0100 | [diff] [blame] | 640 | @unittest.skipIf(sys.base_prefix != sys.prefix, |
| 641 | 'Test is not venv-compatible') |
Victor Stinner | 171ba05 | 2010-03-12 14:20:59 +0000 | [diff] [blame] | 642 | def test_executable(self): |
Petri Lehtinen | 9713321 | 2012-02-02 20:59:48 +0200 | [diff] [blame] | 643 | # sys.executable should be absolute |
| 644 | self.assertEqual(os.path.abspath(sys.executable), sys.executable) |
| 645 | |
Victor Stinner | 171ba05 | 2010-03-12 14:20:59 +0000 | [diff] [blame] | 646 | # Issue #7774: Ensure that sys.executable is an empty string if argv[0] |
Serhiy Storchaka | 6a7b3a7 | 2016-04-17 08:32:47 +0300 | [diff] [blame] | 647 | # has been set to a non existent program name and Python is unable to |
Victor Stinner | 171ba05 | 2010-03-12 14:20:59 +0000 | [diff] [blame] | 648 | # retrieve the real program name |
Florent Xicluna | 02ea12b2 | 2010-07-28 16:39:41 +0000 | [diff] [blame] | 649 | |
Victor Stinner | 171ba05 | 2010-03-12 14:20:59 +0000 | [diff] [blame] | 650 | # For a normal installation, it should work without 'cwd' |
| 651 | # argument. For test runs in the build directory, see #7774. |
| 652 | python_dir = os.path.dirname(os.path.realpath(sys.executable)) |
| 653 | p = subprocess.Popen( |
| 654 | ["nonexistent", "-c", |
| 655 | 'import sys; print(sys.executable.encode("ascii", "backslashreplace"))'], |
| 656 | executable=sys.executable, stdout=subprocess.PIPE, cwd=python_dir) |
| 657 | stdout = p.communicate()[0] |
| 658 | executable = stdout.strip().decode("ASCII") |
| 659 | p.wait() |
| 660 | self.assertIn(executable, ["b''", repr(sys.executable.encode("ascii", "backslashreplace"))]) |
| 661 | |
Victor Stinner | 85ca2af | 2010-08-19 11:23:47 +0000 | [diff] [blame] | 662 | def check_fsencoding(self, fs_encoding, expected=None): |
| 663 | self.assertIsNotNone(fs_encoding) |
| 664 | codecs.lookup(fs_encoding) |
| 665 | if expected: |
| 666 | self.assertEqual(fs_encoding, expected) |
| 667 | |
Victor Stinner | c732e3b | 2010-08-18 22:44:15 +0000 | [diff] [blame] | 668 | def test_getfilesystemencoding(self): |
Victor Stinner | c732e3b | 2010-08-18 22:44:15 +0000 | [diff] [blame] | 669 | fs_encoding = sys.getfilesystemencoding() |
Victor Stinner | 85ca2af | 2010-08-19 11:23:47 +0000 | [diff] [blame] | 670 | if sys.platform == 'darwin': |
| 671 | expected = 'utf-8' |
| 672 | elif sys.platform == 'win32': |
| 673 | expected = 'mbcs' |
| 674 | else: |
| 675 | expected = None |
Victor Stinner | 9943524 | 2010-08-19 11:30:09 +0000 | [diff] [blame] | 676 | self.check_fsencoding(fs_encoding, expected) |
Victor Stinner | c732e3b | 2010-08-18 22:44:15 +0000 | [diff] [blame] | 677 | |
Victor Stinner | 97f17a7 | 2014-03-18 02:28:10 +0100 | [diff] [blame] | 678 | def c_locale_get_error_handler(self, isolated=False, encoding=None): |
Victor Stinner | 7143029 | 2014-03-18 01:18:21 +0100 | [diff] [blame] | 679 | # Force the POSIX locale |
| 680 | env = os.environ.copy() |
| 681 | env["LC_ALL"] = "C" |
| 682 | code = '\n'.join(( |
Victor Stinner | 97f17a7 | 2014-03-18 02:28:10 +0100 | [diff] [blame] | 683 | 'import sys', |
Victor Stinner | 7143029 | 2014-03-18 01:18:21 +0100 | [diff] [blame] | 684 | 'def dump(name):', |
| 685 | ' std = getattr(sys, name)', |
Victor Stinner | 97f17a7 | 2014-03-18 02:28:10 +0100 | [diff] [blame] | 686 | ' print("%s: %s" % (name, std.errors))', |
Victor Stinner | 7143029 | 2014-03-18 01:18:21 +0100 | [diff] [blame] | 687 | 'dump("stdin")', |
| 688 | 'dump("stdout")', |
| 689 | 'dump("stderr")', |
| 690 | )) |
Victor Stinner | 97f17a7 | 2014-03-18 02:28:10 +0100 | [diff] [blame] | 691 | args = [sys.executable, "-c", code] |
| 692 | if isolated: |
| 693 | args.append("-I") |
Serhiy Storchaka | fc43511 | 2016-04-10 14:34:13 +0300 | [diff] [blame] | 694 | if encoding is not None: |
Victor Stinner | 97f17a7 | 2014-03-18 02:28:10 +0100 | [diff] [blame] | 695 | env['PYTHONIOENCODING'] = encoding |
Serhiy Storchaka | fc43511 | 2016-04-10 14:34:13 +0300 | [diff] [blame] | 696 | else: |
| 697 | env.pop('PYTHONIOENCODING', None) |
Victor Stinner | 97f17a7 | 2014-03-18 02:28:10 +0100 | [diff] [blame] | 698 | p = subprocess.Popen(args, |
| 699 | stdout=subprocess.PIPE, |
| 700 | stderr=subprocess.STDOUT, |
| 701 | env=env, |
| 702 | universal_newlines=True) |
| 703 | stdout, stderr = p.communicate() |
| 704 | return stdout |
| 705 | |
| 706 | def test_c_locale_surrogateescape(self): |
| 707 | out = self.c_locale_get_error_handler(isolated=True) |
Victor Stinner | 7143029 | 2014-03-18 01:18:21 +0100 | [diff] [blame] | 708 | self.assertEqual(out, |
Victor Stinner | 97f17a7 | 2014-03-18 02:28:10 +0100 | [diff] [blame] | 709 | 'stdin: surrogateescape\n' |
| 710 | 'stdout: surrogateescape\n' |
| 711 | 'stderr: backslashreplace\n') |
Victor Stinner | 7143029 | 2014-03-18 01:18:21 +0100 | [diff] [blame] | 712 | |
| 713 | # replace the default error handler |
Serhiy Storchaka | fc43511 | 2016-04-10 14:34:13 +0300 | [diff] [blame] | 714 | out = self.c_locale_get_error_handler(encoding=':ignore') |
| 715 | self.assertEqual(out, |
| 716 | 'stdin: ignore\n' |
| 717 | 'stdout: ignore\n' |
| 718 | 'stderr: backslashreplace\n') |
| 719 | |
| 720 | # force the encoding |
| 721 | out = self.c_locale_get_error_handler(encoding='iso8859-1') |
| 722 | self.assertEqual(out, |
| 723 | 'stdin: strict\n' |
| 724 | 'stdout: strict\n' |
| 725 | 'stderr: backslashreplace\n') |
| 726 | out = self.c_locale_get_error_handler(encoding='iso8859-1:') |
Victor Stinner | 7143029 | 2014-03-18 01:18:21 +0100 | [diff] [blame] | 727 | self.assertEqual(out, |
Victor Stinner | 97f17a7 | 2014-03-18 02:28:10 +0100 | [diff] [blame] | 728 | 'stdin: strict\n' |
| 729 | 'stdout: strict\n' |
| 730 | 'stderr: backslashreplace\n') |
Victor Stinner | 7143029 | 2014-03-18 01:18:21 +0100 | [diff] [blame] | 731 | |
Serhiy Storchaka | fc43511 | 2016-04-10 14:34:13 +0300 | [diff] [blame] | 732 | # have no any effect |
| 733 | out = self.c_locale_get_error_handler(encoding=':') |
| 734 | self.assertEqual(out, |
| 735 | 'stdin: surrogateescape\n' |
| 736 | 'stdout: surrogateescape\n' |
| 737 | 'stderr: backslashreplace\n') |
| 738 | out = self.c_locale_get_error_handler(encoding='') |
Victor Stinner | 7143029 | 2014-03-18 01:18:21 +0100 | [diff] [blame] | 739 | self.assertEqual(out, |
Victor Stinner | 97f17a7 | 2014-03-18 02:28:10 +0100 | [diff] [blame] | 740 | 'stdin: surrogateescape\n' |
| 741 | 'stdout: surrogateescape\n' |
| 742 | 'stderr: backslashreplace\n') |
Victor Stinner | 7143029 | 2014-03-18 01:18:21 +0100 | [diff] [blame] | 743 | |
Barry Warsaw | 409da15 | 2012-06-03 16:18:47 -0400 | [diff] [blame] | 744 | def test_implementation(self): |
| 745 | # This test applies to all implementations equally. |
| 746 | |
Georg Brandl | e054f45 | 2012-09-29 09:44:17 +0200 | [diff] [blame] | 747 | levels = {'alpha': 0xA, 'beta': 0xB, 'candidate': 0xC, 'final': 0xF} |
Barry Warsaw | 409da15 | 2012-06-03 16:18:47 -0400 | [diff] [blame] | 748 | |
| 749 | self.assertTrue(hasattr(sys.implementation, 'name')) |
| 750 | self.assertTrue(hasattr(sys.implementation, 'version')) |
| 751 | self.assertTrue(hasattr(sys.implementation, 'hexversion')) |
| 752 | self.assertTrue(hasattr(sys.implementation, 'cache_tag')) |
| 753 | |
| 754 | version = sys.implementation.version |
| 755 | self.assertEqual(version[:2], (version.major, version.minor)) |
| 756 | |
| 757 | hexversion = (version.major << 24 | version.minor << 16 | |
| 758 | version.micro << 8 | levels[version.releaselevel] << 4 | |
| 759 | version.serial << 0) |
| 760 | self.assertEqual(sys.implementation.hexversion, hexversion) |
| 761 | |
Barry Warsaw | 028b37c | 2012-06-04 12:01:56 -0400 | [diff] [blame] | 762 | # PEP 421 requires that .name be lower case. |
Barry Warsaw | efce00c | 2012-06-04 12:02:42 -0400 | [diff] [blame] | 763 | self.assertEqual(sys.implementation.name, |
Barry Warsaw | 028b37c | 2012-06-04 12:01:56 -0400 | [diff] [blame] | 764 | sys.implementation.name.lower()) |
| 765 | |
Victor Stinner | 8e7966b | 2014-08-16 14:11:01 +0200 | [diff] [blame] | 766 | @test.support.cpython_only |
David Malcolm | 49526f4 | 2012-06-22 14:55:41 -0400 | [diff] [blame] | 767 | def test_debugmallocstats(self): |
| 768 | # Test sys._debugmallocstats() |
Berker Peksag | ce64391 | 2015-05-06 06:33:17 +0300 | [diff] [blame] | 769 | from test.support.script_helper import assert_python_ok |
David Malcolm | 49526f4 | 2012-06-22 14:55:41 -0400 | [diff] [blame] | 770 | args = ['-c', 'import sys; sys._debugmallocstats()'] |
| 771 | ret, out, err = assert_python_ok(*args) |
| 772 | self.assertIn(b"free PyDictObjects", err) |
Martin v. Löwis | 0f59989 | 2008-06-02 11:13:03 +0000 | [diff] [blame] | 773 | |
Victor Stinner | ed0b87d | 2013-12-19 17:16:42 +0100 | [diff] [blame] | 774 | # The function has no parameter |
| 775 | self.assertRaises(TypeError, sys._debugmallocstats, True) |
| 776 | |
Antoine Pitrou | f9d0b12 | 2012-12-09 14:28:26 +0100 | [diff] [blame] | 777 | @unittest.skipUnless(hasattr(sys, "getallocatedblocks"), |
| 778 | "sys.getallocatedblocks unavailable on this build") |
| 779 | def test_getallocatedblocks(self): |
| 780 | # Some sanity checks |
Antoine Pitrou | 9284053 | 2012-12-17 23:05:59 +0100 | [diff] [blame] | 781 | with_pymalloc = sysconfig.get_config_var('WITH_PYMALLOC') |
Antoine Pitrou | f9d0b12 | 2012-12-09 14:28:26 +0100 | [diff] [blame] | 782 | a = sys.getallocatedblocks() |
| 783 | self.assertIs(type(a), int) |
Antoine Pitrou | 9284053 | 2012-12-17 23:05:59 +0100 | [diff] [blame] | 784 | if with_pymalloc: |
| 785 | self.assertGreater(a, 0) |
| 786 | else: |
Antoine Pitrou | f61dc4c | 2012-12-18 19:50:58 +0100 | [diff] [blame] | 787 | # When WITH_PYMALLOC isn't available, we don't know anything |
| 788 | # about the underlying implementation: the function might |
| 789 | # return 0 or something greater. |
| 790 | self.assertGreaterEqual(a, 0) |
Antoine Pitrou | f9d0b12 | 2012-12-09 14:28:26 +0100 | [diff] [blame] | 791 | try: |
| 792 | # While we could imagine a Python session where the number of |
| 793 | # multiple buffer objects would exceed the sharing of references, |
| 794 | # it is unlikely to happen in a normal test run. |
| 795 | self.assertLess(a, sys.gettotalrefcount()) |
| 796 | except AttributeError: |
| 797 | # gettotalrefcount() not available |
| 798 | pass |
| 799 | gc.collect() |
| 800 | b = sys.getallocatedblocks() |
| 801 | self.assertLessEqual(b, a) |
| 802 | gc.collect() |
| 803 | c = sys.getallocatedblocks() |
| 804 | self.assertIn(c, range(b - 50, b + 50)) |
| 805 | |
Serhiy Storchaka | a793037 | 2016-07-03 22:27:26 +0300 | [diff] [blame] | 806 | @test.support.requires_type_collecting |
Antoine Pitrou | 5db1bb8 | 2014-12-07 01:28:27 +0100 | [diff] [blame] | 807 | def test_is_finalizing(self): |
| 808 | self.assertIs(sys.is_finalizing(), False) |
| 809 | # Don't use the atexit module because _Py_Finalizing is only set |
| 810 | # after calling atexit callbacks |
| 811 | code = """if 1: |
| 812 | import sys |
| 813 | |
| 814 | class AtExit: |
| 815 | is_finalizing = sys.is_finalizing |
| 816 | print = print |
| 817 | |
| 818 | def __del__(self): |
| 819 | self.print(self.is_finalizing(), flush=True) |
| 820 | |
| 821 | # Keep a reference in the __main__ module namespace, so the |
| 822 | # AtExit destructor will be called at Python exit |
| 823 | ref = AtExit() |
| 824 | """ |
| 825 | rc, stdout, stderr = assert_python_ok('-c', code) |
| 826 | self.assertEqual(stdout.rstrip(), b'True') |
| 827 | |
Antoine Pitrou | f9d0b12 | 2012-12-09 14:28:26 +0100 | [diff] [blame] | 828 | |
Serhiy Storchaka | 5cfc79d | 2014-02-07 10:06:39 +0200 | [diff] [blame] | 829 | @test.support.cpython_only |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 830 | class SizeofTest(unittest.TestCase): |
| 831 | |
| 832 | def setUp(self): |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 833 | self.P = struct.calcsize('P') |
Mark Dickinson | bd79264 | 2009-03-18 20:06:12 +0000 | [diff] [blame] | 834 | self.longdigit = sys.int_info.sizeof_digit |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 835 | import _testcapi |
| 836 | self.gc_headsize = _testcapi.SIZEOF_PYGC_HEAD |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 837 | |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 838 | check_sizeof = test.support.check_sizeof |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 839 | |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 840 | def test_gc_head_size(self): |
| 841 | # Check that the gc header size is added to objects tracked by the gc. |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 842 | vsize = test.support.calcvobjsize |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 843 | gc_header_size = self.gc_headsize |
| 844 | # bool objects are not gc tracked |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 845 | self.assertEqual(sys.getsizeof(True), vsize('') + self.longdigit) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 846 | # but lists are |
Martin v. Löwis | 2b16844 | 2012-07-29 16:38:45 +0200 | [diff] [blame] | 847 | self.assertEqual(sys.getsizeof([]), vsize('Pn') + gc_header_size) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 848 | |
Serhiy Storchaka | 030e92d | 2014-11-15 13:21:37 +0200 | [diff] [blame] | 849 | def test_errors(self): |
| 850 | class BadSizeof: |
| 851 | def __sizeof__(self): |
| 852 | raise ValueError |
| 853 | self.assertRaises(ValueError, sys.getsizeof, BadSizeof()) |
| 854 | |
| 855 | class InvalidSizeof: |
| 856 | def __sizeof__(self): |
| 857 | return None |
| 858 | self.assertRaises(TypeError, sys.getsizeof, InvalidSizeof()) |
| 859 | sentinel = ["sentinel"] |
| 860 | self.assertIs(sys.getsizeof(InvalidSizeof(), sentinel), sentinel) |
| 861 | |
| 862 | class FloatSizeof: |
| 863 | def __sizeof__(self): |
| 864 | return 4.5 |
| 865 | self.assertRaises(TypeError, sys.getsizeof, FloatSizeof()) |
| 866 | self.assertIs(sys.getsizeof(FloatSizeof(), sentinel), sentinel) |
| 867 | |
| 868 | class OverflowSizeof(int): |
| 869 | def __sizeof__(self): |
| 870 | return int(self) |
| 871 | self.assertEqual(sys.getsizeof(OverflowSizeof(sys.maxsize)), |
| 872 | sys.maxsize + self.gc_headsize) |
| 873 | with self.assertRaises(OverflowError): |
| 874 | sys.getsizeof(OverflowSizeof(sys.maxsize + 1)) |
| 875 | with self.assertRaises(ValueError): |
| 876 | sys.getsizeof(OverflowSizeof(-1)) |
| 877 | with self.assertRaises((ValueError, OverflowError)): |
| 878 | sys.getsizeof(OverflowSizeof(-sys.maxsize - 1)) |
| 879 | |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 880 | def test_default(self): |
Martin v. Löwis | 2b16844 | 2012-07-29 16:38:45 +0200 | [diff] [blame] | 881 | size = test.support.calcvobjsize |
| 882 | self.assertEqual(sys.getsizeof(True), size('') + self.longdigit) |
| 883 | self.assertEqual(sys.getsizeof(True, -1), size('') + self.longdigit) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 884 | |
| 885 | def test_objecttypes(self): |
| 886 | # check all types defined in Objects/ |
Serhiy Storchaka | 5185597 | 2015-12-20 11:39:14 +0200 | [diff] [blame] | 887 | calcsize = struct.calcsize |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 888 | size = test.support.calcobjsize |
| 889 | vsize = test.support.calcvobjsize |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 890 | check = self.check_sizeof |
| 891 | # bool |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 892 | check(True, vsize('') + self.longdigit) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 893 | # buffer |
| 894 | # XXX |
| 895 | # builtin_function_or_method |
Antoine Pitrou | b349e4c | 2014-08-06 19:31:40 -0400 | [diff] [blame] | 896 | check(len, size('4P')) # XXX check layout |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 897 | # bytearray |
| 898 | samples = [b'', b'u'*100000] |
| 899 | for sample in samples: |
| 900 | x = bytearray(sample) |
Antoine Pitrou | 5df8a8a | 2013-10-05 21:12:18 +0200 | [diff] [blame] | 901 | check(x, vsize('n2Pi') + x.__alloc__()) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 902 | # bytearray_iterator |
Martin v. Löwis | 2b16844 | 2012-07-29 16:38:45 +0200 | [diff] [blame] | 903 | check(iter(bytearray()), size('nP')) |
Antoine Pitrou | a654510 | 2015-03-10 22:32:00 +0100 | [diff] [blame] | 904 | # bytes |
| 905 | check(b'', vsize('n') + 1) |
| 906 | check(b'x' * 10, vsize('n') + 11) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 907 | # cell |
| 908 | def get_cell(): |
| 909 | x = 42 |
| 910 | def inner(): |
| 911 | return x |
| 912 | return inner |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 913 | check(get_cell().__closure__[0], size('P')) |
Robert Schuppenies | 4efb518 | 2008-06-06 11:49:51 +0000 | [diff] [blame] | 914 | # code |
Martin v. Löwis | 2b16844 | 2012-07-29 16:38:45 +0200 | [diff] [blame] | 915 | check(get_cell().__code__, size('5i9Pi3P')) |
| 916 | check(get_cell.__code__, size('5i9Pi3P')) |
Martin v. Löwis | 3bbd2fa | 2012-07-26 22:23:23 +0200 | [diff] [blame] | 917 | def get_cell2(x): |
| 918 | def inner(): |
| 919 | return x |
| 920 | return inner |
Martin v. Löwis | 2b16844 | 2012-07-29 16:38:45 +0200 | [diff] [blame] | 921 | check(get_cell2.__code__, size('5i9Pi3P') + 1) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 922 | # complex |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 923 | check(complex(0,1), size('2d')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 924 | # method_descriptor (descriptor object) |
Martin v. Löwis | 2b16844 | 2012-07-29 16:38:45 +0200 | [diff] [blame] | 925 | check(str.lower, size('3PP')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 926 | # classmethod_descriptor (descriptor object) |
| 927 | # XXX |
| 928 | # member_descriptor (descriptor object) |
| 929 | import datetime |
Martin v. Löwis | 2b16844 | 2012-07-29 16:38:45 +0200 | [diff] [blame] | 930 | check(datetime.timedelta.days, size('3PP')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 931 | # getset_descriptor (descriptor object) |
| 932 | import collections |
Martin v. Löwis | 2b16844 | 2012-07-29 16:38:45 +0200 | [diff] [blame] | 933 | check(collections.defaultdict.default_factory, size('3PP')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 934 | # wrapper_descriptor (descriptor object) |
Martin v. Löwis | 2b16844 | 2012-07-29 16:38:45 +0200 | [diff] [blame] | 935 | check(int.__add__, size('3P2P')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 936 | # method-wrapper (descriptor object) |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 937 | check({}.__iter__, size('2P')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 938 | # dict |
Serhiy Storchaka | 5185597 | 2015-12-20 11:39:14 +0200 | [diff] [blame] | 939 | check({}, size('n2P') + calcsize('2nPn') + 8*calcsize('n2P')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 940 | longdict = {1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8} |
Serhiy Storchaka | 5185597 | 2015-12-20 11:39:14 +0200 | [diff] [blame] | 941 | check(longdict, size('n2P') + calcsize('2nPn') + 16*calcsize('n2P')) |
| 942 | # dictionary-keyview |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 943 | check({}.keys(), size('P')) |
Serhiy Storchaka | 5185597 | 2015-12-20 11:39:14 +0200 | [diff] [blame] | 944 | # dictionary-valueview |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 945 | check({}.values(), size('P')) |
Serhiy Storchaka | 5185597 | 2015-12-20 11:39:14 +0200 | [diff] [blame] | 946 | # dictionary-itemview |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 947 | check({}.items(), size('P')) |
| 948 | # dictionary iterator |
Martin v. Löwis | 2b16844 | 2012-07-29 16:38:45 +0200 | [diff] [blame] | 949 | check(iter({}), size('P2nPn')) |
Serhiy Storchaka | 5185597 | 2015-12-20 11:39:14 +0200 | [diff] [blame] | 950 | # dictionary-keyiterator |
| 951 | check(iter({}.keys()), size('P2nPn')) |
| 952 | # dictionary-valueiterator |
| 953 | check(iter({}.values()), size('P2nPn')) |
| 954 | # dictionary-itemiterator |
| 955 | check(iter({}.items()), size('P2nPn')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 956 | # dictproxy |
| 957 | class C(object): pass |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 958 | check(C.__dict__, size('P')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 959 | # BaseException |
Antoine Pitrou | 80bc00f | 2013-05-25 23:47:29 +0200 | [diff] [blame] | 960 | check(BaseException(), size('5Pb')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 961 | # UnicodeEncodeError |
Antoine Pitrou | 80bc00f | 2013-05-25 23:47:29 +0200 | [diff] [blame] | 962 | check(UnicodeEncodeError("", "", 0, 0, ""), size('5Pb 2P2nP')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 963 | # UnicodeDecodeError |
Antoine Pitrou | 80bc00f | 2013-05-25 23:47:29 +0200 | [diff] [blame] | 964 | check(UnicodeDecodeError("", b"", 0, 0, ""), size('5Pb 2P2nP')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 965 | # UnicodeTranslateError |
Antoine Pitrou | 80bc00f | 2013-05-25 23:47:29 +0200 | [diff] [blame] | 966 | check(UnicodeTranslateError("", 0, 1, ""), size('5Pb 2P2nP')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 967 | # ellipses |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 968 | check(Ellipsis, size('')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 969 | # EncodingMap |
| 970 | import codecs, encodings.iso8859_3 |
| 971 | x = codecs.charmap_build(encodings.iso8859_3.decoding_table) |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 972 | check(x, size('32B2iB')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 973 | # enumerate |
Martin v. Löwis | 2b16844 | 2012-07-29 16:38:45 +0200 | [diff] [blame] | 974 | check(enumerate([]), size('n3P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 975 | # reverse |
Martin v. Löwis | 2b16844 | 2012-07-29 16:38:45 +0200 | [diff] [blame] | 976 | check(reversed(''), size('nP')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 977 | # float |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 978 | check(float(0), size('d')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 979 | # sys.floatinfo |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 980 | check(sys.float_info, vsize('') + self.P * len(sys.float_info)) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 981 | # frame |
| 982 | import inspect |
| 983 | CO_MAXBLOCKS = 20 |
| 984 | x = inspect.currentframe() |
| 985 | ncells = len(x.f_code.co_cellvars) |
| 986 | nfrees = len(x.f_code.co_freevars) |
| 987 | extras = x.f_code.co_stacksize + x.f_code.co_nlocals +\ |
| 988 | ncells + nfrees - 1 |
Victor Stinner | fdeb6ec | 2013-12-13 02:01:38 +0100 | [diff] [blame] | 989 | check(x, vsize('12P3ic' + CO_MAXBLOCKS*'3i' + 'P' + extras*'P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 990 | # function |
| 991 | def func(): pass |
Martin v. Löwis | 2b16844 | 2012-07-29 16:38:45 +0200 | [diff] [blame] | 992 | check(func, size('12P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 993 | class c(): |
| 994 | @staticmethod |
| 995 | def foo(): |
| 996 | pass |
| 997 | @classmethod |
| 998 | def bar(cls): |
| 999 | pass |
| 1000 | # staticmethod |
Martin v. Löwis | 2b16844 | 2012-07-29 16:38:45 +0200 | [diff] [blame] | 1001 | check(foo, size('PP')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 1002 | # classmethod |
Martin v. Löwis | 2b16844 | 2012-07-29 16:38:45 +0200 | [diff] [blame] | 1003 | check(bar, size('PP')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 1004 | # generator |
| 1005 | def get_gen(): yield 1 |
Victor Stinner | 7db27c8 | 2014-06-16 16:21:57 +0200 | [diff] [blame] | 1006 | check(get_gen(), size('Pb2PPP')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 1007 | # iterator |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 1008 | check(iter('abc'), size('lP')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 1009 | # callable-iterator |
| 1010 | import re |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 1011 | check(re.finditer('',''), size('2P')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 1012 | # list |
| 1013 | samples = [[], [1,2,3], ['1', '2', '3']] |
| 1014 | for sample in samples: |
Martin v. Löwis | 2b16844 | 2012-07-29 16:38:45 +0200 | [diff] [blame] | 1015 | check(sample, vsize('Pn') + len(sample)*self.P) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 1016 | # sortwrapper (list) |
| 1017 | # XXX |
| 1018 | # cmpwrapper (list) |
| 1019 | # XXX |
| 1020 | # listiterator (list) |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 1021 | check(iter([]), size('lP')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 1022 | # listreverseiterator (list) |
Martin v. Löwis | 2b16844 | 2012-07-29 16:38:45 +0200 | [diff] [blame] | 1023 | check(reversed([]), size('nP')) |
Serhiy Storchaka | 9594942 | 2013-08-27 19:40:23 +0300 | [diff] [blame] | 1024 | # int |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 1025 | check(0, vsize('')) |
| 1026 | check(1, vsize('') + self.longdigit) |
| 1027 | check(-1, vsize('') + self.longdigit) |
Mark Dickinson | bd79264 | 2009-03-18 20:06:12 +0000 | [diff] [blame] | 1028 | PyLong_BASE = 2**sys.int_info.bits_per_digit |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 1029 | check(int(PyLong_BASE), vsize('') + 2*self.longdigit) |
| 1030 | check(int(PyLong_BASE**2-1), vsize('') + 2*self.longdigit) |
| 1031 | check(int(PyLong_BASE**2), vsize('') + 3*self.longdigit) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 1032 | # module |
Antoine Pitrou | dcedaf6 | 2013-07-31 23:14:08 +0200 | [diff] [blame] | 1033 | check(unittest, size('PnPPP')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 1034 | # None |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 1035 | check(None, size('')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 1036 | # NotImplementedType |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 1037 | check(NotImplemented, size('')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 1038 | # object |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 1039 | check(object(), size('')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 1040 | # property (descriptor object) |
| 1041 | class C(object): |
| 1042 | def getx(self): return self.__x |
| 1043 | def setx(self, value): self.__x = value |
| 1044 | def delx(self): del self.__x |
| 1045 | x = property(getx, setx, delx, "") |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 1046 | check(x, size('4Pi')) |
Benjamin Peterson | b173f78 | 2009-05-05 22:31:58 +0000 | [diff] [blame] | 1047 | # PyCapsule |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 1048 | # XXX |
| 1049 | # rangeiterator |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 1050 | check(iter(range(1)), size('4l')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 1051 | # reverse |
Martin v. Löwis | 2b16844 | 2012-07-29 16:38:45 +0200 | [diff] [blame] | 1052 | check(reversed(''), size('nP')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 1053 | # range |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 1054 | check(range(1), size('4P')) |
| 1055 | check(range(66000), size('4P')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 1056 | # set |
| 1057 | # frozenset |
| 1058 | PySet_MINSIZE = 8 |
| 1059 | samples = [[], range(10), range(50)] |
Raymond Hettinger | 93035c4 | 2015-01-25 16:12:49 -0800 | [diff] [blame] | 1060 | s = size('3nP' + PySet_MINSIZE*'nP' + '2nP') |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 1061 | for sample in samples: |
| 1062 | minused = len(sample) |
| 1063 | if minused == 0: tmp = 1 |
| 1064 | # the computation of minused is actually a bit more complicated |
| 1065 | # but this suffices for the sizeof test |
| 1066 | minused = minused*2 |
| 1067 | newsize = PySet_MINSIZE |
| 1068 | while newsize <= minused: |
| 1069 | newsize = newsize << 1 |
| 1070 | if newsize <= 8: |
| 1071 | check(set(sample), s) |
| 1072 | check(frozenset(sample), s) |
| 1073 | else: |
Serhiy Storchaka | 5185597 | 2015-12-20 11:39:14 +0200 | [diff] [blame] | 1074 | check(set(sample), s + newsize*calcsize('nP')) |
| 1075 | check(frozenset(sample), s + newsize*calcsize('nP')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 1076 | # setiterator |
Martin v. Löwis | 2b16844 | 2012-07-29 16:38:45 +0200 | [diff] [blame] | 1077 | check(iter(set()), size('P3n')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 1078 | # slice |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 1079 | check(slice(0), size('3P')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 1080 | # super |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 1081 | check(super(int), size('3P')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 1082 | # tuple |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 1083 | check((), vsize('')) |
| 1084 | check((1,2,3), vsize('') + 3*self.P) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 1085 | # type |
Martin v. Loewis | 4f2f3b6 | 2012-04-24 19:13:57 +0200 | [diff] [blame] | 1086 | # static type: PyTypeObject |
Serhiy Storchaka | a793037 | 2016-07-03 22:27:26 +0300 | [diff] [blame] | 1087 | fmt = 'P2n15Pl4Pn9Pn11PIP' |
| 1088 | if hasattr(sys, 'getcounts'): |
| 1089 | fmt += '3n2P' |
| 1090 | s = vsize(fmt) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 1091 | check(int, s) |
Serhiy Storchaka | a793037 | 2016-07-03 22:27:26 +0300 | [diff] [blame] | 1092 | s = vsize(fmt + # PyTypeObject |
Serhiy Storchaka | 5185597 | 2015-12-20 11:39:14 +0200 | [diff] [blame] | 1093 | '3P' # PyAsyncMethods |
| 1094 | '36P' # PyNumberMethods |
| 1095 | '3P' # PyMappingMethods |
| 1096 | '10P' # PySequenceMethods |
| 1097 | '2P' # PyBufferProcs |
| 1098 | '4P') |
Martin v. Loewis | 4f2f3b6 | 2012-04-24 19:13:57 +0200 | [diff] [blame] | 1099 | # Separate block for PyDictKeysObject with 4 entries |
Serhiy Storchaka | 5185597 | 2015-12-20 11:39:14 +0200 | [diff] [blame] | 1100 | s += calcsize("2nPn") + 4*calcsize("n2P") |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 1101 | # class |
| 1102 | class newstyleclass(object): pass |
| 1103 | check(newstyleclass, s) |
Martin v. Loewis | 4f2f3b6 | 2012-04-24 19:13:57 +0200 | [diff] [blame] | 1104 | # dict with shared keys |
Martin v. Löwis | 2b16844 | 2012-07-29 16:38:45 +0200 | [diff] [blame] | 1105 | check(newstyleclass().__dict__, size('n2P' + '2nPn')) |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 1106 | # unicode |
Martin v. Löwis | d63a3b8 | 2011-09-28 07:41:54 +0200 | [diff] [blame] | 1107 | # each tuple contains a string and its expected character size |
| 1108 | # don't put any static strings here, as they may contain |
| 1109 | # wchar_t or UTF-8 representations |
| 1110 | samples = ['1'*100, '\xff'*50, |
| 1111 | '\u0100'*40, '\uffff'*100, |
| 1112 | '\U00010000'*30, '\U0010ffff'*100] |
Antoine Pitrou | 80bc00f | 2013-05-25 23:47:29 +0200 | [diff] [blame] | 1113 | asciifields = "nnbP" |
Martin v. Löwis | 2b16844 | 2012-07-29 16:38:45 +0200 | [diff] [blame] | 1114 | compactfields = asciifields + "nPn" |
Martin v. Löwis | d63a3b8 | 2011-09-28 07:41:54 +0200 | [diff] [blame] | 1115 | unicodefields = compactfields + "P" |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 1116 | for s in samples: |
Martin v. Löwis | d63a3b8 | 2011-09-28 07:41:54 +0200 | [diff] [blame] | 1117 | maxchar = ord(max(s)) |
| 1118 | if maxchar < 128: |
| 1119 | L = size(asciifields) + len(s) + 1 |
| 1120 | elif maxchar < 256: |
| 1121 | L = size(compactfields) + len(s) + 1 |
| 1122 | elif maxchar < 65536: |
| 1123 | L = size(compactfields) + 2*(len(s) + 1) |
| 1124 | else: |
| 1125 | L = size(compactfields) + 4*(len(s) + 1) |
| 1126 | check(s, L) |
| 1127 | # verify that the UTF-8 size is accounted for |
| 1128 | s = chr(0x4000) # 4 bytes canonical representation |
| 1129 | check(s, size(compactfields) + 4) |
Martin v. Löwis | f02aa65 | 2011-09-28 09:22:13 +0200 | [diff] [blame] | 1130 | # compile() will trigger the generation of the UTF-8 |
| 1131 | # representation as a side effect |
| 1132 | compile(s, "<stdin>", "eval") |
| 1133 | check(s, size(compactfields) + 4 + 4) |
Martin v. Löwis | d63a3b8 | 2011-09-28 07:41:54 +0200 | [diff] [blame] | 1134 | # TODO: add check that forces the presence of wchar_t representation |
| 1135 | # TODO: add check that forces layout of unicodefields |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 1136 | # weakref |
| 1137 | import weakref |
Martin v. Löwis | 2b16844 | 2012-07-29 16:38:45 +0200 | [diff] [blame] | 1138 | check(weakref.ref(int), size('2Pn2P')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 1139 | # weakproxy |
| 1140 | # XXX |
| 1141 | # weakcallableproxy |
Martin v. Löwis | 2b16844 | 2012-07-29 16:38:45 +0200 | [diff] [blame] | 1142 | check(weakref.proxy(int), size('2Pn2P')) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 1143 | |
Serhiy Storchaka | 5c4064e | 2015-12-19 20:05:25 +0200 | [diff] [blame] | 1144 | def check_slots(self, obj, base, extra): |
| 1145 | expected = sys.getsizeof(base) + struct.calcsize(extra) |
| 1146 | if gc.is_tracked(obj) and not gc.is_tracked(base): |
Serhiy Storchaka | 9c297e4 | 2015-12-19 22:49:29 +0200 | [diff] [blame] | 1147 | expected += self.gc_headsize |
Serhiy Storchaka | 5c4064e | 2015-12-19 20:05:25 +0200 | [diff] [blame] | 1148 | self.assertEqual(sys.getsizeof(obj), expected) |
| 1149 | |
| 1150 | def test_slots(self): |
| 1151 | # check all subclassable types defined in Objects/ that allow |
| 1152 | # non-empty __slots__ |
| 1153 | check = self.check_slots |
| 1154 | class BA(bytearray): |
| 1155 | __slots__ = 'a', 'b', 'c' |
| 1156 | check(BA(), bytearray(), '3P') |
| 1157 | class D(dict): |
| 1158 | __slots__ = 'a', 'b', 'c' |
| 1159 | check(D(x=[]), {'x': []}, '3P') |
| 1160 | class L(list): |
| 1161 | __slots__ = 'a', 'b', 'c' |
| 1162 | check(L(), [], '3P') |
| 1163 | class S(set): |
| 1164 | __slots__ = 'a', 'b', 'c' |
| 1165 | check(S(), set(), '3P') |
| 1166 | class FS(frozenset): |
| 1167 | __slots__ = 'a', 'b', 'c' |
| 1168 | check(FS(), frozenset(), '3P') |
| 1169 | from collections import OrderedDict |
| 1170 | class OD(OrderedDict): |
| 1171 | __slots__ = 'a', 'b', 'c' |
| 1172 | check(OD(x=[]), OrderedDict(x=[]), '3P') |
| 1173 | |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 1174 | def test_pythontypes(self): |
| 1175 | # check all types defined in Python/ |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 1176 | size = test.support.calcobjsize |
| 1177 | vsize = test.support.calcvobjsize |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 1178 | check = self.check_sizeof |
| 1179 | # _ast.AST |
| 1180 | import _ast |
Martin v. Löwis | 2b16844 | 2012-07-29 16:38:45 +0200 | [diff] [blame] | 1181 | check(_ast.AST(), size('P')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 1182 | try: |
| 1183 | raise TypeError |
| 1184 | except TypeError: |
| 1185 | tb = sys.exc_info()[2] |
| 1186 | # traceback |
Benjamin Peterson | b29614e | 2012-10-09 11:16:03 -0400 | [diff] [blame] | 1187 | if tb is not None: |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 1188 | check(tb, size('2P2i')) |
Robert Schuppenies | fbe94c5 | 2008-07-14 10:13:31 +0000 | [diff] [blame] | 1189 | # symtable entry |
| 1190 | # XXX |
| 1191 | # sys.flags |
Martin v. Löwis | 33f7997 | 2012-07-29 16:33:05 +0200 | [diff] [blame] | 1192 | check(sys.flags, vsize('') + self.P * len(sys.flags)) |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 1193 | |
| 1194 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 1195 | def test_main(): |
Martin v. Löwis | 00709aa | 2008-06-04 14:18:43 +0000 | [diff] [blame] | 1196 | test.support.run_unittest(SysModuleTest, SizeofTest) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 1197 | |
| 1198 | if __name__ == "__main__": |
| 1199 | test_main() |