如何单元测试/模拟requests.get(url)&它的回应

时间:2013-11-03 13:51:04

标签: python unit-testing python-2.7 mocking

我无法对使用Kenneth Reitz的requests库的函数进行单元测试:

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

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()的返回值,但不能进行pickle。

1 个答案:

答案 0 :(得分:5)

很晚,但我真的很喜欢这个问题的HTTPretty库:

http://falcao.it/HTTPretty/