学艺不精,犯各种低级错误,遇到的问题记录下。
尝试用Python做接口测试,把request请求参数化。
学习过程中将json串通过excel文件写入的时候没有做Unicode和字典的转换,卡了好一会儿。
报错如下:
AttributeError: 'unicode' object has no attribute 'items',看了下
File "C:\Python27\lib\site-packages\requests\models.py", line 438, in prepare_headers
for header in headers.items():
链接过去:
for header in headers.items():
结合我要做的,headers是个字典,需要转换格式,import json。
# coding=utf-8
import requests
import json
import xlrd
def testInterface():
test_file=xlrd.open_workbook(r'D:\mypython\testurl.xlsx') #读取本地excel文件,文件中包含接口信息
table = test_file.sheets()[0] #sheet第一页
nrows = table.nrows #总行数
url1 = table.col_values(2) #获取第3列的内容url
method1 = table.col_values(3) # 获取第4列的内容method
headers1 = table.col_values(4) # 获取第5列的内容headers
data1 = table.col_values(5) # 获取第6列的内容data
for i in range(nrows):
if method1[i]=="get":
url=url1[i]
r=requests.get(url=url)
print r.text
print r.status_code
if method1[i]=="post":
url = url1[i]
headers_s=headers1[i]
headers=json.loads(headers_s) #unicode转换为字典
data_s=data1[i]
data = json.loads(data_s) #unicode转换为字典
r = requests.post(url=url, json=data, headers=headers)
print r.text
print r.status_code
if __name__ == "__main__":
testInterface()
(网上搜了下,遇到AttributeError: 'unicode' object has no attribute 'items'这种类型错误的人不少,有的貌似是Python版本引起,不过还是定位问题不够耐心,一习惯遇到问题就上网搜会产生惰性的。)
postman,soapui,jmeter等等都可以做的接口测试为什么想用Python做一下,学习各种软件也需要成本,比如要实现自动化,压测之类的。正好一直想学Python,结合工作顺便做做,界面自动化在现在几乎每天都有功能变动的情况下得不偿失,还是以接口测试为切入点。
2018/09/03更新:
1、接口headers的content Type多了个空格引起报错,要仔细啊:
"{\"status\":-1,\"data\":\"Content type 'application/octet-stream' not supported\"}"
500
2、一直提示data格式的问题,在soapUi和postman中好好的,python里就出问题了
r = requests.post("url",headers=headers1,data=data1)
报错如下:
"{\"status\":-1,\"data\":\"JSON parse error: Unrecognized token 'store': was expecting ('true', 'false' or 'null'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'store': was expecting ('true', 'false' or 'null')\\n at [Source: (PushbackInputStream); line: 1, column: 7]\"}"
500
查了一下,data增加转换格式json.dumps()就好了:
r = requests.post("url",headers=headers1,data=json.dumps(data1))