我正在尝试检查响应状态代码后,触发了一些API,响应状态代码是MagicMock实例类型,我正在检查状态代码是否在400和500之间。使用在Python 2中起作用但在Python 3中升级的比较操作员3
import mock
response = <MagicMock name='Session().post()' id='130996186'>
以下代码在Python 2
中工作if (400 <= response.status_code <= 500):
print('works')
但是在Python 3中执行时,升高
typeError:'&lt; ='在'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)
这并不是一个解决方法,更多的是解决方法。
而不是进行<=
比较,而是写一个单独的方法:
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.