0

I want to pass code to a test() routine, which has to :

  1. print the code
  2. execute it
  3. and finally do stuff with the result.
  4. 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 of fun(), even for fun(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?

sten
  • 7,028
  • 9
  • 41
  • 63
  • 2
    I can't figure out what you're trying to do, partly because you're relying on your code to demonstrate what you want, but your code is unrunnable and has a bunch of unexplained stuff in it. What's `fun2str`? What do you actually want the `tests()` function to do? What does `#too long` mean? What's the point of any of this -- are you trying to test your code, or are you trying to print it out, or what? – Samwise Jun 20 '22 at 04:55
  • 1
    It looks like you're trying to write unit tests, but your intention isn't clear. If you're looking to test your functions, try either the `unittest` package (which uses OOP) or `pytest` (OOP not required) – nigh_anxiety Jun 20 '22 at 06:00
  • test fwks are both too verbose to write and err reporting is not suitable to my case. I dont see they can print the code.. in short i have to recreate it ;) – sten Jun 20 '22 at 14:21
  • If you want to print the source code of a function, use the `inspect` module function `getsource(function)` https://stackoverflow.com/questions/427453/how-can-i-get-the-source-code-of-a-python-function – nigh_anxiety Jun 20 '22 at 15:22

0 Answers0