我正在嘗試修補執行數據庫查找并返回如下對象的上下文管理器:class MyClass: @contextlib.contextmanager def client_ctx(self, id): # hidrate from DB and yield object yield client # instance of SQAlchemy model Client def run(self, id): with self.client_ctx(id) as cl: # do work here在這種情況下,客戶端類是一個 SQLAlchemy 模型。在我的測試中,我試圖修補此方法client_ctx以簡單地返回在測試中實例化的對象,如下所示:@patch('MyClass.client_ctx')def test_ctx(self, _mocked_ctx_manager): myclass = MyClass() client = Client( id=1, code='test-client') _mocked_ctx_manager.__enter__.return_value = client myclass.run(1)我得到:TypeError: Object of type MagicMock is not JSON serializable這對我來說毫無意義。我做錯了什么,有沒有更好的方法來模擬上下文管理器?
1 回答

30秒到達戰場
TA貢獻1828條經驗 獲得超6個贊
以下應該有效:
_mocked_ctx_manager.return_value.__enter__.return_value = client
您_mocked_ctx_manager
返回一個上下文管理器。因此,您需要設置__enter__.return_value
of _mocked_ctx_manager.return_value
。
我發現以下文章很有幫助:Surrender Python Mocking!我現在有你。
添加回答
舉報
0/150
提交
取消