如何单元测试/模拟requests.get(url)及其响应

ARF*_*ARF 5 python unit-testing mocking python-2.7

我无法对使用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
Run Code Online (Sandbox Code Playgroud)

我的单元测试目前如下.(虽然显然这不起作用.)

@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)
Run Code Online (Sandbox Code Playgroud)

结果回溯是:

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)
Run Code Online (Sandbox Code Playgroud)

一个单元如何使用模拟而不是临时的Web服务器来测试这样的函数?我试着挑选响应并将其设置为requests.get()的返回值,但它无法被pickle.

Rac*_*ers 5

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

http://falcao.it/HTTPretty/