演练环境:http://httpbin.testing-studio.com/
接口测试框架
requests库:https://requests.readthedocs.io/en/master/
接口请求构造
请求目标
import requests
r = requests.get('https://www.baidu.com')
请求参数构造
get query: path query
post body:
form
结构化请求:json xml json rpc
binary
Get Query请求
payload = {'key1':'value1','key2':'value2'}
r = requests.get('https://httpbin.org/get',params=payload)
Form请求参数构造
payload = {'key1':'value1','key2':'value2'}
r = requests.post('https://httpbin.org/post',data=payload)
文件上传
files = {'file':open('report.xls','rb')}
r = requests.post(url,files=files)
header构造
普通的header
headers={'user-agent':'my-app/0.0.1'}
r = requests.get(url,headers=headers)
cookie
cookies = dict(cookies_are='working')
r = requests.get(url,cookies=cookies)
接口测试断言
响应结果
基本信息:r.url r.status_code r.headers r.cookies
响应结果
r.text = r.encoding+r.content
r.json()=r.encoding+r.content+content type json
r.raw.read(10)
对应的请求内容
r.request
json/xml请求
json请求体构造
payload={'some':'data'}
r = requests.post(url,json=payload)
xml请求体构造
import requests
xml = """<?xml version='1.0' encoding='utf-8'?> <a>test</a>"""
header = {'Content-Type':'application/xml'}
r = requests.post(url,data=xml,headers=headers).text
复杂数据解析
数据保存:
将复杂的xml或json请求体保存到文件模板中
数据处理:
使用mustache、freemaker等工具解析
简单的字符串替换
使用json xml api进行结构化解析
数据生成:输出最终结果
json断言
def test_demo(self):
r = requests.get(url)
assert r.json()['key1']['key2'][0]['name']=='test'
jsonpath定位
导入jsonpath库
assert r.json()['key1']['key2'][0]['name']=='test'
assert jsonpath(r.json(),'$..name')[0]=='test'
xpath断言
from requests_xml import XMLSession
session = XMLSession()
r = session.get(url)
r.xml.links
item = r.xml.xpath('//item',first=True)
print(item.text)
xml解析
import xml.etree.ElementTree as ET
root = ET.fromstring(countrydata)
root.findall(".")
root.findall("./country/neighbor")
hamcrest断言
框架自带assert体系:assert、assertEqual
Hamcrest体系:assertThat
导入hamcrest库
schema断言
jsonschema库
schema自动校验
header cookie处理
通过请求头信息传递和通过cookies参数传递
认证体系
基本认证,允许http用户代理在请求时,提供用户名和密码的一种方式