예제 #1
0
    def test_argument_parsing_serialization(self):
        """Testing Instruction.from_code argument parsing and serialization"""
        bytecode = b'%c\x01\x02' % dis.opmap['STORE_FAST']
        instructions = Instruction.from_code(bytecode)

        self.assertEqual(len(instructions), 1)

        instruction = instructions[0]
        self.assertEqual(Instruction(dis.opmap['STORE_FAST'], 0x0201),
                         instruction)
        self.assertEqual(instruction.as_bytes, bytecode)
예제 #2
0
    def decorator(func):
        func_code = func.func_code

        try:
            fn_index = func_code.co_names.index(fn_name)
        except ValueError:
            # fn_name is not called in func.
            return func

        fn_load_instruction = Instruction(dis.opmap['LOAD_GLOBAL'], fn_index)
        pop_top_instruction = Instruction(dis.opmap['POP_TOP'])
        instructions = []
        include = True

        for instruction in Instruction.from_code(func_code.co_code):
            if instruction == fn_load_instruction:
                include = False
            elif not include and instruction == pop_top_instruction:
                include = True
            elif include:
                instructions.append(instruction)

        func.func_code = CodeType(func_code.co_argcount,
                                  func_code.co_nlocals,
                                  func_code.co_stacksize,
                                  func_code.co_flags,
                                  Instruction.to_code(instructions),
                                  func_code.co_consts,
                                  func_code.co_names,
                                  func_code.co_varnames,
                                  func_code.co_filename,
                                  func_code.co_name,
                                  func_code.co_firstlineno,
                                  func_code.co_lnotab,
                                  func_code.co_freevars,
                                  func_code.co_cellvars)

        return func
예제 #3
0
    def test_extended_argument_parsing_serialization(self):
        """Testing Instruction.from_code argument parsing and serialization of
        extended arguments
        """
        bytecode = (b'%c\x03\x04%c\x01\x02'
                    % (dis.EXTENDED_ARG, dis.opmap['STORE_FAST']))

        instructions = Instruction.from_code(bytecode)

        self.assertEqual(len(instructions), 1)

        instruction = instructions[0]
        self.assertEqual(Instruction(dis.opmap['STORE_FAST'], 0x04030201),
                         instruction)
        self.assertEqual(instruction.as_bytes, bytecode)