2013-11-03 190 views
4

我無法單元測試使用肯尼斯·賴茨的requests庫中的函數它的響應:如何單元測試/模擬requests.get(URL)

下面的功能是進行單元測試:

def getPage(url): 
    r = requests.get(url) 
    r.raise_for_status() # raises HTTPError if necessary 
    dom = fromstring(r.text) 
    dom.make_links_absolute(url) 
    return dom 

我的單元測試目前如下。 (雖然顯然這是行不通的。)

@patch('requests.Response') 
@patch('requests.Response.raise_for_status', return_value=None) 
@patch('requests.get', return_value=requests.Response) 
def test_getPage(mock_requests_get, mock_RFS, mock_response): 
    with open("domtest.htm", "r") as testfile: 
     mock_response.text = testfile.read()  

    dom = getPage('http://www.test.com') 
    eq_(dom, dom_test) 

產生的回溯是:

Traceback (most recent call last): 
    File "C:\Anaconda\lib\site-packages\nose\case.py", line 197, in runTest 
    self.test(*self.arg) 
    File "C:\Anaconda\lib\site-packages\mock.py", line 1201, in patched 
    return func(*args, **keywargs) 
    File "C:\...\test_myfile.py", line 79, in test_getPage 
    dom = getPage('http://www.test.com') 
    File "C:\...\myfile.py", line 67, in getPage 
    r.raise_for_status() # raises HTTPError if necessary 
TypeError: unbound method raise_for_status() must be called with Response instance as first argument (got nothing instead) 

怎樣一個單元測試,這樣使用嘲諷,而不是暫時性的網絡服務器的功能?我嘗試酸洗響應並將其設置爲requests.get()的返回值,但不能進行酸洗。

回答

4

很晚了,但我真的很喜歡HTTPretty庫這個確切的問題:

http://falcao.it/HTTPretty/

+0

我也用,這是件好事。 – Adeel

+0

該文檔缺少有關如何檢查代碼所做請求的信息。根據我迄今爲止收集的內容,您只能訪問上次提出的請求,但在測試發出多個請求的函數/方法時,這是不夠的。否則,這是一個相當不錯的項目。 - 另外,過去我使用過https://pypi.python.org/pypi/wsgi_intercept,但這對於簡單的外部服務調用來說有點矯枉過正。 – pumazi