Pytest的UI測(cè)試自動(dòng)化

1.目的
自動(dòng)化測(cè)試可以反復(fù)迅速的執(zhí)行一些測(cè)試用例,從而降低執(zhí)行的成本,提升了回歸的速
度,可以讓團(tuán)隊(duì)把回歸的精力放在另一些不合適用自動(dòng)化測(cè)試去實(shí)現(xiàn)的。
2.用到的python輪子
Pytest、Xpath、Allure
3.簡(jiǎn)單粗暴上代碼
3.1 base.py 對(duì)selenium的二次封裝

def find(self, locator):
    """定位到元素,返回元素對(duì)象,沒(méi)定位到,Timeout異常"""
    if not isinstance(locator, tuple):
        raise LocatorTypeError(self.log.info("參數(shù)類(lèi)型錯(cuò)誤,locator必須是元祖類(lèi)型: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('定位元素出現(xiàn)超時(shí)!')
             raise msg
        return ele

def finds(self,locator):
    '''復(fù)數(shù)定位,返回elements對(duì)象 list'''
    if not isinstance(locator,tuple):
        raise LocatorTypeError(self.log.info('參數(shù)類(lèi)型錯(cuò)誤,locator必須是元組類(lèi)型: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('定位元素出現(xiàn)超時(shí)!')
            raise msg
        return eles

def writein(self,locator,text = ""):
    '''寫(xiě)入文本'''
    ele = self.find(locator)
    if ele.is_displayed():
        ele.send_keys(text)
    else:
        raise ElementNotVisibleException(self.log.info("元素不可見(jiàn)或者不唯一無(wú)法輸入"))

def click(self,locator):
    '''點(diǎn)擊元素'''
    ele = self.find(locator)
    if ele.is_displayed():
        ele.click()
    else:
        raise ElementNotVisibleException(self.log.info("元素不可見(jiàn)或者不唯一無(wú)法點(diǎn)擊"))

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

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("參數(shù)類(lèi)型錯(cuò)誤,locator必須是元祖類(lèi)型: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("參數(shù)類(lèi)型錯(cuò)誤,locator必須是元祖類(lèi)型: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("參數(shù)類(lèi)型錯(cuò)誤,locator必須是元祖類(lèi)型: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("參數(shù)類(lèi)型錯(cuò)誤,locator必須是元祖類(lèi)型: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("參數(shù)類(lèi)型錯(cuò)誤"))
    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):
    '''通過(guò)索引,index是索引第幾個(gè),從0開(kāi)始,默認(rèn)第一個(gè)'''
    if not isinstance(locator,tuple):
        raise LocatorTypeError(self.log.info("參數(shù)類(lèi)型錯(cuò)誤"))
    element = self.find(locator)
    Select(element).select_by_index(index)

def select_by_value(self, locator, value):
    """通過(guò)value屬性"""
    if not isinstance(locator, tuple):
        raise LocatorTypeError(self.log.info("參數(shù)類(lèi)型錯(cuò)誤"))
    element = self.find(locator)
    Select(element).select_by_value(value)

def select_by_text(self,locator,text):
    """通過(guò)文本值定位"""
    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):
    """鼠標(biāo)懸停操作"""
    if not isinstance(locator, tuple):
        raise LocatorTypeError(self.log.info("參數(shù)類(lèi)型錯(cuò)誤"))
    ele = self.find(locator)
    ActionChains(self.driver).move_to_element(ele).perform()

3.2 實(shí)例 可以不用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()#讀取數(shù)據(jù)

class Test_login():
    log = Log()
    # // 項(xiàng)目名稱(chēng)
    @allure.feature("功能點(diǎn):用戶(hù)登錄頁(yè)面")
    @allure.description("描述:用戶(hù)登錄流程")
    # # 分組、用例名稱(chēng)
    @allure.story("用例:用戶(hù)登錄")
    @pytest.mark.parametrize("username,password,msg", testdata["test_login_success_data"])
    # @pytest.mark.skip('跳過(guò)該成功用例')
    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(), "運(yùn)行截圖", attachment_type=allure.attachment_type.PNG)
        # result = web.is_login_success(expect_text=msg)
        # self.log.info("登錄結(jié)果:%s"%result)
        # 斷言成功失敗 boolean參數(shù)
        assert 1
    def test_fail_login(self,driver):
        with allure.step("打開(kāi)服務(wù)平臺(tái)"):
            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("打開(kāi)平臺(tái)地址"):
            self.driver.get(self.base_url)
        with allure.step("點(diǎn)擊第一個(gè)按鈕"):
            # self.click(self.loc1)
            self.click(Home_Xpath.assess_button)
        with allure.step("點(diǎn)擊登錄注冊(cè)"):
            self.click(Assess_Xpath.login_button)
        with allure.step("登錄頁(yè)面 輸入手機(jī)號(hào)"):
            self.writein(Login_Xpath.phone_input, user)
        # 輸入驗(yàn)證碼
        self.writein(Login_Xpath.verification_code_input, "666666")
        # 點(diǎn)擊同意協(xié)議
        self.click(Login_Xpath.agree_button)
        # 點(diǎn)擊登錄
        self.click(Login_Xpath.login_button)
        # self.input_password(password)
        # self.click_button()
def is_login_success(self, expect_text='登錄注冊(cè)'):
    text = self.get_text(self.loc2)
    self.log.info("獲取到斷言元素的文本內(nèi)容:%s" % text)
    return expect_text != text

def is_login_fail(self, expect_text='請(qǐng)輸入正確的用戶(hù)名和密碼'):
    text = self.get_text(self.loc5)
    self.log.info("獲取到斷言元素的文本內(nèi)容:%s" % text)
    return expect_text in text
  1. 執(zhí)行完成后
    找到temp文件路徑
    執(zhí)行命令
allure generate ./temp -o ./report --clean

生成一個(gè)report文件。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容