前言:
在做自动化测试的时候,我思考了一个问题,就是如果我们的测试用例随着项目的推进越来越多时,我们做自动化回归的时间也就越来越长,其中影响自动化测试速度的一个原因就是测试用例的读取问题。用例越多,所消耗的读取用例时间也就越长,这样会消耗很多不必要的时间,所以接下来将介绍一下pandas中的pickle存储格式,pickle存储格式配合pandas的数据读取格式,极大程度上提高了数据速度,提高自动化测试的工作效率!
正文:
1、首先我们要准备一个excel,里面存放1048576行数据(这也是excel单个sheet的最大存储容量)。如果觉得准备这个数据很麻烦呢,也可以先准备一个小数据的excel文件,通过一个循环写入来创建这个大数据量的文件,下面提供思路代码:
import pandas as pd
"""利用pandas来读写数据"""
path = r"D:\software\pycharm\PythonApiHeaders\tools\new.xlsx"
# 读取数据
df = pd.read_excel(path, sheet_name="strategy")
result = []
i = 0
# 循环复制excel中的数据存放在result列表中
while i < 10:
i += 1
list1 = list(copy.deepcopy(df.values)) # 深拷贝
result += list1
print("result len is :", len(result))
# print(result[:1])
# 创建一个新的dataframe对象,取好列名
df = pd.DataFrame(result,
columns=["Case_id", "Checkpoints", "Child_checkpoint", "Priority", "title",
"Is_upload", "Method", "Url", "Headers", "Json",
"Data", "Params", "setup_sql", "Expected_results", "Extract_data",
"Actual_results", "assert_db", "Tester", "Test_result", "Type"
])
# 写入到excel中,指定好sheet名称
df.to_excel(path, index=False, sheet_name="strategy")
# 打印写入到excel的数据长度
print(len(result))
2、接着,我们来查看一下常规使用openpyxl读取excel数据的消耗时间:
import time
import pandas as pd
file_path = r"D:\software\pycharm\PythonApiHeaders\tools\new.xlsx"
print("read excel start!")
cl = HandleExcel(filename=file_path)
start = time.time()
result = cl.get_excel_test_cases(sheet_name="strategy")
cost = time.time() - start
print("read excel cost:", cost)
"""打印结果"""
read excel start!
read excel cost: 5.965034008026123
可以看出读取单个sheet,花费了近6s,如果我们还要读取多个模块的话,这个时间可以想象会消耗非常多的时间!
3、然后我们可以看一下读取pickle存储方式的数据消耗的时间。首先我们要准备一个pickle存储方式的文件!这个就很难了!其实也不难,利用pandas就可以一键转换啦,非常方便。
import time
import pandas as pd
file_path = r"D:\software\pycharm\PythonApiHeaders\tools\new.xlsx"
# 设置pandas读取excel对象
df = pd.read_excel(file_path)
# 输出pickle文件
df.to_pickle("new.pkl")
4、生成pickle文件之后,我们就可以读取pkl文件了,然后看一下读取时间:
import time
import pandas as pd
start = time.time()
df = pd.read_pickle("new.pkl")
cost2 = time.time() - start
print("read pkl cost:", cost2)
# 打印结果
read pkl cost: 0.06400060653686523
5、最后我们看一下读取pkl和读取excel消耗时间的对比:
print("excel / pkl:", cost / cost2)
# 打印结果
excel / pkl: 93.20277307981732
我们可以发现读取excel文件所消耗的时间是读取pkl文件的93倍!如果是读取多个sheet页的话,这个性能可能还会更高!