小编Ren*_*ann的帖子

如何为 pytest 固定装置指定 mypy 类型

我正在尝试为我在测试项目中使用的 pytest 本机装置指定 mypy 类型提示,例如:

import pytest

def pytest_configure(config):
    # Do something useful here
Run Code Online (Sandbox Code Playgroud)

所述config固定装置返回一个_pytest.config.Config对象。如果我尝试天真地建模:

import pytest

def pytest_configure(config: Config) -> None:
    # Do something useful here
Run Code Online (Sandbox Code Playgroud)

我收到一个 mypy 错误: conftest.py:3: error: Name 'Config' is not defined [name-defined]

我可以from _pytest.config import Config,但这似乎不是一个好方法,因为 _pytest 是私有的。另一种选择是忽略带有# type: ignore. 如果这是推荐的方式,我当然会这样做,但我想知道是否有更好的选择。

我在使用任何类型的 pytest 本机装置时都有同样的问题,例如request用于参数化装置。这将是一个_pytest.fixtures.FixtureRequest.

python pytest mypy

5
推荐指数
1
解决办法
1023
查看次数

如何在装饰器中使用 pytest 固定装置而不将其作为装饰函数的参数

我试图在装饰器中使用一个夹具来装饰测试功能。目的是为测试提供注册的测试数据。有两种选择:

  1. 自动导入
  2. 手动导入

手动导入是微不足道的。我只需要全局注册测试数据,然后可以根据其名称在测试中访问它,自动导入比较棘手,因为它应该使用 pytest 夹具。

最后会怎样:

@RegisterTestData("some identifier")
def test_automatic_import(): # everything works automatic, so no import fixture is needed
    # Verify that the test data was correctly imported in the test system
    pass

@RegisterTestData("some identifier", direct_import=False)
def test_manual_import(my_import_fixture):
    my_import_fixture.import_all()
    # Verify that the test data was correctly imported in the test system
Run Code Online (Sandbox Code Playgroud)

我做了什么:

装饰器在类变量中全局注册测试数据。它还使用usefixtures标记用相应的夹具标记测试,以防它不使用它。这是必要的,否则 pytest 将不会my_import_fixture为测试创建对象:

class RegisterTestData:
    # global testdata registry
    testdata_identifier_map = {} # Dict[str, List[str]]

    def __init__(self, testdata_identifier, direct_import = True): …
Run Code Online (Sandbox Code Playgroud)

python pytest

5
推荐指数
1
解决办法
259
查看次数

标签 统计

pytest ×2

python ×2

mypy ×1