Skip to content

Commit 9f6ef38

Browse files
committed
fix(openapi): handle non-numeric OpenAPI response keys in return-doc
sorted() used int(item[0]) as the sort key over the Responses Object, which raised ValueError for valid non-numeric keys such as 'default' or range codes ('2XX'). These are common in real specs, so loading any OpenAPI toolset whose operation declares a 'default' response crashed. Non-numeric keys are now ordered after numeric status codes.
1 parent 4cee97f commit 9f6ef38

2 files changed

Lines changed: 25 additions & 2 deletions

File tree

src/google/adk/tools/openapi_tool/common/common.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -227,8 +227,12 @@ def generate_return_doc(responses: Dict[str, Response]) -> str:
227227

228228
# Only consider 2xx responses for return type hinting.
229229
# Returns the 2xx response with the smallest status code number and with
230-
# content defined.
231-
sorted_responses = sorted(responses.items(), key=lambda item: int(item[0]))
230+
# content defined. Non-numeric OpenAPI response keys (e.g. 'default' or
231+
# range codes like '2XX') are valid and sorted after numeric status codes.
232+
sorted_responses = sorted(
233+
responses.items(),
234+
key=lambda item: int(item[0]) if item[0].isdigit() else float('inf'),
235+
)
232236
qualified_response = next(
233237
filter(
234238
lambda r: r[0].startswith('2') and r[1].content,

tests/unittests/tools/openapi_tool/common/test_common.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -392,6 +392,25 @@ def test_generate_return_doc_2xx_smallest_status_code_response(self):
392392
== expected_doc
393393
)
394394

395+
def test_generate_return_doc_non_numeric_status_keys(self):
396+
# 'default' (and range codes like '2XX') are valid OpenAPI response keys
397+
# and must not crash return-doc generation.
398+
responses = {
399+
'200': {
400+
'description': 'Successful response',
401+
'content': {'application/json': {'schema': {'type': 'string'}}},
402+
},
403+
'default': {
404+
'description': 'Unexpected error',
405+
'content': {'application/json': {'schema': {'type': 'object'}}},
406+
},
407+
}
408+
expected_doc = 'Returns (str): Successful response'
409+
assert (
410+
PydocHelper.generate_return_doc(dict_to_responses(responses))
411+
== expected_doc
412+
)
413+
395414
def test_generate_return_doc_contentful_response(self):
396415
responses = {
397416
'200': {'description': 'No content response'},

0 commit comments

Comments
 (0)