Python - Accessing objects mocked with a patch

I used the mock library to run some of my tests. It has been great so far, but there are some things that I still do not understand.

mock provides a good way to fix the whole method with patch , and I could access the fixed object in this method:

 @patch('package.module') def test_foo(self, patched_obj): # ... call patched_obj here self.assertTrue(patched_obj.called) 

My question is: how do I access the fixed object if I use the patch decorator for the whole class?

For instance:

 @patch('package.module') class TestPackage(unittest.TestCase): def test_foo(self): # how to access the patched object? 
+4
source share
1 answer

In this case, test_foo will have an additional argument, just like when decorating a method. If your method is also fixed, it will also add these arguments:

 @patch.object(os, 'listdir') class TestPackage(unittest.TestCase): @patch.object(sys, 'exit') def test_foo(self, sys_exit, os_listdir): os_listdir.return_value = ['file1', 'file2'] # ... Test logic sys_exit.assert_called_with(1) 

The order of the arguments is determined by the order of the calls to the decorators. The decorator method is created first, so it adds the first argument. The class decorator is external, so it will add a second argument. The same thing happens when you attach multiple patch decorators to the same test method or class (i.e., the external decorator comes last).

+8
source

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


All Articles