asyncio使用发业务实例—(3)编写业务测试部分
##!/usr/bin/python3
# -*- coding: utf-8 -*-
import asyncio
import aiohttp
import time
import logging
import readConfig #配置文件
import os
import config #asyncio使用发业务实例—(2)的内容
import csv
import xlrd
import xlwt
from xlutils.copy import copy
i = 0
# 登录的用户名、密码
admin = "admin"
allpassword = "123456"
tasks = []
test = []
path = os.getcwd().replace('\\', '/')
from logging.handlers import RotatingFileHandler
# 保存log文件 filemode=a (不覆盖)/w(每次覆盖)
loginName = ['test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test7', 'test8', 'test9', 'test10']
timedata = time.strftime('%Y%m%d%H%M%S')
a=logging.basicConfig(filename='./LOG/'+'log'+timedata+'.log',format='[%(asctime)s-%(filename)s-%(levelname)s:%(message)s]', level = logging.INFO,filemode='w',datefmt='%Y-%m-%d%H:%M:%S %p')
rHandler = RotatingFileHandler("log.txt",maxBytes = 10*1024,backupCount = 3)
npassword = readConfig.get_http('npassword')
print(npassword)
"""建立业务"""
"""账户登入+添加操作+查询状态+ 登出"""
async def addXXJudgeStatus(name,npassword ,hostName, hostIp, hostPort, XXType, username, password):
async with aiohttp.ClientSession() as session:
data = Netdata(loop, session)
await data.login(name,npassword)
addStatus = await data.addXX(hostName, hostIp, hostPort, XXType, username, password)
wayStatus = await data.getWay()
re=[]
re.append(addStatus)
re.append(wayStatus)
await asyncio.sleep(3)
await data.logout()
return re
"""使用表格参数化,进行批量操作"""
"""批量进行添加操作并判断状态"""
def judgeNeStatus(number,filename):
loop = asyncio.get_event_loop()
judgeTask = []
openAddCvs = path+'/data/'+filename+'.csv'
with open(openAddCvs, 'r', encoding='utf8')as fp:
data_list = [q for q in csv.reader(fp)]
num = number + 1
five = number * 5
for a in range(five, five + 5):
judgeTask.append(asyncio.ensure_future(addXXJudgeStatus(data_list[a][0],data_list[a][1], data_list[a][2],
data_list[a][3],data_list[a][4], data_list[a][5], data_list[a][6],data_list[a][7])))
loop.run_until_complete(asyncio.wait(judgeTask))
time.sleep(2)
result = loop.run_until_complete(asyncio.gather(*judgeTask))
# 将列表转换成字符串,方便存储
rdata = ", ".join('%s' % id.__str__() for id in result)
#"将判断结果写入表格后面一列"
workbook = xlrd.open_workbook("log.xls") # 打开工作簿
sheets = workbook.sheet_names() # 获取工作簿中的所有表格
worksheet = workbook.sheet_by_name(sheets[0]) # 获取工作簿中所有表格中的的第一个表格
rows_old = worksheet.nrows # 获取表格中已存在的数据的行数
new_workbook = copy(workbook) # 将xlrd对象拷贝转化为xlwt对象
new_worksheet = new_workbook.get_sheet(0) # 获取转化后工作簿中的第一个表格
style = xlwt.XFStyle()
style.alignment.wrap = 1
col3 = new_worksheet.col(2) # xlwt中是行和列都是从0开始计算的
col9 = new_worksheet.col(4)
col3.width = 512 * 20
col9.width = 1012 * 20
new_worksheet.write(rows_old-1, 4, rdata, style)
new_workbook.save("log.xls") # 保存工作簿
"""场景一"""
def sceneOne(i):
"""同时添加5个操作,递增到500个操作为止"""
for p in range(0, 100):
judgeNeStatus(p, "test")
print('------执行-----' + str(i) + '----------')
def write_excel_xls(path, sheet_name):
try:
workbook = xlwt.Workbook(encoding='utf-8') # 新建一个工作簿
sheet = workbook.add_sheet(sheet_name) # 在工作簿中新建一个表格
list = ['客户端执行次数','当前时间','返回结果','操作备注','网元数据判断']
for i in range(0, len(list)):
sheet.write(0, i, list[i])
workbook.save(path) # 保存工作簿
except:
return print("请关闭打开的excel表格")
if __name__ == '__main__':
write_excel_xls('log.xls', 'one')
loop = asyncio.get_event_loop()
start_time = time.time()
"""持续循环"""
for i in range (0,1000):
if i:
sceneOne(i)
time.sleep(600)
end_time = time.time()
t = end_time - start_time
print("开始时间:" + str(start_time) + '>>>>>' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(start_time)))
print("结束时间:" + str(end_time) + '>>>>>' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(end_time)))
print('总共耗时:' + str(end_time - start_time))
print('总共耗时:%.2f' % (end_time - start_time)) # 保留两位小数
print("总共耗时(毫秒):"+str(round(t * 1000))+"ms")