How to check that a function is being called inside a function with nosetists

I am trying to set up automatic unit testing for a project. I have some functions that, as a side effect, are sometimes called another function. I want to write a unit test that checks if the second function is calling, but I'm at a dead end. The following is an example of pseudo code:

def a(self): data = self.get() if len(data) > 3500: self.b() # Bunch of other magic, which is easy to test. def b(self): serial.write("\x00\x01\x02") 

How to verify that a call to b() -gets?

+4
source share
2 answers

You can mock function b with mock and see if it is called. Here is an example:

 import unittest from mock import patch def a(n): if n > 10: b() def b(): print "test" class MyTestCase(unittest.TestCase): @patch('__main__.b') def test_b_called(self, mock): a(11) self.assertTrue(mock.called) @patch('__main__.b') def test_b_not_called(self, mock): a(10) self.assertFalse(mock.called) if __name__ == "__main__": unittest.main() 

See also:

Hope this helps.

+7
source

Various solutions are possible for this thing. But first, I must point out that unit testing is for unit testing; that unit may be a matter of viewing things. In your case, I would say that the unit is the function a() , because you want to check that your device is behaving correctly, that is, it calls the function b() in the right place. Another idea would be to say that the functions a() and b() are one. Then you do not like to check if the function b() called, you just want to check the result of calling the function a() . Make your own mind that suits your business best.

If you really want to test the function a() as a unit, you must prepare your device for testing. In your case, this can be done by adding an additional argument to it (which is used by function b by default) and which will be used instead of the hard encoding function b() in a() :

 def a(self, subfunction=None): is subfunction is None: # for testing subfunction = self.b data = self.get() if len(data) > 3500: subfunction() 

Now you can enter (during testing) an auxiliary function that simply informs the test that it called:

 store = None def injected(*args, **kwargs): global store store = args, kwargs obj.a(subfunction=injected) # now check if global store is set properly 
0
source

Source: https://habr.com/ru/post/1501824/


All Articles