当前位置:网站首页>数据驱动之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.运行结果

边栏推荐
- Classification model - logistic regression, Fisher linear discriminant (SPSS)
- USB to can device in nucleic acid extractor high performance USB interface can card
- solo 文章标题会过滤掉部分标签
- SQL语句实战学习
- Quickly learn to use file permissions
- Grey prediction (matlab)
- bjdctf_ 2020_ babystack
- Galaxy Securities opens an account online. Is it safe to open an account on your mobile phone
- 线程池串行化
- Chinese NFT? NFR was born
猜你喜欢

A great open source micro community light forum source code

Baidu editor uploads pictures and sets custom directories

Esp8266 nodemcu - get real-time weather from Suning API

北大青鸟昌平校区:运维就业现状怎么样?技能要求高吗?
![[OGeek2019]babyrop](/img/7a/18e8b985629488346e596cdf2a215c.png)
[OGeek2019]babyrop

在openEuler社区开源的Embedded SIG,来聊聊它的多 OS 混合部署框架

ubtun 更新源

PHP(2)
![[Fifth space 2019 finals]pwn5](/img/51/03e6078961a8eab991fa08bb178a7b.png)
[Fifth space 2019 finals]pwn5
Solo article body contains & lt; & gt; Labels affect page styles
随机推荐
Flask框架中如何进行数据库的迁移
史上最全的2022年版Android面试题
Regular expressions and bypass cases
Lin Zhiying's injury is relatively stable
BGP基础实验
【攻防世界WEB】难度五星15分进阶题:bug
Solidity-delegateCall插槽冲突分析与解决
虚拟机导入iso后 Operating System not found 解决方法
What are the three-party payment companies?
jarvisoj_level2
The basic syntax of go language (variables, constants, basic data types, for, switch, case, array, slice, make, new, map)
Smart IOT source code with configuration IOT source code industrial IOT source code: support sensor analysis services, real-time data collection and remote control
DDD thinking structure learning
Arrayslist and sequence table -- Simulation Implementation
[OGeek2019]babyrop
ciscn_2019_n_1
How are you preparing for the Android golden nine silver ten interview? The latest Android Interview Questions Summary helps you prepare for the war
网上找客户经理办理基金开户安全吗??
PHP(2)
北大青鸟昌平校区:运维就业现状怎么样?技能要求高吗?