1

In module.py, I have:

def func(x: int) -> str | None:
    if x > 9:
        return "OK"
    return None


def main(x: int) -> str | None:
    return func(x)

In test_module.py, I have:

import pytest
from pytest_mock import MockerFixture
from module import main


@pytest.fixture(name="func")
def fixture_func(mocker: MockerFixture) -> MockerFixture:
    return mocker.patch("module.func", autospec=True)


def test_main(func: MockerFixture) -> None:
    _ = main(11)
    func.assert_called_once()

pytest says:

1 passed in 0.01s [100%]  

But mypy generates the following error:

test_module.py:13:5: error: "MockerFixture" has no attribute
"assert_called_once"  [attr-defined]
Found 1 error in 1 file

What am I missing?

Laurent
  • 12,287
  • 7
  • 21
  • 37
  • it doesn't _directly_ call that function, take a look at the [source code](https://github.com/pytest-dev/pytest-mock/blob/1cb146af21ffd0b5be24703419cf4a192c4ec0ab/src/pytest_mock/plugin.py#L485) – gold_cy May 08 '23 at 16:49

1 Answers1

3

You have declared a wrong type for the func argument. The return type of mocker.patch is unittest.mock.MagicMock:

import pytest
from unittest.mock import MagicMock
from pytest_mock import MockerFixture
from module import main


@pytest.fixture(name="func")
def fixture_func(mocker: MockerFixture) -> MagicMock:
    return mocker.patch("module.func", autospec=True)


def test_main(func: MagicMock) -> None:
    main(11)
    func.assert_called_once()
tmt
  • 7,611
  • 4
  • 32
  • 46