python - Pytest 参数化在最后一次迭代后运行
问题描述
使用时@pytest.mark.parametrize('arg', param)
有没有办法找出最后一项param
是否正在运行?我问的原因是我想运行该测试独有的清理功能,该功能应该只在param
.
param = [(1, 'James'), (2, 'John')]
@pytest.mark.parametrize('id, user', param)
def test_myfunc(id, user):
# Do something
print(user)
# Run this only after the last param which would be after (2, 'John')
print('All done!')
我可以运行一个检查值的条件,param
但我只是想知道 pytest 是否有办法解决这个问题。
解决方案
您需要在 pytest 钩子中执行此逻辑,特别是pytest_runtest_teardown
钩子。
假设您的测试如下所示,
import pytest
param = [(1, 'James'), (2, 'John')]
@pytest.mark.parametrize('id, user', param)
def test_myfunc(id, user):
print(f"Iteration number {id}")
在测试文件夹的根目录中,创建一个conftest.py
文件并放置以下内容,
func_of_interest = "test_myfunc"
def pytest_runtest_teardown(item, nextitem):
curr_name = item.function.__qualname__
# check to see it is the function we want
if curr_name == func_of_interest:
# check to see if there are any more functions after this one
if nextitem is not None:
next_name = nextitem.function.__qualname__
else:
next_name = "random_name"
# check to see if the next item is a different function
if curr_name != next_name:
print("\nPerform some teardown once")
然后当我们运行它时,它会产生以下输出,
===================================== test session starts ======================================
platform darwin -- Python 3.9.1, pytest-6.2.2, py-1.10.0, pluggy-0.13.1
cachedir: .pytest_cache
rootdir: ***
collected 2 items
test_grab.py::test_myfunc[1-James] Iteration number 1
PASSED
test_grab.py::test_myfunc[2-John] Iteration number 2
PASSED
Perform some teardown once
正如我们所见,在测试调用的最后一次迭代之后,拆解逻辑只被调用了一次。
推荐阅读
- python - 如果一列包含指定列表中的某些值,如何在熊猫数据框中删除行
- python - Pytest 使用夹具参数化测试
- c++ - 无法将 std::array 容器拆分为 2 个子部分
- amazon-web-services - 用于生产 EC2 的 Docker
- c++ - 作为 `const&` 轻量级对象传递
- ios - UISearch 在使用 Swift 5 的 UITableview 中不起作用
- python - DoesNotExist at /admin/login/ 站点匹配查询在 wagtail 中不存在
- python - 如何从图中计算不同排列的最小排除项?
- caching - 顺序访问数据以避免缓存未命中的示例?
- scheme - 符号和它的名称有什么区别?