Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
changeKind: fix
packages:
- "@typespec/http-client-python"
---

Fix invalid string literals in generated Python samples for quoted If-Match ETags, preserving the exact header value.
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,6 @@ def _client_params(self) -> dict[str, Any]:

@staticmethod
def handle_param(param: Union[Parameter, BodyParameter], param_value: Any) -> str:
if isinstance(param_value, str):
if any(i in param_value for i in '\r\n"'):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Check commit history to analyze why the logic was added. If there is reason to add it, we need be careful to delete it. Copilot

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Triple quoting originated in autorest.python#1546 to handle multiline runbook content with quotes. Type-level repr preserves that content, including CRLFs, without the delimiter/escaping problems. Added complete-sample regression coverage in 38092bc; all 343 string-literal tests pass.

return f'"""{param_value}"""'

return param.type.serialize_sample_value(param_value)

# prepare operation parameters
Expand Down
57 changes: 57 additions & 0 deletions packages/http-client-python/tests/unit/test_string_literals.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from typing import Literal, Optional, get_args

import pytest
import black
from jinja2 import Environment, PackageLoader

from pygen import OptionsDict
Expand All @@ -31,6 +32,7 @@
from pygen.codegen.serializers.builder_serializer import OperationSerializer, _get_polymorphic_subtype_template
from pygen.codegen.serializers.model_serializer import DpgModelSerializer
from pygen.codegen.serializers.general_serializer import GeneralSerializer
from pygen.codegen.serializers.sample_serializer import SampleSerializer
from pygen.codegen.serializers.parameter_serializer import ParameterSerializer, PopKwargType
from pygen.codegen.serializers.types_serializer import TypesSerializer
from pygen.codegen.serializers.utils import json_dumps_template
Expand Down Expand Up @@ -93,6 +95,61 @@ def env():
return Environment(loader=PackageLoader("pygen.codegen", "templates"), trim_blocks=True, lstrip_blocks=True)


@pytest.mark.parametrize("value", VALUES + ['"1"', 'W/"1"', '"one", "two"', "trailing\\"])
def test_sample_parameter_preserves_string_literal(code_model, value):
parameter = SimpleNamespace(type=StringType({"type": "string"}, code_model))
literal = SampleSerializer.handle_param(parameter, value)
assert ast.literal_eval(literal) == value
source = black.format_str(f"if_match = {literal}\n", mode=black.Mode(line_length=120))
assert ast.literal_eval(ast.parse(source).body[0].value) == value


@pytest.mark.parametrize(
"wire_name, client_name, location, value",
[
("If-Match", "if_match", "header", '"1"'),
("If-Match", "if_match", "header", 'W/"1"'),
("If-Match", "if_match", "header", '"one", "two"'),
("runbookContent", "runbook_content", "body", 'Write-Output "Hello"\r\nWrite-Output "world"\r\n'),
],
)
@pytest.mark.parametrize("positional", [False, True])
def test_sample_preserves_required_string_parameter(
code_model, env, wire_name, client_name, location, value, positional
):
parameter = Parameter(
{
"wireName": wire_name,
"clientName": client_name,
"location": location,
"implementation": "Method",
"optional": False,
},
code_model,
type=StringType({"type": "string"}, code_model),
)
operation = SimpleNamespace(
name="add_binding",
operation_type="operation",
parameters=SimpleNamespace(
positional=[parameter] if positional else [],
keyword_only=[] if positional else [parameter],
),
response_type_annotation=lambda **kwargs: "None",
)
group = SimpleNamespace(client=code_model.clients[0], is_mixin=True)
serializer = SampleSerializer(
code_model, env, group, operation, {"parameters": {wire_name: value}}, "add_binding.py"
)
source = black.format_str(serializer.serialize(), mode=black.Mode(line_length=120))
function = next(node for node in ast.parse(source).body if isinstance(node, ast.FunctionDef))
call = function.body[1].value
assert call.func.attr == "add_binding"
assert len(call.keywords) == 1
assert call.keywords[0].arg == client_name
assert ast.literal_eval(call.keywords[0].value) == value


@pytest.mark.parametrize("async_mode", [False, True])
@pytest.mark.parametrize(
"description, expected",
Expand Down