How do you unit test a nested function? [duplicate]

≡放荡痞女 提交于 2020-05-12 11:24:08

问题


How would you unit test the nested function f1() in the following example?

def f():
    def f1():
       return 1
    return 2

Or should functions that need testing not be nested?


回答1:


There is a similar question in this link. But short answer: you can't access an inner function from an outer element.

For testing purposes, maybe an alternative would be to change the inner function for a private outer one?




回答2:


You don't, because you can't.

You will have to either limit your unit testing to the outer function, or you move the inner function elsewhere.




回答3:


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


来源:https://stackoverflow.com/questions/13606178/how-do-you-unit-test-a-nested-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!