如何在间接参数化中注释request.param? [英] How can request.param be annotated in indirect parametrization?
问题描述
在间接参数化示例中,我想要键入提示 request.param
来指示特定类型,例如 str
.
In the Indirect parametrization example I want to type hint request.param
indicating a specific type, a str
for example.
问题是因为 fixt
的参数必须为应该是(引用文档).
The problem is since the argument to fixt
must be the request
fixture there seems to be no way to indicate what type the parameters passed through the "optional param
attribute" should be (quoting the documentation).
有哪些替代方案?也许在 fixt
文档字符串或 test_indirect
文档字符串中记录类型提示?
What are the alternatives? Perhaps documenting the type hint in the fixt
docstring, or in the test_indirect
docstring?
@pytest.fixture
def fixt(request):
return request.param * 3
@pytest.mark.parametrize("fixt", ["a", "b"], indirect=True)
def test_indirect(fixt):
assert len(fixt) == 3
推荐答案
到目前为止(版本6.2), pytest
尚未为 param
提供任何类型提示.属性.如果您只需要键入 param
,而不管其他 FixtureRequest
字段和方法如何,都可以内联自己的impl存根:
As of now (version 6.2), pytest
doesn't provide any type hint for the param
attribute. If you need to just type param
regardless of the rest of FixtureRequest
fields and methods, you can inline your own impl stub:
from typing import TYPE_CHECKING
if TYPE_CHECKING:
class FixtureRequest:
param: str
else:
from typing import Any
FixtureRequest = Any
@pytest.fixture
def fixt(request: FixtureRequest) -> str:
return request.param * 3
如果您想扩展 FixtureRequest
的现有类型,则存根会变得有些复杂:
If you want to extend existing typing of FixtureRequest
, the stubbing gets somewhat more complex:
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from pytest import FixtureRequest as __FixtureRequest
class FixtureRequest(__FixtureRequest):
param: str
else:
from pytest import FixtureRequest
@pytest.fixture
def fixt(request: FixtureRequest) -> str:
return request.param * 3
理想情况下, pytest
将允许在 FixtureRequest
中使用通用的 param
类型,例如
Ideally, pytest
would allow generic param
types in FixtureRequest
, e.g.
P = TypeVar("P") # generic param type
class FixtureRequest(Generic[P]):
def __init__(self, param: P, ...):
...
然后您会做
from pytest import FixtureRequest
@pytest.fixture
def fixt(request: FixtureRequest[str]) -> str:
return request.param * 3
但是,不确定这种输入是否与当前 pytest
的代码库相符-我猜是由于某种原因而忽略了它...
Not sure, however, whether this typing is agreeable with the current pytest
's codebase - I guess it was omitted for a reason...
这篇关于如何在间接参数化中注释request.param?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!