2017-05-18 23 views
1

在單元測試中,我想從請求庫創建一個假響應。如何創建僞造的響應(Python庫「請求」)

我嘗試這樣做:

response=requests.Response() 
response.content='asf' 

我得到這個異常:

response.content='asf' 
AttributeError: can't set attribute 

如何創建一個假的請求的響應?

「假」我的意思是一個Response實例,但沒有創建任何HTTP流量。

+0

你是什麼意思'假'?你想寫一個新的「響應」類? –

+0

@ t.m.adam對於「假」,我的意思是一個Response實例,但不創建任何http流量。我在這個問題上加了這個。這回答了你的問題了嗎? – guettli

+0

你的意思是像[prepared-requests](http://docs.python-requests.org/en/master/user/advanced/#prepared-requests),是嗎? –

回答

2

您可以使用requests-mock包執行此操作。來自文檔的示例:

>>> @requests_mock.Mocker() 
... def test_function(m): 
...  m.get('http://test.com', text='resp') 
...  return requests.get('http://test.com').text 
... 
>>> test_function() 
'resp' 
+0

非常感謝您的提示。我不知道這個圖書館。謝謝。 – guettli

+1

@guettli:不要混淆*要求推薦*,並用*回答最好用*解決的問題。 –