自動化 selenium +po+pytest 疑點

多多發表於2024-07-11

完整的程式碼在 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'])

相關文章