作者: | 来源:互联网 | 2023-08-29 17:22
需求:测试http的响应头是否包含某属性操作:1.导入requests库,发送请求,对响应头的属性进行断言;2.对请求、需要校验的响应头属性进行参数化,用for循环简化代码;初始代
需求:测试http的响应头是否包含某属性
操作:
1.导入requests库,发送请求,对响应头的属性进行断言;
2. 对请求、需要校验的响应头属性进行参数化,用for循环简化代码;
初始代码:
用单个请求进行初步编码
import requests
r=requests.get("http://xx.xx.xx.xxx:xxxxx/getStatistiscs")
print("请求:", gurl)
print("响应码:", r.status_code)
print("响应头:", r.headers)
assert "X-Content-Type-Options" in r.headers
assert "X-XSS-Protection" in r.headers
assert "Content-Security-Policy" in r.headers
assert "X-Frame-Options" in r.headers
运行结果:
进行优化:参数化请求、需要校验的响应头属性,结合for循环
import requests
def test_url(gurl, hs):
r = requests.get(gurl)
print("请求:", gurl)
print("响应码:", r.status_code)
print("响应头:", r.headers)
# 用for循环检查新增的响应头是否在响应中
for h in hs:
assert h in r.headers
print(h,"在响应头中")
# 用列表存储需要进行检查的接口地址、响应头
resphs = ["X-Content-Type-Options", "X-XSS-Protection", "Content-Security-Policy","X-Frame-Options"]
urls = ["http://xx.xx.xx.xxx:xxxxx/nwt/dataQuery/getStatistics", "http://xx.xx.xx.xxx:xxxxx/nwt/dataQuery/getProvinceCurrentStatistics", "http://xx.xx.xx.xxx:xxxxx/nwt/dataQuery/heartdetection"]
# 用for循环进行多个接口的检查
for a in urls:
test_url(a, resphs)
运行结果: