Json 以 mock_open 读取文件时转储

Json dumps while reading file as mock_open

我想简单地模仿使用 mock_open 读取文件,然后进行一个简单的测试,向我展示 mock_open 没有破坏任何东西。 问题是 mock_file 是这样的:

<MagicMock name='open' spec='builtin_function_or_method' id='140399632712176'>

因此我无法 json.dumps 它,所以它会 return 到 JSON 格式。 我得到的错误是:

TypeError: the JSON object must be str, bytes or bytearray, not builtin_function_or_method

有什么方法可以“取消模拟”模拟文件吗?

我的测试代码:

    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"}
            ])

mock_open() 模拟 open() 内置函数。

正如你不会做 json.loads(open) 一样,你也不能做 json.loads(mock_open())

最重要的是,json.loads() 接收到的是字符串而不是文件。为此使用 json.load().

固定码:

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