一、
新建atp目录,该目录下包含bin(存放启动程序等)、config(存放配置程序)、lib(存放过程程序)、logs(存放生成的日志)、cases(存放用例的excel文件)五个目录,并新建一个txt文件teadme.txt,用于书写说明文档。
二、
1、
首先在lib目录下创建tools.py文件,打开excel表格,若打开失败,则生成log;若打开成功,则读取excel中的用例
tools.py如下
import xlrd from xlutils.copy import copy from config.setting import my_log,MAIL_INFO,TO,CC import yagmail from lib import my_request import time def readExcel(file_path): try: book = xlrd.open_workbook(file_path) except Exception as e: my_log.error('打开用例出错,文件名是%s'%file_path) return [] else: all_case = [] #存放所有的用例 sheet = book.sheet_by_index(0) for i in range(1,sheet.nrows): row_data = sheet.row_values(i) all_case.append(row_data[4:8]) return all_case
在config目录下创建setting.py,编辑配置信息,如日志文件名、存放用例的目录等
setting.py如下
import nnlog,os BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) LOG_FILE_NAME = 'atp.log'#日志文件名 ABS_FILE_PATH = os.path.join(BASE_PATH,'logs',LOG_FILE_NAME) my_log = nnlog.Logger(ABS_FILE_PATH) #日志信息 CASE_PATH = os.path.join(BASE_PATH,'cases') #存放用例的目录
os.path.dirname
os.path.abspath
os.path.join
nnlog.Logger
2、在lib目录下创建my_requests.py文件,用于访问接口、并将返回的结果转化为text格式。(json->text、data->text)
import requests from config.setting import my_log def post(url,data,header=None,cookies=None,is_json=False): try: if is_json: res = requests.post(url, json=data, headers=header, cookies=cookies).text else: res = requests.post(url,data=data,headers=header,cookies=cookies).text except Exception as e: my_log.error('接口请求出错,%s'%e) res = str(e) return res def get(url,data,header=None,cookies=None): try: res = requests.get(url,params=data,headers=header, cookies=cookies).text except Exception as e: my_log.error('接口请求出错,%s'%e) res = str(e) return res
3、运行用例,并将返回结果和用例结果写入excel文件中。
在lib目录下的tools.py文件中添加以下程序:
def check_res(res:str,check:str): new_res = res.replace('": "','=').replace('": ','=') for c in check.split(','): if c not in new_res: return '失败' return '通过' def write_res(file_name,res_list): book = xlrd.open_workbook(file_name) new_book = copy(book) sheet = new_book.get_sheet(0) for row,data in enumerate(res_list,1): res,status = data sheet.write(row,8,res) #写入返回结果和运行状态 sheet.write(row,9,status) new_book.save(file_name) def str_to_dict(s:str,seq='&'): #username=niuhanyang&password=123456 d = {} if s.strip(): for tmp in s.split(seq): k,v = tmp.split('=')#username,niuhanyang d[k]=v return d def run_case(all_case): all_res = [] for case in all_case: url,method,data,check = case my_log.info('正在运行%s'%url) data = str_to_dict(data) #把请求参数转成字典 if method.upper()=='POST': res = my_request.post(url,data) else: res = my_request.get(url,data) status = check_res(res,check) #校验结果 all_res.append([res,status]) return all_res
4、在bin目录下创建start.py文件,启动程序
from lib import my_request from lib import tools def main(): all_case = tools.readExcel(r'F:\besttest\python自动化\day-nn\day10\测试用例.xlsx') all_res = tools.run_case(all_case) tools.write_res(r'F:\besttest\python自动化\day-nn\day10\测试用例.xlsx') main()