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
Asked By: ca9163d9

||

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.

Answered By: Yongle Liu

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")
Answered By: bers
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.