python selenium 多个页面对象类使用同一个webdriver(即只打开一个浏览器窗口)

 1 class BasePage():
 2     """selenium基类"""
 3 
 4     def __init__(self, driver=None):
 5         self.log = Log().logger
 6         self.report = cm.allure_json
 7         self.broswer = CONF.web_broswer or 'firefox'
 8         self.base_url = CONF.web_url
 9         self.timeout = 6
10         if driver is None:
11             self.set_driver(self.broswer)
12         else:
13             self.driver = driver
14             self.wait = WebDriverWait(self.driver, self.timeout)
15             self.action_chain = ActionChains(self.driver)
16 
17     def set_driver(self, driver):
18         if 'chrome' == driver.lower().strip():
19             options = chrome_op()
20             options.add_argument("--ignore-certificate-errors")
21             self.driver = webdriver.Chrome(os.path.join(cm.DRIVER_PATH, 'chromedriver'),
22                                            chrome_options=options)
23         elif 'firefox' == driver.lower().strip():
24             binary_file = CONF.firefox_binary or '/usr/bin/firefox-esr'
25             executable_path = os.path.join(cm.DRIVER_PATH, 'geckodriver')
26             options = firefox_op()
27             options.binary = FirefoxBinary(binary_file)
28             service = Service(executable_path=executable_path)
29             my_profile = webdriver.FirefoxProfile()
30             my_profile.accept_untrusted_certs = True
31             self.driver = webdriver.Firefox(firefox_profile=my_profile, options=options,
32                                             service=service)
33         else:
34             raise Exception('暂不支持%s浏览器驱动' % driver)
35         self.wait = WebDriverWait(self.driver, self.timeout)
36         self.action_chain = ActionChains(self.driver)

10~15行代码,当实例化对象时,如果driver参数为None(默认),则调用set_driver方法设置webdriver,否则设置对象的driver属性为传入的driver参数。

使用方法如下:

class Test260161_ECS():
    def setup(self) -> None:
        self.ecs_manager_page = ecs_manager_page

    def teardown(self) -> None:
        if getattr(self, 'ecs_name', False):
            self.ecs_manager_page.search_ecs('名称', self.ecs_name)
            result = self.ecs_manager_page.check_ecs_table_iszero()
            if result == False:
                self.ecs_manager_page.clear_ecs('名称', self.ecs_name)
            bin_manager_page = BINManagerPage(driver=self.ecs_manager_page.driver)
            bin_manager_page.clear_bin(self.ecs_name)

在ecs_manager_page作为主测对象,bin_manager_page作为辅测对象,主测对象ecs_manager_page实例化话,不传driver参数;而辅测对象bin_manager_page实例化时,driver参数传入ecs_manager_page.driver属性。从而可以达到多个页面对象类使用同一个driver,

执行测试用例时,只会打开一个web窗口。

posted on 2022-03-22 11:00  fdzwdt  阅读(1411)  评论(0编辑  收藏  举报