Python实战之Selenium自动化测试web刷新FW
需求:将手工登录,手工刷新服务器的FW转化为Python+Selenium实现自动化操作。
1.创建用户表,实现数据与脚本分离。需要读取模块。
2.自动化刷新FW.
不说话,直接上代码:
1userdata.py
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
'''
A model that use xlrd to read excel(include user info)
'''
import xlrd class XlUserInfo(object):
#initialize
def __init__(self, path=''):
self.path = path
self.xl = xlrd.open_workbook(self.path) # def get_ip_info(self):
# ip_sheets = self.xl.sheets()[0]
# server_name = ip_sheets.col_values(0)[1:]
# ips = ip_sheets.col_values(1)[1:]
# temp = zip(server_name, ips)
# server_ip = []
# server_ip.append(dict(temp))
# return server_ip # def get_fw_info(self):
# fw_sheets = self.xl.sheets()[1]
# fw_name = fw_sheets.col_values(0)
# fw_dir = fw_sheets.col_values(1)[1:]
# temp = zip(fw_name, fw_dir)
# server_image = []
# server_image.append(dict(temp))
# return server_image
#获取sheet object,处理并读取信息
def get_sheet_info(self):
all_info = []
info0 = []
info1 = []
for row in range(0,self.sheet.nrows):
info = self.sheet.row_values(row)
info0.append(info[0])
info1.append(info[1])
temp = zip(info0,info1)
all_info.append(dict(temp))
return all_info.pop(0)
# return all_info #通过excel的sheet的名字读取信息
def get_sheetinfo_by_name(self, name):
self.sheet = self.xl.sheet_by_name(name)
return self.get_sheet_info() #通过excel的sheet的索引读取信息
def get_sheetinfo_by_index(self, index):
self.sheet = self.xl.sheet_by_index(index)
return self.get_sheet_info() if __name__ == '__main__':
# 实例化
xl = XlUserInfo('user_info.xlsx')
ips = xl.get_sheetinfo_by_name('ip')
fwargs = xl.get_sheetinfo_by_name('fw')
webargs = xl.get_sheetinfo_by_name('webEle')
print("IPS",ips)
for server_name in ips.keys():
machine = server_name.split('_')[0]
test_ip = ips[server_name]
bmc = fwargs['BMC']
official_bmc = fwargs['OfficialBMC']
dsa = fwargs['DSA']
print(test_ip)
print(server_name)
2.Login_model
import time
from outlog_model import OutLog
from selenium import webdriver def login(testip,webarg):
logger = OutLog(filepath='report/{}.log'.format(testip))
profile = webdriver.FirefoxProfile()
profile.accept_untrusted_certs = True
driver = webdriver.Firefox(firefox_profile=profile)
driver.implicitly_wait(30)
driver.verificationErrors = []
driver.accept_next_alert = True
result = 0
try:
driver.get('https://{}/designs/imm/index.php'.format(testip))
except:
logger.Write_info('[Fail to Login Web GUI] : {}'.format(testip))
try:
if driver.find_element_by_id(webarg["uname_id"]):
result = 1
else:
result = 0
# 'uname_id' = 'user'
driver.find_element_by_id(webarg["uname_id"]).send_keys(webarg['uname'])
finally:
print("Wait web to be ready")
time.sleep(15)
# 'uname_id' = 'user'
driver.find_element_by_id(webarg['uname_id']).send_keys(webarg['uname'])
#pwd_id = password
driver.find_element_by_id(webarg['pwd_id']).send_keys(webarg['pwd'])
#login_button_id = btnLogin_label
driver.find_element_by_id(webarg['login_id']).click()
time.sleep(30)
print("Success to login")
# print("Login driver is ",driver)
return driver
3.outlog model
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
'''
A model for produce outlog
'''
import time
import xlsxwriter
import logging
import os #A class to write excel
class XLLoginfo(object):
def __init__(self, path=''):
file_name = "Result-{}".format(time.strftime('%m-%d-%H-%M-%S',time.localtime()))
self.row = 0
self.xl = xlsxwriter.Workbook(path + file_name + '.xlsx')
def xl_write(self, *args):
col = 0
for val in args:
self.sheet.write_string(self.row, col, val)
col += 1
self.row += 1 # The API for users.
def Xl_init(self, sheetname, *title):
self.sheet = self.xl.add_worksheet(sheetname)
self.sheet.set_column('A:G',20)
self.xl_write(*title) def Xl_write(self,*args):
self.xl_write(*args) def Xl_close(self):
self.xl.close() #A class using logging model to get log(info,warining,critical)
class OutLog(object):
def __init__(self,filepath=''):
self.file = filepath
self.logger = logging.getLogger()
self.logger.setLevel(logging.INFO)
self.fh = logging.FileHandler(filepath)
self.ch = logging.StreamHandler()
self.formatter = logging.Formatter('%(message)s = %(name)s = %(asctime)s')
self.fh.setFormatter(self.formatter)
self.ch.setFormatter(self.formatter) self.logger.addHandler(self.fh)
self.logger.addHandler(self.ch) def Write_info(self,info_message):
self.logger.info(info_message) def Write_error(self,error_message):
self.logger.error(error_message) def ReWrite_result(self):
with open(self.file) as fp:
old_info = []
for i in fp:
if i not in old_info:
old_info.append(i)
new_result = []
for r in old_info:
if r not in new_result:
new_result.append(r)
with open(self.file, 'w') as f:
f.truncate()
for h in new_result:
f.writelines(h) class Totlalog(object):
def __init__(self,path):
self.path = path def eachfile(filepath):
pathdir = os.listdir(filepath)
print(pathdir)
for file in pathdir:
filename = os.path.join('%s\%s'%(filepath,file))
with open(filename) as fp:
print(filename,fp.readlines()) if __name__ == '__main__':
# A example to use XLLoginfo API # A example to use Outlog
log = OutLog(filepath='report/log.txt')
log.Write_error('error')
log.Write_info('info')
log.Write_info('info')
log.Write_info('info')
log.ReWrite_result()
4.刷新FW,动作模块
# -*- coding: utf-8 -*-
import time
from login_model import login
from outlog_model import OutLog def test_flash(server_name,testip,fwname,webarg): logger = OutLog(filepath='report/{}.log'.format('result'))
try:
driver = login(testip, webarg)
driver.accept_next_alert = True
print('fwname:',fwname)
print("Now begin to test flash {}".format(fwname))
time.sleep(25)
try:
driver.find_element_by_id("dijit_MenuBarItem_0_text")
except:
driver.quit()
finally:
time.sleep(5)
print("Web is ready now")
driver.find_element_by_id("dijit_PopupMenuBarItem_2_text").click()
driver.find_element_by_css_selector("#dijit_MenuItem_9_text > table > tbody > tr > td").click()
driver.find_element_by_id("btnUpdateFwDlg_label").click()
time.sleep(5)
# .find_element_by_css_selector("input.dijitOffScreen").click()
# driver.find_element_by_name("uploadedfile").clear()
driver.find_element_by_name("uploadedfile").send_keys(fwname) if 'imm' in fwname:
try:
try:
driver.find_element_by_id("updateServerFirmwareWizardbtnNext_label").click()
finally:
time.sleep(10)
print("Now upload {} image".format(fwname))
driver.find_element_by_id("updateServerFirmwareWizardbtnNext_label").click()
time.sleep(200)
try:
driver.find_element_by_id("updateServerFirmwareWizardbtnNext_label").click()
finally:
time.sleep(15)
print("Wait to flash {} image finished".format(fwname))
driver.find_element_by_id("updateServerFirmwareWizardbtnNext_label").click()
time.sleep(5)
driver.find_element_by_id("updateServerFirmwareWizardbtnNext_label").click()
time.sleep(180)
# driver.find_element_by_xpath("(//input[@value=''])[5]").click()
driver.find_element_by_id("restartIMMId_label").click()
time.sleep(5) if driver.find_element_by_id("commonPopupOk_label"):
result = 1
logger.Write_info('[Pass] : IMM {} {} {}'.format(server_name,testip,fwname))
else:
result = 0
logger.Write_info('[Fail] : IMM {} {} {}'.format(server_name, testip, fwname)) print("Reatart imm wait about 5 min")
driver.find_element_by_id("commonPopupOk_label").click()
time.sleep(720)
print("Finish test to flash IMM fw.")
try:
print("Close")
driver.close()
except:
print("Quit")
driver.quit()
finally:
return result
except:
driver.close()
result = -1
logger.Write_error('[Fail] code:{} IMM {} {} {}'.format(result,server_name, testip, fwname))
return result
time.sleep(20) elif 'uefi' in fwname:
try:
try:
driver.find_element_by_id("updateServerFirmwareWizardbtnNext_label").click()
finally:
time.sleep(10)
print("Now upload UEFI image")
driver.find_element_by_id("updateServerFirmwareWizardbtnNext_label").click()
time.sleep(20)
try:
driver.find_element_by_id("updateServerFirmwareWizardbtnNext_label").click()
finally:
time.sleep(15)
driver.find_element_by_id("updateServerFirmwareWizardbtnNext_label").click()
print("Wait to flash UEFI image finished,need 1 min 37 sec")
time.sleep(5)
driver.find_element_by_id("updateServerFirmwareWizardbtnNext_label").click()
time.sleep(110)
# driver.find_element_by_xpath("(//input[@value=''])[4]").click() if driver.find_element_by_id("restartOSId_label"):
print("Restart OS")
time.sleep(10)
driver.find_element_by_id("restartOSId_label").click()
else:
time.sleep(10)
driver.find_element_by_id("restartOSId_label").click()
time.sleep(5)
driver.find_element_by_id("commonPopupOk_label").click()
time.sleep(5)
driver.find_element_by_id("commonPopupClose_label").click()
time.sleep(10)
driver.find_element_by_id("dijit_MenuBarItem_0_text").click()
time.sleep(5)
driver.find_element_by_id("btnserverActionsListHealthSumm_label").click()
time.sleep(5)
driver.find_element_by_id("serverActionsListHealthSumm63_text").click()
time.sleep(5)
driver.find_element_by_id("commonPopupOk_label").click()
time.sleep(5) print("Reatart os,wait about 5 min")
time.sleep(300)
print("Finish test to flash UEFI fw") if driver.find_element_by_id("commonPopupClose_label"):
result = 1
logger.Write_info('[Pass] : UEFI {} {} {}'.format(server_name,testip,fwname))
else:
result = 0
logger.Write_info('[Fail] : UEFI {} {} {}'.format(server_name, testip, fwname)) driver.find_element_by_id("commonPopupClose_label").click()
try:
print("Quit")
driver.quit()
except:
print("Close")
driver.close()
finally:
return result
except:
driver.close()
result = -1
logger.Write_error('[Fail] code:{} UEFI {} {} {}'.format(result,server_name, testip, fwname))
return -1 else:
try:
if driver.find_element_by_id("updateServerFirmwareWizardbtnNext_label"):
driver.find_element_by_id("updateServerFirmwareWizardbtnNext_label").click()
print("1.Now upload DSA image,need about 250s")
else:
time.sleep(10)
print("2.Now upload DSA image,need about 250s")
driver.find_element_by_id("updateServerFirmwareWizardbtnNext_label").click()
time.sleep(420)
if driver.find_element_by_id("updateServerFirmwareWizardbtnNext_label"):
print("1.wait to flash dsa")
driver.find_element_by_id("updateServerFirmwareWizardbtnNext_label").click()
else:
time.sleep(30)
print("2.wait to flash dsa")
driver.find_element_by_id("updateServerFirmwareWizardbtnNext_label").click()
driver.find_element_by_id("updateServerFirmwareWizardbtnNext_label").click()
print("Wait to flash DSA image finished,need 120 sec")
time.sleep(5)
driver.find_element_by_id("updateServerFirmwareWizardbtnNext_label").click()
time.sleep(5)
driver.find_element_by_id("updateServerFirmwareWizardbtnNext_label").click()
time.sleep(5) driver.find_element_by_id("updateServerFirmwareWizardbtnNext_label").click()
time.sleep(200)
# updateServerFirmwareWizardbtnFinish_label if driver.find_element_by_id("updateServerFirmwareWizardbtnFinish_label"):
result = 1
logger.Write_info('[Pass] : DSA {} {} {}'.format(server_name,testip,fwname))
driver.find_element_by_id("updateServerFirmwareWizardbtnFinish_label").click()
else:
result = 0
logger.Write_info('[Fail] : DSA {} {} {}'.format(server_name, testip, fwname))
print("Finish test to flash DSA fw")
try:
print("Quit")
driver.quit()
except:
print("Close")
driver.close()
finally:
return result
except:
driver.close()
result = -1
logger.Write_error('[Fail] code:-1 DSA {} {} {}'.format(server_name, testip, fwname))
return result finally:
# return result
driver.close()
if __name__ == "__main__":
pass
5.主模块,运行模块
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import threading
import time
from userdata import XlUserInfo
from flashImage import test_flash
from login_model import login
from outlog_model import OutLog def main(ip,server_name,imm,official_imm,bios,DSA):
# test_ip, serverName, bmc, official_bmc, uefi, dsa
logger = OutLog(filepath='report/{}.log'.format('result'))
# choose to flash imm
imm_result = test_flash(server_name, ip, imm, webargs)
time.sleep(60)
if imm_result != 1:
imm_result = test_flash(server_name, ip, imm, webargs)
time.sleep(60)
# choose to flash uefi
uefi_result = test_flash(server_name, ip, bios, webargs)
if uefi_result != 1:
uefi_result = test_flash(server_name, ip, bios, webargs)
# choose to flash dsa
dsa_result = test_flash(server_name, ip, DSA, webargs)
if dsa_result != 1:
dsa_result = test_flash(server_name, ip, DSA, webargs)
# choose to flash official imm
official_imm_result = test_flash(server_name, ip, official_imm, webargs)
if official_imm_result != 1:
official_imm_result = test_flash(server_name, ip, official_imm, webargs)
# choose to update imm.
upgrade_imm_result = test_flash(server_name, ip, imm, webargs)
if upgrade_imm_result != 1:
upgrade_imm_result = test_flash(server_name, ip, imm, webargs) # try:
# driver = login(test_ip,webargs)
# print(driver)
# if driver:
# driver.close()
# time.sleep(60)
# #choose to flash imm
# imm_result = test_flash(server_name,ip, imm, webargs)
# time.sleep(60)
# if imm_result != 1:
# imm_result = test_flash(server_name, ip, imm, webargs)
# time.sleep(60)
# # choose to flash uefi
# uefi_result = test_flash(server_name,ip, bios, webargs)
# if uefi_result != 1:
# uefi_result = test_flash(server_name, ip, bios, webargs)
# #choose to flash dsa
# dsa_result = test_flash(server_name, ip, DSA, webargs)
# if dsa_result != 1:
# dsa_result = test_flash(server_name, ip, DSA, webargs)
# #choose to flash official imm
# official_imm_result = test_flash(server_name, ip, official_imm, webargs)
# if official_imm_result != 1:
# official_imm_result = test_flash(server_name, ip, official_imm, webargs)
# #choose to update imm.
# upgrade_imm_result = test_flash(server_name, ip, imm, webargs)
# if upgrade_imm_result != 1:
# upgrade_imm_result = test_flash(server_name, ip, imm, webargs)
# else:
# logger.Write_error("[Fail Login into Web] : {} {}".format(server_name, ip))
# except:
# logger.Write_error("[Fail Login into Web]]]]]] : {} {}".format(server_name, ip))
# finally:
# time.sleep(60)
# logger.ReWrite_result() if __name__ == '__main__':
now_time = time.strftime("%Y-%m-%d_%H.%M.%S", time.localtime(time.time()))
#实例化一个xl对象,分别读取ip,fw,webEle的info
xl = XlUserInfo('user_info.xlsx')
ips = xl.get_sheetinfo_by_name('ip')
fwargs = xl.get_sheetinfo_by_name('fw')
webargs = xl.get_sheetinfo_by_name('webEle')
test_thread = []
for serverName in ips.keys():
machine = serverName.split('_')[0]
test_ip = ips[serverName]
bmc = fwargs['BMC']
official_bmc = fwargs['OfficialBMC']
dsa = fwargs['DSA']
uefi = '' for uefi_name in fwargs.keys():
if machine.lower() in uefi_name.lower():
uefi = fwargs[uefi_name]
print("*"*40)
print(test_ip,bmc,official_bmc,uefi,dsa)
print("*" * 40)
t = threading.Thread(target=main,args=(test_ip,serverName,bmc,official_bmc,uefi,dsa))
print(t)
t.start()
test_thread.append(t)
time.sleep(2)
for t in test_thread:
t.join()
print("Finish all Test")
Python实战之Selenium自动化测试web刷新FW的更多相关文章
- Python实战之Selenium自动化测试web登录
#!/usr/bin/env python3 # -*- coding:utf-8 -*- from selenium import webdriver from selenium.webdriver ...
- Python实战之Selenium自动化测试web登录(2)
#!/usr/bin/env python3 # -*- coding:utf-8 -*- from selenium import webdriver from selenium.webdriver ...
- 《手把手教你》系列技巧篇(四十五)-java+ selenium自动化测试-web页面定位toast-上篇(详解教程)
1.简介 在使用appium写app自动化的时候介绍toast的相关元素的定位,在Web UI测试过程中,也经常遇到一些toast,那么这个toast我们这边如何进行测试呢?今天宏哥就分两篇介绍一下. ...
- 《手把手教你》系列技巧篇(四十六)-java+ selenium自动化测试-web页面定位toast-下篇(详解教程)
1.简介 终于经过宏哥的不懈努力,偶然发现了一个toast的web页面,所以直接就用这个页面来夯实一下,上一篇学过的知识-处理toast元素. 2.安居客 事先声明啊,宏哥没有收他们的广告费啊,纯粹是 ...
- python selenium 自动化测试web
如何使用python完成自动化测试web页面呢?首选selenium 那基于python的selenium如何使用,下面看一段测试案例: 基于python的selenium 安装方法: pip i ...
- python实战项目 — selenium登陆豆瓣
利用selenium 模仿浏览器,登陆豆瓣 重点: 1. 要设置好 chromedriver配置与使用, chromedriver.exe 和 Chrome的浏览器版本要对应, http://chro ...
- 使用python+selenium对web进行自动化测试
想用python代码,对web网页进行自动化测试 web自动化测试和手动测试的区别: 手动测试:通过手动去对网页的功能进行点点点 web自动化:可以通过代码,自动对网页点点点 首先,将python+s ...
- 《Selenium自动化测试实战:基于Python》Selenium自动化测试框架入门
第1章 Selenium自动化测试框架入门 1.1 Selenium自动化测试框架概述 说到目前流行的自动化测试工具,相信只要做过软件测试相关工作,就一定听说过Selenium. 图1-1是某企业 ...
- [Python+Java双语版自动化测试(接口测试+Web+App+性能+CICD)
[Python+Java双语版自动化测试(接口测试+Web+App+性能+CICD)开学典礼](https://ke.qq.com/course/453802)**测试交流群:549376944**0 ...
随机推荐
- Maven简述
一.前言 以前做过的项目中,没有真正的使用过Maven,只知道其名声很大,其作用是用来管理jar 包的.最近一段时间在项目过程中使用Maven,用Maven构建的web项目,其项目结构只停留在 ...
- mysql 用多次查询代替一次复杂join查询的优点分析
详见:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt344 多高性能的应用都会对关联查询进行分解.简单地,可以对每一个表进行一次单 ...
- 团队作业10——beta阶段项目复审
小组的名字和链接 优点 缺点(bug报告) 最终名次 拖鞋大队 基本功能都实现了,符合用户的需求:每次都能按时完成博客,满足题目要求,所以作业完成的也比较优秀.较alpha版本新增了查重自定义的功能, ...
- 201521123113 《Java程序设计》第5周学习总结
1. 本周学习总结 1.1 尝试使用思维导图总结有关多态与接口的知识点. 1.2 可选:使用常规方法总结其他上课内容. -继承设计的技巧 1.将公共操作和属性放在父类 2.不要使用protected修 ...
- 201521123064 《Java程序设计》第12周学习总结
本次作业参考文件 正则表达式参考资料 1. 本章学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结多流与文件相关内容. ① 标准输入输出流(字节流):标准输入流 System.in,标准输出流 ...
- 多线程:深入Thread.sleep
一直都说,Threed.sleep是不会释放锁,而wait是释放锁的(对象锁),现理论上来分析一下. 由于CPU分配的每个线程的时间片极为短暂(一般为几十毫秒),所以,CPU通过不停地切换线程执行,这 ...
- 关于Java中数组的常用操作方法
1. 声明一个数组 String[] arr1 = new String[5]; String[] arr2 = {"a","b","c", ...
- 从content-type设置看Spring MVC处理header的一个坑
我们经常需要在HttpResponse中设置一些headers,我们使用Spring MVC框架的时候我们如何给Response设置Header呢? Sooooooooooooo easy, 看下面的 ...
- Ansible系列(五):playbook应用和roles自动化批量安装示例
html { font-family: sans-serif } body { margin: 0 } article,aside,details,figcaption,figure,footer,h ...
- MongoDB中的映射,限制记录和记录拼排序 文档的插入查询更新删除操作
映射 在 MongoDB 中,映射(Projection)指的是只选择文档中的必要数据,而非全部数据.如果文档有 5 个字段,而你只需要显示 3 个,则只需选择 3 个字段即可. find() 方法 ...