pytest-assert断言状态码
时间: 2023-05-12 15:05:43 浏览: 257
可以使用pytest中的assert语句来断言状态码,例如:
```
import requests
def test_status_code():
response = requests.get('https://www.example.com')
assert response.status_code == 200
```
这个测试用例会发送一个GET请求到https://www.example.com,并断言响应的状态码为200。如果状态码不是200,测试用例会失败并显示错误信息。
相关问题
pytest接口自动化断言封装
在pytest接口自动化中,我们可以通过封装断言函数来实现断言的重用,提高代码的可维护性和可读性。下面是一个示例:
```python
import json
def assert_code(response, expected_code):
"""
封装断言状态码的函数
:param response: 接口响应
:param expected_code: 预期状态码
"""
assert response.status_code == expected_code, f"响应状态码错误,预期为{expected_code},实际为{response.status_code}"
def assert_json(response, expected_json):
"""
封装断言json响应的函数
:param response: 接口响应
:param expected_json: 预期json响应
"""
assert response.headers['Content-Type'] == 'application/json', "响应头Content-Type不是application/json"
assert response.json() == json.loads(expected_json), f"响应json内容错误,预期为{expected_json},实际为{response.text}"
```
在上面的代码中,我们封装了两个断言函数,一个用于断言状态码,一个用于断言json响应。这样,在编写测试用例时,我们只需要调用这些函数即可,如下所示:
```python
def test_login():
# 发送登录请求
response = requests.post(url, data=data)
# 断言状态码
assert_code(response, 200)
# 断言json响应
assert_json(response, '{"code": 0, "msg": "登录成功"}')
```
这样,我们就可以通过封装断言函数来实现断言的重用,提高代码的可维护性和可读性。
pytest接口自动化断言
在Pytest中进行接口自动化测试时,可以使用assert关键字来进行断言。断言的作用是判断某个条件是否为True,如果条件为True,则断言通过,测试继续执行;如果条件为False,则断言失败,测试停止执行。
下面是一个示例,演示了如何在Pytest中进行接口自动化断言:
```python
import requests
def test_api():
# 发送接口请求
response = requests.get('https://api.example.com/users')
# 断言接口返回的状态码为200
assert response.status_code == 200
# 断言接口返回的数据中包含指定的字段
assert 'name' in response.json()
assert 'email' in response.json()
# 断言接口返回的数据中某个字段的值符合预期
assert response.json()['name'] == 'John Doe'
```
在上面的示例中,我们使用了requests库发送了一个GET请求,并对返回的数据进行了断言。首先,我们断言了接口返回的状态码为200,然后断言了返回的数据中包含了'name'和'email'字段,最后断言了'name'字段的值为'John Doe'。
通过这样的断言,我们可以验证接口的返回结果是否符合预期,从而判断接口是否正常工作。