blob: 891f5e6fbadf1db279e5884386e0d44cec9bb4a8 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001"""This module includes tests of the code object representation.
2
3>>> def f(x):
4... def g(y):
5... return x + y
6... return g
7...
8
Neal Norwitz221085d2007-02-25 20:55:47 +00009>>> dump(f.__code__)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010name: f
11argcount: 1
Guido van Rossum4f72a782006-10-27 23:31:49 +000012kwonlyargcount: 0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013names: ()
14varnames: ('x', 'g')
15cellvars: ('x',)
16freevars: ()
17nlocals: 2
18flags: 3
Antoine Pitrou86a36b52011-11-25 18:56:07 +010019consts: ('None', '<code object g>', "'f.<locals>.g'")
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000020
Neal Norwitz221085d2007-02-25 20:55:47 +000021>>> dump(f(4).__code__)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022name: g
23argcount: 1
Guido van Rossum4f72a782006-10-27 23:31:49 +000024kwonlyargcount: 0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000025names: ()
26varnames: ('y',)
27cellvars: ()
28freevars: ('x',)
29nlocals: 1
30flags: 19
31consts: ('None',)
32
33>>> def h(x, y):
34... a = x + y
35... b = x - y
36... c = a * b
37... return c
Tim Peters536cf992005-12-25 23:18:31 +000038...
Guido van Rossum4f72a782006-10-27 23:31:49 +000039
Neal Norwitz221085d2007-02-25 20:55:47 +000040>>> dump(h.__code__)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000041name: h
42argcount: 2
Guido van Rossum4f72a782006-10-27 23:31:49 +000043kwonlyargcount: 0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000044names: ()
45varnames: ('x', 'y', 'a', 'b', 'c')
46cellvars: ()
47freevars: ()
48nlocals: 5
49flags: 67
50consts: ('None',)
51
52>>> def attrs(obj):
Guido van Rossum7131f842007-02-09 20:13:25 +000053... print(obj.attr1)
54... print(obj.attr2)
55... print(obj.attr3)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000056
Neal Norwitz221085d2007-02-25 20:55:47 +000057>>> dump(attrs.__code__)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000058name: attrs
59argcount: 1
Guido van Rossum4f72a782006-10-27 23:31:49 +000060kwonlyargcount: 0
Georg Brandl88fc6642007-02-09 21:28:07 +000061names: ('print', 'attr1', 'attr2', 'attr3')
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000062varnames: ('obj',)
63cellvars: ()
64freevars: ()
65nlocals: 1
66flags: 67
67consts: ('None',)
68
Thomas Wouters0e3f5912006-08-11 14:57:12 +000069>>> def optimize_away():
70... 'doc string'
71... 'not a docstring'
72... 53
Guido van Rossume2a383d2007-01-15 16:59:06 +000073... 0x53
Thomas Wouters0e3f5912006-08-11 14:57:12 +000074
Neal Norwitz221085d2007-02-25 20:55:47 +000075>>> dump(optimize_away.__code__)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000076name: optimize_away
77argcount: 0
Guido van Rossum4f72a782006-10-27 23:31:49 +000078kwonlyargcount: 0
Thomas Wouters0e3f5912006-08-11 14:57:12 +000079names: ()
80varnames: ()
81cellvars: ()
82freevars: ()
83nlocals: 0
84flags: 67
85consts: ("'doc string'", 'None')
86
Guido van Rossum4f72a782006-10-27 23:31:49 +000087>>> def keywordonly_args(a,b,*,k1):
88... return a,b,k1
89...
90
Neal Norwitz221085d2007-02-25 20:55:47 +000091>>> dump(keywordonly_args.__code__)
Guido van Rossum4f72a782006-10-27 23:31:49 +000092name: keywordonly_args
93argcount: 2
94kwonlyargcount: 1
95names: ()
96varnames: ('a', 'b', 'k1')
97cellvars: ()
98freevars: ()
99nlocals: 3
100flags: 67
101consts: ('None',)
102
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000103"""
104
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +0300105import sys
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700106import threading
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000107import unittest
Collin Winter4222e9c2010-03-18 22:46:40 +0000108import weakref
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700109from test.support import (run_doctest, run_unittest, cpython_only,
110 check_impl_detail)
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000111
Collin Winter4222e9c2010-03-18 22:46:40 +0000112
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000113def consts(t):
114 """Yield a doctest-safe sequence of object reprs."""
115 for elt in t:
116 r = repr(elt)
117 if r.startswith("<code object"):
118 yield "<code object %s>" % elt.co_name
119 else:
120 yield r
121
122def dump(co):
123 """Print out a text representation of a code object."""
Guido van Rossum4f72a782006-10-27 23:31:49 +0000124 for attr in ["name", "argcount", "kwonlyargcount", "names", "varnames",
125 "cellvars", "freevars", "nlocals", "flags"]:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000126 print("%s: %s" % (attr, getattr(co, "co_" + attr)))
127 print("consts:", tuple(consts(co.co_consts)))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000128
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000129
130class CodeTest(unittest.TestCase):
131
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200132 @cpython_only
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000133 def test_newempty(self):
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200134 import _testcapi
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000135 co = _testcapi.code_newempty("filename", "funcname", 15)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000136 self.assertEqual(co.co_filename, "filename")
137 self.assertEqual(co.co_name, "funcname")
138 self.assertEqual(co.co_firstlineno, 15)
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000139
Serhiy Storchaka09f3d082016-10-04 18:17:22 +0300140
141def isinterned(s):
142 return s is sys.intern(('_' + s + '_')[1:-1])
143
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +0300144class CodeConstsTest(unittest.TestCase):
145
146 def find_const(self, consts, value):
147 for v in consts:
148 if v == value:
149 return v
Serhiy Storchaka09f3d082016-10-04 18:17:22 +0300150 self.assertIn(value, consts) # raises an exception
151 self.fail('Should never be reached')
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +0300152
153 def assertIsInterned(self, s):
Serhiy Storchaka09f3d082016-10-04 18:17:22 +0300154 if not isinterned(s):
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +0300155 self.fail('String %r is not interned' % (s,))
156
Serhiy Storchaka09f3d082016-10-04 18:17:22 +0300157 def assertIsNotInterned(self, s):
158 if isinterned(s):
159 self.fail('String %r is interned' % (s,))
160
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +0300161 @cpython_only
162 def test_interned_string(self):
163 co = compile('res = "str_value"', '?', 'exec')
164 v = self.find_const(co.co_consts, 'str_value')
165 self.assertIsInterned(v)
166
167 @cpython_only
168 def test_interned_string_in_tuple(self):
169 co = compile('res = ("str_value",)', '?', 'exec')
170 v = self.find_const(co.co_consts, ('str_value',))
171 self.assertIsInterned(v[0])
172
173 @cpython_only
174 def test_interned_string_in_frozenset(self):
175 co = compile('res = a in {"str_value"}', '?', 'exec')
176 v = self.find_const(co.co_consts, frozenset(('str_value',)))
177 self.assertIsInterned(tuple(v)[0])
178
179 @cpython_only
180 def test_interned_string_default(self):
181 def f(a='str_value'):
182 return a
183 self.assertIsInterned(f())
184
Serhiy Storchaka09f3d082016-10-04 18:17:22 +0300185 @cpython_only
186 def test_interned_string_with_null(self):
187 co = compile(r'res = "str\0value!"', '?', 'exec')
188 v = self.find_const(co.co_consts, 'str\0value!')
189 self.assertIsNotInterned(v)
190
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000191
Collin Winter4222e9c2010-03-18 22:46:40 +0000192class CodeWeakRefTest(unittest.TestCase):
193
194 def test_basic(self):
195 # Create a code object in a clean environment so that we know we have
196 # the only reference to it left.
197 namespace = {}
198 exec("def f(): pass", globals(), namespace)
199 f = namespace["f"]
200 del namespace
201
202 self.called = False
203 def callback(code):
204 self.called = True
205
206 # f is now the last reference to the function, and through it, the code
207 # object. While we hold it, check that we can create a weakref and
208 # deref it. Then delete it, and check that the callback gets called and
209 # the reference dies.
210 coderef = weakref.ref(f.__code__, callback)
211 self.assertTrue(bool(coderef()))
212 del f
213 self.assertFalse(bool(coderef()))
214 self.assertTrue(self.called)
215
216
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700217if check_impl_detail(cpython=True):
218 import ctypes
219 py = ctypes.pythonapi
220 freefunc = ctypes.CFUNCTYPE(None,ctypes.c_voidp)
221
222 RequestCodeExtraIndex = py._PyEval_RequestCodeExtraIndex
223 RequestCodeExtraIndex.argtypes = (freefunc,)
224 RequestCodeExtraIndex.restype = ctypes.c_ssize_t
225
226 SetExtra = py._PyCode_SetExtra
227 SetExtra.argtypes = (ctypes.py_object, ctypes.c_ssize_t, ctypes.c_voidp)
228 SetExtra.restype = ctypes.c_int
229
230 GetExtra = py._PyCode_GetExtra
231 GetExtra.argtypes = (ctypes.py_object, ctypes.c_ssize_t,
232 ctypes.POINTER(ctypes.c_voidp))
233 GetExtra.restype = ctypes.c_int
234
235 LAST_FREED = None
236 def myfree(ptr):
237 global LAST_FREED
238 LAST_FREED = ptr
239
240 FREE_FUNC = freefunc(myfree)
241 FREE_INDEX = RequestCodeExtraIndex(FREE_FUNC)
242
243 class CoExtra(unittest.TestCase):
244 def get_func(self):
245 # Defining a function causes the containing function to have a
246 # reference to the code object. We need the code objects to go
247 # away, so we eval a lambda.
248 return eval('lambda:42')
249
250 def test_get_non_code(self):
251 f = self.get_func()
252
253 self.assertRaises(SystemError, SetExtra, 42, FREE_INDEX,
254 ctypes.c_voidp(100))
255 self.assertRaises(SystemError, GetExtra, 42, FREE_INDEX,
256 ctypes.c_voidp(100))
257
258 def test_bad_index(self):
259 f = self.get_func()
260 self.assertRaises(SystemError, SetExtra, f.__code__,
261 FREE_INDEX+100, ctypes.c_voidp(100))
262 self.assertEqual(GetExtra(f.__code__, FREE_INDEX+100,
263 ctypes.c_voidp(100)), 0)
264
265 def test_free_called(self):
266 # Verify that the provided free function gets invoked
267 # when the code object is cleaned up.
268 f = self.get_func()
269
270 SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(100))
271 del f
272 self.assertEqual(LAST_FREED, 100)
273
274 def test_get_set(self):
275 # Test basic get/set round tripping.
276 f = self.get_func()
277
278 extra = ctypes.c_voidp()
279
280 SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(200))
281 # reset should free...
282 SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(300))
283 self.assertEqual(LAST_FREED, 200)
284
285 extra = ctypes.c_voidp()
286 GetExtra(f.__code__, FREE_INDEX, extra)
287 self.assertEqual(extra.value, 300)
288 del f
289
290 def test_free_different_thread(self):
291 # Freeing a code object on a different thread then
292 # where the co_extra was set should be safe.
293 f = self.get_func()
294 class ThreadTest(threading.Thread):
295 def __init__(self, f, test):
296 super().__init__()
297 self.f = f
298 self.test = test
299 def run(self):
300 del self.f
301 self.test.assertEqual(LAST_FREED, 500)
302
303 SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(500))
304 tt = ThreadTest(f, self)
305 del f
306 tt.start()
307 tt.join()
308 self.assertEqual(LAST_FREED, 500)
309
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000310def test_main(verbose=None):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000311 from test import test_code
312 run_doctest(test_code, verbose)
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700313 tests = [CodeTest, CodeConstsTest, CodeWeakRefTest]
314 if check_impl_detail(cpython=True):
315 tests.append(CoExtra)
316 run_unittest(*tests)
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000317
Collin Winter4222e9c2010-03-18 22:46:40 +0000318if __name__ == "__main__":
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000319 test_main()