2015-07-21 137 views
0

我无法修补请求发帖方法。我读了http://www.voidspace.org.uk/python/mock/patch.html#where-to-patch。但不明白我犯了什么错误。无法修补请求发帖

结构

tests.py 
package 
    __init__.py 
    module.py 

包/ module.py

import requests 
import mock 

class Class(object): 
    def send_request(self): 
     ... 
     response = requests.post(url, data=data, headers=headers) 
     return response 

tests.py

@mock.patch('package.module.requests.post') 
def some_test(request_mock): 
    ... 
    data = {...} 
    request_mock.return_value = data 
    # invoke some class which create instance of Class 
    # and invokes send_request behind the scene 
    request_mock.assert_called_once_with() 

回溯

Traceback (most recent call last): 
    File "tests.py", line 343, in some_test 
    request_mock.assert_called_once_with() 
    File "/home/discort/python/project/env/local/lib/python2.7/site-packages/mock/mock.py", line 941, in assert_called_once_with 
    raise AssertionError(msg) 
    AssertionError: Expected 'post' to be called once. Called 0 times. 
+0

你确定'package.module.'应该是'@ mock.patch'字符串的一部分吗? – goncalopp

+0

不,但'requests.post'也不能修补 – discort

回答

1

您正在使用requests.post(...)

from requests import post 
... 
post() 

所以不要紧,打补丁 'package.module.requests.post' 或 'requests.post'。两种方式都可以。

#package.module 
... 
class Class(object): 
    def send_request(self): 
     response = requests.post('https://www.google.ru/') 
     return response 

#tests.test_module 
... 
@patch('requests.post') 
def some_test(request_mock): 
    obj = Class() 
    res = obj.send_request() 
    request_mock.assert_called_once_with('https://www.google.ru/') 

该显式调用send_request的变体是pass。你确定send_request被称为?

+0

是的,我确定。我试过了。 – discort