pytest夹具生成器什么时候继续使用,范围会对此产生影响吗?

时间:2019-04-20 01:14:23

标签: python pytest

我的tests目录如下:

tests/
    conftest.py
    some_of_tests/
        conftest.py
        test_parts.py
        test_these_parts.py
    some_other_tests/
        conftest.py
        test_these_other_parts.py

我在/tests/confest.py中拥有一个固定装置,可以创建一些测试文件,实例化数据库连接,然后进行一些数据库清理:

@pytest.fixture(scope='session', autouse=True)
def setup_db():
    try:
        generate_test_files()
        db = connect_to_db()
        yield db
    finally:
        # cleanup 
        print("Cleaning up session scoped fixture")

tests/some_tests/conftest.py中,我还有另一个固定装置,可以创建一些文件,创建数据库表,然后删除这些文件:

@pytest.fixture(scope='package')
def local_setup():
    try:
        generate_test_files()
        # do stuff with db
        yield db
    finally:
        delete_test_files()
        print("Cleaning up package scoped fixture")

我以这样一种方式设置了测试:我希望在some_of_tests中运行测试之前清理some_other_tests生成的测试文件。我期望some_of_tests中的装置能够继续运行并在delete_test_files()中运行测试之前调用some_other_tests,但是当我运行pytest --capture=no tests时,我看到:

Cleaning up session scoped fixture
Cleaning up package scoped fixture

所有测试都已运行后,它们的顺序与我预期的不符。我的误解是什么?在运行下一个测试包之前清理包范围测试的最佳方法是什么?

此外,我了解到pytest以字母顺序运行。我正在利用它来按我想要的顺序运行测试。所以pytest会像some_of_tests/test_parts.py -> some_of_tests/test_these_parts.py -> some_other_tests/test_these_other_parts.py

那样运行它们

1 个答案:

答案 0 :(得分:0)

我面临着同样的问题。但是我得出的结论是,您需要在测试中添加__init__.py,以便可以将它们识别为软件包。 否则,它将最终运行测试的拆解,并像会话一样工作。

例如:

system_test/
     - conftest.py
     - test_dir1/
          - __init__.py
          - conftest.py (here put scope as package)
          - test1.py
          - test2.py
     - test_dir2/
          - __init__.py
          - test1.py
          - test2.py
          - conftest.py (here put scope as package)

它按预期工作。