合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
## 实战要求 >[info] 巩固前面章节中关于requests库,pytests库,threading库的使用 >1. 对一个HTTP接口进行功能测试 >2. 对一个HTTP接口进行压力测试 >练习接口1:http://httpbin.org/json >练习接口2:https://postman-echo.com/get ## 规则 * 请独立完成实战要求,完成后再参考下面的示例代码 * 如果觉得自己的代码<span style="color:red">*更加优雅,更加高效*</span>,欢迎留言**,与大家一起**分享**哦~ :-: <span style="color:green;font-size:30;">一起来挑战吧~</span> <br> ## 参考代码: ```python #!/usr/bin/env python # -*- coding: utf-8 -*- import requests import pytest @pytest.fixture(params=[{"name": "Milton"}, {"name": "Cherish"}]) def test_data(request): return request.param class UrlData(object): def __init__(self): self.title_url = "http://httpbin.org/json" self.name_url = "https://postman-echo.com/get" class TestJson(object): @pytest.fixture(scope="session") def ud(self): return UrlData() def test_title(self, ud): resp = requests.get(ud.title_url) assert resp.status_code == 200, "HTTP返回码不等于200" assert resp.json().get("slideshow").get("title") == "Sample Slide Show", "标题与预期值不符" def test_name(self, ud, test_data): resp = requests.get(ud.name_url, params=test_data) assert resp.status_code == 200, "HTTP返回码不等于200" assert resp.json().get("args").get("name") == test_data.get("name"), "返回名称与传入值不相等" if __name__ == '__main__': pytest.main() ``` 为了对某个接口施压,加入多线程,调整如下`test_title`测试用例如下 ```python #!/usr/bin/env python # -*- coding: utf-8 -*- import requests import pytest import threading class UrlData(object): def __init__(self): self.title_url = "http://httpbin.org/json" self.name_url = "https://postman-echo.com/get" class TestJson(object): @pytest.fixture(scope="session") def ud(self): return UrlData() def title(self,ud): resp = requests.get(ud.title_url) assert resp.status_code == 200, "HTTP返回码不等于200" print(resp.json()) assert resp.json().get("slideshow").get("title") == "Sample Slide Show", "标题与预期值不符" def test_title(self, ud): t1 = threading.Thread(target=self.title,args=(ud,)) t2 = threading.Thread(target=self.title,args=(ud,)) t1.start() t2.start() if __name__ == '__main__': pytest.main() ``` <hr style="margin-top:100px"> :-: ![](https://box.kancloud.cn/2ff0bc02ec938fef8b6dd7b7f16ee11d_258x258.jpg) ***微信扫一扫,关注“python测试开发圈”,了解更多测试教程!***