【发布时间】: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