问题
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