Skip to content

Commit 3324688

Browse files
committed
refactor userver: use match from Python 3.10 where appropriate
commit_hash:bcdff597c3384f8c2c0227a1018aeb4c8e800095
1 parent a54cbce commit 3324688

File tree

9 files changed

+173
-161
lines changed

9 files changed

+173
-161
lines changed

chaotic-openapi/chaotic_openapi/front/openapi.py

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -212,20 +212,21 @@ class SecurityScheme(base_model.BaseModel):
212212
def model_post_init(self, context: Any, /) -> None:
213213
super().model_post_init(context)
214214

215-
if self.type == SecurityType.apiKey:
216-
if not self.name:
217-
raise ValueError(errors.missing_field_msg('name'))
218-
if not self.in_:
219-
raise ValueError(errors.missing_field_msg('in'))
220-
elif self.type == SecurityType.oauth2:
221-
if not self.flows:
222-
raise ValueError(errors.missing_field_msg('flows'))
223-
elif self.type == SecurityType.http:
224-
if not self.scheme_:
225-
raise ValueError(errors.missing_field_msg('scheme'))
226-
elif self.type == SecurityType.openIdConnect:
227-
if not self.openIdConnectUrl:
228-
raise ValueError(errors.missing_field_msg('openIdConnectUrl'))
215+
match self.type:
216+
case SecurityType.apiKey:
217+
if not self.name:
218+
raise ValueError(errors.missing_field_msg('name'))
219+
if not self.in_:
220+
raise ValueError(errors.missing_field_msg('in'))
221+
case SecurityType.oauth2:
222+
if not self.flows:
223+
raise ValueError(errors.missing_field_msg('flows'))
224+
case SecurityType.http:
225+
if not self.scheme_:
226+
raise ValueError(errors.missing_field_msg('scheme'))
227+
case SecurityType.openIdConnect:
228+
if not self.openIdConnectUrl:
229+
raise ValueError(errors.missing_field_msg('openIdConnectUrl'))
229230

230231

231232
SecuritySchemes: TypeAlias = dict[str, SecurityScheme | Ref]

chaotic-openapi/chaotic_openapi/front/parser.py

Lines changed: 54 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -360,63 +360,68 @@ def _convert_openapi_securuty(
360360
return self._state.service.security[self._locate_ref(security_scheme.ref)]
361361

362362
description = security_scheme.description or ''
363-
if security_scheme.type == openapi.SecurityType.http:
364-
assert security_scheme.scheme_
365-
return model.HttpSecurity(description, security_scheme.scheme_, security_scheme.bearerFormat)
366-
elif security_scheme.type == openapi.SecurityType.apiKey:
367-
assert security_scheme.name
368-
assert security_scheme.in_
369-
security_in = model.SecurityIn(security_scheme.in_.name)
370-
return model.ApiKeySecurity(description, security_scheme.name, security_in)
371-
elif security_scheme.type == openapi.SecurityType.oauth2:
372-
assert security_scheme.flows
373-
flows = self._convert_openapi_flows(security_scheme.flows)
374-
if flows_scopes:
375-
for flow in flows:
376-
flow.scopes = {key: flow.scopes[key] for key in flows_scopes if key in flow.scopes}
377-
return model.OAuthSecurity(description, flows)
378-
elif security_scheme.type == openapi.SecurityType.openIdConnect:
379-
assert security_scheme.openIdConnectUrl
380-
return model.OpenIdConnectSecurity(description, security_scheme.openIdConnectUrl)
381-
else:
382-
assert False
363+
match security_scheme.type:
364+
case openapi.SecurityType.http:
365+
assert security_scheme.scheme_
366+
return model.HttpSecurity(description, security_scheme.scheme_, security_scheme.bearerFormat)
367+
case openapi.SecurityType.apiKey:
368+
assert security_scheme.name
369+
assert security_scheme.in_
370+
security_in = model.SecurityIn(security_scheme.in_.name)
371+
return model.ApiKeySecurity(description, security_scheme.name, security_in)
372+
case openapi.SecurityType.oauth2:
373+
assert security_scheme.flows
374+
flows = self._convert_openapi_flows(security_scheme.flows)
375+
if flows_scopes:
376+
for flow in flows:
377+
flow.scopes = {key: flow.scopes[key] for key in flows_scopes if key in flow.scopes}
378+
return model.OAuthSecurity(description, flows)
379+
case openapi.SecurityType.openIdConnect:
380+
assert security_scheme.openIdConnectUrl
381+
return model.OpenIdConnectSecurity(description, security_scheme.openIdConnectUrl)
382+
case _:
383+
assert False
383384

384385
def _convert_swagger_security(
385386
self,
386387
security_def: swagger.SecurityDef,
387388
flows_scopes: list[str] | None = None, # noqa: COM812
388389
) -> model.Security:
389390
description = security_def.description or ''
390-
if security_def.type == swagger.SecurityType.basic:
391-
return model.Security(description)
392-
elif security_def.type == swagger.SecurityType.apiKey:
393-
assert security_def.name
394-
assert security_def.in_
395-
security_in = model.SecurityIn(security_def.in_.name)
396-
return model.ApiKeySecurity(description, security_def.name, security_in)
397-
elif security_def.type == swagger.SecurityType.oauth2:
398-
flow: model.Flow
399-
if security_def.flow == swagger.OAuthFlow.implicit:
400-
assert security_def.authorizationUrl
401-
flow = model.ImplicitFlow('', security_def.scopes, security_def.authorizationUrl)
402-
elif security_def.flow == swagger.OAuthFlow.password:
403-
assert security_def.tokenUrl
404-
flow = model.PasswordFlow('', security_def.scopes, security_def.tokenUrl)
405-
elif security_def.flow == swagger.OAuthFlow.application:
406-
assert security_def.tokenUrl
407-
flow = model.ClientCredFlow('', security_def.scopes, security_def.tokenUrl)
408-
elif security_def.flow == swagger.OAuthFlow.accessCode:
409-
assert security_def.authorizationUrl
410-
assert security_def.tokenUrl
411-
flow = model.AuthCodeFlow('', security_def.scopes, security_def.authorizationUrl, security_def.tokenUrl)
412-
else:
413-
assert False
391+
match security_def.type:
392+
case swagger.SecurityType.basic:
393+
return model.Security(description)
394+
case swagger.SecurityType.apiKey:
395+
assert security_def.name
396+
assert security_def.in_
397+
security_in = model.SecurityIn(security_def.in_.name)
398+
return model.ApiKeySecurity(description, security_def.name, security_in)
399+
case swagger.SecurityType.oauth2:
400+
flow: model.Flow
401+
match security_def.flow:
402+
case swagger.OAuthFlow.implicit:
403+
assert security_def.authorizationUrl
404+
flow = model.ImplicitFlow('', security_def.scopes, security_def.authorizationUrl)
405+
case swagger.OAuthFlow.password:
406+
assert security_def.tokenUrl
407+
flow = model.PasswordFlow('', security_def.scopes, security_def.tokenUrl)
408+
case swagger.OAuthFlow.application:
409+
assert security_def.tokenUrl
410+
flow = model.ClientCredFlow('', security_def.scopes, security_def.tokenUrl)
411+
case swagger.OAuthFlow.accessCode:
412+
assert security_def.authorizationUrl
413+
assert security_def.tokenUrl
414+
flow = model.AuthCodeFlow(
415+
'', security_def.scopes, security_def.authorizationUrl, security_def.tokenUrl
416+
)
417+
case _:
418+
assert False
414419

415-
if flows_scopes:
416-
flow.scopes = {key: flow.scopes[key] for key in flows_scopes if key in flow.scopes}
417-
return model.OAuthSecurity(description, [flow])
418-
else:
419-
assert False
420+
if flows_scopes:
421+
flow.scopes = {key: flow.scopes[key] for key in flows_scopes if key in flow.scopes}
422+
return model.OAuthSecurity(description, [flow])
423+
case _:
424+
assert False
420425

421426
def _append_schema(
422427
self,

chaotic-openapi/chaotic_openapi/front/swagger.py

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -127,28 +127,30 @@ class SecurityDef(base_model.BaseModel):
127127
scopes: dict[str, str] = pydantic.Field(default_factory=dict)
128128

129129
def model_post_init(self, context: Any, /) -> None:
130-
if self.type == SecurityType.apiKey:
131-
if not self.name:
132-
raise ValueError(errors.missing_field_msg('name'))
133-
if not self.in_:
134-
raise ValueError(errors.missing_field_msg('in'))
135-
elif self.type == SecurityType.oauth2:
136-
if not self.flow:
137-
raise ValueError(errors.missing_field_msg('flow'))
138-
if self.flow == OAuthFlow.implicit:
139-
if not self.authorizationUrl:
140-
raise ValueError(errors.missing_field_msg('authorizationUrl'))
141-
elif self.flow == OAuthFlow.password:
142-
if not self.tokenUrl:
143-
raise ValueError(errors.missing_field_msg('tokenUrl'))
144-
elif self.flow == OAuthFlow.application:
145-
if not self.tokenUrl:
146-
raise ValueError(errors.missing_field_msg('tokenUrl'))
147-
elif self.flow == OAuthFlow.accessCode:
148-
if not self.tokenUrl:
149-
raise ValueError(errors.missing_field_msg('tokenUrl'))
150-
if not self.authorizationUrl:
151-
raise ValueError(errors.missing_field_msg('authorizationUrl'))
130+
match self.type:
131+
case SecurityType.apiKey:
132+
if not self.name:
133+
raise ValueError(errors.missing_field_msg('name'))
134+
if not self.in_:
135+
raise ValueError(errors.missing_field_msg('in'))
136+
case SecurityType.oauth2:
137+
match self.flow:
138+
case None:
139+
raise ValueError(errors.missing_field_msg('flow'))
140+
case OAuthFlow.implicit:
141+
if not self.authorizationUrl:
142+
raise ValueError(errors.missing_field_msg('authorizationUrl'))
143+
case OAuthFlow.password:
144+
if not self.tokenUrl:
145+
raise ValueError(errors.missing_field_msg('tokenUrl'))
146+
case OAuthFlow.application:
147+
if not self.tokenUrl:
148+
raise ValueError(errors.missing_field_msg('tokenUrl'))
149+
case OAuthFlow.accessCode:
150+
if not self.tokenUrl:
151+
raise ValueError(errors.missing_field_msg('tokenUrl'))
152+
if not self.authorizationUrl:
153+
raise ValueError(errors.missing_field_msg('authorizationUrl'))
152154

153155

154156
# https://spec.openapis.org/oas/v2.0.html#security-requirement-object

chaotic/chaotic/back/cpp/translator.py

Lines changed: 24 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -326,17 +326,15 @@ def to_camel_case(text: str) -> str:
326326
enums=emum_items,
327327
)
328328

329-
if schema.format is None:
330-
raw_cpp_type = 'int'
331-
elif schema.format.value == 32:
332-
raw_cpp_type = 'std::int32_t'
333-
elif schema.format.value == 64:
334-
raw_cpp_type = 'std::int64_t'
335-
else:
336-
self._raise(
337-
schema,
338-
f'"format: {schema.format.value}" is not implemented',
339-
)
329+
match schema.format:
330+
case None:
331+
raw_cpp_type = 'int'
332+
case types.IntegerFormat.INT32:
333+
raw_cpp_type = 'std::int32_t'
334+
case types.IntegerFormat.INT64:
335+
raw_cpp_type = 'std::int64_t'
336+
case _:
337+
self._raise(schema, f'"format: {schema.format}" is not implemented')
340338

341339
typedef_tag = schema.get_x_property_str(
342340
'x-usrv-cpp-typedef-tag',
@@ -459,23 +457,21 @@ def _gen_string(
459457
validators.pattern = '^[a-z][-a-z0-9+.]*:.*'
460458

461459
if schema.format and schema.format not in {types.StringFormat.BINARY, types.StringFormat.URI}:
462-
if schema.format == types.StringFormat.BYTE:
463-
format_cpp_type = 'crypto::base64::String64'
464-
elif schema.format == types.StringFormat.UUID:
465-
format_cpp_type = 'boost::uuids::uuid'
466-
elif schema.format == types.StringFormat.DATE:
467-
format_cpp_type = 'userver::utils::datetime::Date'
468-
elif schema.format == types.StringFormat.DATE_TIME:
469-
format_cpp_type = 'userver::utils::datetime::TimePointTz'
470-
elif schema.format == types.StringFormat.DATE_TIME_ISO_BASIC:
471-
format_cpp_type = 'userver::utils::datetime::TimePointTzIsoBasic'
472-
elif schema.format == types.StringFormat.DATE_TIME_FRACTION:
473-
format_cpp_type = 'userver::utils::datetime::TimePointTzFraction'
474-
else:
475-
self._raise(
476-
schema,
477-
f'"format: {schema.format}" is unsupported yet',
478-
)
460+
match schema.format:
461+
case types.StringFormat.BYTE:
462+
format_cpp_type = 'crypto::base64::String64'
463+
case types.StringFormat.UUID:
464+
format_cpp_type = 'boost::uuids::uuid'
465+
case types.StringFormat.DATE:
466+
format_cpp_type = 'userver::utils::datetime::Date'
467+
case types.StringFormat.DATE_TIME:
468+
format_cpp_type = 'userver::utils::datetime::TimePointTz'
469+
case types.StringFormat.DATE_TIME_ISO_BASIC:
470+
format_cpp_type = 'userver::utils::datetime::TimePointTzIsoBasic'
471+
case types.StringFormat.DATE_TIME_FRACTION:
472+
format_cpp_type = 'userver::utils::datetime::TimePointTzFraction'
473+
case _:
474+
self._raise(schema, f'"format: {schema.format}" is unsupported yet')
479475
return cpp_types.CppStringWithFormat(
480476
json_schema=schema,
481477
nullable=schema.nullable,

core/functional_tests/basic_chaos/tests/resolver/conftest.py

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -88,20 +88,21 @@ def datagram_received(self, data, addr):
8888
response += struct.pack('!H', 1) # class IN
8989
response += struct.pack('!I', 99999) # TTL
9090

91-
if query_type == b'\x00\x01': # type A record
92-
response += struct.pack('!H', 4) # data length (IPv4)
93-
response += socket.inet_pton(
94-
socket.AF_INET,
95-
'77.88.55.55',
96-
) # our fake IPv4 address
97-
elif query_type == b'\x00\x1c': # type AAAA record
98-
response += struct.pack('!H', 16) # data length (IPv6)
99-
response += socket.inet_pton(
100-
socket.AF_INET6,
101-
'2a02:6b8:a::a',
102-
) # our fake IPv6 address
103-
else:
104-
raise Exception('unknown type')
91+
match query_type:
92+
case b'\x00\x01': # type A record
93+
response += struct.pack('!H', 4) # data length (IPv4)
94+
response += socket.inet_pton(
95+
socket.AF_INET,
96+
'77.88.55.55',
97+
) # our fake IPv4 address
98+
case b'\x00\x1c': # type AAAA record
99+
response += struct.pack('!H', 16) # data length (IPv6)
100+
response += socket.inet_pton(
101+
socket.AF_INET6,
102+
'2a02:6b8:a::a',
103+
) # our fake IPv6 address
104+
case _:
105+
raise Exception('unknown type')
105106

106107
logger.info(
107108
f'Dns "{self.name}" sends {len(response)} bytes to {addr} '

core/functional_tests/basic_chaos/tests/resolver/test_resolver.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -33,16 +33,17 @@ async def _call(
3333
params={'type': htype, 'host_to_resolve': resolve, **args},
3434
)
3535

36-
if check_query == CheckQuery.FROM_MOCK:
37-
# Could be two different requests for IPv4 and IPv6,
38-
# or a single one, or some retries.
39-
assert dns_mock_stats.get_stats() > dns_times_called
40-
queries = dns_mock_stats.get_queries()
41-
assert resolve in queries[-dns_times_called:]
42-
elif check_query == CheckQuery.FROM_CACHE:
43-
assert dns_mock_stats.get_stats() == dns_times_called
44-
elif check_query == CheckQuery.NO_CHECK:
45-
pass
36+
match check_query:
37+
case CheckQuery.FROM_MOCK:
38+
# Could be two different requests for IPv4 and IPv6,
39+
# or a single one, or some retries.
40+
assert dns_mock_stats.get_stats() > dns_times_called
41+
queries = dns_mock_stats.get_queries()
42+
assert resolve in queries[-dns_times_called:]
43+
case CheckQuery.FROM_CACHE:
44+
assert dns_mock_stats.get_stats() == dns_times_called
45+
case CheckQuery.NO_CHECK:
46+
pass
4647

4748
return response
4849

scripts/gdb/pretty_printers/cmd/utask/cmd.py

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -582,17 +582,19 @@ def invoke_per_task(self, task: TaskContext, cmd: str, from_tty: bool):
582582

583583
def complete(self, text: str, word: str) -> list[str] | int | None:
584584
complete_args_count = len(text.split()) - int(bool(word))
585-
if complete_args_count == 0: # utask apply
586-
return ['all'] + [
587-
task.attached_span.name if task.attached_span else task.task_id
588-
for task in get_all_tasks()
589-
if not word
590-
or (task.attached_span and task.attached_span.name.startswith(word))
591-
or task.task_id.startswith(word)
592-
]
593-
elif complete_args_count == 1: # utask apply <task_id>
594-
return gdb.COMPLETE_COMMAND
595-
return None
585+
match complete_args_count:
586+
case 0: # utask apply
587+
return ['all'] + [
588+
task.attached_span.name if task.attached_span else task.task_id
589+
for task in get_all_tasks()
590+
if not word
591+
or (task.attached_span and task.attached_span.name.startswith(word))
592+
or task.task_id.startswith(word)
593+
]
594+
case 1: # utask apply <task_id>
595+
return gdb.COMPLETE_COMMAND
596+
case _:
597+
return None
596598

597599

598600
if __name__ == '__main__':

testsuite/pytest_plugins/pytest_userver/client.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1404,13 +1404,16 @@ def _apply_cache_control_actions(
14041404
[],
14051405
)
14061406
for cache_name, action in actions:
1407-
if action == caches.CacheControlAction.INCREMENTAL:
1408-
force_incremental_names.append(cache_name)
1409-
elif action == caches.CacheControlAction.EXCLUDE:
1410-
if cache_names is not None:
1411-
cache_names.remove(cache_name)
1412-
else:
1413-
exclude_names.append(cache_name)
1407+
match action:
1408+
case caches.CacheControlAction.FULL:
1409+
pass
1410+
case caches.CacheControlAction.INCREMENTAL:
1411+
force_incremental_names.append(cache_name)
1412+
case caches.CacheControlAction.EXCLUDE:
1413+
if cache_names is not None:
1414+
cache_names.remove(cache_name)
1415+
else:
1416+
exclude_names.append(cache_name)
14141417

14151418
def _update_state(self, body: dict[str, Any]) -> None:
14161419
body_invalidate_caches = body.get('invalidate_caches', {})

0 commit comments

Comments
 (0)