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 接口进行封装

上一篇:什么是RESTful风格?


下一篇:API-6_2 Web API_RESTful