Json dumps while reading file as mock_open

Solution 1:

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())