I want to make a simple imitation of reading the file using mock_open and then to make a simple test that would show me, the mock_open didn't break anything.
The problem is that the mock_file is like this:
<MagicMock name='open' spec='builtin_function_or_method' id='140399632712176'>
and as a result I am not able to json.dumps it, so it would return to the JSON format.
The error I get is:
TypeError: the JSON object must be str, bytes or bytearray, not builtin_function_or_method
Is there any way to "unmock" the mocked file?
My test code:
def test_get_all_students_true_148(self):
stub_storage = self.storage
stub_register = self.register
data = mock_open(read_data=json.dumps([
{'id': 1, 'firstName': "User", 'lastName': "Random"},
{'id': 2, 'firstName': "User 2", 'lastName': "Random 2"},
{'id': 3, 'firstName': "User 3 ", 'lastName': "Random 3"}
]))
with patch('builtins.open', data) as mock_file:
data_to_return = json.loads(mock_file)
stub_storage.get_students = MagicMock(return_value=data_to_return)
assert_that(stub_register.get_students(), [
{'id': 1, 'firstName': "User", 'lastName': "Random"},
{'id': 2, 'firstName': "User 2", 'lastName': "Random 2"},
{'id': 3, 'firstName': "User 3 ", 'lastName': "Random 3"}
])
CodePudding user response:
mock_open() mocks the open() builtin function.
Just as you wouldn't do json.loads(open), you can't do json.loads(mock_open()).
On top of that, json.loads() receives a string and not a file. For that use json.load().
Fixed code:
from unittest.mock import *
import json
data = mock_open(read_data=json.dumps([
{'id': 1, 'firstName': "User", 'lastName': "Random"},
{'id': 2, 'firstName': "User 2", 'lastName': "Random 2"},
{'id': 3, 'firstName': "User 3 ", 'lastName': "Random 3"}
]))
with patch('builtins.open', data) as new_open:
data_to_return = json.load(new_open())
