动态代理模式与PageObjct在selenium上的应用

常规PageObject中,Page中使用driver的属性或方法,都必须通过self.driver.xxx进行访问。而且,只有被定义在Page中的方法才能在测试类中使用,在部分测试场景下是不方便的。

目录结构


image.png

search_test.py

import unittest
from selenium import webdriver
import baidu_search.page as page


class Search(unittest.TestCase):
    driver = None

    @classmethod
    def setUpClass(cls):
        cls.driver = webdriver.Chrome()

    @classmethod
    def tearDownClass(cls):
        cls.driver.close()
        cls.driver.quit()

    def tearDown(self):
        self.driver.delete_all_cookies()

    def test_001(self):
        driver = page.Page(self.driver) # 可以使用Page中定义的方法
        driver.to_url()
        driver.set_search(u"张三")
        driver.search()
        import time
        time.sleep(1)

    def test_002(self):
        driver = page.Page(self.driver)  # 可以直接使用selenium中的方法
        driver.get("https://www.jianshu.com/p/f4a3659d6bf9")

    def test_003(self):
        driver = page.Page(self.driver)  # 可以直接使用selenium中的属性
        driver.to_url()
        print(driver.title)

proxy.py

# coding=utf-8
class NativeProxy(object):
    def __init__(self, target):
        object.__setattr__(self, "_target", target)

    def __getattribute__(self, item):
        """修改get逻辑"""
        try:
            target = object.__getattribute__(self, item)
            if isinstance(target, type(object().__str__)):  # wrapped method
                raise AttributeError
            else:
                return target
        except AttributeError:
            target = object.__getattribute__(self, "_target")
            return getattr(target, item)

    def __setattr__(self, key, value):
        """修改set逻辑"""
        target = object.__getattribute__(self, "_target")
        if key in dir(target):
            setattr(target, key, value)
        else:
            object.__setattr__(self, key, value)


page.py

import proxy
from . import var


class Page(proxy.NativeProxy):
    def to_url(self):
        self.get(var.url)

    def set_search(self, value):
        control = self.find_element_by_id(var.search_context_control_id)
        control.send_keys(value)

    def search(self):
        control = self.find_element_by_id(var.search_button)
        control.click()

var.py

url = "https://www.baidu.com/"
search_context_control_id = "kw"
search_button = "su"

你可能感兴趣的:(动态代理模式与PageObjct在selenium上的应用)