我想做一個簡單的模仿閱讀檔案mock_open,然后做一個簡單的測驗來告訴我,mock_open沒有破壞任何東西。問題是mock_file是這樣的:
<MagicMock name='open' spec='builtin_function_or_method' id='140399632712176'>
結果我做不到json.dumps,所以它會回傳 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"}
])
uj5u.com熱心網友回復:
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())
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/416388.html
標籤:
上一篇:使用包含重新加載類
