繁体   English   中英

在 pytest 中使用 conftest 进行设置/拆卸

[英]setup/teardown using conftest in pytest

我有不同的测试文件夹(包)。 我想设置和拆卸特定包(文件夹)的一些数据。

问题是set_up()在运行该文件夹的测试用例之前执行,但在运行所有测试用例之后, tear_down没有执行。 它也在运行其他包(文件夹)的所有测试用例之后执行(在整个 pytest 会话之后)。

     [conftest.py]

     @pytest.fixture(scope="session", autouse=True)
         def set_up(request):
            '''Test package setup'''

         def tear_down():
            '''Test package teardown'''

每个文件夹都包含__init__.py文件,这是显而易见的。

那么,如何执行tear_down()刚刚运行的文件夹中的所有测试用例后,其set_up执行?

据我所知: scope="module"在这种情况下是无用的,因为我不想为每个测试设置和拆卸。

任何帮助都会很棒。 谢谢

pytest 不直接支持包级装置。 单元测试也不行。

至于主要的测试框架,我相信nose是唯一支持包fixtures的框架。 但是,nose2 正在放弃封装夹具支持。 请参阅nose2 文档

pytest 支持 xunit 风格的设备的模块、函数、类和方法级别的设备。

conftest.py文件是目录级(读取“包”)配置。 因此,如果您将其放在测试的根目录中,则其会话范围的装置将在该范围的开头运行,并且相应的tear_down将在执行之前等待范围的结论(即整个测试会话)。 如果您需要创建仅跨越子目录(子包)的装置,您需要在这些级别放置额外的conftest.py文件(使用它们自己的scope='session'装置)。 一个常见的例子是向数据库添加数据。 想象一下,想要在相应的测试包中为您的所有测试填充一些行来填充您的purchases数据库表。 您可以将完成工作的夹具放在tests.purchases.conftest.py

shopping_app/
tests/
    __init__.py
    conftest.py # applies to all tests
    buyers/
    products/
    purchases/
        conftest.py # only applies to this scope and sub-scopes
        __init__.py
        test1.py
        test2.py
        payments/
        refunds/
    sellers/
    stores/

tests.purchases.conftest.py你会有普通的fixture 声明。 例如,用于预填充和删除 db 表行的 set_up/tear_down 组合将如下所示:

@pytest.fixture(scope='session', autouse=True)
def prep_purchases(db, data):
    # set_up: fill table at beginning of scope
    populate_purchase_table_with_data(db, data)

    # yield, to let all tests within the scope run
    yield 

    # tear_down: then clear table at the end of the scope
    empty_purchase_table(db)

一些夹具不需要显式注入测试(我们只对它们的副作用感兴趣,而不是它们的返回值),因此是autouse参数。 至于 set_up/tear_down (带yield )的上下文管理器语法,如果您不满意,您也可以将tear_down部分作为它自己的单独函数放置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM