使用pytest进行API测试主要涉及以下几个步骤:
首先,确保你已经安装了pytest。如果没有安装,可以使用pip进行安装:
pip install pytest
创建一个新的Python文件,例如test_api.py,用于存放你的API测试代码。
在test_api.py文件中编写测试用例。你可以使用requests库来发送HTTP请求。首先,确保你已经安装了requests库:
pip install requests
import requests
import pytest
BASE_URL = "https://api.example.com"
def test_get_endpoint():
response = requests.get(f"{BASE_URL}/endpoint")
assert response.status_code == 200
assert "expected_key" in response.json()
import requests
import pytest
BASE_URL = "https://api.example.com"
def test_post_endpoint():
payload = {"key": "value"}
response = requests.post(f"{BASE_URL}/endpoint", json=payload)
assert response.status_code == 201
assert response.json()["key"] == "value"
你可以使用pytest的fixture功能来管理测试数据和环境设置。
import requests
import pytest
BASE_URL = "https://api.example.com"
@pytest.fixture(scope="module")
def api_client():
return requests.Session()
def test_get_endpoint(api_client):
response = api_client.get(f"{BASE_URL}/endpoint")
assert response.status_code == 200
assert "expected_key" in response.json()
在命令行中运行pytest来执行你的测试:
pytest test_api.py
你可以添加更多的功能来增强你的测试,例如:
pytest.mark.parametrize来参数化测试数据。pytest.fixture来管理测试环境。pytest.mark.skip和pytest.mark.skipif来跳过某些测试。pytest.mark.xfail来标记预期失败的测试。import requests
import pytest
BASE_URL = "https://api.example.com"
@pytest.mark.parametrize("payload, expected_status", [
({"key": "value"}, 201),
({"key": "wrong_value"}, 400),
])
def test_post_endpoint(payload, expected_status):
response = requests.post(f"{BASE_URL}/endpoint", json=payload)
assert response.status_code == expected_status
通过以上步骤,你可以使用pytest进行API测试,并且可以根据需要添加更多的功能和复杂性。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。