I want to pass code to a test() routine, which has to :
- print the code
- execute it
- and finally do stuff with the result.
- should handle args in the background
For quick code snippets I can use eval(code-string)
, like this:
def test_eval(expr_str, expected):
global a,b
res = eval(expr_str) == expected
print(f'{res} : {expr_str}')
but for:
- code with assignment
test()
should do argumentless calling offun()
, even forfun(a, b...)
- or longer code
the approach is unusable.
SOLVED
def test(fun,expected,args):
res = fun(*args) == expected
expr = inspect.getsource(fun)
print(f'{res} : {expr}')
def tests():fun()
def w(a,b):#args
a += b #assignment
return a.sym == "(a + b)"
a = ...
b = ...
test(w,True,(a,b))
better ideas?