mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Mypy to recognize the return type of pytest fixtures

Open bavobbr opened this issue 1 year ago • 0 comments

Feature

When using pytest one can declare fixtures and also define a return type for them, which IDE's like Pycharm can then use to provide further code completion. Currently mypy does not know what the type of the fixture is and ignores any obvious errors towards the type. A mechanism could be added to make sure mypy knows the type to detect issues in tests at static code check (either via mypy directly or by adding a plugin hook that changes argument types)

Pitch

either integrated into mypy or a way to write a plugin to do this. The current hooks in the plugins do not allow to inform mypy what type a specific argument is, they only seem to change what return type are of the functions it sees. Mypy does not seem know pytest fixture arguments are actually function calls, and does not provide a way for plugins to tell it what type an argument is.


import pytest

class MyClass:
    def foo(self):
        pass

def test_myclass(my_typed_fixture):
    my_typed_fixture.foo()
    my_typed_fixture.bar()
    assert True

@pytest.fixture
def my_typed_fixture() -> MyClass:
    return MyClass()

This should see that 'bar' does not exist, but it does not because we did not add a type hint to the argument my_typed_fixture being 'MyClass' (while we could, this makes it harder for testers and it is not needed for typing to work in major IDE's)

Pycharm does know, by scanning the hierarchy for matching fixtures (in test, in conftest.py of same direcvtory and higher directories). This makes pycharm very powerful for checking code validity, but that is not run in pipelines or commit-hooks.

Screenshot 2024-08-13 at 11 13 00

bavobbr avatar Aug 13 '24 09:08 bavobbr