Python HTTP Post方法将响应作为magicmock对象而不是值返回 [英] Python HTTP Post method returns response as magicmock object instead of value

查看:206
本文介绍了Python HTTP Post方法将响应作为magicmock对象而不是值返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to check the response status code after trigerring some API with a POST method, Response status code is of Magicmock instance type, i am checking whether the status code is inbetween 400 and 500 using comparison operator which works in python 2 but raises TypeError in python 3

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 =无

But when executed in python 3, raises

TypeError: '<=' not supported between instances of 'int' and 'MagicMock'

class BMRAPI(object): root_url = None

    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')

下面是UNit测试用例

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

推荐答案

这并非完全是修复,更多的是解决方法.

This isn't exactly a fix, more of a workaround.

编写一个单独的方法,而不是进行<=比较:

Instead of making that <= comparison, write a separate method:

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')

然后在测试中对其进行模拟.

Then mock it in your tests.

@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.

这篇关于Python HTTP Post方法将响应作为magicmock对象而不是值返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆