2、使用pageobject形式达到页面代码与测试代码分离

通常是三类文件
1、定位:把所有元素的定位写在这(属性),如果系统大,可以按功能模块写在不同的文件夹中
locators.py

# 页面中有二类:一类是元素,元素的定位,一类是元素的方法
from selenium.webdriver.common.by import By

# 一个大的功能模块写在一个文件中
class MainPageLocators(object):
    search_text = (By.ID, "sb_form_q")
    click_search = (By.ID, "sb_form_go")


class SearchResultPageLocators(object):
    search_result = (By.ID, "b_results")


2、操作方法:把页面所有的动作写成方法(方法),每个方法封装,等待,清除和操作等
pages.py

# 与定位的类名匹配
# 公共的方法提取出来
from .locators import MainPageLocators,SearchResultPageLocators
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


class BasePage(object):
    def __init__(self,driver):
        self.driver=driver

    def save_pic(self, filepath):
        self.driver.get_screenshot_as_file(filepath)


class MainPage(BasePage):
    def enter_search_text(self, text):
        # lambda是匿名函数 *是传参的格式是元组类型需要解包
        WebDriverWait(self.driver, 10).until(
            lambda driver: driver.find_element(*MainPageLocators.search_text)
        )
        element = self.driver.find_element(*MainPageLocators.search_text)
        element.clear()
        element.send_keys(text)

    def click_search_button(self):
        element = self.driver.find_element(*MainPageLocators.click_search)
        element.click()

    def title_matches(self):
        return self.driver.title


class SearchResultPage(BasePage):
    def results_found(self):
        # 等待元素加载出来后返回元素文本信息
        WebDriverWait(self.driver, 10).until(EC.presence_of_element_located(SearchResultPageLocators.search_result))
        print(self.driver.find_element(*SearchResultPageLocators.search_result).text)
        return self.driver.find_element(*SearchResultPageLocators.search_result).text

3、测试用例:
使用测试管理执行框架:可以是unittest或pytest都可以

from selenium import webdriver
import time
import unittest
import datetime,os
from ..pages import pages


class TestBingSo(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        print("这是初始化开始测试")
        parent_abspath = os.path.abspath(os.path.dirname(os.getcwd()))
        driver_path =os.path.join(parent_abspath,"driver/chromedriver")
        cls.driver = webdriver.Chrome(executable_path=driver_path)
        cls.driver.get("https://cn.bing.com/?ensearch=1&FORM=BEHPTB")
        cls.driver.maximize_window()


    @classmethod
    def tearDownClass(cls):
        print("执行完成环境销毁")
        cls.driver.quit()

    def test_soso(self):
        main_page =pages.MainPage(self.driver)
        assert 'Bing' in main_page.title_matches()
        main_page.enter_search_text("python")
        main_page.click_search_button()
        search_result_page = pages.SearchResultPage(self.driver)
        assert 'Python' in search_result_page.results_found()
        search_result_page.save_pic(str(datetime.datetime.now())+"_soso.png")


if __name__ == '__main__':
    unittest.main()

你可能感兴趣的:(2、使用pageobject形式达到页面代码与测试代码分离)