i have a function in a my_fuction.py
def my_funtion(): #do something print("doing something") return True
i also have a a threading.Thread inhereting class called my_thread.py
from threading import Thread,Eventimport timeclass MyThread(Thread): def __init__(self): super().__init__(name="MyThread") self.running = Event() def run(self): self.running.set() while self.running.is_set(): return_value = my_function() print(return_value) time.sleep(3)
I want to test MyThread run method mocking my_function such that the run will not call the real my_function function but the mocked one
i have a unittest script for testing MyThread called test_my_thread.py and is as follows:
from my_thread import My_Threadimport unittestimport timefrom unittest.mock import Mock, patchdef mock_my_function(): print('didn't do anything') return Falseclass TestMyThread(unittest.TestCase): def setUp(self): self.my_thread = MyThread() def test_my_thread_run_method(self): with patch("my_function.my_function", side_effect = mock_my_function) as mock_func: self.my_thread.run() #hoping that this run method will call the my_function in its run method as mock_func time.sleep(5) self.my_thread.running.clear() self.my_thread.join() mock_func.assert_called_once() #This statement is failing which i assume is because the function was not patched in the MyThread.run method were it i s used
How can I mock 'my_function' inside the run of MyThread or is there an alternative method of testing if it is running without actually running it (an alternative to mocking it) .