您何时退出pytest固定装置的上下文?

时间:2018-12-13 20:55:56

标签: python-3.x peewee

我创建了一个夹具来初始化数据库

@pytest.fixture
def test_db():
    """Setup Database"""
    _db = SqliteDatabase(":memory:")
    dbs = (Resource, Reservation, Token)
    with _db.bind_ctx(dbs):
        _db.create_tables(dbs)
        try:
            yield test_db
        finally:
            _db.drop_tables(dbs)

我的测试使用此夹具在干净的内存数据库中运行:

@pytest.mark.parametrize(
    "attrs, exception, std",
    [
        (
            {"name": "Test1", "count": 1, "resource_type": "test_flavor"},
            peewee.IntegrityError,
            "resource.max_reservation_time may not be NULL",
        ),
    ],
)
def test_bad_resoruce_create(attrs, exception, std, test_db):
    with pytest.raises(exception) as db_error:
        resource = Resource.create(**attrs)
    assert str(db_error.value) == std

当该夹具yields实际触发finally时是什么?是在测试用例结束并且夹具传递到的范围退出时?

1 个答案:

答案 0 :(得分:0)

我将您的test_db固定装置简化为以下内容:

@pytest.fixture
def test_db():
    """Setup Database"""
    print("\nInitialized resources")
    try:
        yield test_db
    finally:
        print("\nFinally executed")

您的测试功能可以:

@pytest.mark.parametrize(
    "attrs, exception, std",
    [ ( "attrs1", "ErrorObject", "std",) ]
)
def test_bad_resoruce_create(test_db, attrs, exception, std):
    print("Doing testings")
    assert 1 == 1

当我使用pytest -sv进行测试(-s捕获了所有print,而-v使输出变得冗长)时,我得到的输出类似于以下内容:

============================= test session starts ==============================
platform linux -- Python 3.5.3, pytest-4.2.1, py-1.8.0, pluggy-0.9.0 -- /usr/bin/python3
cachedir: .pytest_cache
rootdir: , inifile:
plugins: flask-0.14.0
collected 1 item                                                               

try.py::test_bad_resoruce_create[attrs1-ErrorObject-std] 
Initialized resources
Doing testings
PASSED
Finally executed


=========================== 1 passed in 0.10 seconds ===========================

请注意,Finally executed是在测试完成后打印的。

因此,我同意您的猜测,即finally语句是在销毁灯具后执行的。

此外,我认为在测试范围的末尾,pytest的作用类似于

try:
    next(yielded_fixture)
except StopIteration:
    pass

为了执行在Fixture函数中的yield语句之后编写的任何拆解语句。