当前位置:网站首页>数据驱动之Excel读写
数据驱动之Excel读写
2022-07-23 23:38:00 【司小幽】
目录
1.Excel内容
路径下的文件

Sheet1

Sheet2

2.Py文件数据驱动
class DataDriver:
NAME = 'xuzhu'
AGE = '16'
ADDRESS = '汤臣一品'
if __name__ == '__main__':
print(DataDriver.NAME)
3.log.ini
[loggers]
keys=root
[handlers]
keys=fileHandler,streamHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=INFO
handlers=fileHandler,streamHandler
[handler_fileHandler]
class=FileHandler
level=INFO
formatter=simpleFormatter
args=('mylog.log','a','utf-8')
[handler_streamHandler]
class=StreamHandler
level=INFO
formatter=simpleFormatter
[formatter_simpleFormatter]
format=%(asctime)s %(filename)s %(levelname)s %(funcName)s %(message)s
4.生成日志器的配置
''' 生成日志器的配置 '''
import logging.config
# 路径一定要在调用的地方进行填写,不然会报错。
def get_log(path):
logging.config.fileConfig(path)
return logging.getLogger()
5.用于配置excel的写入格式内容
''' 用于配置excel的写入格式内容 把断言的结果Pass和Failed更加突出一些 PatternFill类用于定义颜色 Font类用于定义格式 '''
from openpyxl.styles import Alignment
from openpyxl.styles import Font
from openpyxl.styles import PatternFill
# pass的写入配置
def pass_(cell,row,column):
cell(row=row, column=column).value = 'Pass'
# 单元格显示: 绿色加粗
cell(row=row, column=column).fill = PatternFill('solid',fgColor='AACF91')
cell(row=row, column=column).font = Font(bold = 'True')
cell(row=row, column=column).alignment = Alignment(horizontal='center', vertical='center')
# Failed写入配置
def failed(cell,row,column):
cell(row=row, column=column).value = 'Failed'
# 单元格显示: 红色加粗
cell(row=row, column=column).fill = PatternFill('solid',fgColor='FF0000')
cell(row=row, column=column).font = Font(bold = 'True')
cell(row=row, column=column).alignment = Alignment(horizontal='center', vertical='center')
6.excel文件读取类,用于实现测试用例文件的读取与执行
''' excel文件读取类,用于实现测试用例文件的读取与执行 '''
import pathlib
import openpyxl
from class25.excel_driver import excel_conf
from class26 import log_conf
# 解析测试用例中测试参数单元格的内容,并转换为字典的形态返回
from class24.web_keys import Keys
def arguments(value):
data = dict()
# 如果value有值,进行切分
if value:
str_temp = value.split(';')
for temp in str_temp:
t = temp.split("=", 1)
data[t[0]] = t[1]
# 如果value没有值,就不做任何操作
else:
# data = None
pass
return data
# 获取当前路径,并切换到excel路径下,pathlib.Path函数返回的
def path():
file = pathlib.Path(__file__).resolve().parents[1] / 'data/自动化测试用例demo.xlsx'
return file
# 获取指定的测试用例文件,进行自动化执行。
def read(file,log):
# 获取log
# log_file = pathlib.Path(__file__).resolve().parents[1] / '../class26/conf/log.ini'
# log = log_conf.get_log(log_file)
# 获取excel中的内容\
# excel = openpyxl.load_workbook('../data/自动化测试用例demo.xlsx')
# file = pathlib.Path(__file__).resolve().parents[1] / 'data/自动化测试用例demo.xlsx'
excel = openpyxl.load_workbook(file)
# sheet = excel['Sheet1']
# 获取所有的sheet页,来执行里面的测试内容
for name in excel.sheetnames:
sheet = excel[name]
# print('*************正在执行{}Sheet页***************'.format(name))
log.info('*************正在执行{}Sheet页***************'.format(name))
for values in sheet.values:
# 获取测试用例的正文内容
if type(values[0]) is int:
# 用例描述可以用于日志的输出
# print('***********************正在执行:{}******************************'.format(values[3]))
log.info('***********************正在执行:{}******************************'.format(values[3]))
# print(values)
# 参数的处理:通过一个dict来接收所有的参数内容,便于定值不定长的传参形态
# 参数最终形态:'type_ = Chrome' 改变为 {type_: 'Chrome'}
# print(values[2])
data = arguments(values[2])
# print(data)
# print(str_temp)
''' 调用的函数values[1],这是固定的。 操作行为的调用分为以下几种不同类型: 1.实例化 2.基于实例化对象进行的操作行为 3.断言机制:有预期与实际的对比,以及有单元格测试结果的写入 '''
''' 第一行open_browser 第二行open:getattr(key,'open')(**data) key.open(**data) key.open(url = 'http://www.baidu.com') 第三行input:getattr(key,'open')(**data) key.input(**data) key.input(by='id',value='kw',txt='虚竹的excel') 第四行click '''
# 实例化操作
if values[1] == 'open_browser':
key = Keys(**data)
# 断言行为:基于断言的返回结果来判定测试的成功失败,并进行写入操作
elif 'assert' in values[1]:
status = getattr(key, values[1])(expected=values[4],**data)
#基于status判定写入的测试结果
if status:
excel_conf.pass_(sheet.cell,row=values[0]+2,column=6)
else:
excel_conf.failed(sheet.cell,row=values[0]+2,column=6)
# 保存Excel:放在这里以确保每一次写入都可以被保存,避免因为代码报错而未保存之前的测试结果
excel.save(file)
# 常规操作行为
else:
# if data:
# getattr(key,values[1])(**data)
# else:
# getattr(key,values[1])()
getattr(key, values[1])(**data)
excel.close()
log.info('**************执行完毕*******************')
7.main函数
import os
from class25.excel_driver.excel_read import path, read
from class26 import log_conf
if __name__ == '__main__':
# 创建log对象
log = log_conf.get_log('./conf/log.ini')
# 通过读取data路径下是否有测试用例,有,就执行,没有就不执行
# 测试用例集合
cases = list()
# 读取路径下的测试用例
for path,dir,files in os.walk('../class25/data/'):
for file in files:
# 获取文件的后缀名
file_type = os.path.splitext(file)[1]
# file_name = os.path.split(file)[1]
file_name = os.path.splitext(file)[0]
# print(file_type)
# print(path+file)
if file_type == '.xlsx':
# print(file_type)
if 'old' not in file_name:
case_path = path+file
cases.append(case_path)
else:
log.error('文件类型错误:{}'.format(file))
for case in cases:
log.info('********正在执行{}文件*********'.format(case))
read(case,log)
8.运行结果

边栏推荐
- 虚拟机导入iso后 Operating System not found 解决方法
- 1、 Simplification of digital logic
- No wonder the application effect of ERP in domestic enterprises is generally not ideal
- DGS之联邦(Federation)
- Chinese NFT? NFR was born
- DGS之文件上传
- ciscn_ 2019_ n_ one
- Lin Zhiying's injury is relatively stable
- Baidu editor uploads pictures and sets custom directories
- Tree DP
猜你喜欢
随机推荐
Qt创建背景遮罩,弹出子窗口,父窗口背景变黑变暗
pwn1_ sctf_ two thousand and sixteen
ciscn_ 2019_ n_ eight
Chapter 5: implementation of Web adapter
Is Zhongyuan securities reliable? Is it legal? Is it safe to open a stock account?
cannot meet the needs of the people? How can programmers take private jobs to effectively increase their income?
DGS's mutations
Chapter 7: test architecture elements
难怪国内企业ERP应用效果普遍不理想
Baidu editor uploads pictures and sets custom directories
Galaxy Securities opens an account online. Is it safe to open an account on your mobile phone
PyTorch 中遇到的问题
【Error】TypeError: expected str, bytes or os. PathLike object, not int
Software architecture
BGP routing, MPLS
关于使用 Jackson 解析 JSON 你需要知道的一切
汇编语言伪指令详解(附实例)
Principal component analysis (matlab)
Tensorflow one layer neural network training handwritten digit recognition
strncat() strncmp()

![[ssm] joint debugging of front and rear protocols ①](/img/47/c1016c5c5e4ffc0d6cc93cf50d52df.png)





![[ssm] joint commissioning of front and rear console protocols ②](/img/ed/6a42e19f384fa0d4a039e52f5a95f4.png)

