首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >何时退出pytest夹具的上下文?

何时退出pytest夹具的上下文?
EN

Stack Overflow用户
提问于 2018-12-13 20:55:55
回答 1查看 977关注 0票数 0

我创建了一个用于初始化数据库的夹具

代码语言:javascript
复制
@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)

我的测试使用这个夹具来操作一个干净的内存数据库:

代码语言:javascript
复制
@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?这是在测试用例结束时,以及将夹具传递给的范围退出时吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-23 00:55:43

我将您的test_db夹具简化为:

代码语言:javascript
复制
@pytest.fixture
def test_db():
    """Setup Database"""
    print("\nInitialized resources")
    try:
        yield test_db
    finally:
        print("\nFinally executed")

以及您的测试功能:

代码语言:javascript
复制
@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使输出冗长)时,得到的输出类似于以下内容:

代码语言:javascript
复制
============================= 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做了类似的事情

代码语言:javascript
复制
try:
    next(yielded_fixture)
except StopIteration:
    pass

为了执行任何在yield语句之后写入的工具函数中的teardown语句。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53769945

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档