我创建了一个用于初始化数据库的夹具
@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?这是在测试用例结束时,以及将夹具传递给的范围退出时吗?
发布于 2019-04-23 00:55:43
我将您的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为了执行任何在yield语句之后写入的工具函数中的teardown语句。
https://stackoverflow.com/questions/53769945
复制相似问题