blob: b86cc86856808da46a4df81920e61e558e8435bd [file] [log] [blame]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001# Minimal tests for dis module
2
Nick Coghlaneae2da12010-08-17 08:03:36 +00003from test.support import run_unittest, captured_stdout
Benjamin Petersond6afe722011-03-15 14:44:52 -05004import difflib
Guido van Rossumd8faa362007-04-27 19:54:29 +00005import unittest
Skip Montanaroadd0ccc2003-02-27 21:27:07 +00006import sys
7import dis
Guido van Rossum34d19282007-08-09 01:03:29 +00008import io
Zachary Waree80e8062013-12-26 09:53:49 -06009import re
Skip Montanaroadd0ccc2003-02-27 21:27:07 +000010
Benjamin Petersond6afe722011-03-15 14:44:52 -050011class _C:
12 def __init__(self, x):
13 self.x = x == 1
14
15dis_c_instance_method = """\
16 %-4d 0 LOAD_FAST 1 (x)
17 3 LOAD_CONST 1 (1)
18 6 COMPARE_OP 2 (==)
19 9 LOAD_FAST 0 (self)
20 12 STORE_ATTR 0 (x)
21 15 LOAD_CONST 0 (None)
22 18 RETURN_VALUE
23""" % (_C.__init__.__code__.co_firstlineno + 1,)
24
25dis_c_instance_method_bytes = """\
26 0 LOAD_FAST 1 (1)
27 3 LOAD_CONST 1 (1)
28 6 COMPARE_OP 2 (==)
29 9 LOAD_FAST 0 (0)
30 12 STORE_ATTR 0 (0)
31 15 LOAD_CONST 0 (0)
32 18 RETURN_VALUE
33"""
Skip Montanaroadd0ccc2003-02-27 21:27:07 +000034
Skip Montanaroadd0ccc2003-02-27 21:27:07 +000035def _f(a):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000036 print(a)
Tim Peterseabafeb2003-03-07 15:55:36 +000037 return 1
Skip Montanaroadd0ccc2003-02-27 21:27:07 +000038
39dis_f = """\
Georg Brandl88fc6642007-02-09 21:28:07 +000040 %-4d 0 LOAD_GLOBAL 0 (print)
41 3 LOAD_FAST 0 (a)
Alexander Belopolsky74482202012-06-07 14:28:14 -040042 6 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
Georg Brandl88fc6642007-02-09 21:28:07 +000043 9 POP_TOP
Skip Montanaroadd0ccc2003-02-27 21:27:07 +000044
Georg Brandl88fc6642007-02-09 21:28:07 +000045 %-4d 10 LOAD_CONST 1 (1)
46 13 RETURN_VALUE
Georg Brandlebbf63b2010-10-14 07:23:01 +000047""" % (_f.__code__.co_firstlineno + 1,
48 _f.__code__.co_firstlineno + 2)
Michael W. Hudson26848a32003-04-29 17:07:36 +000049
50
Benjamin Petersond6afe722011-03-15 14:44:52 -050051dis_f_co_code = """\
52 0 LOAD_GLOBAL 0 (0)
53 3 LOAD_FAST 0 (0)
Alexander Belopolsky74482202012-06-07 14:28:14 -040054 6 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
Benjamin Petersond6afe722011-03-15 14:44:52 -050055 9 POP_TOP
56 10 LOAD_CONST 1 (1)
57 13 RETURN_VALUE
58"""
59
60
Michael W. Hudson26848a32003-04-29 17:07:36 +000061def bug708901():
62 for res in range(1,
63 10):
64 pass
65
66dis_bug708901 = """\
67 %-4d 0 SETUP_LOOP 23 (to 26)
68 3 LOAD_GLOBAL 0 (range)
69 6 LOAD_CONST 1 (1)
70
71 %-4d 9 LOAD_CONST 2 (10)
Alexander Belopolsky74482202012-06-07 14:28:14 -040072 12 CALL_FUNCTION 2 (2 positional, 0 keyword pair)
Michael W. Hudson26848a32003-04-29 17:07:36 +000073 15 GET_ITER
74 >> 16 FOR_ITER 6 (to 25)
75 19 STORE_FAST 0 (res)
76
77 %-4d 22 JUMP_ABSOLUTE 16
78 >> 25 POP_BLOCK
79 >> 26 LOAD_CONST 0 (None)
80 29 RETURN_VALUE
Georg Brandlebbf63b2010-10-14 07:23:01 +000081""" % (bug708901.__code__.co_firstlineno + 1,
82 bug708901.__code__.co_firstlineno + 2,
83 bug708901.__code__.co_firstlineno + 3)
Skip Montanaroadd0ccc2003-02-27 21:27:07 +000084
Neal Norwitz51abbc72005-12-18 07:06:23 +000085
86def bug1333982(x=[]):
87 assert 0, ([s for s in x] +
88 1)
89 pass
90
91dis_bug1333982 = """\
92 %-4d 0 LOAD_CONST 1 (0)
Zachary Waree80e8062013-12-26 09:53:49 -060093 3 POP_JUMP_IF_TRUE 35
94 6 LOAD_GLOBAL 0 (AssertionError)
95 9 LOAD_CONST 2 (<code object <listcomp> at 0x..., file "%s", line %d>)
96 12 LOAD_CONST 3 ('bug1333982.<locals>.<listcomp>')
97 15 MAKE_FUNCTION 0
98 18 LOAD_FAST 0 (x)
99 21 GET_ITER
100 22 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
Neal Norwitz51abbc72005-12-18 07:06:23 +0000101
Zachary Waree80e8062013-12-26 09:53:49 -0600102 %-4d 25 LOAD_CONST 4 (1)
103 28 BINARY_ADD
104 29 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
105 32 RAISE_VARARGS 1
Neal Norwitz51abbc72005-12-18 07:06:23 +0000106
Zachary Waree80e8062013-12-26 09:53:49 -0600107 %-4d >> 35 LOAD_CONST 0 (None)
108 38 RETURN_VALUE
Georg Brandlebbf63b2010-10-14 07:23:01 +0000109""" % (bug1333982.__code__.co_firstlineno + 1,
Zachary Waree80e8062013-12-26 09:53:49 -0600110 __file__,
111 bug1333982.__code__.co_firstlineno + 1,
Georg Brandlebbf63b2010-10-14 07:23:01 +0000112 bug1333982.__code__.co_firstlineno + 2,
113 bug1333982.__code__.co_firstlineno + 3)
Neal Norwitz51abbc72005-12-18 07:06:23 +0000114
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000115_BIG_LINENO_FORMAT = """\
116%3d 0 LOAD_GLOBAL 0 (spam)
117 3 POP_TOP
118 4 LOAD_CONST 0 (None)
119 7 RETURN_VALUE
120"""
121
Guido van Rossume7ba4952007-06-06 23:52:48 +0000122dis_module_expected_results = """\
123Disassembly of f:
124 4 0 LOAD_CONST 0 (None)
125 3 RETURN_VALUE
126
127Disassembly of g:
128 5 0 LOAD_CONST 0 (None)
129 3 RETURN_VALUE
130
131"""
132
Nick Coghlan5c8b54e2010-07-03 07:36:51 +0000133expr_str = "x + 1"
134
135dis_expr_str = """\
136 1 0 LOAD_NAME 0 (x)
137 3 LOAD_CONST 0 (1)
138 6 BINARY_ADD
139 7 RETURN_VALUE
140"""
141
142simple_stmt_str = "x = x + 1"
143
144dis_simple_stmt_str = """\
145 1 0 LOAD_NAME 0 (x)
146 3 LOAD_CONST 0 (1)
147 6 BINARY_ADD
148 7 STORE_NAME 0 (x)
149 10 LOAD_CONST 1 (None)
150 13 RETURN_VALUE
151"""
152
153compound_stmt_str = """\
154x = 0
155while 1:
156 x += 1"""
157# Trailing newline has been deliberately omitted
158
159dis_compound_stmt_str = """\
160 1 0 LOAD_CONST 0 (0)
161 3 STORE_NAME 0 (x)
162
163 2 6 SETUP_LOOP 13 (to 22)
164
165 3 >> 9 LOAD_NAME 0 (x)
166 12 LOAD_CONST 1 (1)
167 15 INPLACE_ADD
168 16 STORE_NAME 0 (x)
169 19 JUMP_ABSOLUTE 9
170 >> 22 LOAD_CONST 2 (None)
171 25 RETURN_VALUE
172"""
Guido van Rossume7ba4952007-06-06 23:52:48 +0000173
Skip Montanaroadd0ccc2003-02-27 21:27:07 +0000174class DisTests(unittest.TestCase):
Benjamin Petersond6afe722011-03-15 14:44:52 -0500175
176 def get_disassembly(self, func, lasti=-1, wrapper=True):
Guido van Rossum34d19282007-08-09 01:03:29 +0000177 s = io.StringIO()
Michael W. Hudson26848a32003-04-29 17:07:36 +0000178 save_stdout = sys.stdout
179 sys.stdout = s
Benjamin Petersond6afe722011-03-15 14:44:52 -0500180 try:
181 if wrapper:
182 dis.dis(func)
183 else:
184 dis.disassemble(func, lasti)
185 finally:
186 sys.stdout = save_stdout
Michael W. Hudson26848a32003-04-29 17:07:36 +0000187 # Trim trailing blanks (if any).
Benjamin Petersond6afe722011-03-15 14:44:52 -0500188 return [line.rstrip() for line in s.getvalue().splitlines()]
189
190 def get_disassemble_as_string(self, func, lasti=-1):
191 return '\n'.join(self.get_disassembly(func, lasti, False))
192
193 def do_disassembly_test(self, func, expected):
194 lines = self.get_disassembly(func)
195 expected = expected.splitlines()
Zachary Waree80e8062013-12-26 09:53:49 -0600196 if expected == lines:
197 return
198 else:
199 lines = [re.sub('0x[0-9A-Fa-f]+', '0x...', l) for l in lines]
200 if expected == lines:
201 return
202 self.fail(
Michael W. Hudson26848a32003-04-29 17:07:36 +0000203 "events did not match expectation:\n" +
204 "\n".join(difflib.ndiff(expected,
205 lines)))
206
Skip Montanaroadd0ccc2003-02-27 21:27:07 +0000207 def test_opmap(self):
Benjamin Peterson76f7f4d2011-07-17 22:49:50 -0500208 self.assertEqual(dis.opmap["NOP"], 9)
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000209 self.assertIn(dis.opmap["LOAD_CONST"], dis.hasconst)
210 self.assertIn(dis.opmap["STORE_NAME"], dis.hasname)
Skip Montanaroadd0ccc2003-02-27 21:27:07 +0000211
212 def test_opname(self):
213 self.assertEqual(dis.opname[dis.opmap["LOAD_FAST"]], "LOAD_FAST")
214
215 def test_boundaries(self):
216 self.assertEqual(dis.opmap["EXTENDED_ARG"], dis.EXTENDED_ARG)
217 self.assertEqual(dis.opmap["STORE_NAME"], dis.HAVE_ARGUMENT)
218
219 def test_dis(self):
Michael W. Hudson26848a32003-04-29 17:07:36 +0000220 self.do_disassembly_test(_f, dis_f)
221
222 def test_bug_708901(self):
223 self.do_disassembly_test(bug708901, dis_bug708901)
Skip Montanaroadd0ccc2003-02-27 21:27:07 +0000224
Neal Norwitz51abbc72005-12-18 07:06:23 +0000225 def test_bug_1333982(self):
Tim Peters83a8c392005-12-25 22:52:32 +0000226 # This one is checking bytecodes generated for an `assert` statement,
227 # so fails if the tests are run with -O. Skip this test then.
Zachary Waree80e8062013-12-26 09:53:49 -0600228 if not __debug__:
229 self.skipTest('need asserts, run without -O')
Zachary Ware9fe6d862013-12-08 00:20:35 -0600230
Zachary Waree80e8062013-12-26 09:53:49 -0600231 self.do_disassembly_test(bug1333982, dis_bug1333982)
Neal Norwitz51abbc72005-12-18 07:06:23 +0000232
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000233 def test_big_linenos(self):
234 def func(count):
235 namespace = {}
236 func = "def foo():\n " + "".join(["\n "] * count + ["spam\n"])
Georg Brandl7cae87c2006-09-06 06:51:57 +0000237 exec(func, namespace)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000238 return namespace['foo']
239
240 # Test all small ranges
Guido van Rossum805365e2007-05-07 22:24:25 +0000241 for i in range(1, 300):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000242 expected = _BIG_LINENO_FORMAT % (i + 2)
243 self.do_disassembly_test(func(i), expected)
244
245 # Test some larger ranges too
Guido van Rossum805365e2007-05-07 22:24:25 +0000246 for i in range(300, 5000, 10):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000247 expected = _BIG_LINENO_FORMAT % (i + 2)
248 self.do_disassembly_test(func(i), expected)
249
Guido van Rossume7ba4952007-06-06 23:52:48 +0000250 from test import dis_module
251 self.do_disassembly_test(dis_module, dis_module_expected_results)
252
Nick Coghlan5c8b54e2010-07-03 07:36:51 +0000253 def test_disassemble_str(self):
254 self.do_disassembly_test(expr_str, dis_expr_str)
255 self.do_disassembly_test(simple_stmt_str, dis_simple_stmt_str)
256 self.do_disassembly_test(compound_stmt_str, dis_compound_stmt_str)
257
Benjamin Petersond6afe722011-03-15 14:44:52 -0500258 def test_disassemble_bytes(self):
259 self.do_disassembly_test(_f.__code__.co_code, dis_f_co_code)
260
261 def test_disassemble_method(self):
262 self.do_disassembly_test(_C(1).__init__, dis_c_instance_method)
263
264 def test_disassemble_method_bytes(self):
265 method_bytecode = _C(1).__init__.__code__.co_code
266 self.do_disassembly_test(method_bytecode, dis_c_instance_method_bytes)
267
268 def test_dis_none(self):
Benjamin Peterson47afc2a2011-03-15 15:54:50 -0500269 try:
270 del sys.last_traceback
271 except AttributeError:
272 pass
Benjamin Petersond6afe722011-03-15 14:44:52 -0500273 self.assertRaises(RuntimeError, dis.dis, None)
274
Benjamin Petersond6afe722011-03-15 14:44:52 -0500275 def test_dis_traceback(self):
Benjamin Peterson47afc2a2011-03-15 15:54:50 -0500276 try:
277 del sys.last_traceback
278 except AttributeError:
279 pass
Benjamin Petersond6afe722011-03-15 14:44:52 -0500280
281 try:
282 1/0
283 except Exception as e:
284 tb = e.__traceback__
285 sys.last_traceback = tb
Benjamin Petersond6afe722011-03-15 14:44:52 -0500286
287 tb_dis = self.get_disassemble_as_string(tb.tb_frame.f_code, tb.tb_lasti)
288 self.do_disassembly_test(None, tb_dis)
289
290 def test_dis_object(self):
291 self.assertRaises(TypeError, dis.dis, object())
292
Nick Coghlaneae2da12010-08-17 08:03:36 +0000293code_info_code_info = """\
294Name: code_info
Nick Coghlan46e63802010-08-17 11:28:07 +0000295Filename: (.*)
Nick Coghlaneae2da12010-08-17 08:03:36 +0000296Argument count: 1
297Kw-only arguments: 0
298Number of locals: 1
299Stack size: 4
300Flags: OPTIMIZED, NEWLOCALS, NOFREE
301Constants:
Georg Brandlebbf63b2010-10-14 07:23:01 +0000302 0: %r
Nick Coghlaneae2da12010-08-17 08:03:36 +0000303 1: '__func__'
304 2: '__code__'
305 3: '<code_info>'
306 4: 'co_code'
Georg Brandlebbf63b2010-10-14 07:23:01 +0000307 5: "don't know how to disassemble %%s objects"
308%sNames:
Nick Coghlaneae2da12010-08-17 08:03:36 +0000309 0: hasattr
310 1: __func__
311 2: __code__
312 3: isinstance
313 4: str
314 5: _try_compile
315 6: _format_code_info
316 7: TypeError
317 8: type
318 9: __name__
319Variable names:
Georg Brandlebbf63b2010-10-14 07:23:01 +0000320 0: x""" % (('Formatted details of methods, functions, or code.', ' 6: None\n')
321 if sys.flags.optimize < 2 else (None, ''))
Nick Coghlaneae2da12010-08-17 08:03:36 +0000322
323@staticmethod
324def tricky(x, y, z=True, *args, c, d, e=[], **kwds):
325 def f(c=c):
326 print(x, y, z, c, d, e, f)
327 yield x, y, z, c, d, e, f
328
Nick Coghlaneae2da12010-08-17 08:03:36 +0000329code_info_tricky = """\
330Name: tricky
Nick Coghlan46e63802010-08-17 11:28:07 +0000331Filename: (.*)
Nick Coghlaneae2da12010-08-17 08:03:36 +0000332Argument count: 3
333Kw-only arguments: 3
334Number of locals: 8
335Stack size: 7
336Flags: OPTIMIZED, NEWLOCALS, VARARGS, VARKEYWORDS, GENERATOR
337Constants:
338 0: None
Nick Coghlan46e63802010-08-17 11:28:07 +0000339 1: <code object f at (.*), file "(.*)", line (.*)>
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100340 2: 'tricky.<locals>.f'
Nick Coghlaneae2da12010-08-17 08:03:36 +0000341Variable names:
342 0: x
343 1: y
344 2: z
345 3: c
346 4: d
347 5: e
348 6: args
349 7: kwds
350Cell variables:
Georg Brandla1082272012-02-20 21:41:03 +0100351 0: [edfxyz]
352 1: [edfxyz]
353 2: [edfxyz]
354 3: [edfxyz]
355 4: [edfxyz]
356 5: [edfxyz]"""
357# NOTE: the order of the cell variables above depends on dictionary order!
Nick Coghlan46e63802010-08-17 11:28:07 +0000358
359co_tricky_nested_f = tricky.__func__.__code__.co_consts[1]
Nick Coghlaneae2da12010-08-17 08:03:36 +0000360
361code_info_tricky_nested_f = """\
362Name: f
Nick Coghlan46e63802010-08-17 11:28:07 +0000363Filename: (.*)
Nick Coghlaneae2da12010-08-17 08:03:36 +0000364Argument count: 1
365Kw-only arguments: 0
366Number of locals: 1
367Stack size: 8
368Flags: OPTIMIZED, NEWLOCALS, NESTED
369Constants:
370 0: None
371Names:
372 0: print
373Variable names:
374 0: c
375Free variables:
Georg Brandl27fe2262012-02-20 22:03:28 +0100376 0: [edfxyz]
377 1: [edfxyz]
378 2: [edfxyz]
379 3: [edfxyz]
380 4: [edfxyz]
381 5: [edfxyz]"""
Nick Coghlaneae2da12010-08-17 08:03:36 +0000382
383code_info_expr_str = """\
384Name: <module>
385Filename: <code_info>
386Argument count: 0
387Kw-only arguments: 0
388Number of locals: 0
389Stack size: 2
390Flags: NOFREE
391Constants:
392 0: 1
393Names:
394 0: x"""
395
396code_info_simple_stmt_str = """\
397Name: <module>
398Filename: <code_info>
399Argument count: 0
400Kw-only arguments: 0
401Number of locals: 0
402Stack size: 2
403Flags: NOFREE
404Constants:
405 0: 1
406 1: None
407Names:
408 0: x"""
409
410code_info_compound_stmt_str = """\
411Name: <module>
412Filename: <code_info>
413Argument count: 0
414Kw-only arguments: 0
415Number of locals: 0
416Stack size: 2
417Flags: NOFREE
418Constants:
419 0: 0
420 1: 1
421 2: None
422Names:
423 0: x"""
424
425class CodeInfoTests(unittest.TestCase):
426 test_pairs = [
427 (dis.code_info, code_info_code_info),
428 (tricky, code_info_tricky),
429 (co_tricky_nested_f, code_info_tricky_nested_f),
430 (expr_str, code_info_expr_str),
431 (simple_stmt_str, code_info_simple_stmt_str),
432 (compound_stmt_str, code_info_compound_stmt_str),
433 ]
434
435 def test_code_info(self):
436 self.maxDiff = 1000
437 for x, expected in self.test_pairs:
Ezio Melottied3a7d22010-12-01 02:32:32 +0000438 self.assertRegex(dis.code_info(x), expected)
Nick Coghlaneae2da12010-08-17 08:03:36 +0000439
440 def test_show_code(self):
441 self.maxDiff = 1000
442 for x, expected in self.test_pairs:
443 with captured_stdout() as output:
444 dis.show_code(x)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000445 self.assertRegex(output.getvalue(), expected+"\n")
Nick Coghlaneae2da12010-08-17 08:03:36 +0000446
Benjamin Petersond6afe722011-03-15 14:44:52 -0500447 def test_code_info_object(self):
448 self.assertRaises(TypeError, dis.code_info, object())
449
450 def test_pretty_flags_no_flags(self):
451 self.assertEqual(dis.pretty_flags(0), '0x0')
452
453
Skip Montanaroadd0ccc2003-02-27 21:27:07 +0000454if __name__ == "__main__":
Zachary Waree80e8062013-12-26 09:53:49 -0600455 unittest.main()