思考:我们进行自动化测试时,如果把代码都写在一个脚本中,代码的可读性会变差,且后期代码维护也麻烦,最好的想法就是测试对象和测试用例可以分离,可以很快定位问题,代码可读性高,也比较容易理解。这里推荐大家在自动化框架中加入PO模型思想,那什么是PO模型呢?
所谓的PO就是page object,通俗解释一下就是每个页面当成一个对象,给这些页面写一个类,主要就是完成元素定位和业务操作;至于测试脚本要和ta区别开来,需要什么去这些页面类去调用即可。
上面流程图意思就是测试用例类调用不同的页面类,页面类调用公共基类,基类里面封装定义定位页面元素和基本业务操作方法。
BasePage.py(页面基类脚本)
# -*- coding: utf-8 -*- ''' Created on 2018-11-4 @author: 丹姐 Project:UI页面公共类 ''' from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import selenium.common.exceptions from selenium.webdriver.common.by import By #定义页面基类 class BasePage(object): #初始化 def __init__(self,driver): self.driver=driver # 重写元素定位方法 def find_element(self,timeout,poll_frequency,type,*loc): element=WebDriverWait(self.driver, timeout, poll_frequency).until( EC.presence_of_element_located((type,*loc))) return element # 重写定义send_keys方法 def send_keys(self,timeout,poll_frequency,type,loc,value): try: self.find_element(timeout,poll_frequency,type,loc).clear() return self.find_element(timeout,poll_frequency,type,loc).send_keys(value) except AttributeError: print("%s 页面中未能找到 %s 元素" % (self,loc)) # 重写定义click方法 def click(self,timeout,poll_frequency,type,*loc): return self.find_element(timeout,poll_frequency,type,*loc).click() # 重写多元素定位方法 def find_elements(self,timeout,poll_frequency,index,type,*loc ): elements = WebDriverWait(self.driver, timeout, poll_frequency).until( EC.presence_of_all_elements_located((type, *loc))) return elements[index]
LoginPage.py(登录页面脚本)
# coding=utf-8 ''' Created on 2018-11-4 @author: 丹姐 Project:登录页面 ''' from src.common.BasePage import BasePage from selenium.webdriver.common.by import By # 定义登录页面类,父类是BasePage class Login(BasePage): etUser_loc = "com.baidu.baidu:id/et_name" etPws_loc = "com.baidu.baidu:id/et_pass" btnLogin_loc = "com.baidu.baidu:id/rt_login" def login_in(self, username, password): print(u'输入用户名', username) self.send_keys(10, 0.1, By.ID, self.etUser_loc, username) print(u'输入密码', password) self.send_keys(10, 0.1, By.ID, self.etPws_loc, password) print(u'点击登录按钮') self.click(20, 0.1, By.ID, self.btnLogin_loc)
TestCase.py(测试用例脚本)
# coding=utf-8 ''' Created on 2018-12-24 @author: 丹姐 Project:登录测试用例 ''' import unittest from config import DriverConfigure from src.pages.Login import Login class Login(unittest.TestCase): @classmethod def setUpClass(cls): driver = DriverConfigure.get_driver() cls.driver = driver def setUp(self): self.login_page = Login(self.driver) def test_login(self): # 登录 self.login_page.login_in("zhanghao", "123456") def tearDown(self): pass @classmethod def tearDownClass(cls): cls.driver.quit()
if __name__ =="__main__": unittest.main()