I have a test as follows:
import mock
# other test code, test suite class declaration here
@mock.patch("other_file.another_method")
@mock.patch("other_file.open", new=mock.mock_open(read=["First line", "Second line"])
def test_file_open_and_read(self, mock_open_method, mock_another_method):
self.assertTrue(True) # Various assertions.
I'm getting the following error:
TypeError: test_file_open_and_read() takes exactly 3 arguments (2 given)
I'm trying to specify that I want the other file's __builtin__.open
method to be mocked with mock.mock_open
rather than mock.MagicMock
which is the default behavior for the patch
decorator. How can I do this?
Should use new_callable
instead of new
. That is,
@mock.patch("other_file.open", new_callable=mock.mock_open)
def test_file_open_and_read(self, mock_open_method):
# assert on the number of times open().write was called.
self.assertEqual(mock_open_method().write.call_count,
num_write_was_called)
Note that we are passing the function handle mock.mock_open
to new_callable
, not the resulting object. This allows us to do mock_open_method().write
to access the write
function, just like the example in the documentation of mock_open
shows.
You missed the parameter create
from open
builtin.
@mock.patch("other_file.open", new=mock.mock_open(read=["First line", "Second line"], create=True)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With