【问题标题】:How to include test classes with init in a Pytest test suite?如何在 Pytest 测试套件中包含带有 init 的测试类?
【发布时间】:2019-05-29 20:59:40
【问题描述】:

我正在尝试使用 pytest 和 Selenium 创建一个测试套件,使用页面对象模型进行模式设计。为了在我的测试中使用我的页面类,我只是将它们导入到我的 TestClass __init__ 方法中,因为它们需要使用驱动程序进行实例化。

我知道,默认情况下,pytest 会忽略具有__init__ 方法的类。我也知道,通过阅读here,可以配置 pytest 收集测试的位置。是否也可以考虑使用__init__ 进行类测试,而不是返回“Empty Suite”错误?

@pytest.fixture(scope="session")
def driver_init(request):
    from selenium import webdriver
    driver = webdriver.Chrome()
    session = request.node
    page = PageFunctions(driver)
    login_page = LoginPage(driver)
    registration_page = RegistrationPage(driver)

    for item in session.items:
        cls = item.getparent(pytest.Class)
        setattr(cls.obj, "driver", driver)
        setattr(cls.obj, "page", page)
        setattr(cls.obj, "login", login_page)
        setattr(cls.obj, "registration", registration_page)

【问题讨论】:

  • 你能提供一个你的来源的例子吗?
  • 我实际上通过绕过需要 __init__ 方法并使用我的 driver_init pytest 夹具来启动我需要的东西来管理一个解决方法。作为参考,这是我最终用来启动我需要的类并将它们用作我的测试类中的类属性的代码

标签: python pytest


【解决方案1】:

Pytest 和 Unittest 有一些不同的约定。在同一个测试函数中混合两者通常是值得避免的。

如果您只使用 Pytest,您可以将您的固定装置作为参数传递给您的测试函数,例如:

import pytest
from selenium import webdriver


@pytest.fixture
def driver():
    driver = webdriver.Chrome()
    return driver


def test_func(driver):
    # `driver` is found by pytest in the fixture above and
    # automatically passed in
    request = ... # Instantiate your request (not in your included code)

    session = request.node
    page = PageFunctions(driver)
    login_page = LoginPage(driver)
    registration_page = RegistrationPage(driver)

    # Make some assertions about your data, e.g.:
    assert page is not None

您尚未包含所有对象定义/导入,因此很难看出您要通过测试完成什么,但希望这能让您了解 pytest 约定。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-15
    • 1970-01-01
    • 2019-11-17
    • 1970-01-01
    • 1970-01-01
    • 2013-12-09
    • 1970-01-01
    • 2018-08-01
    相关资源
    最近更新 更多