1import dis 2from test.support.import_helper import import_module 3import unittest 4 5_opcode = import_module("_opcode") 6from _opcode import stack_effect 7 8 9class OpcodeTests(unittest.TestCase): 10 11 def test_stack_effect(self): 12 self.assertEqual(stack_effect(dis.opmap['POP_TOP']), -1) 13 self.assertEqual(stack_effect(dis.opmap['DUP_TOP_TWO']), 2) 14 self.assertEqual(stack_effect(dis.opmap['BUILD_SLICE'], 0), -1) 15 self.assertEqual(stack_effect(dis.opmap['BUILD_SLICE'], 1), -1) 16 self.assertEqual(stack_effect(dis.opmap['BUILD_SLICE'], 3), -2) 17 self.assertRaises(ValueError, stack_effect, 30000) 18 self.assertRaises(ValueError, stack_effect, dis.opmap['BUILD_SLICE']) 19 self.assertRaises(ValueError, stack_effect, dis.opmap['POP_TOP'], 0) 20 # All defined opcodes 21 for name, code in dis.opmap.items(): 22 with self.subTest(opname=name): 23 if code < dis.HAVE_ARGUMENT: 24 stack_effect(code) 25 self.assertRaises(ValueError, stack_effect, code, 0) 26 else: 27 stack_effect(code, 0) 28 self.assertRaises(ValueError, stack_effect, code) 29 # All not defined opcodes 30 for code in set(range(256)) - set(dis.opmap.values()): 31 with self.subTest(opcode=code): 32 self.assertRaises(ValueError, stack_effect, code) 33 self.assertRaises(ValueError, stack_effect, code, 0) 34 35 def test_stack_effect_jump(self): 36 JUMP_IF_TRUE_OR_POP = dis.opmap['JUMP_IF_TRUE_OR_POP'] 37 self.assertEqual(stack_effect(JUMP_IF_TRUE_OR_POP, 0), 0) 38 self.assertEqual(stack_effect(JUMP_IF_TRUE_OR_POP, 0, jump=True), 0) 39 self.assertEqual(stack_effect(JUMP_IF_TRUE_OR_POP, 0, jump=False), -1) 40 FOR_ITER = dis.opmap['FOR_ITER'] 41 self.assertEqual(stack_effect(FOR_ITER, 0), 1) 42 self.assertEqual(stack_effect(FOR_ITER, 0, jump=True), -1) 43 self.assertEqual(stack_effect(FOR_ITER, 0, jump=False), 1) 44 JUMP_FORWARD = dis.opmap['JUMP_FORWARD'] 45 self.assertEqual(stack_effect(JUMP_FORWARD, 0), 0) 46 self.assertEqual(stack_effect(JUMP_FORWARD, 0, jump=True), 0) 47 self.assertEqual(stack_effect(JUMP_FORWARD, 0, jump=False), 0) 48 # All defined opcodes 49 has_jump = dis.hasjabs + dis.hasjrel 50 for name, code in dis.opmap.items(): 51 with self.subTest(opname=name): 52 if code < dis.HAVE_ARGUMENT: 53 common = stack_effect(code) 54 jump = stack_effect(code, jump=True) 55 nojump = stack_effect(code, jump=False) 56 else: 57 common = stack_effect(code, 0) 58 jump = stack_effect(code, 0, jump=True) 59 nojump = stack_effect(code, 0, jump=False) 60 if code in has_jump: 61 self.assertEqual(common, max(jump, nojump)) 62 else: 63 self.assertEqual(jump, common) 64 self.assertEqual(nojump, common) 65 66 67if __name__ == "__main__": 68 unittest.main() 69