python接口测试实例--数据驱动(程序与数据分离)

#encoding=utf-8
import requests
import json
import os
import hashlib
import pickle
from conf import *

static_data = {}
def send_request(interface,value):       #将请求封装成函数send_request
r = requests.post(interface, data= value)
return r

def get_response_info(response_obj):      #将响应封装成函数get_response_info
print ("-----------------------------接口响应-------------------------")
print (response_obj.status_code)
print (response_obj.text)
print (type(response_obj.json()))
print (str(response_obj.json()))
print (response_obj.url)

def assert_response(response_obj,assert_word):        #将断言封装成函数assert_response
assert assert_word in str(response_obj.json())

#需要默认文件里面写个初始化值1
with open("e:\\data.txt","r+") as fp:        #打开data.txt文件
unique_number = fp.readline().strip()      #读取data.txt文件的参数(多行的话要加for循环)
fp.seek(0,0)                  #游标回到初始位置,为修改参数做准备
fp.write(str(int(unique_number)+10))

with open("e:\\test_data.txt","r+") as fp:        #打开文件e:\\test_data.txt,文件内参数格式parameter1|parameter2|parameter3
line=fp.readline()
interface=eval(line.split("|")[0])            #切片取【0】位置的参数register(具体值由from conf import *导入)作为请求的url
value=json.dumps(eval(line.split("|")[1]))        #读取数据后切片取【1】位置的参数作为请求的参数
assert_word=line.split("|")[2]              #读取数据后切片取【2】位置的参数作为响应的断言值

#print(interface)
#print(type(value))
r=send_request(interface,value)          #调用函数send_request,请求接口,并把响应赋值给r
get_response_info(r)                #调用响应内容函数get_response_info,打印请求的响应信息
assert_response(r,assert_word)            #调用断言函数assert_response,判断用例是否通过

static_data["username"]=eval(line.split("|")[1])["username"]          #将username存到全局变量中,下次有关联时使用
print(static_data["username"])

 

posted @ 2018-11-07 21:25  WhiteMouse  Views(761)  Comments(0Edit  收藏  举报