Skip to content
Merged
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"
---

Support inline discriminated unions whose variants extend a base model, including variants that inherit through an intermediate model.
10 changes: 9 additions & 1 deletion packages/http-client-python/emitter/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,11 @@ import type {
SdkType,
SdkUnionType,
} from "@azure-tools/typespec-client-generator-core";
import { isHttpMetadata, UsageFlags } from "@azure-tools/typespec-client-generator-core";
import {
getSdkModel,
isHttpMetadata,
UsageFlags,
} from "@azure-tools/typespec-client-generator-core";
import type { Type } from "@typespec/compiler";
import { getEncode } from "@typespec/compiler";
import type { HttpAuth } from "@typespec/http";
Expand Down Expand Up @@ -289,6 +293,9 @@ function emitModel(context: PythonSdkContext, type: SdkModelType): Record<string
externalTypeInfo: type.external,
});
}
const isDiscriminatedUnionBase = [...(context.__discriminatedUnionModels?.values() ?? [])].some(
(base) => getSdkModel(context, base) === type,
);
const parents: Record<string, any>[] = [];
const newValue = {
type: type.kind,
Expand All @@ -306,6 +313,7 @@ function emitModel(context: PythonSdkContext, type: SdkModelType): Record<string
isXml: type.usage & UsageFlags.Xml ? true : false,
xmlMetadata: getXmlMetadata(type),
clientNamespace: getClientNamespace(context, type.namespace),
...(isDiscriminatedUnionBase ? { isDiscriminatedUnionBase: true } : {}),
};

context.__typesMap.set(type, newValue);
Expand Down
88 changes: 87 additions & 1 deletion packages/http-client-python/emitter/test/emitter.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { expectDiagnostics, t } from "@typespec/compiler/testing";
import { expect, it } from "vitest";
import { EmitterTester, emitCodeModel } from "./test-host.js";
import { EmitterTester, UnionExtendsEmitterTester, emitCodeModel } from "./test-host.js";

it("preserves numeric property names while fixing numeric enum members", async () => {
const { codeModel, diagnostics } = await emitCodeModel(`
Expand Down Expand Up @@ -131,3 +131,89 @@ it("generates models when no service exists", async () => {
true,
);
});

it("uses TCGC's model conversion for inherited discriminated unions", async () => {
const { codeModel, diagnostics } = await emitCodeModel(
`
import "@typespec/http";
using TypeSpec.Http;
@service namespace Test;
model PetBase { name: string; }
model Cat extends PetBase { meow: boolean; }
model Dog extends PetBase { bark: boolean; }
@discriminated(#{ envelope: "none", discriminatorPropertyName: "petType" })
union Pet extends PetBase { feline: Cat, canine: Dog }
@post op send(@body pet: Pet): Pet;
`,
{},
UnionExtendsEmitterTester,
);

expectDiagnostics(diagnostics, []);
expect(codeModel.types).toContainEqual(
expect.objectContaining({
type: "model",
name: "PetBase",
isDiscriminatedUnionBase: true,
properties: expect.arrayContaining([
expect.objectContaining({ wireName: "petType", isDiscriminator: true }),
]),
discriminatedSubtypes: {
feline: expect.objectContaining({ name: "Cat", discriminatorValue: "feline" }),
canine: expect.objectContaining({ name: "Dog", discriminatorValue: "canine" }),
},
}),
);
expect(codeModel.types).not.toContainEqual(
expect.objectContaining({ type: "combined", name: "Pet" }),
);
});

it("leaves structural variants as a union when TCGC cannot convert them", async () => {
const { codeModel, diagnostics } = await emitCodeModel(
`
import "@typespec/http";
using TypeSpec.Http;
@service namespace Test;
model PetBase { name: string; }
model Cat { name: string; meow: boolean; }
model Dog { name: string; bark: boolean; }
@discriminated(#{ envelope: "none" })
union Pet extends PetBase { cat: Cat, dog: Dog }
@post op send(@body pet: Pet): Pet;
`,
{},
UnionExtendsEmitterTester,
);

expectDiagnostics(diagnostics, [
{ code: "@azure-tools/typespec-azure-core/union-enums-invalid-kind", severity: "warning" },
{ code: "@azure-tools/typespec-azure-core/union-enums-invalid-kind", severity: "warning" },
]);
expect(codeModel.types).toContainEqual(
expect.objectContaining({
type: "combined",
name: "Pet",
types: [expect.objectContaining({ name: "Cat" }), expect.objectContaining({ name: "Dog" })],
}),
);
expect(codeModel.types.find((type) => type.name === "PetBase")).not.toHaveProperty(
"isDiscriminatedUnionBase",
);
});
it("does not mark an ordinary discriminator model as a discriminated union", async () => {
const { codeModel, diagnostics } = await emitCodeModel(`
import "@typespec/http";
using TypeSpec.Http;

@service namespace Test;
@discriminator("kind") model PetBase { kind: string; name: string; }
model Cat extends PetBase { kind: "cat"; meow: boolean; }
@post op send(@body pet: PetBase): PetBase;
`);

expectDiagnostics(diagnostics, []);
expect(codeModel.types.find((type) => type.name === "PetBase")).not.toHaveProperty(
"isDiscriminatedUnionBase",
);
});
43 changes: 28 additions & 15 deletions packages/http-client-python/emitter/test/test-host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,33 @@ export const Tester = PythonTester;
// `@typespec/http-client-python` is intentionally excluded from the pnpm workspace, so it isn't
// linked into its own `node_modules` and `.emit()` can't resolve it by name. Register a minimal
// virtual package whose entrypoint re-exports the real `$onEmit`, so the emitter under test runs.
export const EmitterTester = PythonTester.files({
"node_modules/@typespec/http-client-python/package.json": JSON.stringify({
name: "@typespec/http-client-python",
version: "0.0.0",
tspMain: "./lib.tsp",
exports: { ".": "./index.js" },
}),
"node_modules/@typespec/http-client-python/lib.tsp": 'import "./index.js";',
"node_modules/@typespec/http-client-python/index.js": mockFile.js({
$onEmit,
$lib,
function withPythonEmitter(tester: typeof PythonTester) {
return tester
.files({
"node_modules/@typespec/http-client-python/package.json": JSON.stringify({
name: "@typespec/http-client-python",
version: "0.0.0",
tspMain: "./lib.tsp",
exports: { ".": "./index.js" },
}),
"node_modules/@typespec/http-client-python/lib.tsp": 'import "./index.js";',
"node_modules/@typespec/http-client-python/index.js": mockFile.js({
$onEmit,
$lib,
}),
})
.emit("@typespec/http-client-python", {
"generate-packaging-files": false,
});
}

export const EmitterTester = withPythonEmitter(PythonTester);
export const UnionExtendsEmitterTester = withPythonEmitter(
createTester(resolvePath(import.meta.dirname, "../.."), {
libraries: ["@azure-tools/typespec-client-generator-core", "@typespec/http"],
features: ["union-extends"],
}),
}).emit("@typespec/http-client-python", {
"generate-packaging-files": false,
});
);

/** A type entry in the emitted code model. */
export interface CodeModelType {
Expand All @@ -53,6 +65,7 @@ export interface CodeModel {
export async function emitCodeModel(
code: string,
options: PythonEmitterOptions = {},
tester = EmitterTester,
): Promise<{
codeModel: CodeModel;
commandArgs: Record<string, unknown>;
Expand All @@ -61,7 +74,7 @@ export async function emitCodeModel(
const outputDir = await mkdtemp(join(tmpdir(), "typespec-python-"));
let yamlPath: string | undefined;
try {
const [, diagnostics] = await EmitterTester.compileAndDiagnose(code, {
const [, diagnostics] = await tester.compileAndDiagnose(code, {
compilerOptions: {
options: {
"@typespec/http-client-python": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,7 @@ export interface BuildTaskGroupsOptions {

// ---- Public constants ----

export const SKIP_SPECS: string[] = [
"type/file",
"azure/core/authentication/configurations",
"type/union/discriminated/extends",
];
export const SKIP_SPECS: string[] = ["type/file", "azure/core/authentication/configurations"];

export const SpecialFlags: Record<string, Record<string, any>> = {
azure: {
Expand Down Expand Up @@ -554,6 +550,12 @@ export async function compileSpec(

try {
const compilerOptions = {
configFile: {
projectRoot: ctx.pluginDir,
features: ["union-extends"],
diagnostics: [],
outputDir: ctx.pluginDir,
},
emit: [ctx.pluginDir],
options: {
[ctx.emitterName]: options,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ def _get_properties(type: "ModelType", properties: list[Property]) -> list[Prope
# any of our own properties
property_names = set([p.client_name for p in properties] + [p.client_name for p in type.properties])
chosen_parent_properties = [p for p in parent.properties if p.client_name not in property_names]
properties = _get_properties(parent, chosen_parent_properties) + properties
inherited_properties = _get_properties(parent, chosen_parent_properties)
properties = [p for p in inherited_properties if p.client_name not in property_names] + properties
return properties


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,28 @@ def declare_model(self, model: ModelType) -> str:
basename += f", discriminator={discriminator_value}"
return f"class {model.name}({basename}):{self.class_pylint_disable(model)}"

@staticmethod
def transitive_discriminator_registrations(model: ModelType) -> list[str]:
registrations: list[str] = []
visited = set(model.parents)

def visit(base: ModelType, expression: str) -> None:
for index, ancestor in enumerate(base.parents):
if ancestor in visited:
continue
visited.add(ancestor)
ancestor_expression = f"{expression}.__bases__[{index}]"
if ancestor.yaml_data.get("isDiscriminatedUnionBase"):
for value, subtype in ancestor.discriminated_subtypes.items():
if subtype is model:
key = python_string_literal(value)
registrations.append(f'getattr({ancestor_expression}, "__mapping__")[{key}] = {model.name}')
visit(ancestor, ancestor_expression)

for parent in model.parents:
visit(parent, parent.name)
return registrations

def class_pylint_disable(self, model: ModelType) -> str:
retval = super().class_pylint_disable(model)
# DPG models render an empty ``@overload def __init__(self, *, ...)`` body, so the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -247,11 +247,9 @@ def has_keyword_wire_names(model: ModelType) -> bool:
def needs_flat_typeddict(model: ModelType) -> bool:
"""Whether a TypedDict must be emitted in flat (non-inheriting) form.

PEP 589 forbids changing an inherited TypedDict field's requiredness in a subclass. When a
child redeclares an inherited field with a different requiredness (e.g. the parent renders it
as optional via ``total=False`` while the child needs ``Required[...]``), subclassing would
emit an illegal ``Overwriting TypedDict field ... while extending`` construct. Such models are
instead rendered as a flat TypedDict that lists every field (inherited + own) directly.
TypedDict subclasses cannot redeclare inherited fields, including when a discriminator
narrows a string to a literal or changes its requiredness. Render those models flat,
listing every field (inherited + own) directly.

Models with keyword wire_names already flatten all fields via the functional form, so they
never hit this path.
Expand All @@ -267,12 +265,17 @@ def needs_flat_typeddict(model: ModelType) -> bool:
(p for p in model.properties if p.client_name == parent_prop.client_name),
None,
)
if child_prop is None or child_prop is parent_prop:
# Not overridden by the child (same object is reused when inherited unchanged).
if child_prop is None:
continue
parent_required = not (parent_prop.optional or parent_prop.client_default_value is not None)
child_required = not (child_prop.optional or child_prop.client_default_value is not None)
if parent_required != child_required:
if (
parent_required != child_required
or child_prop.is_base_discriminator
or child_prop.type_annotation() != parent_prop.type_annotation()
or child_prop.type_annotation(serialize_namespace_type=NamespaceType.TYPES_FILE)
!= parent_prop.type_annotation(serialize_namespace_type=NamespaceType.TYPES_FILE)
):
return True
return False

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,7 @@
super().__setattr__(key, value)
{% endif %}
{% endif %}

{% for registration in serializer.transitive_discriminator_registrations(model) %}
{{ registration }}
{% endfor %}
Loading
Loading