Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use mock_open with a Python UnitTest decorator?

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?

like image 960
YPCrumble Avatar asked May 17 '16 01:05

YPCrumble


2 Answers

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.

like image 96
vector_bundle Avatar answered Oct 19 '22 23:10

vector_bundle


You missed the parameter create from open builtin.

@mock.patch("other_file.open", new=mock.mock_open(read=["First line", "Second line"], create=True)
like image 40
Mauro Baraldi Avatar answered Oct 20 '22 00:10

Mauro Baraldi