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 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())

 

posted @ 2021-09-26 20:32  鹄望  阅读(697)  评论(0编辑  收藏  举报