I am using Python's unittest
module to test a script I am writing.
The script contains a loop like this:
// my_script.py
def my_loopy_function():
aggregate_value = 0
for x in range(10):
aggregate_value = aggregate_value + complicated_function(x)
return aggregate_value
def complicated_function(x):
a = do()
b = something()
c = complicated()
return a + b + c
I have no problems using unittest
to test complicated_function
. But I would like to test my_loopy_function
by overriding complicated_function
.
I tried modifying my script so that my_loopy_function
takes complicated_function
as an optional parameter so that I can pass in a simple version from the test:
// my_modified_script.py
def my_loopy_function(action_function=None):
if action_function is not None:
complicated_function = action_function
aggregate_value = 0
for x in range(10):
aggregate_value = aggregate_value + complicated_function(x)
return aggregate_value
def complicated_function(x):
a = do()
b = something()
c = complicated()
return a + b + c
// test_my_script.py
from myscript import my_loopy_function
class TestMyScript(unittest.TestCase):
test_loopy_function(self):
def simple_function():
return 1
self.assertEqual(10, my_loopy_function(action_function=simple_function))
It has not worked as I had hoped, are there any suggestions on how I should be doing this?
mock
package. It's now part of Python 3. docs.python.org/3/library/unittest.mock.htmlcomplicated_function
withsimple_function
it stays pointing tosimple_function
even in a later test where I do not pass an 'action_function
'.