Skip to content

Commit

Permalink
#85 Use get_type_hints and add gitlens and gitgraph to dev container (
Browse files Browse the repository at this point in the history
#86)

* Leverage get_type_hints instead of string check logic
* Add .mypy_cache and .pytest_cache to git ignore
* Add gitlens and git-graph to dev container
  • Loading branch information
JamesHutchison authored May 14, 2023
1 parent ea1999e commit aa1587b
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 17 deletions.
4 changes: 3 additions & 1 deletion .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@
"extensions": [
"ms-python.python",
"tamasfe.even-better-toml",
"stkb.rewrap"
"stkb.rewrap",
"mhutchie.git-graph",
"eamodio.gitlens"
],
"settings": {
"python.defaultInterpreterPath": "/workspaces/python/.venv/python"
Expand Down
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@
*.pyc
.dmypy.json
dist
.mypy_cache
.pytest_cache
30 changes: 14 additions & 16 deletions megamock/megamocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,16 @@
from collections import defaultdict
from dataclasses import dataclass, field
from inspect import isawaitable, isclass, iscoroutinefunction
from typing import Any, Callable, Generic, Literal, TypeVar, cast, overload
from typing import (
Any,
Callable,
Generic,
Literal,
TypeVar,
cast,
get_type_hints,
overload,
)
from unittest import mock
from unittest.mock import create_autospec

Expand Down Expand Up @@ -398,24 +407,13 @@ def _megamock_set_attr(self, key, value) -> None:
def _set_attr_annotations_check(self, key: str, value: Any) -> None:
# do not check type if assigning a mock object
# note that MegaMock is a subclass of NonCallableMagicMock
if not isinstance(
value, mock.NonCallableMock | mock.NonCallableMagicMock
):
allowed_values = self.megamock.spec.__annotations__[key]
if not isinstance(value, mock.NonCallableMock | mock.NonCallableMagicMock):
allowed_values = get_type_hints(self.megamock.spec)[key]

def raise_type_error() -> None:
raise TypeError(
f"{value!r} is not an instance of {allowed_values}"
)
raise TypeError(f"{value!r} is not an instance of {allowed_values}")

# handle:
# "from __future__ import annotations" converting type to str
if isinstance(allowed_values, str):
if str(value.__class__.__name__) not in [
x.strip() for x in allowed_values.split("|")
]:
raise_type_error()
elif not isinstance(value, allowed_values):
if not isinstance(value, allowed_values):
raise_type_error()

def _get_spec_from_parents(
Expand Down

0 comments on commit aa1587b

Please sign in to comment.