简体   繁体   English

Json 在将文件读取为 mock_open 时转储

[英]Json dumps while reading file as mock_open

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.我想简单地模仿使用mock_open读取文件,然后做一个简单的测试来告诉我, mock_open没有破坏任何东西。 The problem is that the mock_file is like this:问题是mock_file是这样的:

<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.结果我无法json.dumps它,所以它会返回到 JSON 格式。 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"}
            ])

mock_open() mocks the open() builtin function. mock_open() open()内置 function。

Just as you wouldn't do json.loads(open) , you can't do json.loads(mock_open()) .就像你不会做json.loads(open)一样,你也不能做json.loads(mock_open())

On top of that, json.loads() receives a string and not a file.最重要的是, json.loads()接收字符串而不是文件。 For that use json.load() .为此使用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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM