blob: 90cb584ac40a01fbd5164358f38f3066294e4500 [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
Victor Stinnera4b091e2017-06-23 15:08:55 +0200109try:
110 import ctypes
111except ImportError:
112 ctypes = None
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700113from test.support import (run_doctest, run_unittest, cpython_only,
114 check_impl_detail)
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000115
Collin Winter4222e9c2010-03-18 22:46:40 +0000116
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000117def consts(t):
118 """Yield a doctest-safe sequence of object reprs."""
119 for elt in t:
120 r = repr(elt)
121 if r.startswith("<code object"):
122 yield "<code object %s>" % elt.co_name
123 else:
124 yield r
125
126def dump(co):
127 """Print out a text representation of a code object."""
Guido van Rossum4f72a782006-10-27 23:31:49 +0000128 for attr in ["name", "argcount", "kwonlyargcount", "names", "varnames",
129 "cellvars", "freevars", "nlocals", "flags"]:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000130 print("%s: %s" % (attr, getattr(co, "co_" + attr)))
131 print("consts:", tuple(consts(co.co_consts)))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000132
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000133
134class CodeTest(unittest.TestCase):
135
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200136 @cpython_only
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000137 def test_newempty(self):
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200138 import _testcapi
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000139 co = _testcapi.code_newempty("filename", "funcname", 15)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000140 self.assertEqual(co.co_filename, "filename")
141 self.assertEqual(co.co_name, "funcname")
142 self.assertEqual(co.co_firstlineno, 15)
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000143
Serhiy Storchaka09f3d082016-10-04 18:17:22 +0300144
145def isinterned(s):
146 return s is sys.intern(('_' + s + '_')[1:-1])
147
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +0300148class CodeConstsTest(unittest.TestCase):
149
150 def find_const(self, consts, value):
151 for v in consts:
152 if v == value:
153 return v
Serhiy Storchaka09f3d082016-10-04 18:17:22 +0300154 self.assertIn(value, consts) # raises an exception
155 self.fail('Should never be reached')
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +0300156
157 def assertIsInterned(self, s):
Serhiy Storchaka09f3d082016-10-04 18:17:22 +0300158 if not isinterned(s):
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +0300159 self.fail('String %r is not interned' % (s,))
160
Serhiy Storchaka09f3d082016-10-04 18:17:22 +0300161 def assertIsNotInterned(self, s):
162 if isinterned(s):
163 self.fail('String %r is interned' % (s,))
164
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +0300165 @cpython_only
166 def test_interned_string(self):
167 co = compile('res = "str_value"', '?', 'exec')
168 v = self.find_const(co.co_consts, 'str_value')
169 self.assertIsInterned(v)
170
171 @cpython_only
172 def test_interned_string_in_tuple(self):
173 co = compile('res = ("str_value",)', '?', 'exec')
174 v = self.find_const(co.co_consts, ('str_value',))
175 self.assertIsInterned(v[0])
176
177 @cpython_only
178 def test_interned_string_in_frozenset(self):
179 co = compile('res = a in {"str_value"}', '?', 'exec')
180 v = self.find_const(co.co_consts, frozenset(('str_value',)))
181 self.assertIsInterned(tuple(v)[0])
182
183 @cpython_only
184 def test_interned_string_default(self):
185 def f(a='str_value'):
186 return a
187 self.assertIsInterned(f())
188
Serhiy Storchaka09f3d082016-10-04 18:17:22 +0300189 @cpython_only
190 def test_interned_string_with_null(self):
191 co = compile(r'res = "str\0value!"', '?', 'exec')
192 v = self.find_const(co.co_consts, 'str\0value!')
193 self.assertIsNotInterned(v)
194
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000195
Collin Winter4222e9c2010-03-18 22:46:40 +0000196class CodeWeakRefTest(unittest.TestCase):
197
198 def test_basic(self):
199 # Create a code object in a clean environment so that we know we have
200 # the only reference to it left.
201 namespace = {}
202 exec("def f(): pass", globals(), namespace)
203 f = namespace["f"]
204 del namespace
205
206 self.called = False
207 def callback(code):
208 self.called = True
209
210 # f is now the last reference to the function, and through it, the code
211 # object. While we hold it, check that we can create a weakref and
212 # deref it. Then delete it, and check that the callback gets called and
213 # the reference dies.
214 coderef = weakref.ref(f.__code__, callback)
215 self.assertTrue(bool(coderef()))
216 del f
217 self.assertFalse(bool(coderef()))
218 self.assertTrue(self.called)
219
220
Victor Stinnera4b091e2017-06-23 15:08:55 +0200221if check_impl_detail(cpython=True) and ctypes is not None:
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700222 py = ctypes.pythonapi
223 freefunc = ctypes.CFUNCTYPE(None,ctypes.c_voidp)
224
225 RequestCodeExtraIndex = py._PyEval_RequestCodeExtraIndex
226 RequestCodeExtraIndex.argtypes = (freefunc,)
227 RequestCodeExtraIndex.restype = ctypes.c_ssize_t
228
229 SetExtra = py._PyCode_SetExtra
230 SetExtra.argtypes = (ctypes.py_object, ctypes.c_ssize_t, ctypes.c_voidp)
231 SetExtra.restype = ctypes.c_int
232
233 GetExtra = py._PyCode_GetExtra
234 GetExtra.argtypes = (ctypes.py_object, ctypes.c_ssize_t,
235 ctypes.POINTER(ctypes.c_voidp))
236 GetExtra.restype = ctypes.c_int
237
238 LAST_FREED = None
239 def myfree(ptr):
240 global LAST_FREED
241 LAST_FREED = ptr
242
243 FREE_FUNC = freefunc(myfree)
244 FREE_INDEX = RequestCodeExtraIndex(FREE_FUNC)
245
246 class CoExtra(unittest.TestCase):
247 def get_func(self):
248 # Defining a function causes the containing function to have a
249 # reference to the code object. We need the code objects to go
250 # away, so we eval a lambda.
251 return eval('lambda:42')
252
253 def test_get_non_code(self):
254 f = self.get_func()
255
256 self.assertRaises(SystemError, SetExtra, 42, FREE_INDEX,
257 ctypes.c_voidp(100))
258 self.assertRaises(SystemError, GetExtra, 42, FREE_INDEX,
259 ctypes.c_voidp(100))
260
261 def test_bad_index(self):
262 f = self.get_func()
263 self.assertRaises(SystemError, SetExtra, f.__code__,
264 FREE_INDEX+100, ctypes.c_voidp(100))
265 self.assertEqual(GetExtra(f.__code__, FREE_INDEX+100,
266 ctypes.c_voidp(100)), 0)
267
268 def test_free_called(self):
269 # Verify that the provided free function gets invoked
270 # when the code object is cleaned up.
271 f = self.get_func()
272
273 SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(100))
274 del f
275 self.assertEqual(LAST_FREED, 100)
276
277 def test_get_set(self):
278 # Test basic get/set round tripping.
279 f = self.get_func()
280
281 extra = ctypes.c_voidp()
282
283 SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(200))
284 # reset should free...
285 SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(300))
286 self.assertEqual(LAST_FREED, 200)
287
288 extra = ctypes.c_voidp()
289 GetExtra(f.__code__, FREE_INDEX, extra)
290 self.assertEqual(extra.value, 300)
291 del f
292
293 def test_free_different_thread(self):
294 # Freeing a code object on a different thread then
295 # where the co_extra was set should be safe.
296 f = self.get_func()
297 class ThreadTest(threading.Thread):
298 def __init__(self, f, test):
299 super().__init__()
300 self.f = f
301 self.test = test
302 def run(self):
303 del self.f
304 self.test.assertEqual(LAST_FREED, 500)
305
306 SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(500))
307 tt = ThreadTest(f, self)
308 del f
309 tt.start()
310 tt.join()
311 self.assertEqual(LAST_FREED, 500)
312
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000313def test_main(verbose=None):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000314 from test import test_code
315 run_doctest(test_code, verbose)
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700316 tests = [CodeTest, CodeConstsTest, CodeWeakRefTest]
Victor Stinnera4b091e2017-06-23 15:08:55 +0200317 if check_impl_detail(cpython=True) and ctypes is not None:
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700318 tests.append(CoExtra)
319 run_unittest(*tests)
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000320
Collin Winter4222e9c2010-03-18 22:46:40 +0000321if __name__ == "__main__":
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000322 test_main()