使用selenium和pytest设置项目

问题描述 投票:0回答:1

最近我用 Selenium 和 Pytest 开始了一个新项目,我不确定设置驱动程序和项目总体结构的最佳方法是什么。

我已经在 BaseClass 中设置了驱动程序:

class BaseClass:
    service_obj = Service()
    chrome_options = Options()
    driver = webdriver.Chrome(service=service_obj, options=chrome_options)

页面对象模型以及测试本身都继承自 BaseClass:

# Page Object class
class LoginPage(BaseClass):
    username_input = (By.ID, 'username-input')
    username_password = (By.ID, 'username-password')

    @classmethod
    def type_login_password(self, login, password):
        self.driver.find_element(LoginPage.username_input).send_keys(login)
        self.driver.find_element(LoginPage.username_password).send_keys(password)

    
# Test class
class TestLogin(BaseClass):
    def test_login(self):
        LoginPage.type_login_password('username', 'password')

我试图解决的问题是,使用上面的解决方案,LoginPage 中的所有方法都是 @classmethods。这是正确的解决方案吗?我不明白为什么每次都必须在测试类或页面对象类中初始化驱动程序对象。

我知道我可以简单地删除类,但保留它们有助于更好地设置测试环境 - >具有不同范围的 pytest 装置

我尝试在不同的论坛或博客上寻找答案,但从我在大多数示例中发现的情况来看,人们只是在每个类中初始化新的驱动程序实例。

python selenium-webdriver testing pytest fixtures
1个回答
0
投票

我在你的基类中做了一些修改。 @pytest.fixture 装饰器允许您定义可重用的固定装置以进行设置和拆卸。

import pytest
from selenium import webdriver

@pytest.fixture(scope="class")
def setup(request):
    service_obj = Service()
    chrome_options = Options()
    driver = webdriver.Chrome(service=service_obj, options=chrome_options)
    request.cls.driver = driver
    yield
    driver.quit()
 

您可以删除 classmethod 装饰器并使用由安装装置设置的 self.driver 实例变量。

class LoginPage:
    def __init__(self, driver):
        self.driver = driver
        self.username_input = (By.ID, 'username-input')
        self.username_password = (By.ID, 'username-password')

    def type_login_password(self, login, password):
        self.driver.find_element(*self.username_input).send_keys(login)
        self.driver.find_element(*self.username_password).send_keys(password)

class TestLogin:
    def test_login(self):
        page = LoginPage(self.driver)
        page.type_login_password('username', 'password')

希望它对你有用。

© www.soinside.com 2019 - 2024. All rights reserved.