当前位置:网站首页>Data driven excel reading and writing
Data driven excel reading and writing
2022-07-23 23:42:00 【Si Xiaoyou】
Catalog
1.Excel Content
Files under path

Sheet1

Sheet2

2.Py File data driven
class DataDriver:
NAME = 'xuzhu'
AGE = '16'
ADDRESS = ' Tangchen Yipin '
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. Configuration of the generation logger
''' Configuration of the generation logger '''
import logging.config
# The path must be filled in where it is called , Otherwise, it will report a mistake .
def get_log(path):
logging.config.fileConfig(path)
return logging.getLogger()
5. Used for configuration excel Write format content of
''' Used for configuration excel Write format content of Put the result of the assertion Pass and Failed More prominent PatternFill Class is used to define colors Font Class is used to define the format '''
from openpyxl.styles import Alignment
from openpyxl.styles import Font
from openpyxl.styles import PatternFill
# pass Write configuration for
def pass_(cell,row,column):
cell(row=row, column=column).value = 'Pass'
# cell display : Green bold
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 Write configuration
def failed(cell,row,column):
cell(row=row, column=column).value = 'Failed'
# cell display : Red bold
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 File read class , It is used to read and execute test case files
''' excel File read class , It is used to read and execute test case files '''
import pathlib
import openpyxl
from class25.excel_driver import excel_conf
from class26 import log_conf
# Analyze the contents of test parameter cells in test cases , And convert it into the form of dictionary and return
from class24.web_keys import Keys
def arguments(value):
data = dict()
# If value Valuable , Segmentation
if value:
str_temp = value.split(';')
for temp in str_temp:
t = temp.split("=", 1)
data[t[0]] = t[1]
# If value No value , Do nothing
else:
# data = None
pass
return data
# Get the current path , And switch to excel Under the path ,pathlib.Path Function return
def path():
file = pathlib.Path(__file__).resolve().parents[1] / 'data/ Automated test cases demo.xlsx'
return file
# Get the specified test case file , Perform automated execution .
def read(file,log):
# obtain log
# log_file = pathlib.Path(__file__).resolve().parents[1] / '../class26/conf/log.ini'
# log = log_conf.get_log(log_file)
# obtain excel The content in \
# excel = openpyxl.load_workbook('../data/ Automated test cases demo.xlsx')
# file = pathlib.Path(__file__).resolve().parents[1] / 'data/ Automated test cases demo.xlsx'
excel = openpyxl.load_workbook(file)
# sheet = excel['Sheet1']
# Get all sheet page , To execute the test content
for name in excel.sheetnames:
sheet = excel[name]
# print('************* Being implemented {}Sheet page ***************'.format(name))
log.info('************* Being implemented {}Sheet page ***************'.format(name))
for values in sheet.values:
# Get the body content of the test case
if type(values[0]) is int:
# Use case descriptions can be used for log output
# print('*********************** Being implemented :{}******************************'.format(values[3]))
log.info('*********************** Being implemented :{}******************************'.format(values[3]))
# print(values)
# Processing of parameters : Through one dict To receive all parameter contents , It is convenient for parameter transmission with fixed value and variable length
# Parameter final form :'type_ = Chrome' Change for {type_: 'Chrome'}
# print(values[2])
data = arguments(values[2])
# print(data)
# print(str_temp)
''' Called function values[1], It's fixed . The invocation of operation behavior is divided into the following different types : 1. Instantiation 2. Operation behavior based on instantiated object 3. Assertion mechanism : There is a comparison between expectation and reality , And the writing of cell test results '''
''' first line open_browser The second line open:getattr(key,'open')(**data) key.open(**data) key.open(url = 'http://www.baidu.com') The third line input:getattr(key,'open')(**data) key.input(**data) key.input(by='id',value='kw',txt=' Diabolo excel') In the fourth row click '''
# Instantiation operation
if values[1] == 'open_browser':
key = Keys(**data)
# Assertion behavior : Determine the success or failure of the test based on the returned results of the assertion , And write
elif 'assert' in values[1]:
status = getattr(key, values[1])(expected=values[4],**data)
# be based on status Determine the test result written
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)
# preservation Excel: Put it here to ensure that every write can be saved , Avoid not saving previous test results because of code errors
excel.save(file)
# Routine operation behavior
else:
# if data:
# getattr(key,values[1])(**data)
# else:
# getattr(key,values[1])()
getattr(key, values[1])(**data)
excel.close()
log.info('************** completion of enforcement *******************')
7.main function
import os
from class25.excel_driver.excel_read import path, read
from class26 import log_conf
if __name__ == '__main__':
# establish log object
log = log_conf.get_log('./conf/log.ini')
# By reading the data Whether there are test cases under the path , Yes , Is executed , No, No
# Test case collection
cases = list()
# Read the test cases under the path
for path,dir,files in os.walk('../class25/data/'):
for file in files:
# Get the suffix of the file
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(' Wrong file type :{}'.format(file))
for case in cases:
log.info('******** Being implemented {} file *********'.format(case))
read(case,log)
8. Running results

边栏推荐
- Arrayslist and sequence table -- Simulation Implementation
- The basic syntax of go language (variables, constants, basic data types, for, switch, case, array, slice, make, new, map)
- cmake 编译工具小记
- 最长递增子序列变种[深刻理解最长递增序列]
- 线程池串行化
- strncat() strncmp()
- Sql156 average completion rate of each video
- [tensorflow] check whether tensorflow GPU is available
- PHP(2)
- Application of merging and sorting thought
猜你喜欢

Kirin OS and Godson environment compilation and installation of greatsql

logback

jarvisoj_level2

strncat() strncmp()

ciscn_ 2019_ n_ eight

Error handling of DGS

How to migrate databases in the flask framework
![[redis] redis installation and client redis cli use (batch operation)](/img/d7/7500e99bc3cf172f895a47aec0b44c.png)
[redis] redis installation and client redis cli use (batch operation)

Android金九银十的面试你准备的怎么样了?最新Android面试真题汇总助你备战

BGP基础实验
随机推荐
难怪国内企业ERP应用效果普遍不理想
[Fifth space 2019 finals]pwn5
ret2shellcode
strncat() strncmp()
Tensorflow one layer neural network training handwritten digit recognition
JS convert numbers to uppercase
Quickly learn to use file permissions
anchor free yolov1
ret2text
strncat() strncmp()
Stm32mp1 M4 bare metal cubeide Development Guide Chapter 6 stm32cube firmware package
归并排序思想应用
Windows软件:如何安装Mysql5.7并配置环境变量
Use of pairwise
ArraysList 与顺序表 ——模拟实现
[redis] redis installation and client redis cli use (batch operation)
Federation of DGS
y75.第四章 Prometheus大厂监控体系及实战 -- prometheus报警设置(六)
Esp8266 nodemcu - get real-time weather from Suning API
Ubtun update source