How to use mock_open () with patch.object () in test annotation

I am trying to mock a file. Using examples, this can be done using a construction such as:

with patch('__builtin__.open', mock_open(read_data='1'), create=True) as m: with open('foo') as h: result = h.read() 

I wonder if there is a way to trick an open function using my testcase annotation. How:

 @patch.object(__builtin__, 'open') def test_check_status_running(self, m_open): 

I did not find the correct path, because for me it works for int and does not work for strings:

 @patch.object(__builtin__, 'open') def test_check_status_running1(self, m_open): m_open = mock_open(read_data='1') pid = open('testfile').read().strip() print type(pid) # <class 'mock.MagicMock'> self.assertEqual(1, int(pid)) # Pass self.assertEqual('1', pid) # Fails MismatchError: '1' != <MagicMock name='open().read()' id='39774928'> 
+4
source share
2 answers

You can fix the open method in many ways. I prefer the builtins.open patch and pass the tricked object to the testing method as follows:

 from unittest.mock import patch, mock_open from mymodule import method_that_read_with_open class TestPatch(unittest.TestCase): @patch('builtins.open', new_callable=mock_open, read_data='1') def test_open_file(self, m): string_read = method_that_read_with_open() self.assertEqual(string_read, '1') m.assert_called_with('filename', 'r') 

Note that we pass the mock_open function without calling it!

But since you are fixing the built-in method, you can also:

 class TestPatch(unittest.TestCase): @patch('builtins.open', mock_open(read_data='1')) def test_open_file(self): string_read = method_that_read_with_open() self.assertEqual(string_read, '1') open.assert_called_with('filename', 'r') 

These two examples are basically equivalent: in the first we give the patch method a factory the function that it is called to create a mock object, in the second we use the already created object as an argument.

+5
source

Assign the mock_open instance to the new_callable parameter:

 class TestClass(unittest.TestCase): @mock.patch('file_tested.open', new_callable=mock.mock_open()) def test_function(self, mock_open): pass 
+1
source

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


All Articles