跳到内容

pytest-useless-yield-fixture (PT022)

源自 flake8-pytest-style linter。

修复总是可用的。

作用

检查 pytest fixtures 中不必要的 yield 表达式。

为什么这不好?

pytest fixtures 中,yield 表达式应仅用于包含拆卸代码的 fixtures,以在测试函数执行完毕后清理 fixture。

示例

import pytest


@pytest.fixture()
def my_fixture():
    resource = acquire_resource()
    yield resource

建议改为

import pytest


@pytest.fixture()
def my_fixture_with_teardown():
    resource = acquire_resource()
    yield resource
    resource.release()


@pytest.fixture()
def my_fixture_without_teardown():
    resource = acquire_resource()
    return resource

参考