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?
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()