python / python/mypy

Mypy to recognize the return type of pytest fixtures

Open
#17,668 1 comment 12 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reading mypy's existing plugin hooks and the pytest fixture example in the issue. Determine how fixture arguments are represented and whether mypy or a plugin can supply their annotated return types. Done means mypy reports invalid fixture usage such as the missing bar method without requiring an argument annotation.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
testing, tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.