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

# Python code coverage for Lib/test/test_code.py

#countcontent
1n/a"""This module includes tests of the code object representation.
2n/a
3n/a>>> def f(x):
4n/a... def g(y):
5n/a... return x + y
6n/a... return g
7n/a...
8n/a
9n/a>>> dump(f.__code__)
10n/aname: f
11n/aargcount: 1
12n/akwonlyargcount: 0
13n/anames: ()
14n/avarnames: ('x', 'g')
15n/acellvars: ('x',)
16n/afreevars: ()
17n/anlocals: 2
18n/aflags: 3
19n/aconsts: ('None', '<code object g>', "'f.<locals>.g'")
20n/a
21n/a>>> dump(f(4).__code__)
22n/aname: g
23n/aargcount: 1
24n/akwonlyargcount: 0
25n/anames: ()
26n/avarnames: ('y',)
27n/acellvars: ()
28n/afreevars: ('x',)
29n/anlocals: 1
30n/aflags: 19
31n/aconsts: ('None',)
32n/a
33n/a>>> def h(x, y):
34n/a... a = x + y
35n/a... b = x - y
36n/a... c = a * b
37n/a... return c
38n/a...
39n/a
40n/a>>> dump(h.__code__)
41n/aname: h
42n/aargcount: 2
43n/akwonlyargcount: 0
44n/anames: ()
45n/avarnames: ('x', 'y', 'a', 'b', 'c')
46n/acellvars: ()
47n/afreevars: ()
48n/anlocals: 5
49n/aflags: 67
50n/aconsts: ('None',)
51n/a
52n/a>>> def attrs(obj):
53n/a... print(obj.attr1)
54n/a... print(obj.attr2)
55n/a... print(obj.attr3)
56n/a
57n/a>>> dump(attrs.__code__)
58n/aname: attrs
59n/aargcount: 1
60n/akwonlyargcount: 0
61n/anames: ('print', 'attr1', 'attr2', 'attr3')
62n/avarnames: ('obj',)
63n/acellvars: ()
64n/afreevars: ()
65n/anlocals: 1
66n/aflags: 67
67n/aconsts: ('None',)
68n/a
69n/a>>> def optimize_away():
70n/a... 'doc string'
71n/a... 'not a docstring'
72n/a... 53
73n/a... 0x53
74n/a
75n/a>>> dump(optimize_away.__code__)
76n/aname: optimize_away
77n/aargcount: 0
78n/akwonlyargcount: 0
79n/anames: ()
80n/avarnames: ()
81n/acellvars: ()
82n/afreevars: ()
83n/anlocals: 0
84n/aflags: 67
85n/aconsts: ("'doc string'", 'None')
86n/a
87n/a>>> def keywordonly_args(a,b,*,k1):
88n/a... return a,b,k1
89n/a...
90n/a
91n/a>>> dump(keywordonly_args.__code__)
92n/aname: keywordonly_args
93n/aargcount: 2
94n/akwonlyargcount: 1
95n/anames: ()
96n/avarnames: ('a', 'b', 'k1')
97n/acellvars: ()
98n/afreevars: ()
99n/anlocals: 3
100n/aflags: 67
101n/aconsts: ('None',)
102n/a
103n/a"""
104n/a
105n/aimport sys
106n/aimport unittest
107n/aimport weakref
108n/afrom test.support import run_doctest, run_unittest, cpython_only
109n/a
110n/a
111n/adef consts(t):
112n/a """Yield a doctest-safe sequence of object reprs."""
113n/a for elt in t:
114n/a r = repr(elt)
115n/a if r.startswith("<code object"):
116n/a yield "<code object %s>" % elt.co_name
117n/a else:
118n/a yield r
119n/a
120n/adef dump(co):
121n/a """Print out a text representation of a code object."""
122n/a for attr in ["name", "argcount", "kwonlyargcount", "names", "varnames",
123n/a "cellvars", "freevars", "nlocals", "flags"]:
124n/a print("%s: %s" % (attr, getattr(co, "co_" + attr)))
125n/a print("consts:", tuple(consts(co.co_consts)))
126n/a
127n/a
128n/aclass CodeTest(unittest.TestCase):
129n/a
130n/a @cpython_only
131n/a def test_newempty(self):
132n/a import _testcapi
133n/a co = _testcapi.code_newempty("filename", "funcname", 15)
134n/a self.assertEqual(co.co_filename, "filename")
135n/a self.assertEqual(co.co_name, "funcname")
136n/a self.assertEqual(co.co_firstlineno, 15)
137n/a
138n/a
139n/adef isinterned(s):
140n/a return s is sys.intern(('_' + s + '_')[1:-1])
141n/a
142n/aclass CodeConstsTest(unittest.TestCase):
143n/a
144n/a def find_const(self, consts, value):
145n/a for v in consts:
146n/a if v == value:
147n/a return v
148n/a self.assertIn(value, consts) # raises an exception
149n/a self.fail('Should never be reached')
150n/a
151n/a def assertIsInterned(self, s):
152n/a if not isinterned(s):
153n/a self.fail('String %r is not interned' % (s,))
154n/a
155n/a def assertIsNotInterned(self, s):
156n/a if isinterned(s):
157n/a self.fail('String %r is interned' % (s,))
158n/a
159n/a @cpython_only
160n/a def test_interned_string(self):
161n/a co = compile('res = "str_value"', '?', 'exec')
162n/a v = self.find_const(co.co_consts, 'str_value')
163n/a self.assertIsInterned(v)
164n/a
165n/a @cpython_only
166n/a def test_interned_string_in_tuple(self):
167n/a co = compile('res = ("str_value",)', '?', 'exec')
168n/a v = self.find_const(co.co_consts, ('str_value',))
169n/a self.assertIsInterned(v[0])
170n/a
171n/a @cpython_only
172n/a def test_interned_string_in_frozenset(self):
173n/a co = compile('res = a in {"str_value"}', '?', 'exec')
174n/a v = self.find_const(co.co_consts, frozenset(('str_value',)))
175n/a self.assertIsInterned(tuple(v)[0])
176n/a
177n/a @cpython_only
178n/a def test_interned_string_default(self):
179n/a def f(a='str_value'):
180n/a return a
181n/a self.assertIsInterned(f())
182n/a
183n/a @cpython_only
184n/a def test_interned_string_with_null(self):
185n/a co = compile(r'res = "str\0value!"', '?', 'exec')
186n/a v = self.find_const(co.co_consts, 'str\0value!')
187n/a self.assertIsNotInterned(v)
188n/a
189n/a
190n/aclass CodeWeakRefTest(unittest.TestCase):
191n/a
192n/a def test_basic(self):
193n/a # Create a code object in a clean environment so that we know we have
194n/a # the only reference to it left.
195n/a namespace = {}
196n/a exec("def f(): pass", globals(), namespace)
197n/a f = namespace["f"]
198n/a del namespace
199n/a
200n/a self.called = False
201n/a def callback(code):
202n/a self.called = True
203n/a
204n/a # f is now the last reference to the function, and through it, the code
205n/a # object. While we hold it, check that we can create a weakref and
206n/a # deref it. Then delete it, and check that the callback gets called and
207n/a # the reference dies.
208n/a coderef = weakref.ref(f.__code__, callback)
209n/a self.assertTrue(bool(coderef()))
210n/a del f
211n/a self.assertFalse(bool(coderef()))
212n/a self.assertTrue(self.called)
213n/a
214n/a
215n/adef test_main(verbose=None):
216n/a from test import test_code
217n/a run_doctest(test_code, verbose)
218n/a run_unittest(CodeTest, CodeConstsTest, CodeWeakRefTest)
219n/a
220n/a
221n/aif __name__ == "__main__":
222n/a test_main()