使用pytest框架进行接口请求

import requests
import pytest

class TestSendRequest:

全局变量,即类变量,通过类名访问

access_token=””
cks=””

def test_get_token(self):
url=’https://coolapi.coolcollege.cn/login-api/v3/login’
data={#body填写json格式、form格式
“mobile”:”132*”,
“password”:”
“,
“password_encrypted”:”1″,
“sms_code”:””,
“login_type”:”account_password_login”,
“enterprise_id”:””,
“anonymous_id”:”1800819662242582528″,
“outer_login_type”:””
}

发送get请求

rep=requests.get(url=url,json=data)
print(rep.json())
access_token = rep.json()[‘$.code’]

发送post请求

def test_edit_flag(self):
url=”…?access_token=”+TestSendRequest.access_token+””
data={}
rep=requests.post(url,json=data

data=json.dumps(data) 序列化,把字典格式的数据转换成string格式

json.loads(data) 反序列化:把str格式转换成字典格式

)
print(rep.json()

上传文件:图片/文档等

def test_file_upload(self):
url=
data={“media”:open(r”本地文件地址”,”rb”)

    }
    rep=response.post(url=url,files=data)
    print(rep.json())

需要带请求头以及需要cookie关联的接口如何测试

def test_start(self):
url=”,
rep=requests.get(url=url)
print(rep.text)

通过正则表达式从html中获得鉴权码和cookie

token=rep.search(‘name=”token” value=”(.*?)”‘,rep.text)[1]
print(token)
cks=rep.cookies

def test_login(self):
url=”…”
data={}
headers={}
rep=requests.post(url,json=data,headers=header,cookies=TestSendRequest.cks

data=json.dumps(data) 序列化,把字典格式的数据转换成string格式

json.loads(data) 反序列化:把str格式转换成字典格式

)
print(rep.json())
if name == ‘ main‘:
pytest.main([‘-vs’])

Original: https://blog.csdn.net/Alva_Li/article/details/127619998
Author: Alva_Li
Title: 使用pytest框架进行接口请求

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/776181/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球