用例——我有很多目录在pytest中使用相同的测试方法,我想把它集中在一个基类中,其他类将导入这个基类/继承它,以便使用通用的测试方法。
我的问题是夹具。因为对于每个类,在夹具中创建的对象是不同的,我想在基类中创建一个动态夹具,它将能够从子类中获得对象,并根据这个给定的对象创建夹具。
更具体地说,让我们看一个描述我的情况的例子(这是我现在的情况):
# test_connection_foo.py
from tests.base_connection_class import ConBaseTest
import FooCon
connection_obj=ConBaseTest()
@pytest.fixture()
def connection_str():
con = FooCon()
return con
def test_it(connection_str):
connection_obj.connection_string(connection_str)
# tests.base_connection_class.py --> aka "base class"
import pytest
class ConBaseTest():
def test_connection_string(self, connection_str):
my_con = connection_str._check_con('foo')
assert my_con is not None
assert type(my_con) is str
在当前情况下,我需要为每个子类创建这个fixture方法。我想将FooCon()对象作为参数发送给一个动态夹具装饰器,该装饰器将根据该对象创建夹具。
我愿意听取其他解决方案,以创建一个具有通用测试方法的基类,以便其他类可以在fixture中使用他的方法。
要使用fixture,测试需要被pytest发现,然后简单地将其作为函数/方法参数包含就可以了。如果为多个文件定义fixture,请将它们放在conftest.py中。
您的测试类是不可发现的,因为它不是以Test
开头的。所以完整的测试设置应该是:
intests/conftest.py
:
@pytest.fixture()
def connection_str():
con = FooCon() # define/import
return con
intests/base_connection_class.py
:
class TestConBase():
# This will be tested automatically with the fixture
def test_connection_string(self, connection_str):
my_con = connection_str._check_con('foo')
assert my_con is not None
assert type(my_con) is str