Pytest的UI测试自动化

1.目的
自动化测试可以反复迅速的执行一些测试用例,从而降低执行的成本,提升了回归的速
度,可以让团队把回归的精力放在另一些不合适用自动化测试去实现的。
2.用到的python轮子
Pytest、Xpath、Allure
3.简单粗暴上代码
3.1 base.py 对selenium的二次封装

def find(self, locator):
    """定位到元素,返回元素对象,没定位到,Timeout异常"""
    if not isinstance(locator, tuple):
        raise LocatorTypeError(self.log.info("参数类型错误,locator必须是元祖类型:loc = ('id','value1')"))
    else:
        self.log.info("正在定位元素信息:定位方式->%s,value值->%s" % (locator[0], locator[1]))
        #print("正在定位元素信息:定位方式->%s,value值->%s" % (locator[0], locator[1]))
        try:
            ele = WebDriverWait(self.driver, self.timeout, self.t).until(EC.presence_of_element_located(locator))
        except TimeoutException as msg:
             self.log.info('定位元素出现超时!')
             raise msg
        return ele

def finds(self,locator):
    '''复数定位,返回elements对象 list'''
    if not isinstance(locator,tuple):
        raise LocatorTypeError(self.log.info('参数类型错误,locator必须是元组类型:loc = ("id","value")'))
    else:
        self.log.info("正在定位元素信息:定位方式->%s,value值->%s" % (locator[0], locator[1]))
        #print("正在定位元素信息:定位方式->%s,value值->%s"%(locator[0],locator[1]))
        try:
            eles = WebDriverWait(self.driver, self.timeout, self.t).until(EC.presence_of_all_elements_located(locator))
        except TimeoutException as msg:
            self.log.info('定位元素出现超时!')
            raise msg
        return eles

def writein(self,locator,text = ""):
    '''写入文本'''
    ele = self.find(locator)
    if ele.is_displayed():
        ele.send_keys(text)
    else:
        raise ElementNotVisibleException(self.log.info("元素不可见或者不唯一无法输入"))

def click(self,locator):
    '''点击元素'''
    ele = self.find(locator)
    if ele.is_displayed():
        ele.click()
    else:
        raise ElementNotVisibleException(self.log.info("元素不可见或者不唯一无法点击"))

def clear(self,locator):
    '''清空输入框文本'''
    ele = self.find(locator)
    if ele.is_displayed():
        ele.clear()
    else:
        raise ElementNotVisibleException(self.log.info("元素不可见或者不唯一"))

def is_selected(self,locator):
    '''判断元素是否被选中,返回bool值'''
    ele  = self.find(locator)
    r = ele.is_selected()
    return r

def is_element_exist(self,locator):
    '''是否找到'''
    try:
        self.find(locator)
        return True
    except :
        return False

def is_title(self,title = ""):
    '''返回bool值'''
    try:
        result = WebDriverWait(self.driver,self.timeout,self.t).until(EC.title_is(title))
        return result
    except :
        return False

def is_title_contains(self, title=''):
    """返回bool值"""
    try:
        result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.title_contains(title))
        return result
    except:
        return False

def is_text_in_element(self,locator,text = ''):
    '''返回bool值'''
    if not isinstance(locator,tuple):
        raise LocatorTypeError(self.log.info("参数类型错误,locator必须是元祖类型:loc = ('id','value1')"))
    try:
        result = WebDriverWait(self.driver, self.timeout, self.t).until(
            EC.text_to_be_present_in_element(locator, text))
        return result
    except :
        return False

def is_value_in_element(self,locator,value = ""):
    if not isinstance(locator, tuple):
        raise LocatorTypeError(self.log.info("参数类型错误,locator必须是元祖类型:loc = ('id','value1')"))
    try:
        result = WebDriverWait(self.driver, self.timeout, self.t).until(
            EC.text_to_be_present_in_element_value(locator, value))
        return result
    except:
        return False

def is_alert(self,timeout = 8):
    try:
        result = WebDriverWait(self.driver, timeout, self.t).until(EC.alert_is_present())
        return result
    except:
        return False

def get_title(self):
    """获取title"""
    return self.driver.title

def get_text(self, locator):
    """获取文本"""
    if not isinstance(locator, tuple):
        raise LocatorTypeError(self.log.info("参数类型错误,locator必须是元祖类型:loc = ('id','value1')"))
    try:
        t = self.find(locator).text
        return t
    except:
        self.log.info("获取text失败,返回''")
        #print("获取text失败,返回''")
        return ""

def get_attribute(self, locator, name):
    """获取属性"""
    if not isinstance(locator, tuple):
        raise LocatorTypeError(self.log.info("参数类型错误,locator必须是元祖类型:loc = ('id','value1')"))
    try:
        element = self.find(locator)
        return element.get_attribute(name)
    except:
        self.log.info("获取%s属性失败,返回''" % name)
        #print("获取%s属性失败,返回''" % name)
        return ''

def js_focus_element(self,locator):
    '''聚焦元素'''
    if not isinstance(locator,tuple):
        raise LocatorTypeError(self.log.info("参数类型错误"))
    target = self.find(locator)
    self.driver.execute_script("arguments[0].scrollIntoView();", target)

def js_scroll_top(self):
    '''滚到顶部'''
    js = "window.scrollTo(0,0)"
    self.driver.execute_script(js)

def js_scroll_end(self,x = 0):
    '''滚到底部'''
    js = "window.scrollTo(%s, document.body.scrollHeight)" % x
    self.driver.execute_script(js)

def select_by_index(self,locator,index =0):
    '''通过索引,index是索引第几个,从0开始,默认第一个'''
    if not isinstance(locator,tuple):
        raise LocatorTypeError(self.log.info("参数类型错误"))
    element = self.find(locator)
    Select(element).select_by_index(index)

def select_by_value(self, locator, value):
    """通过value属性"""
    if not isinstance(locator, tuple):
        raise LocatorTypeError(self.log.info("参数类型错误"))
    element = self.find(locator)
    Select(element).select_by_value(value)

def select_by_text(self,locator,text):
    """通过文本值定位"""
    element = self.find(locator)
    Select(element).select_by_visible_text(text)

def switch_iframe(self, id_index_locator):
    """切换iframe"""
    try:
        if isinstance(id_index_locator, int):
            self.driver.switch_to.frame(id_index_locator)
        elif isinstance(id_index_locator, str):
            self.driver.switch_to.frame(id_index_locator)
        elif isinstance(id_index_locator, tuple):
            ele = self.find(id_index_locator)
            self.driver.switch_to.frame(ele)
    except:
        self.log.info("iframe切换异常")
        #print("iframe切换异常")

def switch_handle(self,window_name):
    self.driver.switch_to.window(window_name)

def switch_alert(self):
    r = self.is_alert()
    if not r:
        self.log.info("alert不存在")
        #print("alert不存在")
    else:
        return r

def move_to_element(self, locator):
    """鼠标悬停操作"""
    if not isinstance(locator, tuple):
        raise LocatorTypeError(self.log.info("参数类型错误"))
    ele = self.find(locator)
    ActionChains(self.driver).move_to_element(ele).perform()

3.2 实例 可以不用yml文件

import pytest
import allure
from common.log import Log
from common.read_yml import ReadYaml
from pages.login_page import LoginPage
from selenium import webdriver
testdata = ReadYaml('login_page.yml').get_yaml_data()#读取数据

class Test_login():
    log = Log()
    # // 项目名称
    @allure.feature("功能点:用户登录页面")
    @allure.description("描述:用户登录流程")
    # # 分组、用例名称
    @allure.story("用例:用户登录")
    @pytest.mark.parametrize("username,password,msg", testdata["test_login_success_data"])
    # @pytest.mark.skip('跳过该成功用例')
    def test_success_login(self, driver, username, password, msg):
        driver = webdriver.Chrome()
        web = LoginPage(driver)
        web.login(user=username, allure=allure)
        allure.attach(driver.get_screenshot_as_png(), "运行截图", attachment_type=allure.attachment_type.PNG)
        # result = web.is_login_success(expect_text=msg)
        # self.log.info("登录结果:%s"%result)
        # 断言成功失败 boolean参数
        assert 1
    def test_fail_login(self,driver):
        with allure.step("打开服务平台"):
            print("1111")
        with allure.step("失败"):
            print(2222)
        assert 1


if __name__ == '__main__':
    pytest.main(['-s', './test_login.py', '--alluredir', 'temp'])

3.3 login_page.py

from common.base import Base
from common.des_decrypt import get_code, decrypt_des
from common.read_yml import ReadYaml
from data.home import Home_Xpath, Assess_Xpath, Login_Xpath
testelement = ReadYaml("login_page.yml").get_yaml_data()
 class LoginPage(Base):
      def login(self, user, allure):
        with allure.step("打开平台地址"):
            self.driver.get(self.base_url)
        with allure.step("点击第一个按钮"):
            # self.click(self.loc1)
            self.click(Home_Xpath.assess_button)
        with allure.step("点击登录注册"):
            self.click(Assess_Xpath.login_button)
        with allure.step("登录页面 输入手机号"):
            self.writein(Login_Xpath.phone_input, user)
        # 输入验证码
        self.writein(Login_Xpath.verification_code_input, "666666")
        # 点击同意协议
        self.click(Login_Xpath.agree_button)
        # 点击登录
        self.click(Login_Xpath.login_button)
        # self.input_password(password)
        # self.click_button()
def is_login_success(self, expect_text='登录注册'):
    text = self.get_text(self.loc2)
    self.log.info("获取到断言元素的文本内容:%s" % text)
    return expect_text != text

def is_login_fail(self, expect_text='请输入正确的用户名和密码'):
    text = self.get_text(self.loc5)
    self.log.info("获取到断言元素的文本内容:%s" % text)
    return expect_text in text
  1. 执行完成后
    找到temp文件路径
    执行命令
allure generate ./temp -o ./report --clean

生成一个report文件。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容