完整的代码在 github 上,ssh:git@github.com:GrowthDuo/pom_mumu.git
我想将 driver 设置为会话级别,想要优化一下,首页代码可以直接调用登录的方法。

这是我的driver的代码
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.firefox.service import Service as FirefoxService
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.firefox.options import Options as FirefoxOptions

@pytest.fixture(scope="session")
def driver(request):
    browser_type = request.config.getoption("--browser")
    headless = request.config.getoption("--headless")

    if browser_type == 'chrome':
        chrome_options = ChromeOptions()
        if headless:
            chrome_options.add_argument('--headless')
        chrome_service = ChromeService(executable_path='/path/to/chromedriver')
        driver = webdriver.Chrome(service=chrome_service, options=chrome_options)
    elif browser_type == 'firefox':
        firefox_options = FirefoxOptions()
        if headless:
            firefox_options.add_argument('--headless')
        firefox_service = FirefoxService(executable_path='/path/to/geckodriver')
        driver = webdriver.Firefox(service=firefox_service, options=firefox_options)
    else:
        raise ValueError("Unsupported browser type")

    driver.maximize_window()
    yield driver
    driver.quit()

接下来的是登录测试代码

import time
import allure
from page_object.UserLoginPage import UserLoginPage
from config.config_driver import initialize_driver
from common.yaml_config import UserConfig  # 假设你将上面的类保存在config/user_config.py中
from util import util
# 使用pytest类启动
# @pytest.mark.parametrize('username, password', [('will', '<PASSWORD>'), ('tom', '123456')])
class TestLoginPage():
    @classmethod
    def setup_class(cls):
        """
        测试用例执行前执行
        :return:
        """
        # 初始化浏览器驱动
        cls.driver = initialize_driver('chrome')
        # 实例化页面对象
        cls.login_page = UserLoginPage(cls.driver)
    def test_login(self):
        # driver = initialize_driver('chrome')  # 假设使用Chrome浏览器
        # # 实例化页面对象
        # login_page = UserLoginPage(driver)

        # 加载用户配置
        config = UserConfig()  # 单一实例
        login_url = config.get_url()
        self.driver.get(login_url)
        # 获取日志对象
        logger = util.get_logger()
        logger.info('测试用户登录')

        # 获取用户名和密码
        username, password = config.get_credentials('will')

        # 输入用户名和密码
        with allure.step("第一步: 输入用户名"):

            self.login_page.input_username(username)
            logger.debug('输入用户名称: %s', username)

        with allure.step("第二步: 输入密码"):
            self.login_page.input_pwd(password)
            logger.debug('输入密码: %s', password)

            # 在打开网页前截屏
            before_screenshot = self.driver.get_screenshot_as_png()
            allure.attach(before_screenshot, name='登录网页', attachment_type=allure.attachment_type.PNG)

        with allure.step("第三步: 点击登录"):
            self.login_page.login_click()
            logger.debug('点击登录')
            print(self.driver.title)
            time.sleep(3)
            # # 等待页面加载完成,这里以等待某个特定元素出现为例
            # login_page.wait_for_title()
            # 登录后截屏
            after_screenshot = self.driver.get_screenshot_as_png()
            allure.attach(after_screenshot, name='登录成功后进入首页', attachment_type=allure.attachment_type.PNG)

        # 这里可以添加断言来验证登录是否成功
        with allure.step("登录"):
            try:
                assert 'AutoMeter' == self.driver.title
            except AssertionError:
                allure.attach(after_screenshot, name='登录失败', attachment_type=allure.attachment_type.PNG)
                logger.error("注意,注意,  %s", "报错了", exc_info=1)
    @classmethod
    def teardown_class(cls):
        cls.driver.quit()

下面的是首页,首页要先登录,我想直接调用登录的登录方法

import time

import pytest
import allure
from page_object.UserLoginPage import UserLoginPage
from page_object.ProjectManagementPage import ProjectManagementPage
from config.config_driver import initialize_driver
from common.yaml_config import UserConfig
from util import util

class TestHomePage:
    @classmethod
    def setup_class(cls):
        cls.driver = initialize_driver('chrome')
        cls.login_page = UserLoginPage(cls.driver)
        cls.project_page = ProjectManagementPage(cls.driver)

    def test_home_page(self):
        config = UserConfig()
        login_url = config.get_url()
        self.driver.get(login_url)
        self.logger = util.get_logger()
        self.logger.info('测试首页')

        username, password = config.get_credentials('will')

        with allure.step("第一步: 输入用户名"):
            self.login_page.input_username(username)
            self.logger.debug('输入用户名称: %s', username)

        with allure.step("第二步: 输入密码"):
            self.login_page.input_pwd(password)
            self.logger.debug('输入密码: %s', password)

        with allure.step("第三步: 点击登录"):
            self.login_page.login_click()
            self.logger.debug('点击登录')
            #
            self.login_page.wait_for_title()

        with allure.step("第四步: 点击项目管理"):
            self.project_page.click_pro()
            self.logger.debug('点击项目管理')
            time.sleep(3)
        # 点击项目管理
        with allure.step("第四步: 点击项目管理"):
            self.project_page.click_pro()
            self.logger.debug('点击项目管理')
            time.sleep(3)

        with allure.step("第五步: 输入项目名称"):
            time.sleep(3)
            project_name = "测试项目"
            self.project_page.input_project_name(project_name)
            self.logger.debug('输入项目名称: %s', project_name)

        with allure.step("第六步: 点击查询"):
            self.project_page.click_project()
            self.logger.debug('点击查询')

    @classmethod
    def teardown_class(cls):
        cls.driver.quit()
if __name__ == '__main__':
    pytest.main(['-v' ,'-s', 'test_home_page.py'])


↙↙↙阅读原文可查看相关链接,并与作者交流