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文件。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,907评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,987评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,298评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,586评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,633评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,488评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,275评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,176评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,619评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,819评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,932评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,655评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,265评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,871评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,994评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,095评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,884评论 2 354

推荐阅读更多精彩内容