跳到内容

pytest-parametrize-values-wrong-type (PT007)

源自 flake8-pytest-style linter。

有时提供修复。

作用

检查传递给 pytest.mark.parametrize 的参数值的类型。

为什么这不好?

pytest.mark.parametrizeargvalues 参数接受参数值的迭代器,可以作为列表或元组提供。

为了提高可读性,建议为值行的列表使用一致的风格,并且在有多个参数的情况下,为每行值使用一致的风格。

值行的列表的风格可以通过 lint.flake8-pytest-style.parametrize-values-type 设置进行配置,而每行值的风格可以通过 lint.flake8-pytest-style.parametrize-values-row-type 设置进行配置。

例如,lint.flake8-pytest-style.parametrize-values-type 将导致以下预期

  • tuple: @pytest.mark.parametrize("value", ("a", "b", "c"))
  • list: @pytest.mark.parametrize("value", ["a", "b", "c"])

类似地,lint.flake8-pytest-style.parametrize-values-row-type 将导致以下预期

  • tuple: @pytest.mark.parametrize(("key", "value"), [("a", "b"), ("c", "d")])
  • list: @pytest.mark.parametrize(("key", "value"), [["a", "b"], ["c", "d"]])

示例

import pytest


# expected list, got tuple
@pytest.mark.parametrize("param", (1, 2))
def test_foo(param): ...


# expected top-level list, got tuple
@pytest.mark.parametrize(
    ("param1", "param2"),
    (
        (1, 2),
        (3, 4),
    ),
)
def test_bar(param1, param2): ...


# expected individual rows to be tuples, got lists
@pytest.mark.parametrize(
    ("param1", "param2"),
    [
        [1, 2],
        [3, 4],
    ],
)
def test_baz(param1, param2): ...

建议改为

import pytest


@pytest.mark.parametrize("param", [1, 2, 3])
def test_foo(param): ...


@pytest.mark.parametrize(("param1", "param2"), [(1, 2), (3, 4)])
def test_bar(param1, param2): ...

Options (选项)

参考