1 | n/a | """bytecode_helper - support tools for testing correct bytecode generation""" |
---|
2 | n/a | |
---|
3 | n/a | import unittest |
---|
4 | n/a | import dis |
---|
5 | n/a | import io |
---|
6 | n/a | |
---|
7 | n/a | _UNSPECIFIED = object() |
---|
8 | n/a | |
---|
9 | n/a | class BytecodeTestCase(unittest.TestCase): |
---|
10 | n/a | """Custom assertion methods for inspecting bytecode.""" |
---|
11 | n/a | |
---|
12 | n/a | def get_disassembly_as_string(self, co): |
---|
13 | n/a | s = io.StringIO() |
---|
14 | n/a | dis.dis(co, file=s) |
---|
15 | n/a | return s.getvalue() |
---|
16 | n/a | |
---|
17 | n/a | def assertInBytecode(self, x, opname, argval=_UNSPECIFIED): |
---|
18 | n/a | """Returns instr if op is found, otherwise throws AssertionError""" |
---|
19 | n/a | for instr in dis.get_instructions(x): |
---|
20 | n/a | if instr.opname == opname: |
---|
21 | n/a | if argval is _UNSPECIFIED or instr.argval == argval: |
---|
22 | n/a | return instr |
---|
23 | n/a | disassembly = self.get_disassembly_as_string(x) |
---|
24 | n/a | if argval is _UNSPECIFIED: |
---|
25 | n/a | msg = '%s not found in bytecode:\n%s' % (opname, disassembly) |
---|
26 | n/a | else: |
---|
27 | n/a | msg = '(%s,%r) not found in bytecode:\n%s' |
---|
28 | n/a | msg = msg % (opname, argval, disassembly) |
---|
29 | n/a | self.fail(msg) |
---|
30 | n/a | |
---|
31 | n/a | def assertNotInBytecode(self, x, opname, argval=_UNSPECIFIED): |
---|
32 | n/a | """Throws AssertionError if op is found""" |
---|
33 | n/a | for instr in dis.get_instructions(x): |
---|
34 | n/a | if instr.opname == opname: |
---|
35 | n/a | disassembly = self.get_disassembly_as_string(x) |
---|
36 | n/a | if argval is _UNSPECIFIED: |
---|
37 | n/a | msg = '%s occurs in bytecode:\n%s' % (opname, disassembly) |
---|
38 | n/a | elif instr.argval == argval: |
---|
39 | n/a | msg = '(%s,%r) occurs in bytecode:\n%s' |
---|
40 | n/a | msg = msg % (opname, argval, disassembly) |
---|
41 | n/a | self.fail(msg) |
---|