ยปCore Development>Code coverage>Lib/test/test_sys.py

Python code coverage for Lib/test/test_sys.py

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