Repository navigation
[BUG][JAVA][okhttp-gson] add regression tests for null additionalProperties values #25611
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
Open
Inf1mum
wants to merge
5
commits into
OpenAPITools:master
Choose a base branch
from
Inf1mum:fix/24393-gson-null-additional-properties
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+203
−1
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
0074031
fix(java): add gson JsonNull regression tests for null additionalProp…
Inf1mum a48efba
chore: update sample test fingerprint record for JSONTest
Inf1mum 349bca4
test: run gson null additionalProperties round trip through the clien…
Inf1mum 1ebfe98
fix(maven): drop direct test-scope jsr305, keep transitive compile-sc…
Inf1mum 7bf3c79
fix(maven): pin test okio to 3.2.0 whose Kotlin metadata the test com…
Inf1mum 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
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
126 changes: 126 additions & 0 deletions
126
...c/test/java/org/openapitools/codegen/java/JavaOkHttpGsonNullAdditionalPropertiesTest.java
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,126 @@ | ||
| /* | ||
| * Copyright 2026 OpenAPI-Generator Contributors (https://openapi-generator.tech) | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
| package org.openapitools.codegen.java; | ||
|
|
||
| import com.google.gson.Gson; | ||
| import com.google.gson.JsonElement; | ||
| import com.google.gson.JsonObject; | ||
| import io.gsonfire.GsonFireBuilder; | ||
| import okio.ByteString; | ||
| import org.openapitools.codegen.DefaultGenerator; | ||
| import org.openapitools.codegen.config.CodegenConfigurator; | ||
| import org.testng.annotations.Test; | ||
|
|
||
| import javax.tools.ToolProvider; | ||
| import java.io.ByteArrayOutputStream; | ||
| import java.io.File; | ||
| import java.net.URL; | ||
| import java.net.URLClassLoader; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.nio.file.Path; | ||
| import java.nio.file.Paths; | ||
| import java.util.Arrays; | ||
| import java.util.Collections; | ||
| import java.util.Map; | ||
|
|
||
| import static org.openapitools.codegen.TestUtils.newTempFolder; | ||
| import static org.testng.Assert.*; | ||
|
|
||
| public class JavaOkHttpGsonNullAdditionalPropertiesTest { | ||
|
|
||
| @Test | ||
| public void testNullAdditionalPropertiesRoundTrip() throws Exception { | ||
| Path output = newTempFolder(); | ||
| CodegenConfigurator config = new CodegenConfigurator().setGeneratorName("java").setLibrary("okhttp-gson") | ||
| .setInputSpec("src/test/resources/3_0/java/okhttp-gson-null-additional-properties.yaml") | ||
| .setOutputDir(output.toString()) | ||
| .addGlobalProperty("models", "").addGlobalProperty("supportingFiles", "") | ||
| .addGlobalProperty("modelDocs", "false").addGlobalProperty("modelTests", "false"); | ||
| new DefaultGenerator().opts(config.toClientOptInput()).generate(); | ||
|
|
||
| // Compile the generated client sources (the JSON factory and the model) against the real | ||
| // Gson runtime, mirroring the sample-side JSONTest setup: the model's CustomTypeAdapterFactory | ||
| // is registered by the generated JSON class, and JSON.java plus the generated model need the | ||
| // client's runtime dependencies (gson-fire, okio, jsr305 @Nullable) on the compile classpath. | ||
| Path generatedSource = output.resolve("src/main/java"); | ||
| Path jsonSource = generatedSource.resolve("org/openapitools/client/JSON.java"); | ||
| Path modelSource = generatedSource.resolve("org/openapitools/client/model/AdditionalPropertiesModel.java"); | ||
| String classpath = Paths.get(Gson.class.getProtectionDomain().getCodeSource().getLocation().toURI()) | ||
| + File.pathSeparator | ||
| + Paths.get(GsonFireBuilder.class.getProtectionDomain().getCodeSource().getLocation().toURI()) | ||
| + File.pathSeparator | ||
| + Paths.get(ByteString.class.getProtectionDomain().getCodeSource().getLocation().toURI()) | ||
| + File.pathSeparator | ||
| + Paths.get(javax.annotation.Nullable.class.getProtectionDomain().getCodeSource().getLocation().toURI()) | ||
| + File.pathSeparator | ||
| + Paths.get(kotlin.jvm.internal.Intrinsics.class.getProtectionDomain().getCodeSource().getLocation().toURI()); | ||
| ByteArrayOutputStream diagnostics = new ByteArrayOutputStream(); | ||
| assertNotNull(ToolProvider.getSystemJavaCompiler()); | ||
| assertEquals(ToolProvider.getSystemJavaCompiler().run(null, diagnostics, diagnostics, | ||
| "--release", "8", "-classpath", classpath, "-d", output.toString(), | ||
| jsonSource.toString(), modelSource.toString()), | ||
| 0, diagnostics.toString(StandardCharsets.UTF_8)); | ||
|
|
||
| try (URLClassLoader loader = new URLClassLoader(new URL[]{output.toUri().toURL()}, getClass().getClassLoader())) { | ||
| Class<?> jsonType = loader.loadClass("org.openapitools.client.JSON"); | ||
| Class<?> modelType = loader.loadClass("org.openapitools.client.model.AdditionalPropertiesModel"); | ||
| // the client's configured Gson (JSON.getGson), not a hand-built one: its static | ||
| // initializer registers the generated CustomTypeAdapterFactory for the model | ||
| Gson gson = (Gson) jsonType.getMethod("getGson").invoke(null); | ||
| // same pattern as the sample JSONTest: serializeNulls so named nulls are written | ||
| Gson gsonWithNulls = gson.newBuilder().serializeNulls().create(); | ||
|
|
||
| // build the model with a null undeclared-property value | ||
| Object model = modelType.getConstructor().newInstance(); | ||
| modelType.getMethod("setName", String.class).invoke(model, "x"); | ||
| modelType.getMethod("putAdditionalProperty", String.class, Object.class).invoke(model, "unknownField", null); | ||
|
|
||
| // write: a null undeclared-property value used to throw | ||
| // IllegalStateException("Not a JSON Object: null") in the CustomTypeAdapterFactory; | ||
| // the ApiClient's writer omits named nulls, but must not throw | ||
| assertEquals(gson.toJson(model, modelType), "{\"name\":\"x\"}"); | ||
|
|
||
| // serialize through the client's Gson and inspect the tree | ||
| String serialized = gsonWithNulls.toJson(model, modelType); | ||
| assertEquals(serialized, "{\"name\":\"x\",\"unknownField\":null}"); | ||
| JsonObject obj = gsonWithNulls.toJsonTree(model, modelType).getAsJsonObject(); | ||
| assertTrue(obj.get("unknownField").isJsonNull(), "A null additional property must be written as JSON null"); | ||
| assertEquals(obj.get("name").getAsString(), "x"); | ||
| assertNull(obj.get("additionalProperties"), "The raw additionalProperties field must be removed from the output"); | ||
|
|
||
| // full round trip: deserialize the resulting JSON (not a hand-written string) | ||
| Object deserialized = gsonWithNulls.fromJson(serialized, modelType); | ||
| assertEquals(modelType.getMethod("getName").invoke(deserialized), "x"); | ||
| Map<?, ?> props = (Map<?, ?>) modelType.getMethod("getAdditionalProperties").invoke(deserialized); | ||
| assertTrue(props.containsKey("unknownField"), "A JSON null undeclared property must be preserved by the round trip"); | ||
| assertNull(props.get("unknownField")); | ||
|
|
||
| // serialize again: the round trip must be byte-stable | ||
| assertEquals(gsonWithNulls.toJson(deserialized, modelType), serialized, "Re-serialization must be byte-stable"); | ||
| assertEquals(gson.toJson(deserialized, modelType), "{\"name\":\"x\"}"); | ||
|
|
||
| // keep the existing behavior for non-null additional properties | ||
| modelType.getMethod("putAdditionalProperty", String.class, Object.class).invoke(model, "extra", "e"); | ||
| modelType.getMethod("putAdditionalProperty", String.class, Object.class).invoke(model, "list", Arrays.asList("a", "b")); | ||
| modelType.getMethod("putAdditionalProperty", String.class, Object.class).invoke(model, "nested", Collections.singletonMap("k", "v")); | ||
| JsonElement tree = gsonWithNulls.toJsonTree(model, modelType); | ||
| obj = tree.getAsJsonObject(); | ||
| assertEquals(obj.get("extra").getAsString(), "e"); | ||
| assertTrue(obj.get("list").isJsonArray()); | ||
| assertTrue(obj.get("nested").isJsonObject()); | ||
| } | ||
| } | ||
| } |
18 changes: 18 additions & 0 deletions
18
...openapi-generator/src/test/resources/3_0/java/okhttp-gson-null-additional-properties.yaml
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,18 @@ | ||
| openapi: 3.0.3 | ||
| info: {title: t, version: '1'} | ||
| paths: | ||
| /m: | ||
| get: | ||
| responses: | ||
| '200': | ||
| description: ok | ||
| content: | ||
| application/json: | ||
| schema: {$ref: '#/components/schemas/AdditionalPropertiesModel'} | ||
| components: | ||
| schemas: | ||
| AdditionalPropertiesModel: | ||
| type: object | ||
| properties: | ||
| name: {type: string} | ||
| additionalProperties: true |
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P3:
deserializedis populated from unrelated hard-coded JSON, so this does not exercise the claimed serialize→deserialize→serialize path. Parse the serialized output instead, and initializemap_propertyonmodelif that field must remain asserted.Prompt for AI agents
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed in 349bca4: the generator-side test (JavaOkHttpGsonNullAdditionalPropertiesTest) now runs the full serialize -> deserialize -> serialize round-trip through the client's configured Gson. It generates the client (model + supporting JSON factory), compiles the generated sources against the real Gson runtime (gson-fire, okio and jsr305 added as test-scoped dependencies of the generator module) and takes the Gson from the generated JSON.getGson() instead of a hand-built builder over a model stub. A model instance with a null-valued additionalProperties entry is serialized, the resulting JSON is fed back into fromJson, the null entry is asserted to survive the round trip, and re-serialization is asserted byte-stable; the existing no-throw-on-serialize assertion is kept. The generator-side test and the sample JSONTest (34 tests) both pass locally.