Python+requests库怎么做关联接口的测试?【杭州多测师】【杭州多测师_王sir】

首先定义一个类,然后调通登录接口之后,通过正则表达式把登录接口返回的响应体

中的token值提取出来,然后存在构造函数里面,然后在下一个接口的请求头中引

用构造函数中的token值,达到关联接口的测试。

 

# 面试题:接口自动化当中的关联接口测试你是怎么做的?
import requests
class Api:

    def __init__(self):
        self.dict1={}   #定义一个空的字典用来接受token值

    def login(self):
        '''定义一个登录接口、调通之后获取token值'''
        url = 'http://192.168.1.1:8080/login'
        data ={"username":"admin","password":123456}
        headers = {"content-type":"application/x-www-form-urlencoded"}
        response = requests.post(url,data=data,headers=headers)
        print(response.json())  #打印输出
        token = re.findall('"token":"(.+)","code"',response)
        self.dict1['token'] = token[0]   #把token值进行设置键值对

    def query(self):
        '''查询用户接口、取到上个接口返回值中的token作为下个接口的请求头的里面入参、完成鉴权的操作'''
        url = 'http://192.168.1.1:8080/query'
        data = {"search": "1", "page": 5}
        headers = {"content-type": "application/x-www-form-urlencoded",
                   "token":self.dict1['token']}
        response = requests.post(url, data=data, headers=headers)
        print(response.json())  # 打印输出

if __name__ == '__main__':
    m = Api()
    m.login()
    m.query()

 

posted @ 2022-03-31 11:46  多测师_王sir  阅读(219)  评论(0编辑  收藏  举报