This works:
I got my program:
# module/core_functions.py
def new_input(question):
print(question)
value = input(">").strip()
return value
def main_function():
#do things
new_input("question1")
#do other things
new_input("question2")
...
I wrote an unittest:
import unittest
from unittest.mock import patch, Mock
from module.core_functions import main_function
class MytestClass(unittest.TestCase):
@patch('module.core_functions.new_input')
def test_multiple_answer(self, mock_input):
mock_input.return_value = Mock()
mock_input.side_effect = ['Answer1', 'Answer2']
result = main_function()
self.assertIn('ExpectedResult', result)
This works perfectly fine (I use nose2
to run all my tests).
Now this is not working:
As my code is getting bigger and bigger, I would like to involve other people in my project and I need to modularise my functions to make modification easier and cleaner.
So I put the new_input
function in a new file module/io.py
and I got a new subfunctions:
# module/subfunctions.py
from module.io import new_input
def subfunction():
# do things
new_input("question")
# do things
return things
And my core program evolved to:
# module/core_functions.py
from module.io import new_input
from module.subfunctions import subfunction
def main_function():
#do things
new_input("question1")
#do other things
subfuntion()
...
So the problem is that the function to mock is in several places: in the main function and in some subfunctions. I can't find a way to have my unittest working (I can't predict if AnswerX will be needed in the main function or in one subfunction).
Do you have any idea how can I fix my test so it works? Thank you (I hope I've been rather clear).
Edit:
I tried something like:
@patch('module.core_functions.new_input')
@patch('module.subfunctions.new_input')
def test_multiple_answer(self, mock_input):
mock_input.return_value = Mock()
mock_input.side_effect = ['Answer1', 'Answer2']
result = main_function()
self.assertIn('ExpectedResult', result)
But I got the error: TypeError: test_multiple_answer() takes 2 positional arguments but 3 were given
.