我正在使用bottle框架。我有這樣的代碼在Python中模擬bottle.request對象
from bottle import request
def abc():
x = request.get_header('x')
...
...
data = request.json()
...
...
我寫UT的這個功能,我想嘲笑get_header
和bottle.request
json
,並從返回我的模擬數據。
我試過了。
from mock import patch
@patch('bottle.request.headers', return_value={'x': 'x'})
@patch('bottle.request.json', return_value=...)
def test_abc(self, _, __):
...
...
但它給出的錯誤爲request.headers
是隻讀的。我也必須模擬request.json
。
感謝您的幫助提前:)。
模擬實際的'request'對象並給它適當的'json'和'headers'屬性。 –
@AlexHall,謝謝你的回覆。如果我嘲笑整個'請求'對象,那麼我必須模擬許多相同的屬性。有沒有什麼辦法嘲笑只有1-2屬性,然後它的好選擇。 – Nilesh
@AlexHallI嘗試過'request = Mock(headers = {'x':'x'},json = {})'但它失敗。 :( – Nilesh