5

我在对使用 Kenneth Reitz请求库的函数进行单元测试时遇到问题:

以下功能要进行单元测试:

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

1 回答 1

5

很晚了,但我真的很喜欢 HTTPretty 库来解决这个确切的问题:

http://falcao.it/HTTPretty/

于 2013-11-26T22:21:08.237 回答