3

我试图在使用 POST 方法触发某些 API 后检查响应状态代码,响应状态代码是 Magicmock 实例类型,我正在使用在 python 2 中工作但引发 TypeError 的比较运算符检查状态代码是否介于 400 和 500 之间在蟒蛇 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 = 无

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

1 回答 1

1

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

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

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.
于 2019-06-17T15:43:22.300 回答