diff options
author | Joannah Nanjekye <33177550+nanjekyejoannah@users.noreply.github.com> | 2019-09-12 09:02:59 (GMT) |
---|---|---|
committer | Stéphane Wirtel <stephane@wirtel.be> | 2019-09-12 09:02:59 (GMT) |
commit | 92777d5e5aed1753bafe07265dbe98b2d271815b (patch) | |
tree | a609553e4f137751da0e2624372e9b96e4f79d4e /Lib/test/support | |
parent | a06d683d7fd88721eaf59abcf5b02eb82045c7b1 (diff) | |
download | cpython-92777d5e5aed1753bafe07265dbe98b2d271815b.zip cpython-92777d5e5aed1753bafe07265dbe98b2d271815b.tar.gz cpython-92777d5e5aed1753bafe07265dbe98b2d271815b.tar.bz2 |
bpo-18578: Rename and document test.bytecode_helper as test.support.bytecode_helper (GH-15168)
Rename and document test.bytecode_helper as test.support.bytecode_helper
Diffstat (limited to 'Lib/test/support')
-rw-r--r-- | Lib/test/support/bytecode_helper.py | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/Lib/test/support/bytecode_helper.py b/Lib/test/support/bytecode_helper.py new file mode 100644 index 0000000..348e277 --- /dev/null +++ b/Lib/test/support/bytecode_helper.py @@ -0,0 +1,41 @@ +"""bytecode_helper - support tools for testing correct bytecode generation""" + +import unittest +import dis +import io + +_UNSPECIFIED = object() + +class BytecodeTestCase(unittest.TestCase): + """Custom assertion methods for inspecting bytecode.""" + + def get_disassembly_as_string(self, co): + s = io.StringIO() + dis.dis(co, file=s) + return s.getvalue() + + def assertInBytecode(self, x, opname, argval=_UNSPECIFIED): + """Returns instr if opname is found, otherwise throws AssertionError""" + for instr in dis.get_instructions(x): + if instr.opname == opname: + if argval is _UNSPECIFIED or instr.argval == argval: + return instr + disassembly = self.get_disassembly_as_string(x) + if argval is _UNSPECIFIED: + msg = '%s not found in bytecode:\n%s' % (opname, disassembly) + else: + msg = '(%s,%r) not found in bytecode:\n%s' + msg = msg % (opname, argval, disassembly) + self.fail(msg) + + def assertNotInBytecode(self, x, opname, argval=_UNSPECIFIED): + """Throws AssertionError if opname is found""" + for instr in dis.get_instructions(x): + if instr.opname == opname: + disassembly = self.get_disassembly_as_string(x) + if argval is _UNSPECIFIED: + msg = '%s occurs in bytecode:\n%s' % (opname, disassembly) + elif instr.argval == argval: + msg = '(%s,%r) occurs in bytecode:\n%s' + msg = msg % (opname, argval, disassembly) + self.fail(msg) |