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")
时间: 2024-10-22 22:24:53

Python实战之Selenium自动化测试web刷新FW的相关文章

Python实战之Selenium自动化测试web登录

#!/usr/bin/env python3 # -*- coding:utf-8 -*- from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains import time class LoginTest(object): def __init__(self): self.url = '' self.uname = '' self.pwd = '' self.us

基于python语言的Selenium自动化测试

  一.Selenium简介 Selenium是一个web自动化应用测试工具,还支持所有的web的管理任务自动化.并且开源免费,也是一个web自动化轻量级框架.它支持多种浏览器.跨平台.跨操作系统.支持多种编程语言编写脚本,还能进行分布式测试用例的执行. Selenium经历三个版本,Selenium1.Selenium2.Selenium3.它不是单独的一个工具,而是由一些类库.插件.工具等组合而成.主要的工具: Selenium IDE:Selenium IDE是嵌入火狐浏览器中的一个插件,

python 学习笔记,selenium 自动化测试 更新开始

学python快两个月了,因为时间很少,经常都是每天只能看半个到一个钟的时间,有些东西看了又忘记了!所以从今天起,每天更新自己学习python 和 selenium 自动化测试的总觉,每天进步一点,好记性不如烂笔头,就从今天开始吧! -------------I Will Show You How Greate I am!

python+selenium 自动化测试环境搭建

selenium 是一个web的自动化测试工具,不少学习功能自动化的同学开始首选selenium ,相因为它相比QTP有诸多有点: *  免费,也不用再为破解QTP而大伤脑筋 *  小巧,对于不同的语言它只是一个包而已,而QTP需要下载安装1个多G 的程序. *  这也是最重要的一点,不管你以前更熟悉C. java.ruby.python.或都是C# ,你都可以通过selenium完成自动化测试,而QTP只支持VBS *  支持多平台:windows.linux.MAC ,支持多浏览器:ie.f

【Selenium02篇】python+selenium实现Web自动化:鼠标操作和键盘操作!

一.前言 最近问我自动化的人确实有点多,个人突发奇想:想从0开始讲解python+selenium实现Web自动化测试,请关注博客持续更新! 这是python+selenium实现Web自动化第二篇博文 二.Selenium第一篇博文地址: [Selenium01篇]python+selenium实现Web自动化:搭建环境,Selenium原理,定位元素以及浏览器常规操作! 三.Selenium之鼠标操作和键盘操作 1.鼠标事件 在webdriver中,鼠标操作的方法封装在 ActionChai

自动化测试学习笔记1——Python + Selenium自动化测试环境配置

Python + Selenium自动化测试环境配置(Windows平台) 准备工具: 下载python    http://python.org/getit/ 下载setuptools http://pypi.python.org/pypi/setuptools 下载pip https://pypi.python.org/pypi/pip 下载selenium   https://pypi.python.org/pypi/selenium 下载selenium服务端 https://code.

《手把手教你》系列进阶篇之2-python+ selenium自动化测试 - python基础扫盲(详细教程)

1. 简介 这篇文章主要是分享讲解一下,如何封装自己用到的方法和类.以便方便自己和别人的调用,这样就可以避免重复地再造轮子. 封装(Encapsulation)是面向对象的三大特征之一(另外两个是继承和多态),它指的是将对象的状态信息隐藏在对象内部,不允许外部程序直接访问对象内部信息,而是通过该类所提供的方法来实现对内部信息的操作和访问. 就好比使用计算机,我们只需要使用计算机提供的键盘,就可以达到操作计算机的目的,至于在敲击键盘时计算机内部是如何工作,我们根本不需要知道. 封装机制保证了类内部

Python Selenium 自动化测试

本文转载 作者:灰蓝蓝蓝蓝蓝蓝链接:http://www.jianshu.com/p/5188cb3ab790來源:简书著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处.更多技术博客见http://blog.csdn.net/huilan_same 第一部分:Selenium的学习网站,看了这些网站的内容,相信你的Selenium就能到达一定水平了.第二部分:Selenium的资源整理,各种版本浏览器.driver.selenium的下载,你需不需要?第三部分:博主整理的Chr

selenium自动化测试(1):环境搭建

Selenium是一款优秀的WEB自动化测试工具,它功能强大,易于使用,支持多种平台.多种浏览器和多种开发语言.这里介绍使用python+selenium进行自动化测试的一些基础知识. 在Windows下搭建测试环境,首先需要下载Python,Selenium应该还不支持Python 3.x系列,所以最好选择Python 2.x,注意区分32位和64位. Python的安装特别简单,需要提醒的是,安装路径中千万不要包含空格(最好也别包含中文),否则后面使用pip安装扩展包的时候可能会失败!其他的