blob: 1506fe9f6e0cf8bfcb4a2780be6175146c37f358 [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
Skip Montanaroadd0ccc2003-02-27 21:27:07 +00009
Benjamin Petersond6afe722011-03-15 14:44:52 -050010class _C:
11 def __init__(self, x):
12 self.x = x == 1
13
14dis_c_instance_method = """\
15 %-4d 0 LOAD_FAST 1 (x)
16 3 LOAD_CONST 1 (1)
17 6 COMPARE_OP 2 (==)
18 9 LOAD_FAST 0 (self)
19 12 STORE_ATTR 0 (x)
20 15 LOAD_CONST 0 (None)
21 18 RETURN_VALUE
22""" % (_C.__init__.__code__.co_firstlineno + 1,)
23
24dis_c_instance_method_bytes = """\
25 0 LOAD_FAST 1 (1)
26 3 LOAD_CONST 1 (1)
27 6 COMPARE_OP 2 (==)
28 9 LOAD_FAST 0 (0)
29 12 STORE_ATTR 0 (0)
30 15 LOAD_CONST 0 (0)
31 18 RETURN_VALUE
32"""
Skip Montanaroadd0ccc2003-02-27 21:27:07 +000033
Skip Montanaroadd0ccc2003-02-27 21:27:07 +000034def _f(a):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000035 print(a)
Tim Peterseabafeb2003-03-07 15:55:36 +000036 return 1
Skip Montanaroadd0ccc2003-02-27 21:27:07 +000037
38dis_f = """\
Georg Brandl88fc6642007-02-09 21:28:07 +000039 %-4d 0 LOAD_GLOBAL 0 (print)
40 3 LOAD_FAST 0 (a)
41 6 CALL_FUNCTION 1
42 9 POP_TOP
Skip Montanaroadd0ccc2003-02-27 21:27:07 +000043
Georg Brandl88fc6642007-02-09 21:28:07 +000044 %-4d 10 LOAD_CONST 1 (1)
45 13 RETURN_VALUE
Georg Brandlebbf63b2010-10-14 07:23:01 +000046""" % (_f.__code__.co_firstlineno + 1,
47 _f.__code__.co_firstlineno + 2)
Michael W. Hudson26848a32003-04-29 17:07:36 +000048
49
Benjamin Petersond6afe722011-03-15 14:44:52 -050050dis_f_co_code = """\
51 0 LOAD_GLOBAL 0 (0)
52 3 LOAD_FAST 0 (0)
53 6 CALL_FUNCTION 1
54 9 POP_TOP
55 10 LOAD_CONST 1 (1)
56 13 RETURN_VALUE
57"""
58
59
Michael W. Hudson26848a32003-04-29 17:07:36 +000060def bug708901():
61 for res in range(1,
62 10):
63 pass
64
65dis_bug708901 = """\
66 %-4d 0 SETUP_LOOP 23 (to 26)
67 3 LOAD_GLOBAL 0 (range)
68 6 LOAD_CONST 1 (1)
69
70 %-4d 9 LOAD_CONST 2 (10)
71 12 CALL_FUNCTION 2
72 15 GET_ITER
73 >> 16 FOR_ITER 6 (to 25)
74 19 STORE_FAST 0 (res)
75
76 %-4d 22 JUMP_ABSOLUTE 16
77 >> 25 POP_BLOCK
78 >> 26 LOAD_CONST 0 (None)
79 29 RETURN_VALUE
Georg Brandlebbf63b2010-10-14 07:23:01 +000080""" % (bug708901.__code__.co_firstlineno + 1,
81 bug708901.__code__.co_firstlineno + 2,
82 bug708901.__code__.co_firstlineno + 3)
Skip Montanaroadd0ccc2003-02-27 21:27:07 +000083
Neal Norwitz51abbc72005-12-18 07:06:23 +000084
85def bug1333982(x=[]):
86 assert 0, ([s for s in x] +
87 1)
88 pass
89
90dis_bug1333982 = """\
91 %-4d 0 LOAD_CONST 1 (0)
Antoine Pitrouf289ae62008-12-18 11:06:25 +000092 3 JUMP_IF_TRUE 33 (to 39)
Neal Norwitz51abbc72005-12-18 07:06:23 +000093 6 POP_TOP
94 7 LOAD_GLOBAL 0 (AssertionError)
95 10 BUILD_LIST 0
Antoine Pitrouf289ae62008-12-18 11:06:25 +000096 13 LOAD_FAST 0 (x)
97 16 GET_ITER
98 >> 17 FOR_ITER 12 (to 32)
99 20 STORE_FAST 1 (s)
100 23 LOAD_FAST 1 (s)
101 26 LIST_APPEND 2
102 29 JUMP_ABSOLUTE 17
Neal Norwitz51abbc72005-12-18 07:06:23 +0000103
Antoine Pitrouf289ae62008-12-18 11:06:25 +0000104 %-4d >> 32 LOAD_CONST 2 (1)
105 35 BINARY_ADD
106 36 RAISE_VARARGS 2
107 >> 39 POP_TOP
Neal Norwitz51abbc72005-12-18 07:06:23 +0000108
Antoine Pitrouf289ae62008-12-18 11:06:25 +0000109 %-4d 40 LOAD_CONST 0 (None)
110 43 RETURN_VALUE
Georg Brandlebbf63b2010-10-14 07:23:01 +0000111""" % (bug1333982.__code__.co_firstlineno + 1,
112 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()
Michael W. Hudson26848a32003-04-29 17:07:36 +0000196 if expected != lines:
197 self.fail(
198 "events did not match expectation:\n" +
199 "\n".join(difflib.ndiff(expected,
200 lines)))
201
Skip Montanaroadd0ccc2003-02-27 21:27:07 +0000202 def test_opmap(self):
Benjamin Peterson76f7f4d2011-07-17 22:49:50 -0500203 self.assertEqual(dis.opmap["NOP"], 9)
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000204 self.assertIn(dis.opmap["LOAD_CONST"], dis.hasconst)
205 self.assertIn(dis.opmap["STORE_NAME"], dis.hasname)
Skip Montanaroadd0ccc2003-02-27 21:27:07 +0000206
207 def test_opname(self):
208 self.assertEqual(dis.opname[dis.opmap["LOAD_FAST"]], "LOAD_FAST")
209
210 def test_boundaries(self):
211 self.assertEqual(dis.opmap["EXTENDED_ARG"], dis.EXTENDED_ARG)
212 self.assertEqual(dis.opmap["STORE_NAME"], dis.HAVE_ARGUMENT)
213
214 def test_dis(self):
Michael W. Hudson26848a32003-04-29 17:07:36 +0000215 self.do_disassembly_test(_f, dis_f)
216
217 def test_bug_708901(self):
218 self.do_disassembly_test(bug708901, dis_bug708901)
Skip Montanaroadd0ccc2003-02-27 21:27:07 +0000219
Neal Norwitz51abbc72005-12-18 07:06:23 +0000220 def test_bug_1333982(self):
Guido van Rossume7ba4952007-06-06 23:52:48 +0000221 # XXX: re-enable this test!
Tim Peters83a8c392005-12-25 22:52:32 +0000222 # This one is checking bytecodes generated for an `assert` statement,
223 # so fails if the tests are run with -O. Skip this test then.
Nick Coghlan650f0d02007-04-15 12:05:43 +0000224 pass # Test has been disabled due to change in the way
225 # list comps are handled. The byte code now includes
226 # a memory address and a file location, so they change from
227 # run to run.
228 # if __debug__:
229 # self.do_disassembly_test(bug1333982, dis_bug1333982)
Neal Norwitz51abbc72005-12-18 07:06:23 +0000230
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000231 def test_big_linenos(self):
232 def func(count):
233 namespace = {}
234 func = "def foo():\n " + "".join(["\n "] * count + ["spam\n"])
Georg Brandl7cae87c2006-09-06 06:51:57 +0000235 exec(func, namespace)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000236 return namespace['foo']
237
238 # Test all small ranges
Guido van Rossum805365e2007-05-07 22:24:25 +0000239 for i in range(1, 300):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000240 expected = _BIG_LINENO_FORMAT % (i + 2)
241 self.do_disassembly_test(func(i), expected)
242
243 # Test some larger ranges too
Guido van Rossum805365e2007-05-07 22:24:25 +0000244 for i in range(300, 5000, 10):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000245 expected = _BIG_LINENO_FORMAT % (i + 2)
246 self.do_disassembly_test(func(i), expected)
247
Guido van Rossume7ba4952007-06-06 23:52:48 +0000248 def test_big_linenos(self):
249 from test import dis_module
250 self.do_disassembly_test(dis_module, dis_module_expected_results)
251
Nick Coghlan5c8b54e2010-07-03 07:36:51 +0000252 def test_disassemble_str(self):
253 self.do_disassembly_test(expr_str, dis_expr_str)
254 self.do_disassembly_test(simple_stmt_str, dis_simple_stmt_str)
255 self.do_disassembly_test(compound_stmt_str, dis_compound_stmt_str)
256
Benjamin Petersond6afe722011-03-15 14:44:52 -0500257 def test_disassemble_bytes(self):
258 self.do_disassembly_test(_f.__code__.co_code, dis_f_co_code)
259
260 def test_disassemble_method(self):
261 self.do_disassembly_test(_C(1).__init__, dis_c_instance_method)
262
263 def test_disassemble_method_bytes(self):
264 method_bytecode = _C(1).__init__.__code__.co_code
265 self.do_disassembly_test(method_bytecode, dis_c_instance_method_bytes)
266
267 def test_dis_none(self):
Benjamin Peterson47afc2a2011-03-15 15:54:50 -0500268 try:
269 del sys.last_traceback
270 except AttributeError:
271 pass
Benjamin Petersond6afe722011-03-15 14:44:52 -0500272 self.assertRaises(RuntimeError, dis.dis, None)
273
274 def test_dis_object(self):
275 self.assertRaises(TypeError, dis.dis, object())
276
277 def test_dis_traceback(self):
Benjamin Peterson47afc2a2011-03-15 15:54:50 -0500278 try:
279 del sys.last_traceback
280 except AttributeError:
281 pass
Benjamin Petersond6afe722011-03-15 14:44:52 -0500282
283 try:
284 1/0
285 except Exception as e:
286 tb = e.__traceback__
287 sys.last_traceback = tb
Benjamin Petersond6afe722011-03-15 14:44:52 -0500288
289 tb_dis = self.get_disassemble_as_string(tb.tb_frame.f_code, tb.tb_lasti)
290 self.do_disassembly_test(None, tb_dis)
291
292 def test_dis_object(self):
293 self.assertRaises(TypeError, dis.dis, object())
294
Nick Coghlaneae2da12010-08-17 08:03:36 +0000295code_info_code_info = """\
296Name: code_info
Nick Coghlan46e63802010-08-17 11:28:07 +0000297Filename: (.*)
Nick Coghlaneae2da12010-08-17 08:03:36 +0000298Argument count: 1
299Kw-only arguments: 0
300Number of locals: 1
301Stack size: 4
302Flags: OPTIMIZED, NEWLOCALS, NOFREE
303Constants:
Georg Brandlebbf63b2010-10-14 07:23:01 +0000304 0: %r
Nick Coghlaneae2da12010-08-17 08:03:36 +0000305 1: '__func__'
306 2: '__code__'
307 3: '<code_info>'
308 4: 'co_code'
Georg Brandlebbf63b2010-10-14 07:23:01 +0000309 5: "don't know how to disassemble %%s objects"
310%sNames:
Nick Coghlaneae2da12010-08-17 08:03:36 +0000311 0: hasattr
312 1: __func__
313 2: __code__
314 3: isinstance
315 4: str
316 5: _try_compile
317 6: _format_code_info
318 7: TypeError
319 8: type
320 9: __name__
321Variable names:
Georg Brandlebbf63b2010-10-14 07:23:01 +0000322 0: x""" % (('Formatted details of methods, functions, or code.', ' 6: None\n')
323 if sys.flags.optimize < 2 else (None, ''))
Nick Coghlaneae2da12010-08-17 08:03:36 +0000324
325@staticmethod
326def tricky(x, y, z=True, *args, c, d, e=[], **kwds):
327 def f(c=c):
328 print(x, y, z, c, d, e, f)
329 yield x, y, z, c, d, e, f
330
Nick Coghlaneae2da12010-08-17 08:03:36 +0000331code_info_tricky = """\
332Name: tricky
Nick Coghlan46e63802010-08-17 11:28:07 +0000333Filename: (.*)
Nick Coghlaneae2da12010-08-17 08:03:36 +0000334Argument count: 3
335Kw-only arguments: 3
336Number of locals: 8
337Stack size: 7
338Flags: OPTIMIZED, NEWLOCALS, VARARGS, VARKEYWORDS, GENERATOR
339Constants:
340 0: None
Nick Coghlan46e63802010-08-17 11:28:07 +0000341 1: <code object f at (.*), file "(.*)", line (.*)>
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100342 2: 'tricky.<locals>.f'
Nick Coghlaneae2da12010-08-17 08:03:36 +0000343Variable names:
344 0: x
345 1: y
346 2: z
347 3: c
348 4: d
349 5: e
350 6: args
351 7: kwds
352Cell variables:
Georg Brandla1082272012-02-20 21:41:03 +0100353 0: [edfxyz]
354 1: [edfxyz]
355 2: [edfxyz]
356 3: [edfxyz]
357 4: [edfxyz]
358 5: [edfxyz]"""
359# NOTE: the order of the cell variables above depends on dictionary order!
Nick Coghlan46e63802010-08-17 11:28:07 +0000360
361co_tricky_nested_f = tricky.__func__.__code__.co_consts[1]
Nick Coghlaneae2da12010-08-17 08:03:36 +0000362
363code_info_tricky_nested_f = """\
364Name: f
Nick Coghlan46e63802010-08-17 11:28:07 +0000365Filename: (.*)
Nick Coghlaneae2da12010-08-17 08:03:36 +0000366Argument count: 1
367Kw-only arguments: 0
368Number of locals: 1
369Stack size: 8
370Flags: OPTIMIZED, NEWLOCALS, NESTED
371Constants:
372 0: None
373Names:
374 0: print
375Variable names:
376 0: c
377Free variables:
Georg Brandl27fe2262012-02-20 22:03:28 +0100378 0: [edfxyz]
379 1: [edfxyz]
380 2: [edfxyz]
381 3: [edfxyz]
382 4: [edfxyz]
383 5: [edfxyz]"""
Nick Coghlaneae2da12010-08-17 08:03:36 +0000384
385code_info_expr_str = """\
386Name: <module>
387Filename: <code_info>
388Argument count: 0
389Kw-only arguments: 0
390Number of locals: 0
391Stack size: 2
392Flags: NOFREE
393Constants:
394 0: 1
395Names:
396 0: x"""
397
398code_info_simple_stmt_str = """\
399Name: <module>
400Filename: <code_info>
401Argument count: 0
402Kw-only arguments: 0
403Number of locals: 0
404Stack size: 2
405Flags: NOFREE
406Constants:
407 0: 1
408 1: None
409Names:
410 0: x"""
411
412code_info_compound_stmt_str = """\
413Name: <module>
414Filename: <code_info>
415Argument count: 0
416Kw-only arguments: 0
417Number of locals: 0
418Stack size: 2
419Flags: NOFREE
420Constants:
421 0: 0
422 1: 1
423 2: None
424Names:
425 0: x"""
426
427class CodeInfoTests(unittest.TestCase):
428 test_pairs = [
429 (dis.code_info, code_info_code_info),
430 (tricky, code_info_tricky),
431 (co_tricky_nested_f, code_info_tricky_nested_f),
432 (expr_str, code_info_expr_str),
433 (simple_stmt_str, code_info_simple_stmt_str),
434 (compound_stmt_str, code_info_compound_stmt_str),
435 ]
436
437 def test_code_info(self):
438 self.maxDiff = 1000
439 for x, expected in self.test_pairs:
Ezio Melottied3a7d22010-12-01 02:32:32 +0000440 self.assertRegex(dis.code_info(x), expected)
Nick Coghlaneae2da12010-08-17 08:03:36 +0000441
442 def test_show_code(self):
443 self.maxDiff = 1000
444 for x, expected in self.test_pairs:
445 with captured_stdout() as output:
446 dis.show_code(x)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000447 self.assertRegex(output.getvalue(), expected+"\n")
Nick Coghlaneae2da12010-08-17 08:03:36 +0000448
Benjamin Petersond6afe722011-03-15 14:44:52 -0500449 def test_code_info_object(self):
450 self.assertRaises(TypeError, dis.code_info, object())
451
452 def test_pretty_flags_no_flags(self):
453 self.assertEqual(dis.pretty_flags(0), '0x0')
454
455
Skip Montanaroadd0ccc2003-02-27 21:27:07 +0000456def test_main():
Nick Coghlaneae2da12010-08-17 08:03:36 +0000457 run_unittest(DisTests, CodeInfoTests)
Skip Montanaroadd0ccc2003-02-27 21:27:07 +0000458
Skip Montanaroadd0ccc2003-02-27 21:27:07 +0000459if __name__ == "__main__":
460 test_main()