-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpycfile.py
50 lines (45 loc) · 1.46 KB
/
pycfile.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import sys
import dis
import random
import unittest
import pyceditor
class TestPycFile(unittest.TestCase):
def test_edit_consts(self):
def f():
return 123
pyc = pyceditor.PycFile.load_from_pycode(f.__code__)
code = pyc.code
x = random.randint(15, 10**4)
code.co_consts = (None, x)
self.assertEqual(eval(pyc.pycode), x)
def test_bytecode_edit(self):
args = {
'co_argcount': 0,
'co_kwonlyargcount': 0,
'co_nlocals': 0,
'co_stacksize': 2,
'co_flags': 64,
'co_code': bytes(
[
dis.opmap['LOAD_NAME'], 0,
dis.opmap['LOAD_CONST'], 0,
dis.opmap['BINARY_MULTIPLY'], 0,
dis.opmap['RETURN_VALUE'], 0,
],
),
'co_consts': (3, 'any else'),
'co_names': ('x',),
'co_varnames': (),
'co_freevars': (),
'co_cellvars': (),
'co_filename': '<stdin>',
'co_name': '<module>',
'co_firstlineno': 1,
'co_lnotab': b'',
}
if sys.version_info[1] >= 8:
args['co_posonlyargcount'] = 0
code = pyceditor.Code(**args)
pyc = pyceditor.PycFile.load_from_code(code)
self.assertEqual(eval(pyc.pycode, {'x': 123}), 123 * 3)
self.assertEqual(eval(pyc.pycode, {'x': '123'}), '123123123')