How to import SubRequest (pytest)?
Question:
In the following code, the request has the type of <class '_pytest.fixtures.SubRequest'>
. I want to add type hint to the parameter request.
@pytest.fixture
def dlv_service(request: SubRequest): # How to import SubRequest?
print(type(request), request)
filepath = pathlib.Path(request.node.fspath.strpath)
f = filepath.with_name("file.json")
The following import doesn’t work.
from pytest.fixtures import SubRequest
Answers:
I’ve found one on the internet, hope this will help.
from _pytest.fixtures import SubRequest
I think it’s worth trying, but not sure whether it could work, sorry.
For some applications, such as accessing the node
property, you can import FixtureRequest
, which is part of the public API and a superclass of SubRequest
. See yourself:
from _pytest.fixtures import SubRequest
from pytest import FixtureRequest
issubclass(SubRequest, FixtureRequest)
hasattr(FixtureRequest, "node")
Applying this to your example:
from pathlib import Path
import pytest
from pytest import FixtureRequest
@pytest.fixture
def dlv_service(request: FixtureRequest) -> Path:
print(type(request), request)
filepath = Path(request.node.fspath.strpath)
return filepath.with_name("file.json")
In the following code, the request has the type of <class '_pytest.fixtures.SubRequest'>
. I want to add type hint to the parameter request.
@pytest.fixture
def dlv_service(request: SubRequest): # How to import SubRequest?
print(type(request), request)
filepath = pathlib.Path(request.node.fspath.strpath)
f = filepath.with_name("file.json")
The following import doesn’t work.
from pytest.fixtures import SubRequest
I’ve found one on the internet, hope this will help.
from _pytest.fixtures import SubRequest
I think it’s worth trying, but not sure whether it could work, sorry.
For some applications, such as accessing the node
property, you can import FixtureRequest
, which is part of the public API and a superclass of SubRequest
. See yourself:
from _pytest.fixtures import SubRequest
from pytest import FixtureRequest
issubclass(SubRequest, FixtureRequest)
hasattr(FixtureRequest, "node")
Applying this to your example:
from pathlib import Path
import pytest
from pytest import FixtureRequest
@pytest.fixture
def dlv_service(request: FixtureRequest) -> Path:
print(type(request), request)
filepath = Path(request.node.fspath.strpath)
return filepath.with_name("file.json")