Type annotation for fixtures
See original GitHub issueAs reported by others, the fact that fixture can exist magically is confusing for many users unfamiliar with pytest and it can be gruesome to track in larger projects with many fixtures.
Since type annotation is working well in python 3 I was thinking that one explicit way would be to have a new Fixture type to help annotate the fixture arguments.
from typing import Union
import pytest
Fixture = Union
@pytest.fixture
def bob() -> str:
return '42'
@pytest.fixture
def alice() -> int:
return 42
def test_foo(bob: Fixture[str], alice: Fixture[int]):
assert bob != alice
In this example I ‘abuse’ Union so that existing tools are taking the hinting without any issue. For the person coming in and reading the code, especially in larger projects, the fact that the arguments are fixtures becomes very explicit and in the spirit of the Zen of Python:
Explicit is better than implicit.
Unfortunately mypy and other type checking tools don’t seem to ‘alias’ Union since it is a special case.
This on the other hand works but I would prefer the annotation of the first example:
from typing import Union
import pytest
@pytest.fixture
def bob() -> str:
return '42'
@pytest.fixture
def alice() -> int:
return 42
FixtureStr = Union[str]
FixtureInt = Union[int]
def test_bar(bob: FixtureStr, alice: FixtureInt):
assert bob != alice
IDEs such as PyCharm then now able to hint on bob being a string and as a user I can tell that it is a fixture argument.
Issue Analytics
- State:
- Created 4 years ago
- Reactions:6
- Comments:22 (14 by maintainers)
Top Related StackOverflow Question
I’m personally opposed to typing tests and find it a waste of time (though I do check_untyped_defs for tests which I do think is valuable). tests are going to fail anyway if there’s a typing error so it does not provide value for me
but that’s entirely off topic for this issue. this issue is about changing the way fixtures work to not be dependency injected by name
Why not just write it as
def test_bar(bob: str): ...at that point? IMO theFixturejust makes it more confusing.I just finally have to write pytest support in Jedi. I’m using both tools daily so I should really just do myself a favor 😃.