From aab0854b101b1d39ae2df4c01d24f6488ed8d341 Mon Sep 17 00:00:00 2001 From: Shubham Padkonde Date: Sat, 19 Sep 2026 21:17:09 +0530 Subject: [PATCH 1/2] fix(http-client-python): bind response in LRO output callback when it is read With models-mode none and TypedDict generation, get_long_running_output only assigned `response = pipeline_response.http_response` when the final LRO response had headers, but the deserialization still read `response.content` / `response.json()`. A successful LRO then raised NameError. Emit the assignment whenever the generated deserialization uses `response`. Fixes #11966 Co-Authored-By: Claude Opus 5 --- .../python-lro-output-response-2026-8-19.md | 7 + .../codegen/serializers/builder_serializer.py | 10 +- .../tests/unit/test_lro_output_callback.py | 121 ++++++++++++++++++ 3 files changed, 135 insertions(+), 3 deletions(-) create mode 100644 .chronus/changes/python-lro-output-response-2026-8-19.md create mode 100644 packages/http-client-python/tests/unit/test_lro_output_callback.py diff --git a/.chronus/changes/python-lro-output-response-2026-8-19.md b/.chronus/changes/python-lro-output-response-2026-8-19.md new file mode 100644 index 00000000000..2c8a8e9a6b7 --- /dev/null +++ b/.chronus/changes/python-lro-output-response-2026-8-19.md @@ -0,0 +1,7 @@ +--- +changeKind: fix +packages: + - "@typespec/http-client-python" +--- + +Bind `response` in the generated LRO `get_long_running_output` callback whenever its deserialization reads it, fixing a `NameError` for `models-mode: none` clients whose final LRO response has a body but no headers. diff --git a/packages/http-client-python/generator/pygen/codegen/serializers/builder_serializer.py b/packages/http-client-python/generator/pygen/codegen/serializers/builder_serializer.py index 52cfe05783d..32edf24e8a9 100644 --- a/packages/http-client-python/generator/pygen/codegen/serializers/builder_serializer.py +++ b/packages/http-client-python/generator/pygen/codegen/serializers/builder_serializer.py @@ -4,6 +4,7 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- +import re from abc import abstractmethod from collections import defaultdict from typing import Generic, Type, TypeVar, Union, Optional, cast @@ -46,6 +47,9 @@ T = TypeVar("T") OrderedSet = dict[T, None] +# Matches a use of the local ``response`` variable, but not ``pipeline_response``. +_USES_RESPONSE = re.compile(r"(? str: """Return the generated expression that decodes an SSE event's UTF-8 data field.""" @@ -1842,15 +1846,15 @@ def get_long_running_output(self, builder: LROOperationType) -> list[str]: if builder.lro_response: if builder.lro_response.headers: retval.append(" response_headers = {}") + deserialization = self.response_headers_and_deserialization(builder, builder.lro_response) if ( (not self.code_model.options["models-mode"] and not self.code_model.generate_typeddict_only) or self.code_model.options["models-mode"] == "dpg" or builder.lro_response.headers + or any(_USES_RESPONSE.search(line) for line in deserialization) ): retval.append(" response = pipeline_response.http_response") - retval.extend( - [f" {line}" for line in self.response_headers_and_deserialization(builder, builder.lro_response)] - ) + retval.extend([f" {line}" for line in deserialization]) retval.append(" if cls:") retval.append( " return cls(pipeline_response, {}, {}){}".format( diff --git a/packages/http-client-python/tests/unit/test_lro_output_callback.py b/packages/http-client-python/tests/unit/test_lro_output_callback.py new file mode 100644 index 00000000000..9d7d966d7d6 --- /dev/null +++ b/packages/http-client-python/tests/unit/test_lro_output_callback.py @@ -0,0 +1,121 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +"""Tests for the ``get_long_running_output`` callback generated for LRO operations.""" + +import json + +import pytest + +from pygen.codegen.models import ( + CodeModel, + Client, + LROOperation, + ParameterList, + RequestBuilder, + Response, +) +from pygen.codegen.models.parameter_list import RequestBuilderParameterList +from pygen.codegen.models.primitive_types import StringType +from pygen.codegen.serializers.builder_serializer import LROOperationSerializer + +_CLIENT_YAML = { + "name": "client", + "namespace": "blah", + "moduleName": "blah", + "parameters": [], + "url": "", + "operationGroups": [], +} +_OPERATION_YAML = { + "url": "http://fake.com", + "method": "PUT", + "groupName": "blah", + "isOverload": False, + "apiVersions": [], +} + + +def _make_lro_operation(options): + code_model = CodeModel( + {"clients": [_CLIENT_YAML], "namespace": "namespace"}, + options={ + "show-send-request": True, + "builders-visibility": "public", + "show-operations": True, + "version-tolerant": True, + **options, + }, + ) + client = Client(_CLIENT_YAML, code_model, parameters=[]) + request_builder = RequestBuilder( + yaml_data=_OPERATION_YAML, + client=client, + code_model=code_model, + name="create", + parameters=RequestBuilderParameterList({}, code_model, parameters=[]), + ) + operation = LROOperation( + yaml_data=_OPERATION_YAML, + client=client, + code_model=code_model, + request_builder=request_builder, + name="begin_create", + parameters=ParameterList({}, code_model, []), + responses=[], + exceptions=[], + ) + operation.responses = [ + Response( + yaml_data={"statusCodes": [200]}, + code_model=code_model, + headers=[], + type=StringType({"type": "string"}, code_model), + ) + ] + return code_model, operation + + +class _FakeHttpResponse: + def __init__(self, body): + self.content = json.dumps(body).encode() + self._body = body + + def json(self): + return self._body + + def text(self): + return self._body + + +class _FakePipelineResponse: + def __init__(self, body): + self.http_response = _FakeHttpResponse(body) + + +@pytest.mark.parametrize("async_mode", [False, True]) +@pytest.mark.parametrize( + "options", + [ + # 'models-mode: none' with TypedDict generation (TypeSpec) + {"models-mode": None, "generate-typeddict": True, "tsp_file": True}, + {"models-mode": None}, + {"models-mode": "dpg"}, + ], +) +def test_long_running_output_binds_response_before_using_it(options, async_mode): + code_model, operation = _make_lro_operation(options) + serializer = LROOperationSerializer(code_model, async_mode=async_mode, client_namespace="blah") + + lines = serializer.get_long_running_output(operation) + source = "\n".join(lines) + uses_response = any("response." in line and "pipeline_response." not in line for line in lines) + if uses_response: + assert " response = pipeline_response.http_response" in lines + + # The generated callback must run without a NameError for an unbound ``response``. + namespace = {"cls": None, "_deserialize": lambda _type, value, *args, **kwargs: value} + exec(compile(source, "", "exec"), namespace) # pylint: disable=exec-used + assert namespace["get_long_running_output"](_FakePipelineResponse("done")) == "done" From 35dba90dd166225b716a2bfa3635511bdb07641f Mon Sep 17 00:00:00 2001 From: Shubham Padkonde Date: Mon, 21 Sep 2026 14:15:13 +0530 Subject: [PATCH 2/2] Build the LRO test response as an LROResponse The serializer reaches the response through builder.lro_response, which is an LROResponse in a real code model. The test built a plain Response, so it exercised a slightly different model than generation does. Co-Authored-By: Claude Opus 5 --- .../tests/unit/test_lro_output_callback.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/packages/http-client-python/tests/unit/test_lro_output_callback.py b/packages/http-client-python/tests/unit/test_lro_output_callback.py index 9d7d966d7d6..c82b0cb1e44 100644 --- a/packages/http-client-python/tests/unit/test_lro_output_callback.py +++ b/packages/http-client-python/tests/unit/test_lro_output_callback.py @@ -15,8 +15,8 @@ LROOperation, ParameterList, RequestBuilder, - Response, ) +from pygen.codegen.models.response import LROResponse from pygen.codegen.models.parameter_list import RequestBuilderParameterList from pygen.codegen.models.primitive_types import StringType from pygen.codegen.serializers.builder_serializer import LROOperationSerializer @@ -67,9 +67,17 @@ def _make_lro_operation(options): responses=[], exceptions=[], ) + # The serializer reaches these through ``builder.lro_response``, which is + # an LROResponse in a real code model rather than a plain Response. operation.responses = [ - Response( - yaml_data={"statusCodes": [200]}, + LROResponse( + yaml_data={ + "statusCodes": [200], + "pollerSync": "azure.core.polling.LROPoller", + "pollerAsync": "azure.core.polling.AsyncLROPoller", + "pollingMethodSync": "azure.core.polling.base_polling.LROBasePolling", + "pollingMethodAsync": "azure.core.polling.async_base_polling.AsyncLROBasePolling", + }, code_model=code_model, headers=[], type=StringType({"type": "string"}, code_model),