diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c3bbb89..e06b818c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### Fixed - A generated Python model rejects an explicit `None` for an omittable field whose type serde can't read from `null`. Since 0.21 the client sends an explicit `None` as `null`, which the server refuses, so `Model(page=None)` for a `#[serde(default)] page: Page` failed with a 400. It now raises a `ValidationError` where the model is built. Leaving the field out is unchanged. Whether a value may be `null` is now part of the shared field contract and is decided from the schema, not from Python's rendered annotation. Before, only primitives and containers were checked. Now these reject `null` too: structs with fields, tuple structs, tagged enums, newtypes and wrappers such as `Box` of those, and primitives such as `chrono::DateTime`, `uuid::Uuid` and `url::Url`. Unit structs, untagged enums with a variant that accepts `null`, newtypes of an `Option`, generic parameters and fields with a custom codec on their side (`deserialize_with` in a request, `serialize_with` in a response), including a newtype's inner field, still accept `None`. +- A generated Python module with an omittable field of a unit type, `()` or a unit struct, imports again. The field was annotated `None | None`, which Python can't evaluate, so importing the module raised `TypeError`. It is now `None`. ## 0.23.0 diff --git a/reflectapi-demo/src/tests/serde.rs b/reflectapi-demo/src/tests/serde.rs index 829eaaca..3d529b27 100644 --- a/reflectapi-demo/src/tests/serde.rs +++ b/reflectapi-demo/src/tests/serde.rs @@ -228,6 +228,28 @@ fn test_struct_with_serde_default_named_types() { assert_snapshot!(TestStructWithSerdeDefaultNamedTypes); } +#[derive(Default, reflectapi::Input, reflectapi::Output, serde::Deserialize, serde::Serialize)] +struct TestUnitMarker; + +#[derive(Default, reflectapi::Input, reflectapi::Output, serde::Deserialize, serde::Serialize)] +struct TestOptionalNewtype(Option); + +/// Each type already renders with `None` in it, so the omission default +/// must not add another. +#[derive(reflectapi::Input, reflectapi::Output, serde::Deserialize, serde::Serialize)] +struct TestStructWithSerdeDefaultNoneTypes { + #[serde(default)] + marker: TestUnitMarker, + #[serde(default)] + nothing: (), + #[serde(default)] + optional_newtype: TestOptionalNewtype, +} +#[test] +fn test_struct_with_serde_default_none_types() { + assert_snapshot!(TestStructWithSerdeDefaultNoneTypes); +} + #[derive(reflectapi::Input, reflectapi::Output, serde::Deserialize, serde::Serialize)] struct TestStructWithSerdeSkip { #[serde(skip)] diff --git a/reflectapi-demo/src/tests/snapshots/reflectapi_demo__tests__serde__struct_with_serde_default_named_types-5.snap b/reflectapi-demo/src/tests/snapshots/reflectapi_demo__tests__serde__struct_with_serde_default_named_types-5.snap index 35161010..5f3ba191 100644 --- a/reflectapi-demo/src/tests/snapshots/reflectapi_demo__tests__serde__struct_with_serde_default_named_types-5.snap +++ b/reflectapi-demo/src/tests/snapshots/reflectapi_demo__tests__serde__struct_with_serde_default_named_types-5.snap @@ -100,7 +100,7 @@ class ReflectapiDemoTestsSerdeInputTestStructWithSerdeDefaultNamedTypes( structure: reflectapi_demo.tests.serde.TestDefaultStruct | None = None tagged: reflectapi_demo.tests.serde.TestDefaultTaggedEnum | None = None untagged: reflectapi_demo.tests.serde.TestDefaultUntaggedEnum | None = None - nullable_newtype: int | None | None = None + nullable_newtype: int | None = None @field_validator("structure", "tagged", mode="before") @classmethod diff --git a/reflectapi-demo/src/tests/snapshots/reflectapi_demo__tests__serde__struct_with_serde_default_none_types-2.snap b/reflectapi-demo/src/tests/snapshots/reflectapi_demo__tests__serde__struct_with_serde_default_none_types-2.snap new file mode 100644 index 00000000..b8057ef6 --- /dev/null +++ b/reflectapi-demo/src/tests/snapshots/reflectapi_demo__tests__serde__struct_with_serde_default_none_types-2.snap @@ -0,0 +1,87 @@ +--- +source: reflectapi-demo/src/tests/serde.rs +expression: "super :: into_typescript_code :: < TestStructWithSerdeDefaultNoneTypes > ()" +--- +// DO NOT MODIFY THIS FILE MANUALLY +// This file was generated by reflectapi-cli +// +// Schema name: + +export function client(base: string | Client): __definition.Interface { + return __implementation.__client(base); +} + +export namespace __definition { + export interface Interface { + inout_test: ( + input: reflectapi_demo.tests.serde.input.TestStructWithSerdeDefaultNoneTypes, + headers: {}, + options?: RequestOptions, + ) => AsyncResult< + reflectapi_demo.tests.serde.output.TestStructWithSerdeDefaultNoneTypes, + {} + >; + } +} +export namespace reflectapi { + /** + * Struct object with no fields + */ + export interface Empty {} + + /** + * Error object which is expected to be never returned + */ + export interface Infallible {} +} + +export namespace reflectapi_demo { + export namespace tests { + export namespace serde { + export type TestOptionalNewtype = string | null; + + export type TestUnitMarker = null; + + export namespace input { + /** + * Each type already renders with `None` in it, so the omission default + * must not add another. + */ + export interface TestStructWithSerdeDefaultNoneTypes { + marker?: reflectapi_demo.tests.serde.TestUnitMarker; + nothing?: null; + optional_newtype?: reflectapi_demo.tests.serde.TestOptionalNewtype; + } + } + + export namespace output { + /** + * Each type already renders with `None` in it, so the omission default + * must not add another. + */ + export interface TestStructWithSerdeDefaultNoneTypes { + marker: reflectapi_demo.tests.serde.TestUnitMarker; + nothing: null; + optional_newtype: reflectapi_demo.tests.serde.TestOptionalNewtype; + } + } + } + } +} + +namespace __implementation { + + function inout_test(client: Client) { + return ( + input: reflectapi_demo.tests.serde.input.TestStructWithSerdeDefaultNoneTypes, + headers: {}, + options?: RequestOptions, + ) => + __request< + reflectapi_demo.tests.serde.input.TestStructWithSerdeDefaultNoneTypes, + {}, + reflectapi_demo.tests.serde.output.TestStructWithSerdeDefaultNoneTypes, + {} + >(client, "/inout_test", input, headers, options); + } +} diff --git a/reflectapi-demo/src/tests/snapshots/reflectapi_demo__tests__serde__struct_with_serde_default_none_types-3.snap b/reflectapi-demo/src/tests/snapshots/reflectapi_demo__tests__serde__struct_with_serde_default_none_types-3.snap new file mode 100644 index 00000000..1f802586 --- /dev/null +++ b/reflectapi-demo/src/tests/snapshots/reflectapi_demo__tests__serde__struct_with_serde_default_none_types-3.snap @@ -0,0 +1,87 @@ +--- +source: reflectapi-demo/src/tests/serde.rs +expression: "super :: into_rust_code :: < TestStructWithSerdeDefaultNoneTypes > ()" +--- +// DO NOT MODIFY THIS FILE MANUALLY +// This file was generated by reflectapi-cli +// +// Schema name: + +#![allow(non_camel_case_types)] +#![allow(dead_code)] + +pub use interface::Interface; +pub use reflectapi::rt::*; + +pub mod interface { + + #[derive(Debug)] + pub struct Interface { + client: C, + } + + impl Interface { + pub fn new(client: C) -> Self { + Self { client } + } + pub async fn inout_test(&self, input: super::types::reflectapi_demo::tests::serde::input::TestStructWithSerdeDefaultNoneTypes, headers: reflectapi::Empty) + -> Result>{ + reflectapi::rt::__request_impl(&self.client, "/inout_test", input, headers).await + } + } + + #[cfg(feature = "reqwest")] + impl Interface> { + /// Convenience: build the client backed by a bare `reqwest::Client` + /// and the given base URL. Hides the + /// [`reflectapi::rt::ReqwestClient`] adapter so callers don't need + /// to name it. + pub fn try_new( + client: reqwest::Client, + base_url: reflectapi::rt::Url, + ) -> std::result::Result { + Ok(Self::new(reflectapi::rt::ReqwestClient::try_new( + client, base_url, + )?)) + } + } +} +pub mod types { + pub mod reflectapi_demo { + pub mod tests { + pub mod serde { + + pub type TestOptionalNewtype = std::option::Option; + + #[derive(Debug, serde::Deserialize, serde::Serialize)] + pub struct TestUnitMarker; + + pub mod input { + + /// Each type already renders with `None` in it, so the omission default + /// must not add another. + #[derive(Debug, serde::Serialize)] + pub struct TestStructWithSerdeDefaultNoneTypes { + #[serde(default = "Default::default")] + pub marker: super::super::super::super::reflectapi_demo::tests::serde::TestUnitMarker, + #[serde(default = "Default::default")] + pub nothing: (), + #[serde(default = "Default::default")] + pub optional_newtype: super::super::super::super::reflectapi_demo::tests::serde::TestOptionalNewtype, +} + } + pub mod output { + + /// Each type already renders with `None` in it, so the omission default + /// must not add another. + #[derive(Debug, serde::Deserialize)] + pub struct TestStructWithSerdeDefaultNoneTypes { + pub marker: super::super::super::super::reflectapi_demo::tests::serde::TestUnitMarker, + pub nothing: (), + pub optional_newtype: super::super::super::super::reflectapi_demo::tests::serde::TestOptionalNewtype, +} + } + } + } + } +} diff --git a/reflectapi-demo/src/tests/snapshots/reflectapi_demo__tests__serde__struct_with_serde_default_none_types-4.snap b/reflectapi-demo/src/tests/snapshots/reflectapi_demo__tests__serde__struct_with_serde_default_none_types-4.snap new file mode 100644 index 00000000..2bdbb999 --- /dev/null +++ b/reflectapi-demo/src/tests/snapshots/reflectapi_demo__tests__serde__struct_with_serde_default_none_types-4.snap @@ -0,0 +1,115 @@ +--- +source: reflectapi-demo/src/tests/serde.rs +expression: "reflectapi :: codegen :: openapi :: Spec :: from(& schema)" +--- +{ + "openapi": "3.1.0", + "info": { + "title": "", + "description": "", + "version": "1.0.0" + }, + "paths": { + "/inout_test": { + "description": "", + "post": { + "operationId": "inout_test", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/reflectapi_demo.tests.serde.input.TestStructWithSerdeDefaultNoneTypes" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "200 OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/reflectapi_demo.tests.serde.output.TestStructWithSerdeDefaultNoneTypes" + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "reflectapi_demo.tests.serde.TestOptionalNewtype": { + "type": "array", + "prefixItems": [ + { + "oneOf": [ + { + "description": "Null", + "type": "null" + }, + { + "$ref": "#/components/schemas/std.string.String" + } + ] + } + ] + }, + "reflectapi_demo.tests.serde.TestUnitMarker": { + "type": "array", + "prefixItems": [ + { + "$ref": "#/components/schemas/std.tuple.Tuple0" + } + ] + }, + "reflectapi_demo.tests.serde.input.TestStructWithSerdeDefaultNoneTypes": { + "description": "Each type already renders with `None` in it, so the omission default\nmust not add another.", + "type": "object", + "title": "reflectapi_demo.tests.serde.input.TestStructWithSerdeDefaultNoneTypes", + "properties": { + "marker": { + "$ref": "#/components/schemas/reflectapi_demo.tests.serde.TestUnitMarker" + }, + "nothing": { + "$ref": "#/components/schemas/std.tuple.Tuple0" + }, + "optional_newtype": { + "$ref": "#/components/schemas/reflectapi_demo.tests.serde.TestOptionalNewtype" + } + } + }, + "reflectapi_demo.tests.serde.output.TestStructWithSerdeDefaultNoneTypes": { + "description": "Each type already renders with `None` in it, so the omission default\nmust not add another.", + "type": "object", + "title": "reflectapi_demo.tests.serde.output.TestStructWithSerdeDefaultNoneTypes", + "required": [ + "marker", + "nothing", + "optional_newtype" + ], + "properties": { + "marker": { + "$ref": "#/components/schemas/reflectapi_demo.tests.serde.TestUnitMarker" + }, + "nothing": { + "$ref": "#/components/schemas/std.tuple.Tuple0" + }, + "optional_newtype": { + "$ref": "#/components/schemas/reflectapi_demo.tests.serde.TestOptionalNewtype" + } + } + }, + "std.string.String": { + "description": "UTF-8 encoded string", + "type": "string" + }, + "std.tuple.Tuple0": { + "description": "Unit type", + "type": "null" + } + } + } +} diff --git a/reflectapi-demo/src/tests/snapshots/reflectapi_demo__tests__serde__struct_with_serde_default_none_types-5.snap b/reflectapi-demo/src/tests/snapshots/reflectapi_demo__tests__serde__struct_with_serde_default_none_types-5.snap new file mode 100644 index 00000000..d4703607 --- /dev/null +++ b/reflectapi-demo/src/tests/snapshots/reflectapi_demo__tests__serde__struct_with_serde_default_none_types-5.snap @@ -0,0 +1,201 @@ +--- +source: reflectapi-demo/src/tests/serde.rs +expression: "super :: into_python_code :: < TestStructWithSerdeDefaultNoneTypes > ()" +--- +""" +DO NOT MODIFY THIS FILE MANUALLY +This file was generated by reflectapi-cli + +Schema name: +""" + +from __future__ import annotations + + +# Standard library imports +from typing import Annotated, Any, Generic, Optional, TypeVar, Union + +# Third-party imports +from pydantic import BaseModel, ConfigDict, Field + +# Runtime imports +from reflectapi_runtime import AsyncClientBase, ClientBase, ApiResponse +from reflectapi_runtime import ReflectapiEmpty +from reflectapi_runtime import ReflectapiInfallible +from reflectapi_runtime import ReflectapiPartialModel + + +class ReflectapiDemoTestsSerdeInputTestStructWithSerdeDefaultNoneTypes( + ReflectapiPartialModel +): + """Each type already renders with `None` in it, so the omission default + must not add another.""" + + model_config = ConfigDict( + extra="ignore", + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + defer_build=True, + ) + + marker: None = Field(default=None) + nothing: None = Field(default=None) + optional_newtype: str | None = None + + +class ReflectapiDemoTestsSerdeOutputTestStructWithSerdeDefaultNoneTypes(BaseModel): + """Each type already renders with `None` in it, so the omission default + must not add another.""" + + model_config = ConfigDict( + extra="ignore", populate_by_name=True, protected_namespaces=(), defer_build=True + ) + + marker: None + nothing: None + optional_newtype: str | None + + +# Namespace classes for dotted access to types +class reflectapi_demo: + """Namespace for reflectapi_demo types.""" + + class tests: + """Namespace for tests types.""" + + class serde: + """Namespace for serde types.""" + + class input: + """Namespace for input types.""" + + TestStructWithSerdeDefaultNoneTypes = ( + ReflectapiDemoTestsSerdeInputTestStructWithSerdeDefaultNoneTypes + ) + + class output: + """Namespace for output types.""" + + TestStructWithSerdeDefaultNoneTypes = ( + ReflectapiDemoTestsSerdeOutputTestStructWithSerdeDefaultNoneTypes + ) + + +class AsyncInoutClient: + """Async client for inout operations.""" + + def __init__(self, client: AsyncClientBase) -> None: + self._client = client + + async def test( + self, + data: Optional[ + reflectapi_demo.tests.serde.input.TestStructWithSerdeDefaultNoneTypes + ] = None, + ) -> ApiResponse[ + reflectapi_demo.tests.serde.output.TestStructWithSerdeDefaultNoneTypes + ]: + """ + + Args: + data: Request data for the test operation. + + Returns: + ApiResponse[reflectapi_demo.tests.serde.output.TestStructWithSerdeDefaultNoneTypes]: Response containing reflectapi_demo.tests.serde.output.TestStructWithSerdeDefaultNoneTypes data + """ + path = "/inout_test" + + params: dict[str, Any] = {} + return await self._client._make_request( + path, + params=params if params else None, + json_model=data, + response_model=reflectapi_demo.tests.serde.output.TestStructWithSerdeDefaultNoneTypes, + ) + + +class AsyncClient(AsyncClientBase): + """Async client for the API.""" + + def __init__( + self, + base_url: str, + **kwargs: Any, + ) -> None: + super().__init__(base_url, **kwargs) + + self.inout: AsyncInoutClient = AsyncInoutClient(self) + + +class InoutClient: + """Synchronous client for inout operations.""" + + def __init__(self, client: ClientBase) -> None: + self._client = client + + def test( + self, + data: Optional[ + reflectapi_demo.tests.serde.input.TestStructWithSerdeDefaultNoneTypes + ] = None, + ) -> ApiResponse[ + reflectapi_demo.tests.serde.output.TestStructWithSerdeDefaultNoneTypes + ]: + """ + + Args: + data: Request data for the test operation. + + Returns: + ApiResponse[reflectapi_demo.tests.serde.output.TestStructWithSerdeDefaultNoneTypes]: Response containing reflectapi_demo.tests.serde.output.TestStructWithSerdeDefaultNoneTypes data + """ + path = "/inout_test" + + params: dict[str, Any] = {} + return self._client._make_request( + path, + params=params if params else None, + json_model=data, + response_model=reflectapi_demo.tests.serde.output.TestStructWithSerdeDefaultNoneTypes, + ) + + +class Client(ClientBase): + """Synchronous client for the API.""" + + def __init__( + self, + base_url: str, + **kwargs: Any, + ) -> None: + super().__init__(base_url, **kwargs) + + self.inout: InoutClient = InoutClient(self) + + +# External type definitions +StdNumNonZeroU32 = Annotated[int, "Rust NonZero u32 type"] +StdNumNonZeroU64 = Annotated[int, "Rust NonZero u64 type"] +StdNumNonZeroI32 = Annotated[int, "Rust NonZero i32 type"] +StdNumNonZeroI64 = Annotated[int, "Rust NonZero i64 type"] + +# Rebuild models to resolve forward references +_rebuild_errors: list[str] = [] +for _model in [ + ReflectapiDemoTestsSerdeInputTestStructWithSerdeDefaultNoneTypes, + ReflectapiDemoTestsSerdeOutputTestStructWithSerdeDefaultNoneTypes, +]: + if not hasattr(_model, "model_rebuild"): + continue + try: + _model.model_rebuild() + except Exception as _exc: + _rebuild_errors.append(f" - {_model.__name__}: {type(_exc).__name__}: {_exc}") +if _rebuild_errors: + raise RuntimeError( + "reflectapi: failed to rebuild " + + str(len(_rebuild_errors)) + + " generated model(s). This usually means the codegen emitted an annotation pointing at a symbol that was never defined (a dangling type reference). Fix the codegen rather than catching this error.\n" + + "\n".join(_rebuild_errors) + ) diff --git a/reflectapi-demo/src/tests/snapshots/reflectapi_demo__tests__serde__struct_with_serde_default_none_types.snap b/reflectapi-demo/src/tests/snapshots/reflectapi_demo__tests__serde__struct_with_serde_default_none_types.snap new file mode 100644 index 00000000..6d00d8e2 --- /dev/null +++ b/reflectapi-demo/src/tests/snapshots/reflectapi_demo__tests__serde__struct_with_serde_default_none_types.snap @@ -0,0 +1,253 @@ +--- +source: reflectapi-demo/src/tests/serde.rs +expression: schema +--- +{ + "name": "", + "functions": [ + { + "name": "inout_test", + "path": "", + "input_type": { + "name": "reflectapi_demo::tests::serde::input::TestStructWithSerdeDefaultNoneTypes" + }, + "output_kind": "complete", + "output_type": { + "name": "reflectapi_demo::tests::serde::output::TestStructWithSerdeDefaultNoneTypes" + }, + "serialization": [ + "json", + "msgpack" + ] + } + ], + "input_types": { + "types": [ + { + "kind": "struct", + "name": "reflectapi::Empty", + "description": "Struct object with no fields", + "fields": "none" + }, + { + "kind": "struct", + "name": "reflectapi_demo::tests::serde::TestOptionalNewtype", + "fields": { + "unnamed": [ + { + "name": "0", + "type": { + "name": "std::option::Option", + "arguments": [ + { + "name": "std::string::String" + } + ] + }, + "required": true + } + ] + } + }, + { + "kind": "struct", + "name": "reflectapi_demo::tests::serde::input::TestStructWithSerdeDefaultNoneTypes", + "description": "Each type already renders with `None` in it, so the omission default\nmust not add another.", + "fields": { + "named": [ + { + "name": "marker", + "type": { + "name": "reflectapi_demo::tests::serde::TestUnitMarker" + } + }, + { + "name": "nothing", + "type": { + "name": "std::tuple::Tuple0" + } + }, + { + "name": "optional_newtype", + "type": { + "name": "reflectapi_demo::tests::serde::TestOptionalNewtype" + } + } + ] + } + }, + { + "kind": "struct", + "name": "reflectapi_demo::tests::serde::TestUnitMarker", + "fields": { + "unnamed": [ + { + "name": "0", + "type": { + "name": "std::tuple::Tuple0" + } + } + ] + } + }, + { + "kind": "enum", + "name": "std::option::Option", + "description": "Optional nullable type", + "parameters": [ + { + "name": "T" + } + ], + "representation": "none", + "variants": [ + { + "name": "None", + "description": "The value is not provided, i.e. null", + "fields": "none" + }, + { + "name": "Some", + "description": "The value is provided and set to some value", + "fields": { + "unnamed": [ + { + "name": "0", + "type": { + "name": "T" + } + } + ] + } + } + ] + }, + { + "kind": "primitive", + "name": "std::string::String", + "description": "UTF-8 encoded string" + }, + { + "kind": "primitive", + "name": "std::tuple::Tuple0", + "description": "Unit type" + } + ] + }, + "output_types": { + "types": [ + { + "kind": "struct", + "name": "reflectapi::Infallible", + "description": "Error object which is expected to be never returned", + "fields": "none" + }, + { + "kind": "struct", + "name": "reflectapi_demo::tests::serde::TestOptionalNewtype", + "fields": { + "unnamed": [ + { + "name": "0", + "type": { + "name": "std::option::Option", + "arguments": [ + { + "name": "std::string::String" + } + ] + }, + "required": true + } + ] + } + }, + { + "kind": "struct", + "name": "reflectapi_demo::tests::serde::output::TestStructWithSerdeDefaultNoneTypes", + "description": "Each type already renders with `None` in it, so the omission default\nmust not add another.", + "fields": { + "named": [ + { + "name": "marker", + "type": { + "name": "reflectapi_demo::tests::serde::TestUnitMarker" + }, + "required": true + }, + { + "name": "nothing", + "type": { + "name": "std::tuple::Tuple0" + }, + "required": true + }, + { + "name": "optional_newtype", + "type": { + "name": "reflectapi_demo::tests::serde::TestOptionalNewtype" + }, + "required": true + } + ] + } + }, + { + "kind": "struct", + "name": "reflectapi_demo::tests::serde::TestUnitMarker", + "fields": { + "unnamed": [ + { + "name": "0", + "type": { + "name": "std::tuple::Tuple0" + } + } + ] + } + }, + { + "kind": "enum", + "name": "std::option::Option", + "description": "Optional nullable type", + "parameters": [ + { + "name": "T" + } + ], + "representation": "none", + "variants": [ + { + "name": "None", + "description": "The value is not provided, i.e. null", + "fields": "none" + }, + { + "name": "Some", + "description": "The value is provided and set to some value", + "fields": { + "unnamed": [ + { + "name": "0", + "type": { + "name": "T" + } + } + ] + } + } + ] + }, + { + "kind": "primitive", + "name": "std::string::String", + "description": "UTF-8 encoded string" + }, + { + "kind": "primitive", + "name": "std::tuple::Tuple0", + "description": "Unit type" + } + ] + } +} diff --git a/reflectapi-demo/tests/codegen_coverage.rs b/reflectapi-demo/tests/codegen_coverage.rs index dba8e09f..7b1c4869 100644 --- a/reflectapi-demo/tests/codegen_coverage.rs +++ b/reflectapi-demo/tests/codegen_coverage.rs @@ -75,6 +75,14 @@ async fn deprecated_shapes( Ok(request) } +async fn omittable_units( + _: Arc, + _request: coverage::OmittableUnits, + _headers: reflectapi::Empty, +) -> Result { + Ok(reflectapi::Empty {}) +} + fn builder() -> reflectapi::Builder> { reflectapi::Builder::new() .name("Codegen coverage") @@ -87,6 +95,10 @@ fn builder() -> reflectapi::Builder> { b.name("coverage.edges") .description("Coverage fixtures for codegen edge cases") }) + .route(omittable_units, |b| { + b.name("coverage.omittable_units") + .description("Omittable fields whose type serializes as null") + }) .route(wire_echo, |b| { b.name("coverage.wire") .description("Echoes its request, for wire-format round trips") @@ -421,6 +433,18 @@ mod coverage { pub count: u32, } + // ---- Omittable fields whose type serializes as null ---- + #[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize, reflectapi::Input)] + pub struct UnitMarker; + + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, reflectapi::Input)] + pub struct OmittableUnits { + #[serde(default)] + pub marker: UnitMarker, + #[serde(default)] + pub nothing: (), + } + #[derive(serde::Serialize, serde::Deserialize, reflectapi::Input, reflectapi::Output)] pub struct CoverageRequest { pub keywords: PyKeywordFields, diff --git a/reflectapi/src/codegen/python.rs b/reflectapi/src/codegen/python.rs index 2f077c27..8f2749dc 100644 --- a/reflectapi/src/codegen/python.rs +++ b/reflectapi/src/codegen/python.rs @@ -100,7 +100,12 @@ fn resolve_field_optionality( (true, false) => ( true, Some("None".to_string()), - format!("{field_type} | None"), + if top_level_alternatives(&field_type).contains(&"None") { + // `None | None` doesn't evaluate: a unit type already is None. + field_type + } else { + format!("{field_type} | None") + }, reject_null, ), (false, _) => (false, None, field_type, false), @@ -126,6 +131,27 @@ fn is_partial_field(field: &reflectapi_schema::Field) -> bool { !field.required && field.type_ref.name == "reflectapi::Option" } +/// The `|`-separated members of an annotation, outside any brackets. +fn top_level_alternatives(annotation: &str) -> Vec<&str> { + let annotation = annotation.trim(); + let mut depth = 0usize; + let mut start = 0usize; + let mut alternatives = Vec::new(); + for (index, character) in annotation.char_indices() { + match character { + '[' | '(' => depth += 1, + ']' | ')' => depth = depth.saturating_sub(1), + '|' if depth == 0 => { + alternatives.push(annotation[start..index].trim()); + start = index + 1; + } + _ => {} + } + } + alternatives.push(annotation[start..].trim()); + alternatives +} + struct PythonTypeMapping { type_hint: &'static str, imports: &'static [&'static str], @@ -7077,7 +7103,16 @@ pub mod templates { } }); - if desc.is_some() || field.alias.is_some() || deprecated.is_some() { + // Pydantic 2.12.0-2.12.2 on Python 3.14 rejects `x: None = None` + // under postponed annotations: it mistakes the evaluated + // annotation for the default and reports a name clash. + let none_annotation = field.type_annotation.trim() == "None" + && (field.optional || field.default_value.is_some()); + if desc.is_some() + || field.alias.is_some() + || deprecated.is_some() + || none_annotation + { // Need Field() with named arguments write!(s, " = Field(").unwrap(); let mut args = Vec::new(); @@ -9059,6 +9094,35 @@ mod tests { }; use crate::TypeReference; + #[test] + fn omittable_field_of_a_unit_type_is_none_once() { + let schema: crate::Schema = serde_json::from_value(serde_json::json!({ + "name": "units", + "input_types": {"types": [ + {"kind": "primitive", "name": "std::tuple::Tuple0"}, + {"kind": "struct", "name": "Marker", "fields": "none"}, + {"kind": "struct", "name": "Request", "fields": {"named": [ + {"name": "nothing", "type": {"name": "std::tuple::Tuple0"}}, + {"name": "marker", "type": {"name": "Marker"}} + ]}} + ]} + })) + .unwrap(); + let python = super::generate( + schema, + &Config { + format: false, + ..Config::default() + }, + ) + .unwrap(); + assert!( + python.contains("nothing: None = Field(default=None)\n"), + "{python}" + ); + assert!(!python.contains("None | None"), "{python}"); + } + #[test] fn optional_nonnullable_fields_reject_explicit_null_without_validating_defaults() { let schema: crate::Schema = serde_json::from_value(serde_json::json!({