python 接口自动化 - 面向对象思想对 Restful 类型的请求进行二次封装 - 写用例
2021/12/23 20:08:49
本文主要是介绍python 接口自动化 - 面向对象思想对 Restful 类型的请求进行二次封装 - 写用例,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
根据 Requests 的源码进行二次封装
rest_client.py
import requests class RestClient(): def __init__(self, KeepLogin, api_root_url): self.KeepLogin = KeepLogin self.api_root_url = api_root_url def get(self, url, data): return self.request(url, "GET", data = data) def post(self, url, data = None, json = None, **kwargs): return self.request(url, "POST", data, json, **kwargs) def request(self, url, method, data = None, json = None, **kwargs): url = self.api_root_url + url if method == "GET": return self.KeepLogin.get(url, params = data) if method == "POST": return self.KeepLogin.post(url, params=data, json=json, **kwargs)
编写测试用例
import random import unittest import requests from rest_client import RestClient Userdict = { "account": "admin", "pwd": "660B8D2D5359FF6F94F8D3345698F88C" } Userdict_error = { "account": "admin", "pwd": "1660B8D2D5359FF6F94F8D3345698F88C" } class SMSLoginAndSchoolAdd(unittest.TestCase): def setUp(self): self.s = requests.session() self.url = "http://192.168.233.128:8080/recruit.students" self.KeepLogin = RestClient(self.s, self.url) def test_01(self): print("测试用例01:正确用户名与密码,登陆成功") a = self.KeepLogin.get("/login/in", Userdict) self.assertIn("退出", a.text) print("测试用例01通过") def test_02(self): print("测试用例02:正确用户名与错误密码,登陆失败") a = self.KeepLogin.get("/login/in", Userdict_error) self.assertNotIn("退出", a.text) print("测试用例02通过") def test_03(self): print("测试用例03:在登陆状态下成功添加任意学校") # 一个随机学校名和一个随机备注 SchoolNameRandom = random.randint(1, 1000000000) RemarkRandom = random.randint(1, 100000) # 新建学校post请求的body参数 SchoolAddBody = { "schoolName": SchoolNameRandom, "listSchoolType[0].id": 2, "canRecruit": 1, "remark": RemarkRandom } a = RestClient("http://192.168.233.128:8080/recruit.students") a.get("/login/in", Userdict) a.post("/school/manage/addSchoolInfo", data=SchoolAddBody) if __name__ == "__main__": unittest.main()
后续可以继续对 python 接口进行封装
这篇关于python 接口自动化 - 面向对象思想对 Restful 类型的请求进行二次封装 - 写用例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-03用FastAPI掌握Python异步IO:轻松实现高并发网络请求处理
- 2025-01-02封装学习:Python面向对象编程基础教程
- 2024-12-28Python编程基础教程
- 2024-12-27Python编程入门指南
- 2024-12-27Python编程基础
- 2024-12-27Python编程基础教程
- 2024-12-27Python编程基础指南
- 2024-12-24Python编程入门指南
- 2024-12-24Python编程基础入门
- 2024-12-24Python编程基础:变量与数据类型