Python使用自定义装饰器的示例详解
城中月 人气:0在Python自动化测试中,使用自定义的装饰器来给测试方法传递测试数据:
reader.py
import csv import json from openpyxl import load_workbook from setting import DATA_DIR from os import path class Reader: @classmethod def read_excel(cls,xlname, min_row, max_row, min_col, max_col): xlname = path.join(DATA_DIR,xlname) data = [] wb = load_workbook(xlname) ws = wb.active # 将选中区域转换为列表 ls = list(ws.iter_rows(min_row=min_row, max_row=max_row, min_col=min_col, max_col=max_col)) wb.save(xlname) for row in ls: data_row = [] for col in row: data_row.append(col.value) data.append(data_row) wb.save(xlname) return data @classmethod def read_csv(cls, filename): file_name = path.join(DATA_DIR,filename) ls = None with open(file=file_name,mode='r',encoding='utf-8') as f: ls = list(csv.reader(f)) return ls
my_decorator.py
def my_decorator(sequeence): def outer(func): def inner(self): for item in sequeence: try: func(self,*item) except Exception: # print()仅供调试用,后期考虑将出错日志写入数据库 print('测试有问题') else:# print()仅供调试用,后期考虑将通过日志写入数据库 print('测试通过') return inner return outer
data.csv
admin,1
wp,1
666666,1
msramsrsa,0
find_test.py
import time import unittest from parameterized import parameterized from pages.page_login import PageLogin from pages.page_system_operate_log import PageSystemOperateLog from utils.decorate import my_decorator from utils.driver import WebDriver from utils.reader import Reader class SysOperateLogFindPageTest(unittest.TestCase): ''' 系统操作日志页面测试类:执行系统操作日志页面的UI测试 作者:awake.silent@qq.com ''' @my_decorator(Reader.read_csv('search_log_by_username.csv')) def test_search_log_by_username(self, username, expect): ''' 对系统操作日志页面的按照账号搜索日志功能进行UI测试 :param username: 账号 :param expect: 期望结果,'0‘代表搜索不到日志记录,'1‘代表可以搜索到日志记录 :return: ''' # 打开系统操作日志页面 self.psol.open() time.sleep(2) # 输入账号并点击搜索 self.psol.do_search(username) time.sleep(2) # 获取搜索结果 result = self.psol.get_search_result() # 进行断言 if expect == '0': self.assertEqual(0,len(result)) else: self.assertNotEqual(0,len(result)) for item in result: self.assertEqual(username, item.text)
加载全部内容