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.
Genma source share