通过类名去调用token
import pytest
import requests
class TestDemo():
access_token=""
path="https://www.baidu.com"
#登录成功的信息
def test_get_token(self):
url=TestDemo.path+"/api/v2/user/login"
data ={
"account":"江大大",
"password":"123456"
}
res=requests.post(url=url,params=data)
#拿到token信息
TestDemo.access_token=res.json()['content']['access_token']
def test_search(self):
url=TestDemo.path+"/api/v2/search"
#TestDemo.access_token 通过类名去调用token
headers={'Content-Type': 'application/json','Authorization':'Bearer '+TestDemo.access_token}
data={
"kewords":"你好"
}
res=requests.post(url=url,params=data,headers=headers)
if __name__ == '__main__':
pytest.main(['-vs'])
断言:
先定义一个变量
a=‘收藏成功’
这里用id()函数
id 是对象的内存地址,并且在每次运行程序时都不同
所以在返回的结果中,进行内容提取
id(res.json()[‘msg’])==id(a)
这样就能断言两个字符串是否相等了
python美化post请求返回的json
print(json.dumps(res.json(),indent=2,separators=(’,’,’:’),ensure_ascii=False))
indent=2是代表缩进几个空格
ensure_ascii=False
如果直接使用json.dumps转换,之前的中文又变成字符了,所以要想不把返回的内容编码得益于ensure_ascii,要设置为False(默认是False),否则中文就会被ascii编码了
post请求传参无法识别参数的时候需要更换成params
res=requests.post(url=url, params=data, headers=headers)
res.json()[‘content’][‘data’][0][‘id’]
json多层级取值先从外层进入,data层分多个的时候要写明白在第几个层取,这里取的是第一层的id值