简体   繁体   English

Python 请求:断言 status_code 没有失败

[英]Python Requests: assert status_code is not failing

I'm trying to fail a test with a specific error message if an api call returns a 403 code.如果 api 调用返回 403 代码,我试图通过特定的错误消息使测试失败。 I've tried a couple options:我尝试了几个选项:

if int(addresses.status_code) is 403:
    fail("Auth Error: Missing Role {}".format(response.json()))

assert addresses.status_code is not 403

assert addresses.status_code is not codes.forbidden

assert addresses.status_code is codes.ok

The only one of these that is failing is the last, assert addresses.status_code is codes.ok .其中唯一失败的是最后一个, assert addresses.status_code is codes.ok However, the status code the api call is responding with is 403. I've played around with making sure the types are the same, etc, but not sure where else to go.但是,api 调用响应的状态代码403。我尝试过确保类型相同等,但不知道还能去哪里。

How do I test that the status_code is not a specific value?如何测试 status_code 不是特定值?

is tests for identity . is身份测试。 The status code is indeed not the same object as 403 or codes.forbidden .状态码确实与403codes.forbidden不是同一个对象。 The status value is an integer, not a singleton enumeration object.状态值是一个整数,而不是一个单例枚举对象。

Use == to test if the value is the same:使用==测试是否相同:

if addresses.status_code == 403:
    # ...

assert addresses.status_code != 403
assert addresses.status_code != codes.forbidden
assert addresses.status_code == codes.ok

or just use或者只是使用

addresses.raise_for_status()  # raises an exception if not 1xx, 2xx or 3xx

The Response.raise_for_status() method raises a requests.exceptions.HTTPError exception (a subclass of requests.exceptions.RequestException , in turn a OSError subclass).所述Response.raise_for_status()方法提出了一个requests.exceptions.HTTPError异常(的一个子类requests.exceptions.RequestException ,在转OSError子类)。

Note that sometimes is will work with integers, or any number of other types.请注意,有时is可用于整数或任意数量的其他类型。 But unless there is specific documentation that you can use identity tests, you have instead found an implementation detail where Python will have re-used objects for performance reasons.但是除非有可以使用身份测试的特定文档,否则您会找到一个实现细节,其中 Python 将出于性能原因重用对象。 Such is the case for small integers (from -5 through to 256), and for strings in certain cases, and many other corner cases.小整数(从 -5 到 256)、某些情况下的字符串以及许多其他极端情况就是这种情况。 So address.status_code is 200 just happens to work in current CPython interpreters, but this is not a given and should not be relied upon .所以address.status_code is 200恰好适用于当前的 CPython 解释器,但这不是给定的,不应依赖

You are using is , which checks the identity of two objects.您正在使用is ,它检查两个对象的身份。 For comparing int s you should use == .为了比较int你应该使用== In fact, always use == except when checking singletons (ie None ) or when you actually need to.事实上,除非检查单例(即None )或实际需要时,否则总是使用==

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM