行為驅動behave結合PO設計模式
阿新 • • 發佈:2021-10-17
用PO的思想去重構或者管理行為驅動測試能使測試更有效率。
以攜程網登入場景為例,專案中體現PO思想的是page目錄下的兩個檔案分別為“base.py”和“loginPage.py”。
其中“base.py”檔案程式碼抽取了一些基本的方法,如元素定位的方法;開啟網站方法和得到當前網頁標題等方法。其程式碼如下:
#學習有疑問請聯絡作者 #作者qq:2574674466 #作者郵箱[email protected] #coding=utf-8 from selenium.webdriver.common.by import By class Base: def __init__(self,driver): self.driver = driver #*loc 函式引數是指傳入的是不定引數,這個知識點在前面章節已經提到過 #意思是findele函式可以傳入1個引數,也可以傳入2個引數等等。 def findele(self,*loc): return self.driver.find_element(*loc) def get_url(self,url): self.driver.get(url) def get_title(self): return self.driver.title
- page目錄下的另外一個檔案loginPage.py其目的是為了封裝登入頁面的操作,將這些操作以類成員方法的形式展現。注意類“loginPage”的建構函式的實現邏輯,具體內容已在以下的程式碼註釋中寫明
#學習有疑問請聯絡作者
#作者qq:2574674466
#作者郵箱[email protected]
#coding=utf-8
from features.com.page.base import Base
from selenium.webdriver.common.by import By
#loginPage繼承了Base類
class loginPage(Base):
#以下為類的初始化函式,其又呼叫了父類的初始化函式,這樣做的目的是為了
#將context.driver串起來,在呼叫PO類時,可以使用超級全域性變數context下的driver物件
def __init__(self,context):
super(loginPage,self).__init__(context.driver)
def login(self,username):
self.findele(By.ID,"nloginname").send_keys(username)
- 專案主目錄下有檔案environment.py,其主要目的是對行為驅動環境進行配置,可以被全域性呼叫。其程式碼如下:
#學習有疑問請聯絡作者
#作者qq:2574674466
#作者郵箱[email protected]
#coding=utf-8
from selenium import webdriver
def before_all(context):
context.driver = webdriver.Chrome("chromedriver路徑")
def after_tag(contex):
context.driver.quit()
專案主目錄下有檔案example.feature,其定義了行為驅動要執行的場景描述細節
Feature: Login
Scenario:open website
When I open the login website "https://passport.ctrip.com/user/login?"
Then I input username "tim"
在目錄steps下有檔案example.py,其定義了行為驅動場景的實現過程,注意程式碼中涉及到了正則表示式的使用,具體見如下程式碼細節
#coding=utf-8
from behave import *
from features.com.page.loginPage import loginPage
#以下re表示在step中定義正則表示式,要使用正則表示式
use_step_matcher('re')
#這裡表示開始抓取正則表示式的匹配值,此次是為了抓取在場景檔案example.feature中的url值,
#抓取到之後傳值給url,然後進行下面的操作
@when('I open the login website "([^"]*)"')
def step_reg(context,url):
loginPage(context).get_url(url)
@Then('I input username "([^"]*)"')
def step_r(context,code):
loginPage(context).login(code)
- 執行測試,測試結構如圖12.8所示:
視訊、學習筆記聯絡qq:2574674466
更多內容請關注公眾號:“大牛測試