python - 无法修补请求帖子

标签 python testing mocking

我无法修补请求发布方法。我读了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

测试.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/

相关文章:

python - numpys张量点的向量化计算

python - Pandas Groupby 对列的特定值进行分组

android - 使用 Firebase 在服务器上对多个设备进行负载测试

android - SQLiteDatabse 单元测试

ruby - 有没有办法在 Rails 中模拟/ stub "puts"

python - 如何使用文本转语音(pyTTS 或 SAPI5)延长单词之间的停顿

python - 删除我的 Python 程序留下的搁置 .dat 文件的简单方法?

java - 验证 JMockit 中的部分有序方法调用

.net - 我应该如何模拟这个简单的服务层方法?

Python 3 : how to tests exceptions within with?