Running unit tests on nested functions

后端 未结 6 2071
野的像风
野的像风 2020-12-16 17:32

I come from the Java world, where you can hide variables and functions and then run unit tests against them using reflection. I have used nested functions to hide implement

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-16 18:14

    I had the same doubt and found a way to get tests going for inner functions.

    def outer():
        def inner():
            pass
    
        if __debug__:
            test_inner(inner)
            # return
    
    def test_inner(f):
         f() # this calls the inner function
    
    outer()
    

    Basically you can send the inner function as a parameter to the outside and test it as you wish. When calling outer(), your test will run, and since it's a closure, it will preserve any extra property from the outer function (like variables). Using a list, you can send as many functions as you wish. To ignore the if, an option is to run the code like that:

    python -O code.py
    

提交回复
热议问题