• 自制快速冒烟测试小工具--基于python多线程


    三、代码实现-封装

    1. 创建包和文件夹目录

    Config:存放配置文件

    Driver:存放不同浏览器驱动

    TestResults:存放测试结果

    TestScripts:存放程序脚本

    Util:存放封装方法

    2. 将所需用到目录及文件路径单独整理

    ProjVar.py

    1import os
    2proj_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    3conf_path = os.path.join(proj_path,"config")
    4dbuser_ini_path = os.path.join(proj_path,"config","DbUser.ini")
    5objectmap_ini_path = os.path.join(proj_path,"config","UiObjectMap.ini")
    6driver_path = os.path.join(proj_path,"Driver")
    7logger_path = os.path.join(proj_path,"config","Logger.conf")
    8result_path = os.path.join(proj_path,"Testresults")
    9testscript_path = os.path.join(proj_path,"TestScripts")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    3. 从ini配置文件读取数据方法

    ReadConfig.py

     1# encoding=utf-8
     2import configparser
     3import os
     4import platform
     5from Config.ProjVar import *
     6
     7def read_ini_file(ini_file_path, section_name, option_name):
     8    #创建一个读取配置文件的实例
     9    cf = configparser.ConfigParser()
    10    #将配置文件内容加载到内存
    11    cf.read(ini_file_path)
    12    try:
    13        #根据section和option获取配置文件中的数据
    14        value = cf.get(section_name, option_name)
    15    except:
    16        print("the specific seciton or the specific option doesn't exit!")
    17        return None
    18    else:
    19        return value
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    4.获取元素对象方法

    根据元素定位方式获取到对应元素对象,后面登录时会用到

    ObjectMap.py

     1#encoding=utf-8
     2from selenium.webdriver.support.ui import WebDriverWait
     3import configparser,os
     4from selenium import webdriver
     5from Config.ProjVar import *
     6from Util.ReadConfig import read_ini_file
     7
     8class ObjectMap(object):
     9    def __init__(self):
    10        # 存放页面元素定位表达方式及定位表达式的配置文件所在绝对路径
    11        self.uiObjMapPath = objectmap_ini_path
    12
    13    def getElementObject(self, driver, webSiteName, elementName):
    14        try:
    15            locators = read_ini_file(self.uiObjMapPath, webSiteName, elementName).split(">")
    16            # 得到定位方式
    17            locatorMethod = locators[0]
    18            # 得到定位表达式
    19            locatorExpression = locators[1]
    20            print(locatorMethod, locatorExpression)
    21            # 通过显示等待方式获取页面元素
    22            element = WebDriverWait(driver, 10).until(lambda x: \
    23                                    x.find_element(locatorMethod, locatorExpression))
    24        except Exception as e:
    25            raise e
    26        else:
    27            # 当页面元素被找到后,将该页面元素对象返回给调用者
    28            return element
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    5. 建立一个绑定cookies的session对象

    从元素定位方式配置文件获取到定位方式,然后用ObjectMap方法获取到元素对象,用selenium webdriver自动登录,登录成功后得到cookies

    GetSessionOfCookie.py

     1from selenium import webdriver
     2import requests,time,os
     3from Config.ProjVar import *
     4from Util.ReadConfig import read_ini_file
     5from Util.ObjectMap import *
     6#from selenium.webdriver.chrome.options import Options
     7
     8def get_session_of_cookie(domain,url,account,password):
     9    #从配置文件获取配置的浏览器类型,并对应去登录获取cookie
    10    browser = read_ini_file(dbuser_ini_path, "driver", "browser")
    11    if browser.lower() == "chrome":
    12        driverpath = os.path.join(driver_path, "chromedriver.exe")
    13        driver = webdriver.Chrome(executable_path=driverpath)
    14    elif browser.lower() == "firefox":
    15        driverpath = os.path.join(driver_path,"geckodriver.exe")
    16        driver = webdriver.Firefox(executable_path=driverpath)
    17    elif browser.lower() == "ie":
    18        driverpath = os.path.join(driver_path, "IEDriverServer.exe")
    19        driver = webdriver.Ie(executable_path=driverpath)
    20    driver.maximize_window()
    21    time.sleep(1)
    22    #打开前后台登录页面
    23    driver.get(url)
    24    driver.implicitly_wait(5)
    25    # 获取登录页面元素传值登录
    26    objmap = ObjectMap()
    27    if domain == "eclp":
    28        objmap.getElementObject(driver, "eclp", "LoginAccount").send_keys(account)
    29        objmap.getElementObject(driver, "eclp", "LoginPassword").send_keys(password)
    30        objmap.getElementObject(driver, "eclp", "LoginButton").click()
    31    elif domain == "uc":
    32        objmap.getElementObject(driver, "uc", "LoginAccount").send_keys(account)
    33        objmap.getElementObject(driver, "uc", "LoginPassword").send_keys(password)
    34        objmap.getElementObject(driver, "uc", "LoginButton").click()
    35    time.sleep(3)
    36    #获取登录后的cookies
    37    allcookies = driver.get_cookies()
    38    print("获取到登录后的cookies:%s" % allcookies)
    39    driver.quit()
    40    #把上面获取的的cookies添加到s中
    41    s = requests.session()
    42    try:
    43        # 添加cookies到CookieJar
    44        c = requests.cookies.RequestsCookieJar()
    45        for i in allcookies:
    46            c.set(i["name"], i['value'])
    47        # 更新session里cookies
    48        s.cookies.update(c)  
    49    except Exception as e:
    50        print(u"添加cookies报错:%s" %str(e))
    51    print("查看添加后s的cookies")
    52    print(s.cookies)
    53    return s
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53

    6. 从数据库表查询URL

    这里使用的是cx_Oracle连接oracle,注意需要使用与python位数(32或64)对应的数据库instantclient客户端:

    GetUrlFromOra.py

     1import cx_Oracle
     2from Util.ReadConfig import read_ini_file
     3from Config.ProjVar import *
     4
     5def get_url_from_oracle(ip,account,password,domain):
     6    db=cx_Oracle.connect(account+'/'+password+'@'+ip+'/orcl')
     7    cr = db.cursor()
     8    sql = ""
     9    #根据是eclp还是uc来获取前端还是后端的url
    10    if domain == "eclp":
    11        sql = 'select sub_system_id,name,url,assert_word from eclp_uc_url where sub_system_id != 0  order by id desc'
    12    elif domain == "uc":
    13        sql = 'select sub_system_id,name,url,assert_word from eclp_uc_url where sub_system_id = 0 order by id desc'
    14    cr.execute(sql)
    15    result = cr.fetchall()
    16    #返回获取到的所有结果
    17    return result
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    7. 创建存放测试结果的文件夹方法

    先创建一个执行当天日期为名称的文件夹,若一天执行了多次,在日期文件夹下建一个“第n次”为名称的文件夹

     1#encoding = utf-8
     2import os
     3import time
     4from Config.ProjVar import *
     5
     6#创建日期格式文件夹
     7def make_date_dir(dir_path):
     8    if os.path.exists(dir_path):
     9        #获取当前时间
    10        timeTup = time.localtime()
    11        #转为xxxx年xx月xx日的格式
    12        currentDate = str(timeTup.tm_year) + "年" + str(timeTup.tm_mon) + "月" + str(timeTup.tm_mday) + "日"
    13        #用目标目录拼接日期得到绝对路径
    14        path = os.path.join(dir_path,currentDate)
    15        if not os.path.exists(path):
    16            os.mkdir(path)
    17    else:
    18        raise Exception("dir_path does not exist!")
    19    return path
    20
    21#创建日期文件夹下多次执行的目录
    22def make_report_dir():
    23    #先创建一个日期格式为名称的文件夹
    24    date_path = make_date_dir(result_path)
    25    #判断当前目录已有文件夹数,加1得到新文件夹名并创建
    26    report_path = os.path.join(date_path, "第" + str(len(os.listdir(date_path)) + 1) + "次测试")
    27    os.mkdir(report_path)
    28    #进入到新创建文件夹并获取当前的绝对路径,作为后面存放测试结果的文件夹
    29    os.chdir(report_path)
    30    result_report_path = os.getcwd()
    31    return result_report_path
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    8. Log日志设置

    使用python的Logger.conf配置文件,设置我们需要的日志级别和存放目录

    9. HTML报告模板

    创建一个htmlTemplate方法,里面先用HTML语言设置好自己想要的报告模板,后面将测试结果与模板拼接即可。

    喜欢软件测试的小伙伴们,如果我的博客对你有帮助、如果你喜欢我的博客内容,请 “点赞” “评论” “收藏” 一 键三连哦!
    在这里插入图片描述

  • 相关阅读:
    【Delphi】IOS 15 UDP 广播消息(局域网)
    net-java-php-python-小学随班就读管理系统设计计算机毕业设计程序
    sqrt函数的实现
    利用vue模拟element-ui的分页器效果
    第二十章·中介者模式
    接口自动化测试用例编写规范
    docker 镜像启动并完成服务部署
    二十五、商城 - 运营商后台审核上下架-注解式事务配置(13)
    Spring框架新手快速上手系列:(二)体验一把自己配置低级容器
    Maven 快速入门
  • 原文地址:https://blog.csdn.net/wx17343624830/article/details/126897881