Skip to main content
 首页 » 编程设计

python之链接多个固定装置 pytest/unittest 混合

2025年02月15日7lautakyan007

我正在使用一个代码库,该代码库主要是用 unittest 编写的。测试使用 pytest 运行。我试图通过参数化其中的一些来简化测试。为了实现这个目标,我正在尝试学习如何使用 pytest fixtures 并重构一些现有的基于单元测试的测试。当前测试在 conftest.py 中有一个全局 fixture :

@pytest.fixture(autouse=True) 
def register_cleanup(): 
    yield True 
    print("cleaning up database") 

现在我想添加一个特定于我的测试模块之一的 fixture ,类似于

@pytest.fixture() 
def foo_fixture(): 
    print("setup fixture") 
    yield 
    print("tear down fixture") 
 
 
class Foo(unittest.TestCase): 
    def setUp(self): 
        print('unittest setUp()') 
 
    def test(self): 
        print('test') 

但是,此模块 fixture 中的 print() 语句永远不会执行。作为中间步骤,我将保留基于单元测试的结构并添加到其中。是否有可能按照我想要的方式让它工作,或者我是否需要完全放弃 unittest 并直接转到 pytest。

请您参考如下方法:

你会想要标记它:

@pytest.mark.usefixtures("foo_fixture") 
class Foo(unittest.TestCase): 
    ... 

注意:您可能有多个 conftest.py。将更具体的 fixture 放入此测试子目录的 conftest.py。