Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add MockOf typing helper #120752

Closed
wants to merge 2 commits into from
Closed

Conversation

epenet
Copy link
Contributor

@epenet epenet commented Jun 28, 2024

Proposed change

Add some typing helpers for Mock, when used in conjuction with a class constructor.

It is completely pointless from a type-checking perspective (ie. mypy/pylance), but I think it makes the code more readable:

from tests.typing import MockOf

@pytest.fixture
def mock_api_client() -> MockOf[ApiClient]:
    """Fixture for ApiClient."""
    return Mock(spec=ApiClient)

async def test_blah(
    hass: HomeAssistant, mock_api_client: MockOf[ApiClient]
) -> None:
    """Test blah."""
    # Use it as an ApiClient
    assert isinstance(mock_api_client, ApiClient) # returns True
    d = Device(client=mock_api_client)

    # Use it as a Mock
    assert isinstance(mock_api_client, Mock) # also returns True
    assert mock_govee_api.start.assert_awaited_once()

Type of change

  • Dependency upgrade
  • Bugfix (non-breaking change which fixes an issue)
  • New integration (thank you!)
  • New feature (which adds functionality to an existing integration)
  • Deprecation (breaking change to happen in the future)
  • Breaking change (fix/feature causing existing functionality to break)
  • Code quality improvements to existing code or addition of tests

Additional information

  • This PR fixes or closes issue: fixes #
  • This PR is related to issue:
  • Link to documentation pull request:

Checklist

  • The code change is tested and works locally.
  • Local tests pass. Your PR cannot be merged unless tests pass
  • There is no commented out code in this PR.
  • I have followed the development checklist
  • I have followed the perfect PR recommendations
  • The code has been formatted using Ruff (ruff format homeassistant tests)
  • Tests have been added to verify that the new code works.

If user exposed functionality or configuration variables are added/changed:

If the code communicates with devices, web services, or third-party tools:

  • The manifest file has all fields filled out correctly.
    Updated and included derived files by running: python3 -m script.hassfest.
  • New or updated dependencies have been added to requirements_all.txt.
    Updated by running python3 -m script.gen_requirements_all.
  • For the updated dependencies - a link to the changelog, or at minimum a diff between library versions is added to the PR description.
  • Untested files have been added to .coveragerc.

To help with the load of incoming pull requests:

@home-assistant
Copy link

Hey there @chishm, mind taking a look at this pull request as it has been labeled with an integration (dlna_dmr) you are listed as a code owner for? Thanks!

Code owner commands

Code owners of dlna_dmr can trigger bot actions by commenting:

  • @home-assistant close Closes the pull request.
  • @home-assistant rename Awesome new title Renames the pull request.
  • @home-assistant reopen Reopen the pull request.
  • @home-assistant unassign dlna_dmr Removes the current integration label and assignees on the pull request, add the integration domain after the command.
  • @home-assistant add-label needs-more-information Add a label (needs-more-information, problem in dependency, problem in custom component) to the pull request.
  • @home-assistant remove-label needs-more-information Remove a label (needs-more-information, problem in dependency, problem in custom component) on the pull request.

@home-assistant
Copy link

Hey there @Galorhallen, mind taking a look at this pull request as it has been labeled with an integration (govee_light_local) you are listed as a code owner for? Thanks!

Code owner commands

Code owners of govee_light_local can trigger bot actions by commenting:

  • @home-assistant close Closes the pull request.
  • @home-assistant rename Awesome new title Renames the pull request.
  • @home-assistant reopen Reopen the pull request.
  • @home-assistant unassign govee_light_local Removes the current integration label and assignees on the pull request, add the integration domain after the command.
  • @home-assistant add-label needs-more-information Add a label (needs-more-information, problem in dependency, problem in custom component) to the pull request.
  • @home-assistant remove-label needs-more-information Remove a label (needs-more-information, problem in dependency, problem in custom component) on the pull request.

@epenet epenet changed the title Add typing helpers for Mock and MagicMock Add MockOf and MockConstructorOf typing helpers Jun 28, 2024
@epenet epenet changed the title Add MockOf and MockConstructorOf typing helpers Add MockOf typing helpers Jun 28, 2024
@epenet epenet marked this pull request as ready for review June 28, 2024 14:52
@epenet epenet changed the title Add MockOf typing helpers Add MockOf typing helper Jun 28, 2024
Copy link
Member

@cdce8p cdce8p left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we should add that. As you point out yourself

It is completely pointless from a type-checking perspective (ie. mypy/pylance)

That also means it isn't validated at any point. We'd have to know to update the type annotation if the patch location or the mock object changes.

Yes, better typing for mocks is a valid issue but that's probably better solved at the Python typing level instead. I'd encourage you to look for / create a new discussion about it over at https://discuss.python.org/c/typing/32

@home-assistant
Copy link

home-assistant bot commented Jul 1, 2024

Please take a look at the requested changes, and use the Ready for review button when you are done, thanks 👍

Learn more about our pull request process.

@home-assistant home-assistant bot marked this pull request as draft July 1, 2024 12:46
@epenet
Copy link
Contributor Author

epenet commented Jul 1, 2024

Interestingly, mypy is quite happy with the composite type MockOfApiClient.
Pylance treats it as Mock, but mypy does recognise that get_devices returns a list of strings.
Now if we could get mypy and pylance to recognise the Generic version that would be great.

"""Test MockOf for mypy."""

from typing import Generic, TypeVar
from unittest.mock import Mock

_T = TypeVar("_T")


class MockOf(Mock, Generic[_T]):
    """Add ability to set underlying type for Mock."""


class ApiClient:
    def get_devices(self) -> list[str]:
        return []


class MockOfApiClient(Mock, ApiClient):
    """Mock of ApiClient."""


mock_client = Mock(spec=ApiClient)
reveal_type(mock_client)
# Revealed type is "unittest.mock.Mock"
reveal_type(mock_client.get_devices)
# Revealed type is "Any"

mock_typed_client: MockOfApiClient = mock_client
reveal_type(mock_typed_client)
# Revealed type is "test_mypy.MockOfApiClient"
reveal_type(mock_typed_client.get_devices)
# Revealed type is "def () -> builtins.list[builtins.str]"

mock_generic_typed_client: MockOf[ApiClient] = mock_client
reveal_type(mock_generic_typed_client)
# Revealed type is test_mypy.MockOf[test_mypy.ApiClient] "
reveal_type(mock_generic_typed_client.get_devices)
# Revealed type is "Any"

Copy link

There hasn't been any activity on this pull request recently. This pull request has been automatically marked as stale because of that and will be closed if no further activity occurs within 7 days.
If you are the author of this PR, please leave a comment if you want to keep it open. Also, please rebase your PR onto the latest dev branch to ensure that it's up to date with the latest changes.
Thank you for your contribution!

@github-actions github-actions bot added the stale label Aug 30, 2024
@github-actions github-actions bot closed this Sep 6, 2024
@epenet epenet deleted the 20240628-1507 branch September 6, 2024 17:45
@github-actions github-actions bot locked and limited conversation to collaborators Sep 7, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants