Skip to content

Commit 7fbb8f8

Browse files
committed
fix(compat): add type annotations and ignores to _compat template and goldens for mypy compliance, format test_requests.py
1 parent fd17594 commit 7fbb8f8

10 files changed

Lines changed: 256 additions & 265 deletions

File tree

packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2

Lines changed: 28 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import google.protobuf.message
1414

1515

1616
try:
17-
from google.api_core.universe import (
17+
from google.api_core.universe import ( # type: ignore
1818
get_default_mtls_endpoint,
1919
get_api_endpoint,
2020
get_universe_domain,
@@ -47,16 +47,17 @@ except ImportError: # pragma: NO COVER
4747

4848
return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
4949

50-
def get_api_endpoint(
50+
def get_api_endpoint( # type: ignore[misc]
5151
api_override: Optional[str],
5252
client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]],
5353
universe_domain: str,
5454
use_mtls_endpoint: str,
5555
default_universe: str,
5656
default_mtls_endpoint: Optional[str],
5757
default_endpoint_template: str,
58-
) -> Optional[str]:
58+
) -> str:
5959
"""Return the API endpoint used by the client."""
60+
api_endpoint: Optional[str] = None
6061
if api_override is not None:
6162
api_endpoint = api_override
6263
elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source):
@@ -67,26 +68,24 @@ except ImportError: # pragma: NO COVER
6768
api_endpoint = default_mtls_endpoint
6869
else:
6970
api_endpoint = default_endpoint_template.format(UNIVERSE_DOMAIN=universe_domain)
70-
return api_endpoint
71+
return api_endpoint # type: ignore[return-value]
7172

72-
def get_universe_domain(
73-
client_universe_domain: Optional[str],
74-
universe_domain_env: Optional[str],
75-
default_universe: str,
73+
def get_universe_domain( # type: ignore[misc]
74+
*potential_universes: Optional[str],
75+
default_universe: str = "googleapis.com",
7676
) -> str:
7777
"""Return the universe domain used by the client."""
78-
universe_domain = default_universe
79-
if client_universe_domain is not None:
80-
universe_domain = client_universe_domain
81-
elif universe_domain_env is not None:
82-
universe_domain = universe_domain_env
83-
if len(universe_domain.strip()) == 0:
84-
raise ValueError("Universe Domain cannot be an empty string.")
85-
return universe_domain
78+
resolved = next(
79+
(x.strip() for x in potential_universes if x is not None),
80+
default_universe,
81+
)
82+
if not resolved:
83+
raise ValueError("Universe Domain cannot be an empty string.")
84+
return resolved
8685

8786

8887
try:
89-
from google.api_core.gapic_v1.config import (
88+
from google.api_core.gapic_v1.config import ( # type: ignore
9089
use_client_cert_effective,
9190
get_client_cert_source,
9291
read_environment_variables,
@@ -147,7 +146,7 @@ try:
147146
except ImportError: # pragma: NO COVER
148147
# TODO(https://github.com/googleapis/google-cloud-python/issues/17813): Request ID setup helper was introduced in google-api-core 2.26.0.
149148
# Remove this fallback definition when google-api-core >= 2.26.0 becomes the minimum required version in generated client setup dependencies.
150-
def setup_request_id(request, field_name: str, is_proto3_optional: bool):
149+
def setup_request_id(request: Any, field_name: str, is_proto3_optional: bool) -> None:
151150
"""Populate a UUID4 field in the request if it is not already set.
152151

153152
Args:
@@ -190,7 +189,7 @@ except ImportError: # pragma: NO COVER
190189

191190

192191
try:
193-
from google.api_core.rest_helpers import (
192+
from google.api_core.rest_helpers import ( # type: ignore
194193
flatten_query_params,
195194
transcode_request,
196195
)
@@ -199,12 +198,12 @@ except ImportError: # pragma: NO COVER
199198
from google.protobuf import json_format # type: ignore
200199
from google.api_core import path_template # type: ignore
201200

202-
def flatten_query_params(obj, strict=False):
201+
def flatten_query_params(obj: Any, strict: bool = False) -> List[Tuple[str, Any]]: # type: ignore[misc]
203202
if obj is not None and not isinstance(obj, dict):
204203
raise TypeError("flatten_query_params must be called with dict object")
205204
return _flatten(obj, key_path=[], strict=strict)
206205

207-
def _flatten(obj, key_path, strict=False):
206+
def _flatten(obj: Any, key_path: List[str], strict: bool = False) -> List[Tuple[str, Any]]:
208207
if obj is None:
209208
return []
210209
if isinstance(obj, dict):
@@ -213,40 +212,40 @@ except ImportError: # pragma: NO COVER
213212
return _flatten_list(obj, key_path=key_path, strict=strict)
214213
return _flatten_value(obj, key_path=key_path, strict=strict)
215214

216-
def _is_primitive_value(obj):
215+
def _is_primitive_value(obj: Any) -> bool:
217216
if obj is None:
218217
return False
219218
if isinstance(obj, (list, dict)):
220219
raise ValueError("query params may not contain repeated dicts or lists")
221220
return True
222221

223-
def _flatten_value(obj, key_path, strict=False):
222+
def _flatten_value(obj: Any, key_path: List[str], strict: bool = False) -> List[Tuple[str, Any]]:
224223
return [(".".join(key_path), _canonicalize(obj, strict=strict))]
225224

226-
def _flatten_dict(obj, key_path, strict=False):
225+
def _flatten_dict(obj: Dict[str, Any], key_path: List[str], strict: bool = False) -> List[Tuple[str, Any]]:
227226
items = (
228227
_flatten(value, key_path=key_path + [key], strict=strict)
229228
for key, value in obj.items()
230229
)
231-
return functools.reduce(operator.concat, items, [])
230+
return functools.reduce(operator.concat, items, []) # type: ignore[arg-type]
232231

233-
def _flatten_list(elems, key_path, strict=False):
232+
def _flatten_list(elems: List[Any], key_path: List[str], strict: bool = False) -> List[Tuple[str, Any]]:
234233
items = (
235234
_flatten_value(elem, key_path=key_path, strict=strict)
236235
for elem in elems
237236
if _is_primitive_value(elem)
238237
)
239-
return functools.reduce(operator.concat, items, [])
238+
return functools.reduce(operator.concat, items, []) # type: ignore[arg-type]
240239

241-
def _canonicalize(obj, strict=False):
240+
def _canonicalize(obj: Any, strict: bool = False) -> Any:
242241
if strict:
243242
value = str(obj)
244243
if isinstance(obj, bool):
245244
value = value.lower()
246245
return value
247246
return obj
248247

249-
def transcode_request(
248+
def transcode_request( # type: ignore[misc]
250249
http_options: List[Dict[str, str]],
251250
request: Any,
252251
required_fields_default_values: Optional[Dict[str, Any]] = None,

packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/_compat.py

Lines changed: 28 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727

2828

2929
try:
30-
from google.api_core.universe import (
30+
from google.api_core.universe import ( # type: ignore
3131
get_default_mtls_endpoint,
3232
get_api_endpoint,
3333
get_universe_domain,
@@ -60,16 +60,17 @@ def get_default_mtls_endpoint(api_endpoint: Optional[str]) -> Optional[str]:
6060

6161
return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
6262

63-
def get_api_endpoint(
63+
def get_api_endpoint( # type: ignore[misc]
6464
api_override: Optional[str],
6565
client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]],
6666
universe_domain: str,
6767
use_mtls_endpoint: str,
6868
default_universe: str,
6969
default_mtls_endpoint: Optional[str],
7070
default_endpoint_template: str,
71-
) -> Optional[str]:
71+
) -> str:
7272
"""Return the API endpoint used by the client."""
73+
api_endpoint: Optional[str] = None
7374
if api_override is not None:
7475
api_endpoint = api_override
7576
elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source):
@@ -80,26 +81,24 @@ def get_api_endpoint(
8081
api_endpoint = default_mtls_endpoint
8182
else:
8283
api_endpoint = default_endpoint_template.format(UNIVERSE_DOMAIN=universe_domain)
83-
return api_endpoint
84+
return api_endpoint # type: ignore[return-value]
8485

85-
def get_universe_domain(
86-
client_universe_domain: Optional[str],
87-
universe_domain_env: Optional[str],
88-
default_universe: str,
86+
def get_universe_domain( # type: ignore[misc]
87+
*potential_universes: Optional[str],
88+
default_universe: str = "googleapis.com",
8989
) -> str:
9090
"""Return the universe domain used by the client."""
91-
universe_domain = default_universe
92-
if client_universe_domain is not None:
93-
universe_domain = client_universe_domain
94-
elif universe_domain_env is not None:
95-
universe_domain = universe_domain_env
96-
if len(universe_domain.strip()) == 0:
97-
raise ValueError("Universe Domain cannot be an empty string.")
98-
return universe_domain
91+
resolved = next(
92+
(x.strip() for x in potential_universes if x is not None),
93+
default_universe,
94+
)
95+
if not resolved:
96+
raise ValueError("Universe Domain cannot be an empty string.")
97+
return resolved
9998

10099

101100
try:
102-
from google.api_core.gapic_v1.config import (
101+
from google.api_core.gapic_v1.config import ( # type: ignore
103102
use_client_cert_effective,
104103
get_client_cert_source,
105104
read_environment_variables,
@@ -160,7 +159,7 @@ def read_environment_variables() -> Tuple[bool, str, Optional[str]]:
160159
except ImportError: # pragma: NO COVER
161160
# TODO(https://github.com/googleapis/google-cloud-python/issues/17813): Request ID setup helper was introduced in google-api-core 2.26.0.
162161
# Remove this fallback definition when google-api-core >= 2.26.0 becomes the minimum required version in generated client setup dependencies.
163-
def setup_request_id(request, field_name: str, is_proto3_optional: bool):
162+
def setup_request_id(request: Any, field_name: str, is_proto3_optional: bool) -> None:
164163
"""Populate a UUID4 field in the request if it is not already set.
165164
166165
Args:
@@ -203,7 +202,7 @@ def setup_request_id(request, field_name: str, is_proto3_optional: bool):
203202

204203

205204
try:
206-
from google.api_core.rest_helpers import (
205+
from google.api_core.rest_helpers import ( # type: ignore
207206
flatten_query_params,
208207
transcode_request,
209208
)
@@ -212,12 +211,12 @@ def setup_request_id(request, field_name: str, is_proto3_optional: bool):
212211
from google.protobuf import json_format # type: ignore
213212
from google.api_core import path_template # type: ignore
214213

215-
def flatten_query_params(obj, strict=False):
214+
def flatten_query_params(obj: Any, strict: bool = False) -> List[Tuple[str, Any]]: # type: ignore[misc]
216215
if obj is not None and not isinstance(obj, dict):
217216
raise TypeError("flatten_query_params must be called with dict object")
218217
return _flatten(obj, key_path=[], strict=strict)
219218

220-
def _flatten(obj, key_path, strict=False):
219+
def _flatten(obj: Any, key_path: List[str], strict: bool = False) -> List[Tuple[str, Any]]:
221220
if obj is None:
222221
return []
223222
if isinstance(obj, dict):
@@ -226,40 +225,40 @@ def _flatten(obj, key_path, strict=False):
226225
return _flatten_list(obj, key_path=key_path, strict=strict)
227226
return _flatten_value(obj, key_path=key_path, strict=strict)
228227

229-
def _is_primitive_value(obj):
228+
def _is_primitive_value(obj: Any) -> bool:
230229
if obj is None:
231230
return False
232231
if isinstance(obj, (list, dict)):
233232
raise ValueError("query params may not contain repeated dicts or lists")
234233
return True
235234

236-
def _flatten_value(obj, key_path, strict=False):
235+
def _flatten_value(obj: Any, key_path: List[str], strict: bool = False) -> List[Tuple[str, Any]]:
237236
return [(".".join(key_path), _canonicalize(obj, strict=strict))]
238237

239-
def _flatten_dict(obj, key_path, strict=False):
238+
def _flatten_dict(obj: Dict[str, Any], key_path: List[str], strict: bool = False) -> List[Tuple[str, Any]]:
240239
items = (
241240
_flatten(value, key_path=key_path + [key], strict=strict)
242241
for key, value in obj.items()
243242
)
244-
return functools.reduce(operator.concat, items, [])
243+
return functools.reduce(operator.concat, items, []) # type: ignore[arg-type]
245244

246-
def _flatten_list(elems, key_path, strict=False):
245+
def _flatten_list(elems: List[Any], key_path: List[str], strict: bool = False) -> List[Tuple[str, Any]]:
247246
items = (
248247
_flatten_value(elem, key_path=key_path, strict=strict)
249248
for elem in elems
250249
if _is_primitive_value(elem)
251250
)
252-
return functools.reduce(operator.concat, items, [])
251+
return functools.reduce(operator.concat, items, []) # type: ignore[arg-type]
253252

254-
def _canonicalize(obj, strict=False):
253+
def _canonicalize(obj: Any, strict: bool = False) -> Any:
255254
if strict:
256255
value = str(obj)
257256
if isinstance(obj, bool):
258257
value = value.lower()
259258
return value
260259
return obj
261260

262-
def transcode_request(
261+
def transcode_request( # type: ignore[misc]
263262
http_options: List[Dict[str, str]],
264263
request: Any,
265264
required_fields_default_values: Optional[Dict[str, Any]] = None,

0 commit comments

Comments
 (0)