使用Python进行接口测试通常涉及以下步骤:
1. 安装必要的库:
pip install requests pytest
2. 编写测试用例:
import requestsimport pytestBASE_URL = "http://example.com/api/users"def test_get_users(requests_mock):requests_mock.get(BASE_URL, json={"users": [{"id": 1, "name": "John"}, {"id": 2, "name": "Jane"}]})response = requests.get(BASE_URL)assert response.status_code == 200assert response.json() == {"users": [{"id": 1, "name": "John"}, {"id": 2, "name": "Jane"}]}
3. 运行测试:
使用`pytest`运行测试用例:
pytest test_file.py
使用`unittest`运行测试用例:
if __name__ == "__main__":unittest.main()
4. 接口请求方式:
GET:获取资源列表或特定资源信息。
POST:创建新资源。
PUT:更新现有资源。
DELETE:删除资源。
5. 接口测试用例示例:

def test_create_user(requests_mock):requests_mock.post(BASE_URL, json={"name": "John", "age": 30})response = requests.post(BASE_URL, json={"name": "John", "age": 30})assert response.status_code == 201
6. 报告生成:
使用`pytest-html`插件生成HTML格式的测试报告:
pip install pytest-htmlpytest --html=report.html
使用`BeautifulReport`生成测试报告:
from BeautifulReport import BeautifulReportbr = BeautifulReport(suite)br.report("第一份测试报告", "brreport.html", report_dir="C:\project\py27_class\py27_01day")
7. 参数化测试:
使用`pytest.mark.parametrize`进行参数化测试:
@pytest.mark.parametrize("city", ["北京", "上海", "广州"])def test_get_weather(city):url = f"http://apis.juhe.cn/simpleWeather/query?city={city}&key=my_key"response = requests.get(url)assert response.status_code == 200
8. 抓包和模拟请求:
使用`urllib2`或`requests`库模拟GET请求:
import urllib2url_save = "http://www.example.com"try:s_save = urllib2.urlopen(url_save).read()print(s_save)except urllib2.HTTPError as e:print(e.code)except urllib2.URLError as e:print(str(e))
9. 基于属性的测试:
使用`hypothesis`库进行基于属性的测试:
from hypothesis import givenfrom hypothesis.strategies import text@given(text())def test_example(name):assert len(name) > 0
以上步骤展示了如何使用Python进行接口测试用例的编写、运行和报告生成。请根据实际需求调整测试用例和测试环境
