From c6f27440c65b78c9f72ef1b11d045b6e3f7ca34a Mon Sep 17 00:00:00 2001 From: Tim Abbott Date: Wed, 7 Apr 2021 09:47:48 -0700 Subject: [PATCH] openapi: Fix display for boolean example values. The comments explain in some detail, but basically we were displaying the types for booleans incorrectly, and the types for strings in a somewhat confusing fashion. Fix this with comments explaining the logic. Using JSON dumping also results in our showing strings inside quotation marks in our examples, which seems net helpful. Thanks to ArunSankarKs for finding where we needed to change the codebase. Fixes #18021. --- zerver/lib/markdown/api_arguments_table_generator.py | 9 ++++++++- zerver/openapi/markdown_extension.py | 5 ++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/zerver/lib/markdown/api_arguments_table_generator.py b/zerver/lib/markdown/api_arguments_table_generator.py index bce1303754..356d6a7b1c 100644 --- a/zerver/lib/markdown/api_arguments_table_generator.py +++ b/zerver/lib/markdown/api_arguments_table_generator.py @@ -124,7 +124,14 @@ class APIArgumentsTablePreprocessor(Preprocessor): # (path, querystring, form data...). We should document this detail. example = "" if "example" in argument: - example = argument["example"] + # We use this style without explicit JSON encoding for + # integers, strings, and booleans. + # * For booleans, JSON encoding correctly corrects for Python's + # str(True)="True" not matching the encoding of "true". + # * For strings, doing so nicely results in strings being quoted + # in the documentation, improving readability. + # * For integers, it is a noop, since json.dumps(3) == str(3) == "3". + example = json.dumps(argument["example"]) else: example = json.dumps(argument["content"]["application/json"]["example"]) diff --git a/zerver/openapi/markdown_extension.py b/zerver/openapi/markdown_extension.py index 17914666ee..9ad7b2be64 100644 --- a/zerver/openapi/markdown_extension.py +++ b/zerver/openapi/markdown_extension.py @@ -208,6 +208,7 @@ def get_openapi_param_example_value_as_string( # union type. But for this logic's purpose, it's good enough # to just check the first parameter. param_type = param["schema"]["oneOf"][0]["type"] + if param_type in ["object", "array"]: example_value = param.get("example", None) if not example_value: @@ -225,7 +226,9 @@ cURL example.""" else: example_value = param.get("example", DEFAULT_EXAMPLE[param_type]) if isinstance(example_value, bool): - example_value = str(example_value).lower() + # Booleans are effectively JSON-encoded, in that we pass + # true/false, not the Python str(True) = "True" + jsonify = True if jsonify: example_value = json.dumps(example_value) if curl_argument: