python——requests:接口测试框架

1、风暴平台自动化接口测试练习

1.1接口测试自动化

1.1.1post方法

import json  #序列化的时引进的库
import requests
#这里以风暴平台为例:
#接口测试post请求方法:
r=requests.post(       #这里的r是响应数据response的缩写。
	url="http://47.95.142.233:8000/login/auth/",
	#json={"username":"用户名","password":"密码"},    #当这里的数据格式是json时,如果直接用JSON表示,响应数据就可以直接获取。
	data=json.dumps({"username":"用户名","password":"密码"}),  #如果时json格式,但是我们想通过data来表示,就需要对响应数据进行序列化。
	headers={"Content-Type":"application/json"}
)
#获取协议状态码:
print(r.status_code)
#获取响应数据:
#第一种:获取文本格式的响应数据
# print(r.text)
#第二种:获取json数据格式的响应数据
print(json.dumps(r.json(),indent=True,ensure_ascii=False))   #当我们用data来表示请求参数,那么响应数据需要进行序列化处理,indent=True使响应数据更具有格式化,ensure_ascii=False处理中文。
#第三种:获取响应数据,以二进制的形式(bytes:编码与解码)
# print(r.content)
#获取响应头
print(r.headers)

1.2全流程练习

也就是一个以风暴平台为例的动态参数处理流程。

1.2.1登录

import requests
#接口测试动态参数处理,以风暴平台为例,这里用到了函数的返回值:
#登录
def login():
	r=requests.post(
		url="http://47.95.142.233:8000/login/auth/",
		json={"username":"13762237226","password":"123456"},
		headers={"Content-Type": "application/json"}
	)
	# print(r.json())   
	return r.json()["token"]
login()

1.2.2个人主页

#个人主页:
def index():
	r=requests.get(url="http://47.95.142.233:8000/interface/index",
	               headers={"Authorization":"JWT {token}".format(token=login())}
	               )
	print(r.status_code)
	print(r.json())
index()

1.2.3产品搜索

#搜索qy的产品:
#接口测试get请求方法:在get请求方法中的,请求地址的问号后面的参数,即接口测试中的query params里的参数,在自动化接口测试中,我们将其填写在params中。
def scan():
	r=requests.get(
		url="http://47.95.142.233:8000/interface/products?name=qy",        #get请求方法的请求地址
		params={"name":"qy"},       #get请求方法的请求参数
		headers={"Authorization":"JWT {token}".format(token=login())}     #身份验证
	)
	print(r.url)
	print(r.json())
	print(r.status_code)
scan()

1.2.4添加产品

#接口测试添加产品:
def addProduct():
	r=requests.post(
		url="http://47.95.142.233:8000/interface/product/",
		json={"name":"qy","product_type":"WEB","version":"123","master":"asd","description":"abc"},
		headers={"Content_type":"application/json;charset=UTF-8","Authorization":"JWT {token}".format(token=login())}
	)
	return r.json()["id"]
#addProduct()

1.2.5修改产品

#接口测试修改产品:
def updateProduct():
	r=requests.put(
		url="http://47.95.142.233:8000/interface/product/{productid}/".format(productid=addProduct()),
		json={"name":"qy","product_type":"APP","version":"234","master":"asd","description":"abc","productid":addProduct()},
		headers={"Content_type":"application/json;charset=UTF-8","Authorization":"JWT {token}".format(token=login())}
	)
	print(r.json())
#updateProduct()

1.2.6删除产品

#接口测试删除产品:
def delete():
	r=requests.delete(
		url="http://47.95.142.233:8000/interface/product/{productid}/".format(productid=addProduct()),
		headers={"Content_type":"application/json;charset=UTF-8",
		         "Authorization":"JWT {token}".format(token=login()),
		         "Referer":"http://101.43.158.84/",
		         "User":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36"
		         })
	print(r.status_code)
delete()

2、session请求流程在互联网产品中的体现

以51CTO为例:

#session请求流程在互联网产品中的体现:
import requests
#登录获取sessionid:
def login():
	r=requests.post(
		url="https://home.51cto.com/index?reback=https%3A%2F%2Fedu.51cto.com%2Fcenter%2Fuser%2Findex%2Flogin-success%3Fsign%3Df70bBwIJBQcEAQZVAlEBCwcOVQdRDwYEC1MAU1FeTEMWSwIYHVxRQhoEBwZGWxdaCVseAldXRAdBHQcOEERLUklNS1JAFlJSQBxFEUdQQBQFWUQTQVxWVQNQ%26client%3Dweb&iframe=0&is_go_to_user_set_mobile=1",
		headers={"Content-Type":"application/x-www-form-urlencoded",
		         "Referer":"https://home.51cto.com/index?reback=https://home.51cto.com/members/in-fo?utm_platform=pc",
		         "Cookie":"_uab_collina=164912882417167002151458; from_fr=2; from_course=2; _csrf=3cfe4db1eccc65abaab5c5697ac56b15fda7212944fcf263a101fc4088b11b95a%3A2%3A%7Bi%3A0%3Bs%3A5%3A%22_csrf%22%3Bi%3A1%3Bs%3A32%3A%22Uzxm570Aw-5BEQPwED4TVbstILGa3ag4%22%3B%7D; _ourplusFirstTime=122-4-5-11-20-24; www51cto=DC52AD91593055F062135B80C53ECE9AQRsX; _bl_uid=w0l2n1yalbdkn9qvL0shlL1jUhX3; sajssdk_2015_cross_new_user=1; Hm_lvt_844390da7774b6a92b34d40f8e16f5ac=1649128825; pub_cookietime=2592000; UM_distinctid=17ff7bd53d6ab8-07d93a6c5b462f-1a343370-151800-17ff7bd53d7321; callback_api_url=https%3A%2F%2Fhome.51cto.com%2Findex%3Freback%3Dhttps%3A%2F%2Fhome.51cto.com%2Fmembers%2Fin-fo%3Futm_platform%3Dpc; pub_wechatopen=aG0wVVNRDlMBDQUDWg; BigUser=881ac9d0d8ba292c3ffd1f5c58f9a98771b1429b38753c752c984fc07e2577f2a%3A2%3A%7Bi%3A0%3Bs%3A7%3A%22BigUser%22%3Bi%3A1%3Bs%3A87%3A%221e4eCAMFA1FWUwEBUQBbClZRUgZVUwtdVAVUVVNWCFMGVAwMAA0GUVVRBlNZBFcMBFQHCVEHAQFWB1xXVFVcAgc%22%3B%7D; reg_sources=edu; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%2215481273%22%2C%22first_id%22%3A%2217ff7bcde38d2d-03b2f2097e21e4-1a343370-1382400-17ff7bcde3938b%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E8%87%AA%E7%84%B6%E6%90%9C%E7%B4%A2%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC%22%2C%22%24latest_referrer%22%3A%22https%3A%2F%2Fwww.sogou.com%2Flink%3Furl%3DB7ss7T7Ay4lQR_V3exeeiQDydjxbYhws%22%2C%22%24latest_utm_source%22%3A%22vip%22%2C%22%24latest_utm_medium%22%3A%2251cto%22%2C%22%24latest_utm_content%22%3A%22xtgg%22%7D%2C%22%24device_id%22%3A%2217ff7bcde38d2d-03b2f2097e21e4-1a343370-1382400-17ff7bcde3938b%22%7D; ssxmod_itna=QqGxgDciY49D2DmxBPGIylcfIHo8exb7=Wpx0yqReGzDAxn40iDt=PHxGqOerm41DUxp+xOfWhD3q=F/Ygb1Ci6meKDHxY=DU=G+IoD4fKGwD0eG+DD4DWeqAoDexGpc2pXKGWD4qDODWKDX2akDiPCDmR8pxGClxDCXAPDwx0CLovF=4YpDiyDRZ0qLxG1F40HYG3xLxOfLbG1RPSAo+bO43YDvxDkDUKDo2PpDB+kBpBerWx3QNrNSQx4fQ0qS7Gbqj2eqlP4KWiP424iNlT5MYWKOCeKeDDWvwx74D===; ssxmod_itna2=QqGxgDciY49D2DmxBPGIylcfIHo8exb7=Wxn9guTP0=Dlog4jRSul0qbL/dRQh8=zPx7=DBeuAxq3qKOB6GNYmWfivYu/D9cYN94/3H+Kosq1HwrWNPrFYXDnRGOafc3RlkPMr5yQ=oy1ViICVWBiRgr=Tpn+KWu1KFH18QyruWYQRampCzHdB=HqceEsPpEhZo3OT=E+Z=oQT2fbf4uNrQPQfIBdy1f8ZPpr=WlTeja2dtwY3ovAN5nGumWraM2dc6YXXWS+ftn1dF3O+9EwDNTSclKyWhPSjEc=R1SiCkt6jTldWMo2nNTx6Na0rOXOx6njijD0rZiRG=dZIY4wo4r9OEhG6=aIj1r9afxQGVO=vrRgn3NzYo=3ifptgtjl5FlR/nvynjZ=v/B61bTnB6G0uGldG/G51w+855SQv8EmQPyObq9Qk=cdpaEFqfUaTR0I20jF2vRpTDG2R2rerHfaPzRr/28kkQiTeGLumk=7xDFqD+rDxD=; PHPSESSID=tj2a1aapofve63mv6o511mp8k4; once_p=ef1876; _ourplusReturnCount=16; _ourplusReturnTime=122-4-5-11-50-12; login_from=edu.51cto.com; reg_from=edu.51cto.com; Hm_lpvt_844390da7774b6a92b34d40f8e16f5ac=1649130613",
		         "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36"
		         },
		data={"_csrf":"WVJDNzhMYjUMKDtaDXtSdC5/dnV9HTJCHBZ3Y24uEUEQHgRWCy0FAQ==",
		      "LoginForm[username]":"18292091170",
		      "LoginForm[password]":"787533",
		      "show_qr":"0"
		      })
	return r.cookies

#在访问主页时,通过请求头中的cookies把session带上,但是由于python的规则,这里我们直接使用cookies关键字带上sessionid即可。
def index():
	r=requests.get(url="https://edu.51cto.com/?utm_source=vip",
	               cookies=login()
	               )
	print(r.text)
index()

3、session会话对象

(1)所有的请求之间session能够共享;

(2)底层TCP只需要建立一次,那么就节约了请求时间。

#session会话对象:
#import requests
# #接口测试动态参数处理,以风暴平台为例,这里用到了函数的返回值:
#登录
import requests
#登录获取sessionid:
def login():
	s=requests.session()    #设置session共享
	r=s.post(
		url="https://home.51cto.com/index?reback=https%3A%2F%2Fedu.51cto.com%2Fcenter%2Fuser%2Findex%2Flogin-success%3Fsign%3Df70bBwIJBQcEAQZVAlEBCwcOVQdRDwYEC1MAU1FeTEMWSwIYHVxRQhoEBwZGWxdaCVseAldXRAdBHQcOEERLUklNS1JAFlJSQBxFEUdQQBQFWUQTQVxWVQNQ%26client%3Dweb&iframe=0&is_go_to_user_set_mobile=1",
		headers={"Content-Type":"application/x-www-form-urlencoded",
		         "Referer":"https://home.51cto.com/index?reback=https://home.51cto.com/members/in-fo?utm_platform=pc",
		         "Cookie":"_uab_collina=164912882417167002151458; from_fr=2; from_course=2; _csrf=3cfe4db1eccc65abaab5c5697ac56b15fda7212944fcf263a101fc4088b11b95a%3A2%3A%7Bi%3A0%3Bs%3A5%3A%22_csrf%22%3Bi%3A1%3Bs%3A32%3A%22Uzxm570Aw-5BEQPwED4TVbstILGa3ag4%22%3B%7D; _ourplusFirstTime=122-4-5-11-20-24; www51cto=DC52AD91593055F062135B80C53ECE9AQRsX; _bl_uid=w0l2n1yalbdkn9qvL0shlL1jUhX3; sajssdk_2015_cross_new_user=1; Hm_lvt_844390da7774b6a92b34d40f8e16f5ac=1649128825; pub_cookietime=2592000; UM_distinctid=17ff7bd53d6ab8-07d93a6c5b462f-1a343370-151800-17ff7bd53d7321; callback_api_url=https%3A%2F%2Fhome.51cto.com%2Findex%3Freback%3Dhttps%3A%2F%2Fhome.51cto.com%2Fmembers%2Fin-fo%3Futm_platform%3Dpc; pub_wechatopen=aG0wVVNRDlMBDQUDWg; BigUser=881ac9d0d8ba292c3ffd1f5c58f9a98771b1429b38753c752c984fc07e2577f2a%3A2%3A%7Bi%3A0%3Bs%3A7%3A%22BigUser%22%3Bi%3A1%3Bs%3A87%3A%221e4eCAMFA1FWUwEBUQBbClZRUgZVUwtdVAVUVVNWCFMGVAwMAA0GUVVRBlNZBFcMBFQHCVEHAQFWB1xXVFVcAgc%22%3B%7D; reg_sources=edu; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%2215481273%22%2C%22first_id%22%3A%2217ff7bcde38d2d-03b2f2097e21e4-1a343370-1382400-17ff7bcde3938b%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E8%87%AA%E7%84%B6%E6%90%9C%E7%B4%A2%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC%22%2C%22%24latest_referrer%22%3A%22https%3A%2F%2Fwww.sogou.com%2Flink%3Furl%3DB7ss7T7Ay4lQR_V3exeeiQDydjxbYhws%22%2C%22%24latest_utm_source%22%3A%22vip%22%2C%22%24latest_utm_medium%22%3A%2251cto%22%2C%22%24latest_utm_content%22%3A%22xtgg%22%7D%2C%22%24device_id%22%3A%2217ff7bcde38d2d-03b2f2097e21e4-1a343370-1382400-17ff7bcde3938b%22%7D; ssxmod_itna=QqGxgDciY49D2DmxBPGIylcfIHo8exb7=Wpx0yqReGzDAxn40iDt=PHxGqOerm41DUxp+xOfWhD3q=F/Ygb1Ci6meKDHxY=DU=G+IoD4fKGwD0eG+DD4DWeqAoDexGpc2pXKGWD4qDODWKDX2akDiPCDmR8pxGClxDCXAPDwx0CLovF=4YpDiyDRZ0qLxG1F40HYG3xLxOfLbG1RPSAo+bO43YDvxDkDUKDo2PpDB+kBpBerWx3QNrNSQx4fQ0qS7Gbqj2eqlP4KWiP424iNlT5MYWKOCeKeDDWvwx74D===; ssxmod_itna2=QqGxgDciY49D2DmxBPGIylcfIHo8exb7=Wxn9guTP0=Dlog4jRSul0qbL/dRQh8=zPx7=DBeuAxq3qKOB6GNYmWfivYu/D9cYN94/3H+Kosq1HwrWNPrFYXDnRGOafc3RlkPMr5yQ=oy1ViICVWBiRgr=Tpn+KWu1KFH18QyruWYQRampCzHdB=HqceEsPpEhZo3OT=E+Z=oQT2fbf4uNrQPQfIBdy1f8ZPpr=WlTeja2dtwY3ovAN5nGumWraM2dc6YXXWS+ftn1dF3O+9EwDNTSclKyWhPSjEc=R1SiCkt6jTldWMo2nNTx6Na0rOXOx6njijD0rZiRG=dZIY4wo4r9OEhG6=aIj1r9afxQGVO=vrRgn3NzYo=3ifptgtjl5FlR/nvynjZ=v/B61bTnB6G0uGldG/G51w+855SQv8EmQPyObq9Qk=cdpaEFqfUaTR0I20jF2vRpTDG2R2rerHfaPzRr/28kkQiTeGLumk=7xDFqD+rDxD=; PHPSESSID=tj2a1aapofve63mv6o511mp8k4; once_p=ef1876; _ourplusReturnCount=16; _ourplusReturnTime=122-4-5-11-50-12; login_from=edu.51cto.com; reg_from=edu.51cto.com; Hm_lpvt_844390da7774b6a92b34d40f8e16f5ac=1649130613",
		         "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36"
		         },
		data={"_csrf":"WVJDNzhMYjUMKDtaDXtSdC5/dnV9HTJCHBZ3Y24uEUEQHgRWCy0FAQ==",
		      "LoginForm[username]":"18292091170",
		      "LoginForm[password]":"787533",
		      "show_qr":"0"
		      })
	return s

#在访问主页时,通过请求头中的cookies把session带上,但是由于python的规则,这里我们直接使用cookies关键字带上sessionid即可。
def index():
	r=login().get(url="https://edu.51cto.com/?utm_source=vip")
	print(r.text)
index()

4、超时处理

当我们在自动化接口测试时,遇到了超时(ConnectTimeout)的错误时,我们可以在请求里面增加一个timeout的关键字,把他的响应时间增加一些,以避免这个错误。

#请求超时
import requests
r=requests.get(
	url="https://www.baidu.com/s?tn=51076811_dg&wd=%E7%99%BE%E5%BA%A6",
	timeout=20   #这里的时间可以根据实际清空调整,单位以s为单位。
)
print(r.text)

 

posted @ 2022-04-05 16:37  柒の夜  阅读(962)  评论(0编辑  收藏  举报