How Can Request.param Be Annotated In Indirect Parametrization?
In the Indirect parametrization example I want to type hint request.param indicating a specific type, a str for example. The problem is since the argument to fixt must be the reque
Solution 1:
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:
classFixtureRequest:
param: str
else:
from typing importAnyFixtureRequest= Any
@pytest.fixture
def fixt(request: FixtureRequest) -> str:
return request.param * 3
If you want to extend existing typing of FixtureRequest
, the stubbing gets somewhat more complex:
from typing importTYPE_CHECKINGifTYPE_CHECKING:
from pytest importFixtureRequestas __FixtureRequest
classFixtureRequest(__FixtureRequest):
param: str
else:
from pytest importFixtureRequest@pytest.fixture
def fixt(request: FixtureRequest) -> str:
return request.param * 3
Ideally, pytest
would allow generic param
types in FixtureRequest
, e.g.
P = TypeVar("P") # generic param typeclassFixtureRequest(Generic[P]):
def__init__(self, param: P, ...):
...
You would then just do
from pytest import FixtureRequest
@pytest.fixture
def fixt(request: FixtureRequest[str]) -> str:
return request.param * 3
Not sure, however, whether this typing is agreeable with the current pytest
's codebase - I guess it was omitted for a reason...
Post a Comment for "How Can Request.param Be Annotated In Indirect Parametrization?"