[英]When do you exit the context of a pytest fixture?
I created a fixture to initialize a database 我创建了一个夹具来初始化数据库
@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)
My test uses this fixture to operate on a clean in-memory database: 我的测试使用此固定装置在干净的内存数据库中进行操作:
@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
When this fixture yields
what is actually triggering the finally
? 当这种夹具yields
,实际上是在触发finally
? Is it when the test case ends and the scope that the fixture was passed to is exited? 是在测试用例结束并且夹具传递到的范围退出时?
I simplified your test_db
fixture to the following: 我将您的test_db
固定装置简化为以下内容:
@pytest.fixture
def test_db():
"""Setup Database"""
print("\nInitialized resources")
try:
yield test_db
finally:
print("\nFinally executed")
And your test function to: 您的测试功能为:
@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
When I ran the test with pytest -sv
( -s
captures all print
s, and -v
makes output verbose), I got output similar to below: 当我使用pytest -sv
运行测试时( -s
捕获了所有print
s,而-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 ===========================
Note that Finally executed
was printed after the test finishes. 请注意,测试完成后将打印“ Finally executed
。
So I would agree with your guess that the finally
statement was executed after the fixture was destroyed. 因此,我同意您的猜测,即Fixture被销毁后执行了finally
语句。
Further, I think at the end of a test scope, pytest does something similar to 此外,我认为在测试范围的末尾,pytest做的事情类似于
try:
next(yielded_fixture)
except StopIteration:
pass
in order to execute whatever teardown statement is written after the yield
statement in the fixture function. 为了执行在fixture函数中yield
语句之后编写的任何拆解语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.