Today I had a pretty annoying programming problem: I had to test a function that was calling another function which took a really long time, „csp_solver“.
def wrapper_fn(one, two=None): if not two: return csp_solver(one=one)
So at first I wrote
from unittest import TestCase class TestWrapperFn(TestCase): def test_csp_solver_is_called(self): result = wrapper_fn(one=1) self.assertEqual(result, 2)
The problem itself was solvable but the annoying thing was that every time I changed one line I had to rerun the whole thing and that tool forever.
csp_solver is a very slow external library. I already wrote a lot of tests for the underlying function so today I just had to make sure the calling function worked.
To do that I remembered „unittest.mock“. With mocks I can temporarily override functions that I don’t need right now and test the environment.
I just want to test that csp_solver is called during the operation and with the correct parameters so it can be patch for our scenario here:
from unittest import TestCase from mock import patch class TestWrapperFn(TestCase): @patch('csp_solver') def test_csp_solver_is_called(self, csp_solver_mock): self.assertFalse(csp_solver_mock.called) csp_solver_mock.return_value = 2 result = wrapper_fn(one=1) self.assertEqual(result, 2) self.assertTrue(csp_solver_mock.called)
This small trick allowed me to improve test execution speed significantly which allowed me to focus on the problem not debugging it, great! Hope this trick saves you some time 🙂