zoukankan      html  css  js  c++  java
  • python自动化之ui自动化框架搭建一(关键字驱动)

    关键字驱动测试框架搭建步骤(使用公司项目,部门信息用*表示):

    一、pycharm中新建一个名叫KeyWordsFrameWork的python工程

    二、在工程中新建三个python Package,一个目录,分别命名为:

      1.config包,朱勇用于实现框架中各种配置

      2.util包,主要用于实现测试过程中调用的工具类方法,例如:读取配置文件、页面元素操作方法、解析Excel文件等

      3.testData目录,主要用户存放框架所需要的测试数据文件

      4.testScripts包,用于实现具有测试逻辑的测试脚本

    三、util包中新建一个名叫ObjectMap.py文件,实现定位页面元素,代码如下:

    # encoding=utf-8
    from selenium.webdriver.support.ui import WebDriverWait
    
    
    # 获取单个页面元素对象
    def getElement(driver, locationType, locatorExpression):
    
        try:
            # 显示等待获取元素,10s,默认每0.5s查询一次
            element = WebDriverWait(driver, 10).until
                (lambda x: x.find_element(by=locationType, value=locatorExpression))
            return element
        except Exception as e:
            raise e
    
    
    # 获取多个相同页面元素对象,以list返回
    def getElements(driver, locationType, locatorExpression):
    
        try:
            elements = WebDriverWait(driver, 10).until
                (lambda x: x.find_elements(by=locationType, value=locatorExpression))
            return elements
        except Exception as e:
            raise e
    
    
    if __name__ == '__main__':
        from selenium import webdriver
    
        # 单元测试
        driver = webdriver.Chrome()
        driver.get("http://www.baidu.com")
        searchBox = getElement(driver, 'id', 'kw')
    
        # 打印页面对象标签名
        print(searchBox.tag_name)
        aList = getElements(driver, 'tag name', 'a')
        print(len(aList))
        driver.quit()

    四、util包中新建一个WaitUtil.py文件,实现智能等待页面元素出现

    # encoding=utf-8
    
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    
    # 实现智能等待页面元素出现
    class WaitUtil(object):
    
        def __init__(self, driver):
    
            self.locationTypeDict = {
                "xpath": By.XPATH,
                "id": By.ID,
                "name": By.NAME,
                "class_name": By.CLASS_NAME,
                "tag_name": By.TAG_NAME,
                "link_text": By.LINK_TEXT,
                "partial_link_text": By.PARTIAL_LINK_TEXT
            }
    
            self.driver = driver
            self.wait = WebDriverWait(self.driver, 10)
    
    
        def frame_available_and_switch_to_it(self, locationType, locatorExpression):
            """检查fram弹框是否存在,存在则切换frame控件中"""
    
            try:
                self.wait.until(EC.frame_to_be_available_and_switch_to_it
                                ((self.locationTypeDict[locationType.lower()], locatorExpression)))
            except Exception as e:
                raise e
    
    
        def visibility_element_located(self, locationType, locatorExpression):
    
            # 显示等待元素出现
            try:
                element = self.wait.until(EC.visibility_of_element_located
                                          ((self.locationTypeDict[locationType.lower()], locatorExpression)))
                return element
            except Exception as e:
                raise e
    
    
    if __name__ == '__main__':
        from selenium import webdriver
        import time
    
        driver = webdriver.Chrome()
        driver.get("****")
        waitUtil = WaitUtil(driver)
        # waitUtil.frame_available_and_switch_to_it("id", "x-URS-iframe")
        e = waitUtil.visibility_element_located("xpath", "//*[@id='ssoLoginMode']/li[2]/a")
        e.click()
        # time.sleep(5)
        driver.quit()

    五、testScripts包中新建Test***.py,用于编写具体的测试逻辑代码,后续修改

    # encoding=utf-8
    from KeyWordsFrameWork.util.ObjectMap import *
    from KeyWordsFrameWork.util import WaitUtil
    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    import time
    
    
    def TestCreatBuild():
    
        # 创建chrom浏览器的实例
        driver = webdriver.Chrome()
    
        # 最大化浏览器
        driver.maximize_window()
        print('启动浏览器成功')
        print('访问登录页')
        driver.get('*****')
    
        # 暂定5s等待页面加载完成
        time.sleep(5)
        assert '***' in driver.title
        print('访问登录页成功')
    
        # wait = WaitUtil(driver)
    
        # 切换登录方式
        login_way = getElement(driver, "xpath", "//*[@id='ssoLoginMode']/li[2]/a")
        login_way.click()
    
        print('输入用户名')
        username = getElement(driver, "xpath", "//*[@id='username']")
        username.send_keys('***')
    
        print('输入登录密码')
        password = getElement(driver, "xpath", "//*[@id='password']")
        password.send_keys('***')
    
        print('登录')
        login = getElement(driver, 'xpath', "//*[@id='accountLogin']/button")
        login.click()
    
        # 等待*秒,验证页面加载完成
        time.sleep(10)
        assert "***" in driver.title
        print("登录成功")
    
    
    
    
    if __name__ == "__main__":
        Test***()

    七、config中新建VarConfig.py,用于定义整个框架中所需要的一些全局变量

    # encoding=utf-8
    
    import os
    
    # 获取当前文件所在目录的父目录的绝对路径
    parenthDirPath = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    screenPicturesDir = parenthDirPath + "/exceptionpictures"

    八、util中新建DirAndTime.py,用于获取当前日期及时间,以及存放异常截图存放目录

    # encoding=utf-8
    
    import time, os
    from datetime import datetime
    from KeyWordsFrameWork.config.VarConfgi import screenPicturesDir
    
    
    # 获取当前日期
    def getCurrentDate():
    
        timeTup = time.localtime()
        currentDate = str(timeTup.tm_year) + '-' + str(timeTup.tm_mon) 
                      + '-' + str(timeTup.tm_mday)
        return currentDate
    
    
    # 获取当前时间
    def getCurrentTime():
    
        timeStr = datetime.now()
        nowTime = timeStr.strftime('%H-%M-%S-%f')
        return nowTime
    
    
    # 创建截图存放的目录
    def createCurrentDateDir():
    
        dirName = os.path.join(screenPicturesDir, getCurrentDate())
        if not os.path.exists(dirName):
            os.makedirs(dirName)
        return dirName
    
    
    if __name__ == '__main__':
    
        print(getCurrentDate())
        print(getCurrentTime())
        print(createCurrentDateDir())
  • 相关阅读:
    23种设计模式
    <转>企业应用架构 --- 分层
    <转>C/S架构分析
    Decorator 模式转载
    2019-10-24 体检结果备查,降甘油三脂药物
    Entity Framework Core 文档 & Core Web API 文档
    MSSQLLocalDB 微软本地数据库,pk SQLlite
    InstallWatch Pro
    学习 skoruba/ IdentityServer4.Admin 完整版
    无代码与低代码开发平台,云+本地,阿里/腾讯
  • 原文地址:https://www.cnblogs.com/huwang-sun/p/15339958.html
Copyright © 2011-2022 走看看