我无法修补请求发布方法。我读了http://www.voidspace.org.uk/python/mock/patch.html#where-to-patch。但是不知道我在哪里犯了错误。

结构体

tests.py
package
    __init__.py
    module.py


包/模块.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.

最佳答案

您正在使用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的此变体通过了。您确定send_request被调用了吗?

关于python - 无法修补请求发布,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31544286/

10-11 03:26