思路:python requests發起接口請求,獲得返回後,檢驗結果
1、框架pytest,數據驅動
import requests
from requests.auth import HTTPBasicAuth
@pytest.mark.parametrize("username,password,expect_key,expect_value",
[("zhanghao1","password123", "user_id",“839745”),
("zhanghao2","password", "error","invalid_grant"),
("zhanghao3","password123", "error","unauthorized"),])
def test_login(self, username, password, expect_key, expect_value):
'''
登錄場景:1、正常;2、錯誤密碼;3、未註冊賬戶
:param username:賬戶名
:param password:密碼
:param expect_key:期望檢驗key
:param expect_value:期望檢驗值
:return: None
'''
url = 'http://host:port/uaa/login'
basic_auth = HTTPBasicAuth('basic_client', 'basic_secret')
params = {
'scope':'read',
'grant_type':'password',
'username':username,
'password':password
}
response = requests.post(url=url, auth=basic_auth, params=params)
json = response.json()
print(json)
if expect_key is None:
return json
actual_value = json.get(expect_key)
assert actual_value == expect_value
2、bearer認證
auth = “token”
headers = {'Content-Type': 'application/json',
'Authorization': 'Bearer {}'.format(auth)}
response = requests.post(url=url, headers=headers, json=body)
3、get請求
params = {
'key1': 'value',
'key2': 'value'
}
response = requests.get(url=url, params=params, headers=GlobalConfig.headers)
4、post body
body = {
"email": email,
"mobile": mobile,
"password": password,
"username": username
}
response = requests.post(url=url, headers=headers, json=body)
5、接口返回文件流時,requests寫入本地
#-*- coding:utf-8 -*-
import requests
from contextlib import closing
url = ""
with closing(requests.get(url,stream=True)) as response:
with open("文件名","wb") as file:
for data in response.iter_content(128):
file.write(data)