【问题标题】:Python HTTP Post method returns response as magicmock object instead of valuePython HTTP Post 方法将响应返回为magicmock 对象而不是值
【发布时间】:2019-09-20 21:51:53
【问题描述】:

我试图在使用 POST 方法触发某些 API 后检查响应状态代码,响应状态代码是 Magicmock 实例类型,我正在使用适用于 python 2 的比较运算符检查状态代码是否介于 400 和 500 之间但在 python 3 中引发 TypeError

import mock
response = <MagicMock name='Session().post()' id='130996186'>

以下代码适用于 python 2

if (400 <= response.status_code <= 500):
    print('works')

但在 python 3 中执行时,引发

TypeError:“int”和“MagicMock”实例之间不支持“

类 BMRAPI(对象): root_url = 无

    def __init__(self, user, api_key, root_url=BMR_URL,
             api_uri=RESULTS_API_URI):
        self.log = 
        logging.getLogger("BMRframework.Reporting.BMR6.BMRAPI")
        self.root_url = root_url
        self.url = urljoin(root_url, api_uri)
        self.log.info("Connecting to BMR REST API: %s" % self.url)
        self.session = requests.Session()
        auth = 'ApiKey {0}:{1}'.format(user, api_key)
        self.session.headers.update({
            'Content-type': 'application/json',
            'Accept': 'text/plain',
            'Authorization': auth})
        self.session.trust_env = False  # bypass the proxy

        self.log.debug("Authenticating as: %s" % user)
        self.log.debug("Using API Key: %s" % api_key)`enter code here`
        self.log.info("Connection to REST API successful")

    def url_for_resource(self, resource_name):
       return urljoin(self.url, resource_name) + "/"

    def create(self, resource_name, data):
        response = self.session.post(self.url_for_resource(resource_name),
                                 json.dumps(data), timeout=TIMEOUT)
        return self.handle_response(response)

    def handle_response(self, response):
        if (400 <= response.status_code <= 500):
            print('mars')

下面是单元测试用例

@mock.patch("requests.Session")
def BMRAPI(Session):
    api = BMRAPI('http://1.2.3.4/', 'dummy_user', '12345')
    data = {'hello': 123}
    api.create('testresource', data)

【问题讨论】:

  • 我尝试进行类型转换,但将 Magicmock 实例转换为 int 类型总是返回 1,有人可以帮我解决这个问题,谢谢
  • @blafkees ,你能帮帮我吗
  • 当我将日志行从 logging.debug(x) 更改为 logging.warning(x) 时,我开始在单元测试中看到同样的错误 - 究竟是什么原因造成的?

标签: python-3.x mocking http-post typeerror magicmock


【解决方案1】:

这并不完全是一种修复,更多的是一种解决方法。

不要进行 &lt;= 比较,而是编写一个单独的方法:

def is_4xx_or_5xx_code(status_code):
    return 400 <= status_code <= 500

if is_4xx_or_5xx_code(status_code=response.status_code):
    print('works')

然后在你的测试中模拟它。

@mock.patch('path.to_code.under_test.is_4xx_or_5xx_code')
def test_your_method(mock_status_code):
    mock_status_code.return_value = True
    # rest of the test.

【讨论】:

    猜你喜欢
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    • 2020-12-08
    相关资源
    最近更新 更多