Skip to content

Commit b8be32a

Browse files
authored
Merge pull request #2157 from python-gitlab/jlvillal/mypy_step_by_step
chore: enable mypy check `warn_return_any`
2 parents 1b7cd31 + 76ec4b4 commit b8be32a

File tree

7 files changed

+47
-13
lines changed

7 files changed

+47
-13
lines changed

gitlab/base.py

+9-3
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
import pprint
2222
import textwrap
2323
from types import ModuleType
24-
from typing import Any, Dict, Iterable, Optional, Type, Union
24+
from typing import Any, Dict, Iterable, Optional, Type, TYPE_CHECKING, Union
2525

2626
import gitlab
2727
from gitlab import types as g_types
@@ -245,14 +245,20 @@ def get_id(self) -> Optional[Union[int, str]]:
245245
"""Returns the id of the resource."""
246246
if self._id_attr is None or not hasattr(self, self._id_attr):
247247
return None
248-
return getattr(self, self._id_attr)
248+
id_val = getattr(self, self._id_attr)
249+
if TYPE_CHECKING:
250+
assert id_val is None or isinstance(id_val, (int, str))
251+
return id_val
249252

250253
@property
251254
def _repr_value(self) -> Optional[str]:
252255
"""Safely returns the human-readable resource name if present."""
253256
if self._repr_attr is None or not hasattr(self, self._repr_attr):
254257
return None
255-
return getattr(self, self._repr_attr)
258+
repr_val = getattr(self, self._repr_attr)
259+
if TYPE_CHECKING:
260+
assert isinstance(repr_val, str)
261+
return repr_val
256262

257263
@property
258264
def encoded_id(self) -> Optional[Union[int, str]]:

gitlab/cli.py

+17-3
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,18 @@
2323
import re
2424
import sys
2525
from types import ModuleType
26-
from typing import Any, Callable, cast, Dict, Optional, Tuple, Type, TypeVar, Union
26+
from typing import (
27+
Any,
28+
Callable,
29+
cast,
30+
Dict,
31+
Optional,
32+
Tuple,
33+
Type,
34+
TYPE_CHECKING,
35+
TypeVar,
36+
Union,
37+
)
2738

2839
from requests.structures import CaseInsensitiveDict
2940

@@ -113,8 +124,11 @@ def gitlab_resource_to_cls(
113124
) -> Type[RESTObject]:
114125
classes = CaseInsensitiveDict(namespace.__dict__)
115126
lowercase_class = gitlab_resource.replace("-", "")
116-
117-
return classes[lowercase_class]
127+
class_type = classes[lowercase_class]
128+
if TYPE_CHECKING:
129+
assert isinstance(class_type, type)
130+
assert issubclass(class_type, RESTObject)
131+
return class_type
118132

119133

120134
def cls_to_gitlab_resource(cls: RESTObject) -> str:

gitlab/client.py

+13-3
Original file line numberDiff line numberDiff line change
@@ -439,6 +439,7 @@ def markdown(
439439
data = self.http_post("/markdown", post_data=post_data, **kwargs)
440440
if TYPE_CHECKING:
441441
assert not isinstance(data, requests.Response)
442+
assert isinstance(data["html"], str)
442443
return data["html"]
443444

444445
@gitlab.exceptions.on_http_error(gitlab.exceptions.GitlabLicenseError)
@@ -808,7 +809,10 @@ def http_get(
808809
and not raw
809810
):
810811
try:
811-
return result.json()
812+
json_result = result.json()
813+
if TYPE_CHECKING:
814+
assert isinstance(json_result, dict)
815+
return json_result
812816
except Exception as e:
813817
raise gitlab.exceptions.GitlabParsingError(
814818
error_message="Failed to parse the server message"
@@ -989,7 +993,10 @@ def http_post(
989993
)
990994
try:
991995
if result.headers.get("Content-Type", None) == "application/json":
992-
return result.json()
996+
json_result = result.json()
997+
if TYPE_CHECKING:
998+
assert isinstance(json_result, dict)
999+
return json_result
9931000
except Exception as e:
9941001
raise gitlab.exceptions.GitlabParsingError(
9951002
error_message="Failed to parse the server message"
@@ -1037,7 +1044,10 @@ def http_put(
10371044
**kwargs,
10381045
)
10391046
try:
1040-
return result.json()
1047+
json_result = result.json()
1048+
if TYPE_CHECKING:
1049+
assert isinstance(json_result, dict)
1050+
return json_result
10411051
except Exception as e:
10421052
raise gitlab.exceptions.GitlabParsingError(
10431053
error_message="Failed to parse the server message"

gitlab/mixins.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -755,7 +755,10 @@ def time_stats(self, **kwargs: Any) -> Dict[str, Any]:
755755
# Use the existing time_stats attribute if it exist, otherwise make an
756756
# API call
757757
if "time_stats" in self.attributes:
758-
return self.attributes["time_stats"]
758+
time_stats = self.attributes["time_stats"]
759+
if TYPE_CHECKING:
760+
assert isinstance(time_stats, dict)
761+
return time_stats
759762

760763
path = f"{self.manager.path}/{self.encoded_id}/time_stats"
761764
result = self.manager.gitlab.http_get(path, **kwargs)

pyproject.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,14 @@ disallow_untyped_defs = true
1616
no_implicit_reexport = true
1717
strict_equality = true
1818
warn_redundant_casts = true
19+
warn_return_any = true
1920
warn_unused_configs = true
2021
warn_unused_ignores = true
2122

2223
# The following need to have changes made to be able to enable them:
2324
# disallow_any_generics = true
2425
# disallow_untyped_calls = true
2526
# no_implicit_optional = true
26-
# warn_return_any = true
2727

2828
[[tool.mypy.overrides]] # Overrides for currently untyped modules
2929
module = [

tests/unit/objects/test_projects.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -431,7 +431,7 @@ def resp_start_housekeeping():
431431
rsps.add(
432432
method=responses.POST,
433433
url="http://localhost/api/v4/projects/1/housekeeping",
434-
json="0ee4c430667fb7be8461f310",
434+
json={},
435435
content_type="application/json",
436436
status=201,
437437
)

tests/unit/test_cli.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424

2525
import pytest
2626

27+
import gitlab.base
2728
from gitlab import cli
2829
from gitlab.exceptions import GitlabError
2930

@@ -43,7 +44,7 @@ def test_gitlab_resource_to_cls(gitlab_resource, expected_class):
4344
def _namespace():
4445
pass
4546

46-
ExpectedClass = type(expected_class, (), {})
47+
ExpectedClass = type(expected_class, (gitlab.base.RESTObject,), {})
4748
_namespace.__dict__[expected_class] = ExpectedClass
4849

4950
assert cli.gitlab_resource_to_cls(gitlab_resource, _namespace) == ExpectedClass

0 commit comments

Comments
 (0)