Repository navigation
fix(python): escape quotes in enum documentation #11897
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Libba Lawrence (l0lawrence)
merged 5 commits into
microsoft:main
from
rksharma-owg:codex/escape-python-docstring-quotes
Sep 29, 2026
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
ca3eb87
fix(python): escape quotes in enum docstrings
rksharma-owg b89dbca
fix(python): escape literal enum documentation in TypedDict output
rksharma-owg d77db5e
Merge remote-tracking branch 'origin/main' into codex/escape-python-d…
rksharma-owg 9548918
Merge remote-tracking branch 'origin/main' into codex/escape-python-d…
rksharma-owg 1996bc9
test(python): cover enum docstrings through serializers
rksharma-owg File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| --- | ||
| changeKind: fix | ||
| packages: | ||
| - "@typespec/http-client-python" | ||
| --- | ||
|
|
||
| Escape quotes in enum and enum member documentation so embedded Python string delimiters remain documentation in generated code. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
137 changes: 137 additions & 0 deletions
137
packages/http-client-python/tests/unit/test_enum_docstrings.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,137 @@ | ||
| # ------------------------------------------------------------------------- | ||
| # Copyright (c) Microsoft Corporation. All rights reserved. | ||
| # Licensed under the MIT License. See License.txt in the project root for | ||
| # license information. | ||
| # -------------------------------------------------------------------------- | ||
| """Enum documentation must remain string literals in generated Python.""" | ||
|
|
||
| import ast | ||
| import inspect | ||
| from pathlib import Path | ||
| from types import SimpleNamespace | ||
|
|
||
| import black | ||
| import pytest | ||
| from jinja2 import Environment, FileSystemLoader, PackageLoader | ||
|
|
||
| from pygen import OptionsDict | ||
| from pygen.codegen.models import CodeModel, build_type | ||
| from pygen.codegen.serializers.enum_serializer import EnumSerializer | ||
| from pygen.codegen.serializers.types_serializer import TypesSerializer | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "description", | ||
| [ | ||
| "Ordinary documentation.", | ||
| 'A"""; print("This should remain documentation"); """B.', | ||
| 'Quotes: " and "" and """.', | ||
| 'Ends with a quote"', | ||
| r'Quotes """ with a regex \W and a path C:\new\test.', | ||
| 'First paragraph.\n\nSecond paragraph with """ quotes.', | ||
| ], | ||
| ) | ||
| @pytest.mark.parametrize("location", ["enum", "member", "literal"]) | ||
| def test_enum_docstrings_preserve_documentation(description, location): | ||
| templates = Path(__file__).parents[2] / "generator/pygen/codegen/templates" | ||
| env = Environment(loader=FileSystemLoader(templates), trim_blocks=True, lstrip_blocks=True) | ||
| value = SimpleNamespace( | ||
| name="FAST", | ||
| value="fast", | ||
| description=lambda **kwargs: description if location == "member" else "", | ||
| ) | ||
| enum = SimpleNamespace( | ||
| name="WidgetMode", | ||
| yaml_data={"description": description if location in ("enum", "literal") else ""}, | ||
| values=[value], | ||
| pylint_disable=lambda: "", | ||
| value_type=SimpleNamespace(type_annotation=lambda **kwargs: "str", get_declaration=repr), | ||
| ) | ||
| if location == "literal": | ||
| source = env.get_template("types.py.jinja2").render( | ||
| code_model=SimpleNamespace(license_header=""), | ||
| imports="", | ||
| literal_enums=[enum], | ||
| models=[], | ||
|
Copilot marked this conversation as resolved.
|
||
| discriminated_bases=[], | ||
| serializer=SimpleNamespace(declare_literal_enum=lambda enum: f'{enum.name} = Literal["fast"]'), | ||
| ) | ||
| else: | ||
| source = env.from_string( | ||
| '{% import "operation_tools.jinja2" as op_tools %}{% include "enum.py.jinja2" %}' | ||
| ).render(enum=enum) | ||
| # Formatting success alone does not prove that documentation stayed inside a string. | ||
| source = black.format_str(source, mode=black.Mode()) | ||
| module = ast.parse(source) | ||
| body = module.body if location == "literal" else module.body[0].body | ||
| assert len(body) == 2 | ||
| doc, assignment = body if location == "enum" else reversed(body) | ||
| assert isinstance(assignment, ast.Assign) | ||
| assert isinstance(doc, ast.Expr) | ||
| assert isinstance(doc.value, ast.Constant) | ||
| assert inspect.cleandoc(doc.value.value).strip() == description | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("typeddict_only", [False, True]) | ||
| def test_enum_serializers_preserve_documentation(typeddict_only): | ||
| description = 'Before """ after a path C:\\new.' | ||
| member_description = 'Member """ documentation.' | ||
| code_model = CodeModel( | ||
| { | ||
| "namespace": "sample", | ||
| "clients": [ | ||
| { | ||
| "name": "client", | ||
| "namespace": "sample", | ||
| "moduleName": "sample", | ||
| "parameters": [], | ||
| "url": "", | ||
| "operationGroups": [], | ||
| } | ||
| ], | ||
| }, | ||
| OptionsDict( | ||
| { | ||
| "models-mode": "none" if typeddict_only else "dpg", | ||
| "generate-typeddict": typeddict_only, | ||
| "flavor": "unbranded", | ||
| "tsp_file": True, | ||
| } | ||
| ), | ||
| ) | ||
| enum_yaml = { | ||
| "type": "enum", | ||
| "name": "WidgetMode", | ||
| "description": description, | ||
| "valueType": {"type": "string"}, | ||
| "values": [], | ||
| } | ||
| enum = build_type(enum_yaml, code_model) | ||
| enum.values.append( | ||
| build_type( | ||
| { | ||
| "type": "enumvalue", | ||
| "name": "FAST", | ||
| "value": "fast", | ||
| "description": member_description, | ||
| "enumType": enum_yaml, | ||
| "valueType": {"type": "string"}, | ||
| }, | ||
| code_model, | ||
| ) | ||
| ) | ||
| env = Environment(loader=PackageLoader("pygen.codegen", "templates"), trim_blocks=True, lstrip_blocks=True) | ||
| serializer = ( | ||
| TypesSerializer(code_model, env, enums=[enum]) | ||
| if typeddict_only | ||
| else EnumSerializer(code_model, env, enums=[enum]) | ||
| ) | ||
|
|
||
| source = black.format_str(serializer.serialize(), mode=black.Mode()) | ||
| module = ast.parse(source) | ||
| docstrings = [ | ||
| inspect.cleandoc(node.value.value).strip() | ||
| for node in ast.walk(module) | ||
| if isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant) and isinstance(node.value.value, str) | ||
| ] | ||
| assert docstrings == ([description] if typeddict_only else [description, member_description]) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.