Skip to content

Commit 7beaad8

Browse files
committed
Maintenance: Update to mypy v1.13.0
This patch intends to contribute to unlock upgrading to Python 3.11.
1 parent 0f4303f commit 7beaad8

19 files changed

+83
-45
lines changed

.pre-commit-config.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ repos:
1818
hooks:
1919
- id: isort
2020
- repo: https://github.com/pre-commit/mirrors-mypy
21-
rev: "v0.770"
21+
rev: "v1.13.0"
2222
hooks:
2323
- id: mypy
2424
- repo: https://github.com/adrienverge/yamllint

crate/operator/config.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -192,8 +192,6 @@ def load(self):
192192
f"Invalid {self._prefix}BOOTSTRAP_TIMEOUT="
193193
f"'{bootstrap_timeout}'. Needs to be a positive integer or 0."
194194
)
195-
if self.BOOTSTRAP_TIMEOUT == 0:
196-
self.BOOTSTRAP_TIMEOUT = None
197195

198196
bootstrap_delay = self.env(
199197
"BOOTSTRAP_RETRY_DELAY", default=str(self.BOOTSTRAP_RETRY_DELAY)

crate/operator/cratedb.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ async def create_user(
7777
name: str,
7878
username: str,
7979
password: str,
80-
privileges: List[str] = None,
80+
privileges: Optional[List[str]] = None,
8181
) -> None:
8282
"""
8383
Create user ``username`` and grant it given privileges.

crate/operator/handlers/handle_create_cratedb.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,10 @@ async def create_cratedb(
5656
logger: logging.Logger,
5757
):
5858
context = status.get(CLUSTER_CREATE_ID)
59+
if context is None:
60+
raise RuntimeError(
61+
f"Operation context is empty or unknown: {CLUSTER_CREATE_ID}"
62+
)
5963
hash = hashlib.md5(str(spec).encode("utf-8")).hexdigest()
6064
name = meta["name"]
6165
base_labels = {

crate/operator/operations.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1059,7 +1059,7 @@ async def _ensure_no_backup_cronjobs_running(
10591059
):
10601060
await kopf.execute(
10611061
fns={
1062-
"notify_backup_running": subhandler_partial(
1062+
"notify_backup_running": subhandler_partial( # type: ignore[dict-item] # noqa: E501
10631063
self._notify_backup_running, logger
10641064
)
10651065
}

crate/operator/prometheus.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919
# with Crate these terms will supersede the license and you may use the
2020
# software solely pursuant to the terms of the relevant commercial agreement.
2121

22+
# mypy: disable-error-code="arg-type, attr-defined, list-item, operator"
23+
2224
import enum
2325
import time
2426
from datetime import datetime

crate/operator/scale.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -515,8 +515,8 @@ async def scale_cluster(
515515
total_number_of_nodes = (
516516
total_number_of_nodes + new_replicas - old_replicas
517517
)
518-
index, *_ = field_path
519-
index = int(index)
518+
index_raw, *_ = field_path
519+
index = int(index_raw)
520520
node_spec = spec["nodes"]["data"][index]
521521
node_name = node_spec["name"]
522522
sts_name = f"crate-data-{node_name}-{name}"
@@ -559,8 +559,8 @@ async def scale_cluster(
559559
total_number_of_nodes = (
560560
total_number_of_nodes + new_replicas - old_replicas
561561
)
562-
index, *_ = field_path
563-
index = int(index)
562+
index_raw, *_ = field_path
563+
index = int(index_raw)
564564
node_spec = spec["nodes"]["data"][index]
565565
node_name = node_spec["name"]
566566
sts_name = f"crate-data-{node_name}-{name}"

crate/operator/utils/kubeapi.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,8 @@ async def call_kubeapi(
4444
*,
4545
continue_on_absence=False,
4646
continue_on_conflict=False,
47-
namespace: str = None,
48-
body: K8sModel = None,
47+
namespace: Optional[str] = None,
48+
body: Optional[K8sModel] = None,
4949
**kwargs,
5050
) -> Optional[Awaitable[K8sModel]]:
5151
"""

crate/operator/utils/version.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121

2222
import re
2323
from distutils.version import Version
24-
from typing import Optional, Tuple
24+
from typing import Optional, Tuple, Union, cast
2525

2626

2727
class CrateVersion(Version):
@@ -63,9 +63,9 @@ class CrateVersion(Version):
6363

6464
version: Optional[Tuple[int, int, int]]
6565

66-
major: int
67-
minor: int
68-
hotfix: int
66+
major: Union[int, None]
67+
minor: Union[int, None]
68+
hotfix: Union[int, None]
6969

7070
stable: bool
7171
snapshot: bool
@@ -130,7 +130,7 @@ def __repr__(self):
130130

131131
def __str__(self):
132132
if self.stable:
133-
return ".".join(map(str, self.version))
133+
return ".".join(map(str, cast(list, self.version)))
134134

135135
if self.nightly:
136136
vstring = "nightly"
@@ -250,14 +250,15 @@ def _parse_regular(self, vstring):
250250
)
251251

252252
if hotfix:
253-
self.version = tuple(map(int, [major, minor, hotfix]))
253+
self.version = tuple(map(int, [major, minor, hotfix])) # type: ignore[assignment] # noqa: E501
254254
else:
255-
self.version = tuple(map(int, [major, minor])) + (0,)
255+
self.version = tuple(map(int, [major, minor])) + (0,) # type: ignore[assignment] # noqa: E501
256256

257257
self.stable = False if snapshot else True
258258
self.nightly = False
259259
self.snapshot = True if snapshot else False
260-
self.major, self.minor, self.hotfix = self.version
260+
if self.version is not None:
261+
self.major, self.minor, self.hotfix = self.version
261262

262263
def _parse_nightly(self, vstring):
263264
match = self.nightly_version_re.match(vstring)
@@ -270,7 +271,7 @@ def _parse_nightly(self, vstring):
270271

271272
if has_version:
272273
self.major, self.minor, self.hotfix = int(major), int(minor), int(hotfix)
273-
self.version = tuple(map(int, [self.major, self.minor, self.hotfix]))
274+
self.version = tuple(map(int, [self.major, self.minor, self.hotfix])) # type: ignore[assignment] # noqa: E501
274275
else:
275276
self.major, self.minor, self.hotfix = None, None, None
276277
self.version = None

docs/source/crate_operator_ext.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ def run_apidoc(_):
4747

4848
def missing_reference(
4949
app: Sphinx, env: BuildEnvironment, node: pending_xref, contnode: Element
50-
) -> Element:
50+
) -> None:
5151
"""
5252
Remove or resolve references to third party packages.
5353

pyproject.toml

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,21 @@ target-version = ['py38']
55
requires = ["setuptools>=58", "wheel", "setuptools_scm>=6.2"]
66

77
[tool.setuptools_scm]
8+
9+
[tool.mypy]
10+
packages = ["crate", "tests"]
11+
check_untyped_defs = true
12+
explicit_package_bases = true
13+
ignore_missing_imports = true
14+
implicit_optional = false
15+
install_types = true
16+
namespace_packages = true
17+
non_interactive = true
18+
show_error_codes = true
19+
strict_equality = true
20+
warn_unused_ignores = false
21+
warn_redundant_casts = false
22+
23+
[[tool.mypy.overrides]]
24+
module = "crate.operator.main"
25+
ignore_errors = true

setup.cfg

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,3 @@
1-
[bdist_wheel]
2-
universal = 1
3-
4-
[mypy]
5-
ignore_missing_imports = true
6-
namespace_packages = true
7-
81
[flake8]
92
max-line-length = 88
103
ignore = E203 W503

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ def read(path: str) -> str:
7676
"black==22.3.0",
7777
"flake8==3.8.4",
7878
"isort==5.12.0",
79-
"mypy==0.770",
79+
"mypy==1.13.0",
8080
],
8181
},
8282
python_requires=">=3.8",

tests/conftest.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@
1919
# with Crate these terms will supersede the license and you may use the
2020
# software solely pursuant to the terms of the relevant commercial agreement.
2121

22+
# Sphinx configuration file does not need type checking.
23+
# type: ignore
24+
2225
import asyncio
2326
import os
2427
import pathlib

tests/test_create.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,8 @@ def test_testing_false(self, faker):
123123
with mock.patch("crate.operator.create.config.TESTING", False):
124124
affinity = get_statefulset_affinity(name, logging.getLogger(__name__), {})
125125

126+
assert affinity, "`affinity` is None or empty"
127+
126128
apa = affinity.pod_anti_affinity
127129
terms = apa.required_during_scheduling_ignored_during_execution[0]
128130
expressions = terms.label_selector.match_expressions
@@ -168,6 +170,8 @@ def test_dedicated_resources_affinity(self, node_spec, faker):
168170
name, logging.getLogger(__name__), node_spec
169171
)
170172

173+
assert affinity, "`affinity` is None or empty"
174+
171175
apa = affinity.pod_anti_affinity
172176
terms = apa.required_during_scheduling_ignored_during_execution[0]
173177
expressions = terms.label_selector.match_expressions
@@ -202,6 +206,8 @@ def test_shared_resources_affinity(self, node_spec, faker):
202206
name, logging.getLogger(__name__), node_spec
203207
)
204208

209+
assert affinity, "`affinity` is None or empty"
210+
205211
na = affinity.node_affinity
206212
selector = na.required_during_scheduling_ignored_during_execution
207213
terms = selector.node_selector_terms[0]
@@ -223,6 +229,8 @@ def test_cloud_provider(self, provider, faker):
223229
):
224230
topospread = get_topology_spread(name, logging.getLogger(__name__))
225231

232+
assert topospread, "`topospread` is None or empty"
233+
226234
terms = topospread[0]
227235
expressions = terms.label_selector.match_expressions
228236
assert [e.to_dict() for e in expressions] == [
@@ -274,6 +282,8 @@ def test_dedicated_resources_tolerations(self, node_spec, faker):
274282
with mock.patch("crate.operator.create.config.TESTING", False):
275283
tolerations = get_tolerations(name, logging.getLogger(__name__), node_spec)
276284

285+
assert tolerations, "`tolerations` is None or empty"
286+
277287
assert len(tolerations) == 1
278288
assert tolerations[0].to_dict() == {
279289
"effect": "NoSchedule",
@@ -302,6 +312,8 @@ def test_shared_resources_tolerations(self, node_spec, faker):
302312
with mock.patch("crate.operator.create.config.TESTING", False):
303313
tolerations = get_tolerations(name, logging.getLogger(__name__), node_spec)
304314

315+
assert tolerations, "`tolerations` is None or empty"
316+
305317
toleration = tolerations[0]
306318
expected = {
307319
"key": "cratedb",
@@ -1009,7 +1021,7 @@ def test_get_data_service(self, provider, dns, faker):
10091021
http = faker.port_number()
10101022
psql = faker.port_number()
10111023
with mock.patch("crate.operator.create.config.CLOUD_PROVIDER", provider):
1012-
service = get_data_service(None, name, None, http, psql, dns)
1024+
service = get_data_service(None, name, {}, http, psql, dns)
10131025
annotation_keys = service.metadata.annotations.keys()
10141026
if provider == "aws":
10151027
assert (
@@ -1442,7 +1454,7 @@ async def test_preserve_unknown_object_keys(
14421454

14431455

14441456
def test_sql_exporter_config():
1445-
result = get_sql_exporter_config(None, "test-name", None)
1457+
result = get_sql_exporter_config(None, "test-name", {})
14461458
assert result.metadata.name == "crate-sql-exporter-test-name"
14471459

14481460
_, _, filenames = next(walk("crate/operator/data"))

tests/test_metrics.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919
# with Crate these terms will supersede the license and you may use the
2020
# software solely pursuant to the terms of the relevant commercial agreement.
2121

22+
# mypy: disable-error-code="attr-defined, arg-type, union-attr"
23+
2224
import logging
2325
import time
2426

tests/test_update_allowed_cidrs.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,8 @@ async def _are_source_ranges_updated(core, name, namespace, cidr_list):
193193
ingress = await read_grand_central_ingress(namespace=namespace, name=name)
194194
actual = cidr_list if len(cidr_list) > 0 else None
195195

196+
assert ingress, "`ingress` is None"
197+
196198
return (
197199
service.spec.load_balancer_source_ranges == actual
198200
and ingress.metadata.annotations.get(

tests/test_webhooks.py

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,8 @@ def test_payload_serialization_scale():
4848
namespace="some-namespace",
4949
cluster="some-cluster",
5050
scale_data=WebhookScalePayload(
51-
old_data_replicas={"a": 1},
52-
new_data_replicas={"a": 2},
51+
old_data_replicas=[{"name": "a", "replicas": "1"}],
52+
new_data_replicas=[{"name": "a", "replicas": "2"}],
5353
old_master_replicas=3,
5454
new_master_replicas=4,
5555
),
@@ -68,8 +68,8 @@ def test_payload_serialization_scale():
6868
"namespace": "some-namespace",
6969
"cluster": "some-cluster",
7070
"scale_data": {
71-
"old_data_replicas": {"a": 1},
72-
"new_data_replicas": {"a": 2},
71+
"old_data_replicas": [{"name": "a", "replicas": "1"}],
72+
"new_data_replicas": [{"name": "a", "replicas": "2"}],
7373
"old_master_replicas": 3,
7474
"new_master_replicas": 4,
7575
},
@@ -136,8 +136,11 @@ async def test_configure():
136136
assert c._url == "http://localhost:1234/some/path"
137137
assert c._session._default_headers["Content-Type"] == "application/json"
138138
assert c._session._default_headers["User-Agent"].startswith("cratedb-operator/")
139-
assert c._session._default_auth.login == "itsme"
140-
assert c._session._default_auth.password == "secr3t password"
139+
assert c._session._default_auth and c._session._default_auth.login == "itsme"
140+
assert (
141+
c._session._default_auth
142+
and c._session._default_auth.password == "secr3t password"
143+
)
141144

142145

143146
@pytest.mark.asyncio
@@ -173,8 +176,8 @@ async def test_send_scale_notification(self):
173176
"my-cluster",
174177
WebhookEvent.SCALE,
175178
WebhookScalePayload(
176-
old_data_replicas={"a": 1},
177-
new_data_replicas={"a": 2},
179+
old_data_replicas=[{"name": "a", "replicas": "1"}],
180+
new_data_replicas=[{"name": "a", "replicas": "2"}],
178181
old_master_replicas=3,
179182
new_master_replicas=4,
180183
),
@@ -192,8 +195,8 @@ async def test_send_scale_notification(self):
192195
"namespace": "my-namespace",
193196
"cluster": "my-cluster",
194197
"scale_data": {
195-
"old_data_replicas": {"a": 1},
196-
"new_data_replicas": {"a": 2},
198+
"old_data_replicas": [{"name": "a", "replicas": "1"}],
199+
"new_data_replicas": [{"name": "a", "replicas": "2"}],
197200
"old_master_replicas": 3,
198201
"new_master_replicas": 4,
199202
},

tests/utils.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
import logging
2424
import os
2525
from functools import reduce
26-
from typing import Any, Callable, List, Mapping, Optional, Set, Tuple, Union
26+
from typing import Any, Callable, Dict, List, Mapping, Optional, Set, Tuple
2727
from unittest import mock
2828

2929
import psycopg2
@@ -439,7 +439,7 @@ async def cluster_routing_allocation_enable_equals(
439439

440440

441441
async def was_notification_sent(
442-
mock_send_notification: mock.AsyncMock, call: mock.call
442+
mock_send_notification: mock.AsyncMock, call: mock._Call
443443
):
444444
if mock_send_notification.call_count == 0:
445445
return False
@@ -459,7 +459,7 @@ async def is_cronjob_schedule_matching(
459459

460460

461461
async def mocked_coro_func_called_with(
462-
mocked_coro_func: mock.AsyncMock, call: mock.call
462+
mocked_coro_func: mock.AsyncMock, call: mock._Call
463463
) -> bool:
464464
if mocked_coro_func.call_count == 0:
465465
return False
@@ -474,7 +474,7 @@ async def mocked_coro_func_called_with(
474474
async def cluster_setting_equals(
475475
conn_factory: Callable[[], Connection],
476476
setting: str,
477-
expected_value: Union[str, int],
477+
expected_value: Dict[Any, Any],
478478
) -> bool:
479479
try:
480480
async with conn_factory() as conn:

0 commit comments

Comments
 (0)