() {
+ }.getType();
+
+ // Act
+ byte[] actualDeserializedBytes = json.deserialize(serializedBytesWithQuotes, type);
+
+ // Assert
+ assertEquals(
+ expectedBytesAsString, new String(actualDeserializedBytes, StandardCharsets.UTF_8));
+ }
+
+ @Test
+ public void testRequiredFieldException() {
+ IllegalArgumentException thrown = Assertions.assertThrows(IllegalArgumentException.class, () -> {
+ // test json string missing required field(s) to ensure exception is thrown
+ Gson gson = json.getGson();
+ //Gson gson = new GsonBuilder()
+ // .registerTypeAdapter(Pet.class, new Pet.CustomDeserializer())
+ // .create();
+ String json = "{\"id\": 5847, \"name\":\"tag test 1\"}"; // missing photoUrls (required field)
+ //String json = "{\"id2\": 5847, \"name\":\"tag test 1\"}";
+ //String json = "{\"id\": 5847}";
+ Pet p = gson.fromJson(json, Pet.class);
+ });
+
+ Assertions.assertEquals("The required field `photoUrls` is not found in the JSON string: {\"id\":5847,\"name\":\"tag test 1\"}", thrown.getMessage());
+ }
+
+ @Test
+ @Disabled("No longer need the following test as additional field(s) should be stored in `additionalProperties`")
+ public void testAdditionalFieldException() {
+ IllegalArgumentException thrown = Assertions.assertThrows(IllegalArgumentException.class, () -> {
+ // test json string with additional field(s) to ensure exception is thrown
+ Gson gson = json.getGson();
+ String json = "{\"id\": 5847, \"name\":\"tag test 1\", \"new-field\": true}";
+ org.openapitools.client.model.Tag t = gson.fromJson(json, org.openapitools.client.model.Tag.class);
+ });
+
+ Assertions.assertEquals("The field `new-field` in the JSON string is not defined in the `Tag` properties. JSON: {\"id\":5847,\"name\":\"tag test 1\",\"new-field\":true}", thrown.getMessage());
+ }
+
+ @Test
+ public void testCustomDeserializer() {
+ // test the custom deserializer to ensure it can deserialize json payload into objects
+ Gson gson = json.getGson();
+ //Gson gson = new GsonBuilder()
+ // .registerTypeAdapter(Tag.class, new Tag.CustomDeserializer())
+ // .create();
+ // id and name
+ String json = "{\"id\": 5847, \"name\":\"tag test 1\"}";
+ org.openapitools.client.model.Tag t = gson.fromJson(json, org.openapitools.client.model.Tag.class);
+ assertEquals(t.getName(), "tag test 1");
+ assertEquals(t.getId(), Long.valueOf(5847L));
+
+ // name only
+ String json2 = "{\"name\":\"tag test 1\"}";
+ org.openapitools.client.model.Tag t2 = gson.fromJson(json2, org.openapitools.client.model.Tag.class);
+ assertEquals(t2.getName(), "tag test 1");
+ assertEquals(t2.getId(), null);
+
+ // with all required fields
+ String json3 = "{\"id\": 5847, \"name\":\"pet test 1\", \"photoUrls\": [\"https://a.com\", \"https://b.com\"]}";
+ Pet t3 = gson.fromJson(json3, Pet.class);
+ assertEquals(t3.getName(), "pet test 1");
+ assertEquals(t3.getId(), Long.valueOf(5847));
+
+ // with all required fields and tags (optional)
+ String json4 = "{\"id\": 5847, \"name\":\"pet test 1\", \"photoUrls\": [\"https://a.com\", \"https://b.com\"],\"tags\":[{\"id\":\"tag 123\"}]}";
+ Pet t4 = gson.fromJson(json3, Pet.class);
+ assertEquals(t4.getName(), "pet test 1");
+ assertEquals(t4.getId(), Long.valueOf(5847));
+ }
+
+ @Test
+ @Disabled("Unknown fields are now correctly deserialized into `additionalProperties`")
+ public void testUnknownFields() {
+ // test unknown fields in the payload
+ Gson gson = json.getGson();
+ // test Tag
+ String json5 = "{\"unknown_field\": 543, \"id\":\"tag 123\"}";
+ Exception exception5 = assertThrows(java.lang.IllegalArgumentException.class, () -> {
+ org.openapitools.client.model.Tag t5 = gson.fromJson(json5, org.openapitools.client.model.Tag.class);
+ });
+ assertTrue(exception5.getMessage().contains("The field `unknown_field` in the JSON string is not defined in the `Tag` properties. JSON: {\"unknown_field\":543,\"id\":\"tag 123\"}"));
+
+ // test Pet with invalid tags
+ String json6 = "{\"id\": 5847, \"name\":\"pet test 1\", \"photoUrls\": [\"https://a.com\", \"https://b.com\"],\"tags\":[{\"unknown_field\": 543, \"id\":\"tag 123\"}]}";
+ Exception exception6 = assertThrows(java.lang.IllegalArgumentException.class, () -> {
+ Pet t6 = gson.fromJson(json6, Pet.class);
+ });
+ assertTrue(exception6.getMessage().contains("The field `unknown_field` in the JSON string is not defined in the `Tag` properties. JSON: {\"unknown_field\":543,\"id\":\"tag 123\"}"));
+
+ // test Pet with invalid tags (required)
+ String json7 = "{\"id\": 5847, \"name\":\"pet test 1\", \"photoUrls\": [\"https://a.com\", \"https://b.com\"],\"tags\":[{\"unknown_field\": 543, \"id\":\"tag 123\"}]}";
+ Exception exception7 = assertThrows(java.lang.IllegalArgumentException.class, () -> {
+ PetWithRequiredTags t7 = gson.fromJson(json7, PetWithRequiredTags.class);
+ });
+ assertTrue(exception7.getMessage().contains("The field `unknown_field` in the JSON string is not defined in the `Tag` properties. JSON: {\"unknown_field\":543,\"id\":\"tag 123\"}"));
+
+ // test Pet with invalid tags (missing reqired)
+ String json8 = "{\"id\": 5847, \"name\":\"pet test 1\", \"photoUrls\": [\"https://a.com\", \"https://b.com\"]}";
+ Exception exception8 = assertThrows(java.lang.IllegalArgumentException.class, () -> {
+ PetWithRequiredTags t8 = gson.fromJson(json8, PetWithRequiredTags.class);
+ });
+ assertTrue(exception8.getMessage().contains("The required field `tags` is not found in the JSON string: {\"id\":5847,\"name\":\"pet test 1\",\"photoUrls\":[\"https://a.com\",\"https://b.com\"]}"));
+ }
+
+ /**
+ * Model tests for Pet
+ */
+ @Test
+ public void testPet() {
+ // test Pet
+ Pet model = new Pet();
+ model.setId(1029L);
+ model.setName("Dog");
+
+ Pet model2 = new Pet();
+ model2.setId(1029L);
+ model2.setName("Dog");
+
+ assertTrue(model.equals(model2));
+ }
+
+ // Obtained 22JAN2018 from stackoverflow answer by PuguaSoft
+ // https://stackoverflow.com/questions/11399491/java-timezone-offset
+ // Direct link https://stackoverflow.com/a/16680815/3166133
+ public static String getCurrentTimezoneOffset() {
+
+ TimeZone tz = TimeZone.getDefault();
+ Calendar cal = GregorianCalendar.getInstance(tz, Locale.ROOT);
+ int offsetInMillis = tz.getOffset(cal.getTimeInMillis());
+
+ String offset =
+ String.format(
+ Locale.ROOT,
+ "%02d:%02d",
+ Math.abs(offsetInMillis / 3600000),
+ Math.abs((offsetInMillis / 60000) % 60));
+ offset = (offsetInMillis >= 0 ? "+" : "-") + offset;
+
+ return offset;
+ }
+
+ /**
+ * Validate an anyOf schema can be deserialized into the expected class.
+ * The anyOf schema does not have a discriminator.
+ */
+ @Test
+ public void testAnyOfSchemaWithoutDiscriminator() throws Exception {
+ {
+ String str = "{ \"cultivar\": \"golden delicious\", \"origin\": \"japan\" }";
+
+ // make sure deserialization works for pojo object
+ Apple a = json.getGson().fromJson(str, Apple.class);
+ assertEquals(a.getCultivar(), "golden delicious");
+ assertEquals(a.getOrigin(), "japan");
+
+ GmFruit o = json.getGson().fromJson(str, GmFruit.class);
+ assertTrue(o.getActualInstance() instanceof Apple);
+ Apple inst = (Apple) o.getActualInstance();
+ assertEquals(inst.getCultivar(), "golden delicious");
+ assertEquals(inst.getOrigin(), "japan");
+ assertEquals(json.getGson().toJson(inst), "{\"cultivar\":\"golden delicious\",\"origin\":\"japan\"}");
+ assertEquals(inst.toJson(), "{\"cultivar\":\"golden delicious\",\"origin\":\"japan\"}");
+ assertEquals(json.getGson().toJson(o), "{\"cultivar\":\"golden delicious\",\"origin\":\"japan\"}");
+ assertEquals(o.toJson(), "{\"cultivar\":\"golden delicious\",\"origin\":\"japan\"}");
+
+ /* comment out the following as we've added "additionalProperties" support
+ String str2 = "{ \"origin_typo\": \"japan\" }";
+ // no match
+ Exception exception = assertThrows(java.lang.IllegalArgumentException.class, () -> {
+ Apple o3 = json.getGson().fromJson(str2, Apple.class);
+ });
+
+ // no match
+ Exception exception3 = assertThrows(java.lang.IllegalArgumentException.class, () -> {
+ Banana o2 = json.getGson().fromJson(str2, Banana.class);
+ });
+
+ // no match
+ Exception exception4 = assertThrows(com.google.gson.JsonSyntaxException.class, () -> {
+ GmFruit o2 = json.getGson().fromJson(str2, GmFruit.class);
+ });
+ */
+ }
+ }
+
+ /**
+ * Validate a oneOf schema can be deserialized into the expected class.
+ * The oneOf schema has a discriminator.
+ */
+ @Test
+ public void testOneOfSchemaWithDiscriminator() throws Exception {
+ {
+ String str = "{ \"className\": \"whale\", \"hasBaleen\": false, \"hasTeeth\": false }";
+
+ // make sure deserialization works for pojo object
+ Whale w = json.getGson().fromJson(str, Whale.class);
+ assertEquals(w.getClassName(), "whale");
+ assertEquals(w.getHasBaleen(), false);
+ assertEquals(w.getHasTeeth(), false);
+
+ Mammal o = json.getGson().fromJson(str, Mammal.class);
+ assertTrue(o.getActualInstance() instanceof Whale);
+ Whale inst = (Whale) o.getActualInstance();
+ assertEquals(inst.getClassName(), "whale");
+ assertEquals(inst.getHasBaleen(), false);
+ assertEquals(inst.getHasTeeth(), false);
+ assertEquals(json.getGson().toJson(inst), "{\"hasBaleen\":false,\"hasTeeth\":false,\"className\":\"whale\"}");
+ assertEquals(inst.toJson(), "{\"hasBaleen\":false,\"hasTeeth\":false,\"className\":\"whale\"}");
+ assertEquals(json.getGson().toJson(o), "{\"hasBaleen\":false,\"hasTeeth\":false,\"className\":\"whale\"}");
+ assertEquals(o.toJson(), "{\"hasBaleen\":false,\"hasTeeth\":false,\"className\":\"whale\"}");
+
+ String str2 = "{ \"className\": \"zebra\", \"type\": \"plains\" }";
+
+ // make sure deserialization works for pojo object
+ Zebra z = Zebra.fromJson(str2);
+ assertEquals(z.toJson(), "{\"type\":\"plains\",\"className\":\"zebra\"}");
+
+ Mammal o2 = json.getGson().fromJson(str2, Mammal.class);
+ assertTrue(o2.getActualInstance() instanceof Zebra);
+ Zebra inst2 = (Zebra) o2.getActualInstance();
+ assertEquals(json.getGson().toJson(inst2), "{\"type\":\"plains\",\"className\":\"zebra\"}");
+ assertEquals(inst2.toJson(), "{\"type\":\"plains\",\"className\":\"zebra\"}");
+ assertEquals(json.getGson().toJson(o2), "{\"type\":\"plains\",\"className\":\"zebra\"}");
+ assertEquals(o2.toJson(), "{\"type\":\"plains\",\"className\":\"zebra\"}");
+ }
+ {
+ // incorrect payload results in exception
+ String str = "{ \"cultivar\": \"golden delicious\", \"mealy\": false, \"garbage_prop\": \"abc\" }";
+ Exception exception = assertThrows(com.google.gson.JsonSyntaxException.class, () -> {
+ Mammal o = json.getGson().fromJson(str, Mammal.class);
+ });
+ //assertEquals("java.io.IOException: Failed deserialization for Mammal: 0 classes match result, expected 1. Detailed failure message for oneOf schemas: [Deserialization for Pig failed with `The JSON string is invalid for Pig with oneOf schemas: BasquePig, DanishPig. 0 class(es) match the result, expected 1. Detailed failure message for oneOf schemas: [Deserialization for BasquePig failed with `The required field `className` is not found in the JSON string: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}`., Deserialization for DanishPig failed with `The required field `className` is not found in the JSON string: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}`.]. JSON: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}`., Deserialization for Whale failed with `The required field `className` is not found in the JSON string: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}`., Deserialization for Zebra failed with `The required field `className` is not found in the JSON string: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}`.]. JSON: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}", exception.getMessage());
+ assertTrue(exception.getMessage().contains("java.io.IOException: Failed deserialization for Mammal"));
+ }
+ {
+ // Try to deserialize empty object. This should fail 'oneOf' because none will match
+ // whale or zebra.
+ String str = "{ }";
+ Exception exception = assertThrows(com.google.gson.JsonSyntaxException.class, () -> {
+ json.getGson().fromJson(str, Mammal.class);
+ });
+ //assertEquals("java.io.IOException: Failed deserialization for Mammal: 0 classes match result, expected 1. Detailed failure message for oneOf schemas: [Deserialization for Pig failed with `The JSON string is invalid for Pig with oneOf schemas: BasquePig, DanishPig. 0 class(es) match the result, expected 1. Detailed failure message for oneOf schemas: [Deserialization for BasquePig failed with `The required field `className` is not found in the JSON string: {}`., Deserialization for DanishPig failed with `The required field `className` is not found in the JSON string: {}`.]. JSON: {}`., Deserialization for Whale failed with `The required field `className` is not found in the JSON string: {}`., Deserialization for Zebra failed with `The required field `className` is not found in the JSON string: {}`.]. JSON: {}", exception.getMessage());
+ assertTrue(exception.getMessage().contains("java.io.IOException: Failed deserialization for Mammal"));
+ }
+ }
+
+ /**
+ * Test JSON validation method
+ */
+ @Test
+ public void testJsonValidation() throws Exception {
+ String str = "{ \"cultivar\": [\"golden delicious\"], \"mealy\": false }";
+ Exception exception = assertThrows(java.lang.IllegalArgumentException.class, () -> {
+ AppleReq a = json.getGson().fromJson(str, AppleReq.class);
+ });
+ assertTrue(exception.getMessage().contains("Expected the field `cultivar` to be a primitive type in the JSON string but got `[\"golden delicious\"]`"));
+
+ String str2 = "{ \"id\": 5847, \"name\":\"pet test 1\", \"photoUrls\": 123 }";
+ Exception exception2 = assertThrows(java.lang.IllegalArgumentException.class, () -> {
+ Pet p1 = json.getGson().fromJson(str2, Pet.class);
+ });
+ assertTrue(exception2.getMessage().contains("Expected the field `photoUrls` to be an array in the JSON string but got `123`"));
+ }
+
+ /**
+ * Validate a oneOf schema can be deserialized into the expected class.
+ * The oneOf schema does not have a discriminator.
+ */
+ @Test
+ public void testOneOfSchemaWithoutDiscriminator() throws Exception {
+ // BananaReq and AppleReq have explicitly defined properties that are different by name.
+ // There is no discriminator property.
+ {
+ String str = "{ \"cultivar\": \"golden delicious\", \"mealy\": false }";
+
+ // make sure deserialization works for pojo object
+ AppleReq a = json.getGson().fromJson(str, AppleReq.class);
+ assertEquals(a.getCultivar(), "golden delicious");
+ assertEquals(a.getMealy(), false);
+
+ FruitReq o = json.getGson().fromJson(str, FruitReq.class);
+ assertTrue(o.getActualInstance() instanceof AppleReq);
+ AppleReq inst = (AppleReq) o.getActualInstance();
+ assertEquals(inst.getCultivar(), "golden delicious");
+ assertEquals(inst.getMealy(), false);
+ assertEquals(json.getGson().toJson(inst), "{\"cultivar\":\"golden delicious\",\"mealy\":false}");
+ assertEquals(inst.toJson(), "{\"cultivar\":\"golden delicious\",\"mealy\":false}");
+ assertEquals(json.getGson().toJson(o), "{\"cultivar\":\"golden delicious\",\"mealy\":false}");
+ assertEquals(o.toJson(), "{\"cultivar\":\"golden delicious\",\"mealy\":false}");
+
+ AppleReq inst2 = o.getAppleReq();
+ assertEquals(inst2.getCultivar(), "golden delicious");
+ assertEquals(inst2.getMealy(), false);
+ assertEquals(json.getGson().toJson(inst2), "{\"cultivar\":\"golden delicious\",\"mealy\":false}");
+ assertEquals(inst2.toJson(), "{\"cultivar\":\"golden delicious\",\"mealy\":false}");
+
+ // test fromJson
+ FruitReq o3 = FruitReq.fromJson(str);
+ assertTrue(o3.getActualInstance() instanceof AppleReq);
+ AppleReq inst3 = (AppleReq) o3.getActualInstance();
+ assertEquals(inst3.getCultivar(), "golden delicious");
+ assertEquals(inst3.getMealy(), false);
+ assertEquals(json.getGson().toJson(inst3), "{\"cultivar\":\"golden delicious\",\"mealy\":false}");
+ assertEquals(inst3.toJson(), "{\"cultivar\":\"golden delicious\",\"mealy\":false}");
+ assertEquals(o3.toJson(), "{\"cultivar\":\"golden delicious\",\"mealy\":false}");
+ }
+ {
+ // test to ensure the oneOf object can be serialized to "null" correctly
+ FruitReq o = new FruitReq();
+ assertEquals(o.getActualInstance(), null);
+ assertEquals(json.getGson().toJson(o), "null");
+ assertEquals(o.toJson(), "null");
+ assertEquals(json.getGson().toJson(null), "null");
+ }
+ {
+ // Same test, but this time with additional (undeclared) properties.
+ // Since FruitReq has additionalProperties: false, deserialization should fail.
+ String str = "{ \"cultivar\": \"golden delicious\", \"mealy\": false, \"garbage_prop\": \"abc\" }";
+ Exception exception = assertThrows(com.google.gson.JsonSyntaxException.class, () -> {
+ FruitReq o = json.getGson().fromJson(str, FruitReq.class);
+ });
+ assertEquals("java.io.IOException: Failed deserialization for FruitReq: 0 classes match result, expected 1. Detailed failure message for oneOf schemas: [Deserialization for AppleReq failed with `The field `garbage_prop` in the JSON string is not defined in the `AppleReq` properties. JSON: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}`., Deserialization for BananaReq failed with `The field `cultivar` in the JSON string is not defined in the `BananaReq` properties. JSON: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}`.]. JSON: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}", exception.getMessage());
+ }
+ {
+ String str = "{ \"lengthCm\": 17 }";
+
+ // make sure deserialization works for pojo object
+ BananaReq b = json.getGson().fromJson(str, BananaReq.class);
+ assertEquals(b.getLengthCm(), new java.math.BigDecimal(17));
+
+ FruitReq o = json.getGson().fromJson(str, FruitReq.class);
+ assertTrue(o.getActualInstance() instanceof BananaReq);
+ BananaReq inst = (BananaReq) o.getActualInstance();
+ assertEquals(inst.getLengthCm(), new java.math.BigDecimal(17));
+ assertEquals(json.getGson().toJson(o), "{\"lengthCm\":17}");
+ assertEquals(json.getGson().toJson(inst), "{\"lengthCm\":17}");
+ }
+ {
+ // Try to deserialize empty object. This should fail 'oneOf' because none will match
+ // AppleReq or BananaReq.
+ String str = "{ }";
+ Exception exception = assertThrows(com.google.gson.JsonSyntaxException.class, () -> {
+ json.getGson().fromJson(str, FruitReq.class);
+ });
+ assertTrue(exception.getMessage().contains("Failed deserialization for FruitReq: 0 classes match result, expected 1"));
+ }
+ }
+
+
+ /**
+ * Test validateJsonObject with null object
+ */
+ @Test
+ public void testValidateJsonObject() throws Exception {
+ JsonObject jsonObject = new JsonObject();
+ Exception exception = assertThrows(java.lang.IllegalArgumentException.class, () -> {
+ Pet.validateJsonElement(jsonObject);
+ });
+ assertEquals(exception.getMessage(), "The required field `photoUrls` is not found in the JSON string: {}");
+ }
+
+ /**
+ * Test additional properties.
+ */
+ @Test
+ public void testAdditionalProperties() throws Exception {
+ String str = "{ \"className\": \"zebra\", \"type\": \"plains\", \"from_json\": 4567, \"from_json_map\": {\"nested_string\": \"nested_value\"} }";
+ Zebra z = Zebra.fromJson(str);
+ z.putAdditionalProperty("new_key", "new_value");
+ z.putAdditionalProperty("new_number", 1.23);
+ z.putAdditionalProperty("new_boolean", true);
+ org.openapitools.client.model.Tag t = new org.openapitools.client.model.Tag();
+ t.setId(34L);
+ t.setName("just a tag");
+ z.putAdditionalProperty("new_object", t);
+ assertEquals(z.toJson(), "{\"type\":\"plains\",\"className\":\"zebra\",\"new_key\":\"new_value\",\"new_boolean\":true,\"new_object\":{\"id\":34,\"name\":\"just a tag\"},\"from_json\":4567,\"from_json_map\":{\"nested_string\":\"nested_value\"},\"new_number\":1.23}");
+ }
+}
diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/StringUtilTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/StringUtilTest.java
new file mode 100644
index 000000000000..c946674e470a
--- /dev/null
+++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/StringUtilTest.java
@@ -0,0 +1,33 @@
+package org.openapitools.client;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.junit.jupiter.api.*;
+
+public class StringUtilTest {
+ @Test
+ public void testContainsIgnoreCase() {
+ assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "abc"));
+ assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "ABC"));
+ assertTrue(StringUtil.containsIgnoreCase(new String[]{"ABC"}, "abc"));
+ assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, "ABC"));
+ assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, null));
+
+ assertFalse(StringUtil.containsIgnoreCase(new String[]{"abc"}, "def"));
+ assertFalse(StringUtil.containsIgnoreCase(new String[]{}, "ABC"));
+ assertFalse(StringUtil.containsIgnoreCase(new String[]{}, null));
+ }
+
+ @Test
+ public void testJoin() {
+ String[] array = {"aa", "bb", "cc"};
+ assertEquals("aa,bb,cc", StringUtil.join(array, ","));
+ assertEquals("aa, bb, cc", StringUtil.join(array, ", "));
+ assertEquals("aabbcc", StringUtil.join(array, ""));
+ assertEquals("aa bb cc", StringUtil.join(array, " "));
+ assertEquals("aa\nbb\ncc", StringUtil.join(array, "\n"));
+
+ assertEquals("", StringUtil.join(new String[]{}, ","));
+ assertEquals("abc", StringUtil.join(new String[]{"abc"}, ","));
+ }
+}
diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/AnotherFakeApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/AnotherFakeApiTest.java
index face3d9b785e..0f49c5e2e01c 100644
--- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/AnotherFakeApiTest.java
+++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/AnotherFakeApiTest.java
@@ -2,31 +2,23 @@
* OpenAPI Petstore
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
- * The version of the OpenAPI document: 1.0.0
- *
+ * OpenAPI spec version: 1.0.0
+ *
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
-
package org.openapitools.client.api;
-import org.openapitools.client.ApiException;
-import java.math.BigDecimal;
-import org.openapitools.client.model.Client;
+
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
+import org.openapitools.client.ApiException;
+import org.openapitools.client.model.Client;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * API tests for AnotherFakeApi
- */
+/** API tests for AnotherFakeApi */
@Disabled
public class AnotherFakeApiTest {
@@ -35,39 +27,15 @@ public class AnotherFakeApiTest {
/**
* To test special tags
*
- * To test special tags and operation ID starting with number
+ * To test special tags and operation ID starting with number
*
* @throws ApiException if the Api call fails
*/
@Test
public void call123testSpecialTagsTest() throws ApiException {
- Client client = null;
- Client response = api.call123testSpecialTags(client);
- // TODO: test validations
- }
+ Client body = null;
+ Client response = api.call123testSpecialTags(body);
- /**
- * parameter array number default value
- *
- * @throws ApiException if the Api call fails
- */
- @Test
- public void getParameterArrayNumberTest() throws ApiException {
- List array = null;
- api.getParameterArrayNumber(array);
- // TODO: test validations
- }
-
- /**
- * parameter string number
- *
- * @throws ApiException if the Api call fails
- */
- @Test
- public void getParameterStringNumberTest() throws ApiException {
- BigDecimal stringNumber = null;
- api.getParameterStringNumber(stringNumber);
// TODO: test validations
}
-
}
diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/FakeApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/FakeApiTest.java
index badfac3b4cc2..4dea80f5e403 100644
--- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/FakeApiTest.java
+++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/FakeApiTest.java
@@ -24,8 +24,8 @@
import org.openapitools.client.model.OuterComposite;
import org.openapitools.client.model.OuterEnum;
import org.openapitools.client.model.User;
-import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Disabled;
import java.util.ArrayList;
import java.util.HashMap;
@@ -40,133 +40,148 @@ public class FakeApiTest {
private final FakeApi api = new FakeApi();
+
/**
* Health check endpoint
*
- * @throws ApiException if the Api call fails
+ *
+ *
+ * @throws ApiException
+ * if the Api call fails
*/
@Test
public void fakeHealthGetTest() throws ApiException {
- HealthCheckResult response = api.fakeHealthGet();
+ HealthCheckResult response = api.fakeHealthGet();
// TODO: test validations
}
-
+
/**
+ *
+ *
* Test serialization of outer boolean types
*
- * @throws ApiException if the Api call fails
+ * @throws ApiException
+ * if the Api call fails
*/
@Test
public void fakeOuterBooleanSerializeTest() throws ApiException {
Boolean body = null;
- Boolean response = api.fakeOuterBooleanSerialize(body);
+ Boolean response = api.fakeOuterBooleanSerialize(body);
// TODO: test validations
}
-
+
/**
+ *
+ *
* Test serialization of object with outer number type
*
- * @throws ApiException if the Api call fails
+ * @throws ApiException
+ * if the Api call fails
*/
@Test
public void fakeOuterCompositeSerializeTest() throws ApiException {
OuterComposite outerComposite = null;
- OuterComposite response = api.fakeOuterCompositeSerialize(outerComposite);
+ OuterComposite response = api.fakeOuterCompositeSerialize(outerComposite);
// TODO: test validations
}
-
+
/**
+ *
+ *
* Test serialization of outer number types
*
- * @throws ApiException if the Api call fails
+ * @throws ApiException
+ * if the Api call fails
*/
@Test
public void fakeOuterNumberSerializeTest() throws ApiException {
BigDecimal body = null;
- BigDecimal response = api.fakeOuterNumberSerialize(body);
+ BigDecimal response = api.fakeOuterNumberSerialize(body);
// TODO: test validations
}
-
+
/**
+ *
+ *
* Test serialization of outer string types
*
- * @throws ApiException if the Api call fails
+ * @throws ApiException
+ * if the Api call fails
*/
@Test
public void fakeOuterStringSerializeTest() throws ApiException {
String body = null;
- String response = api.fakeOuterStringSerialize(body);
+ String response = api.fakeOuterStringSerialize(body);
// TODO: test validations
}
-
+
/**
* Array of Enums
*
- * @throws ApiException if the Api call fails
+ *
+ *
+ * @throws ApiException
+ * if the Api call fails
*/
@Test
public void getArrayOfEnumsTest() throws ApiException {
- List response = api.getArrayOfEnums();
+ List response = api.getArrayOfEnums();
// TODO: test validations
}
-
+
/**
- * parameter name mapping test
+ *
*
- * @throws ApiException if the Api call fails
- */
- @Test
- public void getParameterNameMappingTest() throws ApiException {
- Long underscoreType = null;
- String type = null;
- String typeWithUnderscore = null;
- api.getParameterNameMapping(underscoreType, type, typeWithUnderscore);
- // TODO: test validations
- }
-
- /**
* For this test, the body for this request much reference a schema named `File`.
*
- * @throws ApiException if the Api call fails
+ * @throws ApiException
+ * if the Api call fails
*/
@Test
public void testBodyWithFileSchemaTest() throws ApiException {
FileSchemaTestClass fileSchemaTestClass = null;
- api.testBodyWithFileSchema(fileSchemaTestClass);
+ api.testBodyWithFileSchema(fileSchemaTestClass);
// TODO: test validations
}
-
+
/**
- * @throws ApiException if the Api call fails
+ *
+ *
+ *
+ *
+ * @throws ApiException
+ * if the Api call fails
*/
@Test
public void testBodyWithQueryParamsTest() throws ApiException {
String query = null;
User user = null;
- api.testBodyWithQueryParams(query, user);
+ api.testBodyWithQueryParams(query, user);
// TODO: test validations
}
-
+
/**
* To test \"client\" model
*
* To test \"client\" model
*
- * @throws ApiException if the Api call fails
+ * @throws ApiException
+ * if the Api call fails
*/
@Test
public void testClientModelTest() throws ApiException {
Client client = null;
- Client response = api.testClientModel(client);
+ Client response = api.testClientModel(client);
// TODO: test validations
}
-
+
/**
* Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
*
* Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
*
- * @throws ApiException if the Api call fails
+ * @throws ApiException
+ * if the Api call fails
*/
@Test
public void testEndpointParametersTest() throws ApiException {
@@ -184,16 +199,17 @@ public void testEndpointParametersTest() throws ApiException {
OffsetDateTime dateTime = null;
String password = null;
String paramCallback = null;
- api.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback);
+ api.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback);
// TODO: test validations
}
-
+
/**
* To test enum parameters
*
* To test enum parameters
*
- * @throws ApiException if the Api call fails
+ * @throws ApiException
+ * if the Api call fails
*/
@Test
public void testEnumParametersTest() throws ApiException {
@@ -205,16 +221,17 @@ public void testEnumParametersTest() throws ApiException {
Double enumQueryDouble = null;
List enumFormStringArray = null;
String enumFormString = null;
- api.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString);
+ api.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString);
// TODO: test validations
}
-
+
/**
* Fake endpoint to test group parameters (optional)
*
* Fake endpoint to test group parameters (optional)
*
- * @throws ApiException if the Api call fails
+ * @throws ApiException
+ * if the Api call fails
*/
@Test
public void testGroupParametersTest() throws ApiException {
@@ -224,47 +241,52 @@ public void testGroupParametersTest() throws ApiException {
Integer stringGroup = null;
Boolean booleanGroup = null;
Long int64Group = null;
- api.testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group)
+ api.testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group)
.stringGroup(stringGroup)
.booleanGroup(booleanGroup)
.int64Group(int64Group)
.execute();
// TODO: test validations
}
-
+
/**
* test inline additionalProperties
*
*
*
- * @throws ApiException if the Api call fails
+ * @throws ApiException
+ * if the Api call fails
*/
@Test
public void testInlineAdditionalPropertiesTest() throws ApiException {
Map requestBody = null;
- api.testInlineAdditionalProperties(requestBody);
+ api.testInlineAdditionalProperties(requestBody);
// TODO: test validations
}
-
+
/**
* test json serialization of form data
*
*
*
- * @throws ApiException if the Api call fails
+ * @throws ApiException
+ * if the Api call fails
*/
@Test
public void testJsonFormDataTest() throws ApiException {
String param = null;
String param2 = null;
- api.testJsonFormData(param, param2);
+ api.testJsonFormData(param, param2);
// TODO: test validations
}
-
+
/**
+ *
+ *
* To test the collection format in query parameters
*
- * @throws ApiException if the Api call fails
+ * @throws ApiException
+ * if the Api call fails
*/
@Test
public void testQueryParameterCollectionFormatTest() throws ApiException {
@@ -273,8 +295,8 @@ public void testQueryParameterCollectionFormatTest() throws ApiException {
List http = null;
List url = null;
List context = null;
- api.testQueryParameterCollectionFormat(pipe, ioutil, http, url, context);
+ api.testQueryParameterCollectionFormat(pipe, ioutil, http, url, context);
// TODO: test validations
}
-
+
}
diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/FakeClassnameTags123ApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/FakeClassnameTags123ApiTest.java
index aa1b824dd5a2..3eb19491b9b0 100644
--- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/FakeClassnameTags123ApiTest.java
+++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/FakeClassnameTags123ApiTest.java
@@ -2,30 +2,23 @@
* OpenAPI Petstore
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
- * The version of the OpenAPI document: 1.0.0
- *
+ * OpenAPI spec version: 1.0.0
+ *
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
-
package org.openapitools.client.api;
-import org.openapitools.client.ApiException;
-import org.openapitools.client.model.Client;
+
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
+import org.openapitools.client.ApiException;
+import org.openapitools.client.model.Client;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * API tests for FakeClassnameTags123Api
- */
+/** API tests for FakeClassnameTags123Api */
@Disabled
public class FakeClassnameTags123ApiTest {
@@ -34,15 +27,15 @@ public class FakeClassnameTags123ApiTest {
/**
* To test class name in snake case
*
- * To test class name in snake case
+ * To test class name in snake case
*
* @throws ApiException if the Api call fails
*/
@Test
public void testClassnameTest() throws ApiException {
- Client client = null;
- Client response = api.testClassname(client);
+ Client body = null;
+ Client response = api.testClassname(body);
+
// TODO: test validations
}
-
}
diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/PetApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/PetApiTest.java
new file mode 100644
index 000000000000..89fe1d01c460
--- /dev/null
+++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/PetApiTest.java
@@ -0,0 +1,579 @@
+/*
+ * OpenAPI Petstore
+ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
+ *
+ * OpenAPI spec version: 1.0.0
+ *
+ *
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+package org.openapitools.client.api;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileWriter;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.jupiter.api.*;
+import org.openapitools.client.*;
+import org.openapitools.client.ApiException;
+import org.openapitools.client.auth.*;
+import org.openapitools.client.model.*;
+import org.openapitools.client.model.Pet;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * API tests for PetApi
+ */
+public class PetApiTest {
+
+ private PetApi api = new PetApi();
+ private final Logger LOG = LoggerFactory.getLogger(PetApiTest.class);
+ // In the circle.yml file, /etc/host is configured with an entry to resolve petstore.swagger.io
+ // to 127.0.0.1
+ private static String basePath = "http://petstore.swagger.io:80/v2";
+
+ @BeforeEach
+ public void setup() {
+ // setup authentication
+ ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key");
+ apiKeyAuth.setApiKey("special-key");
+ api.getApiClient().setBasePath(basePath);
+ }
+
+ @Test
+ public void testApiClient() {
+ // the default api client is used
+ assertEquals(Configuration.getDefaultApiClient(), api.getApiClient());
+ assertNotNull(api.getApiClient());
+ assertEquals(basePath, api.getApiClient().getBasePath());
+ assertFalse(api.getApiClient().isDebugging());
+
+ ApiClient oldClient = api.getApiClient();
+
+ ApiClient newClient = new ApiClient();
+ newClient.setVerifyingSsl(true);
+ newClient.setBasePath("http://example.com");
+ newClient.setDebugging(true);
+
+ // set api client via constructor
+ api = new PetApi(newClient);
+ assertNotNull(api.getApiClient());
+ assertEquals("http://example.com", api.getApiClient().getBasePath());
+ assertTrue(api.getApiClient().isDebugging());
+
+ // set api client via setter method
+ api.setApiClient(oldClient);
+ assertNotNull(api.getApiClient());
+ assertEquals(basePath, api.getApiClient().getBasePath());
+ assertFalse(api.getApiClient().isDebugging());
+ }
+
+ @Test
+ public void testCreateAndGetPet() throws Exception {
+ Pet pet = createPet();
+ api.addPet(pet);
+
+ Pet fetched = api.getPetById(pet.getId());
+ assertPetMatches(pet, fetched);
+ api.deletePet(pet.getId(), null);
+ }
+
+ @Test
+ public void testCreateAndGetPetWithHttpInfo() throws Exception {
+ Pet pet = createPet();
+ api.addPetWithHttpInfo(pet);
+
+ ApiResponse resp = api.getPetByIdWithHttpInfo(pet.getId());
+ assertEquals(200, resp.getStatusCode());
+ assertEquals("application/json", resp.getHeaders().get("Content-Type").get(0));
+ Pet fetched = resp.getData();
+
+ assertPetMatches(pet, fetched);
+ api.deletePet(pet.getId(), null);
+ }
+
+ @Test
+ public void testCreateAndGetPetAsync() throws Exception {
+ Pet pet = createPet();
+ api.addPet(pet);
+ // to store returned Pet or error message/exception
+ final Map result = new HashMap();
+
+ api.getPetByIdAsync(
+ pet.getId(),
+ new ApiCallback() {
+ @Override
+ public void onFailure(
+ ApiException e,
+ int statusCode,
+ Map> responseHeaders) {
+ result.put("error", e.getMessage());
+ }
+
+ @Override
+ public void onSuccess(
+ Pet pet, int statusCode, Map> responseHeaders) {
+ result.put("pet", pet);
+ }
+
+ @Override
+ public void onUploadProgress(
+ long bytesWritten, long contentLength, boolean done) {
+ // empty
+ }
+
+ @Override
+ public void onDownloadProgress(
+ long bytesRead, long contentLength, boolean done) {
+ // empty
+ }
+ });
+
+ // wait for the asynchronous call to finish (at most 10 seconds)
+ final int maxTry = 10;
+ int tryCount = 1;
+ Pet fetched = null;
+ do {
+ if (tryCount > maxTry) fail("have not got result of getPetByIdAsync after 10 seconds");
+ Thread.sleep(1000);
+ tryCount += 1;
+ if (result.get("error") != null) fail((String) result.get("error"));
+ if (result.get("pet") != null) {
+ fetched = (Pet) result.get("pet");
+ break;
+ }
+ } while (result.isEmpty());
+ assertPetMatches(pet, fetched);
+ api.deletePet(pet.getId(), null);
+ }
+
+ @Test
+ public void testCreateAndGetPetAsyncInvalidID() throws Exception {
+ Pet pet = createPet();
+ api.addPet(pet);
+ // to store returned Pet or error message/exception
+ final Map result = new HashMap();
+
+ // test getting a nonexistent pet
+ result.clear();
+ api.getPetByIdAsync(
+ -10000L,
+ new ApiCallback() {
+ @Override
+ public void onFailure(
+ ApiException e,
+ int statusCode,
+ Map> responseHeaders) {
+ result.put("exception", e);
+ }
+
+ @Override
+ public void onSuccess(
+ Pet pet, int statusCode, Map> responseHeaders) {
+ result.put("pet", pet);
+ }
+
+ @Override
+ public void onUploadProgress(
+ long bytesWritten, long contentLength, boolean done) {
+ // empty
+ }
+
+ @Override
+ public void onDownloadProgress(
+ long bytesRead, long contentLength, boolean done) {
+ // empty
+ }
+ });
+
+ // wait for the asynchronous call to finish (at most 10 seconds)
+ final int maxTry = 10;
+ int tryCount = 1;
+ Pet fetched = null;
+ ApiException exception = null;
+
+ do {
+ if (tryCount > maxTry) fail("have not got result of getPetByIdAsync after 10 seconds");
+ Thread.sleep(1000);
+ tryCount += 1;
+ if (result.get("pet") != null) fail("expected an error");
+ if (result.get("exception") != null) {
+ exception = (ApiException) result.get("exception");
+ break;
+ }
+ } while (result.isEmpty());
+ assertNotNull(exception);
+ assertEquals(404, exception.getCode());
+ String pattern = "^Message: Not Found\\RHTTP response code: 404\\RHTTP response body: .*\\RHTTP response headers: .*$";
+ assertTrue(exception.getMessage().matches(pattern));
+ assertEquals("application/json", exception.getResponseHeaders().get("Content-Type").get(0));
+ api.deletePet(pet.getId(), null);
+ }
+
+ @Test
+ public void testCreateAndGetMultiplePetsAsync() throws Exception {
+ Pet pet1 = createPet();
+ Pet pet2 = createPet();
+
+ final CountDownLatch addLatch = new CountDownLatch(2);
+ final TestApiCallback addCallback1 = new TestApiCallback(addLatch);
+ final TestApiCallback addCallback2 = new TestApiCallback(addLatch);
+
+ // Make 2 simultaneous calls
+ api.addPetAsync(pet1, addCallback1);
+ api.addPetAsync(pet2, addCallback2);
+
+ // wait for both asynchronous calls to finish (at most 10 seconds)
+ assertTrue(addLatch.await(10, TimeUnit.SECONDS));
+
+ assertTrue(addCallback1.isDone());
+ assertTrue(addCallback2.isDone());
+
+ if (!addCallback1.isSuccess()) throw addCallback1.getException();
+ if (!addCallback2.isSuccess()) throw addCallback2.getException();
+
+ assertValidProgress(addCallback1.getUploadProgress());
+ assertValidProgress(addCallback2.getUploadProgress());
+
+ final CountDownLatch getLatch = new CountDownLatch(3);
+ final TestApiCallback getCallback1 = new TestApiCallback(getLatch);
+ final TestApiCallback getCallback2 = new TestApiCallback(getLatch);
+ final TestApiCallback getCallback3 = new TestApiCallback(getLatch);
+
+ api.getPetByIdAsync(pet1.getId(), getCallback1);
+ api.getPetByIdAsync(pet2.getId(), getCallback2);
+ // Get nonexistent pet
+ api.getPetByIdAsync(-10000L, getCallback3);
+
+ // wait for all asynchronous calls to finish (at most 10 seconds)
+ assertTrue(getLatch.await(10, TimeUnit.SECONDS));
+
+ assertTrue(getCallback1.isDone());
+ assertTrue(getCallback2.isDone());
+ assertTrue(getCallback3.isDone());
+
+ if (!getCallback1.isSuccess()) throw getCallback1.getException();
+ if (!getCallback2.isSuccess()) throw getCallback2.getException();
+
+ assertPetMatches(pet1, getCallback1.getResult());
+ assertPetMatches(pet2, getCallback2.getResult());
+
+ assertValidProgress(getCallback1.getDownloadProgress());
+ assertValidProgress(getCallback2.getDownloadProgress());
+
+ // Last callback should fail with ApiException
+ assertFalse(getCallback3.isSuccess());
+ final ApiException exception = getCallback3.getException();
+ assertNotNull(exception);
+ assertEquals(404, exception.getCode());
+ api.deletePet(pet1.getId(), null);
+ api.deletePet(pet2.getId(), null);
+ }
+
+ @Test
+ public void testUpdatePet() throws Exception {
+ Pet pet = createPet();
+ api.addPet(pet);
+ pet.setName("programmer");
+
+ api.updatePet(pet);
+
+ Pet fetched = api.getPetById(pet.getId());
+ assertPetMatches(pet, fetched);
+ api.deletePet(pet.getId(), null);
+ }
+
+ @Test
+ public void testFindPetsByStatus() throws Exception {
+ assertEquals(basePath, api.getApiClient().getBasePath());
+ Pet pet = createPet();
+ api.addPet(pet);
+ pet.setName("programmer");
+ pet.setStatus(Pet.StatusEnum.PENDING);
+ api.updatePet(pet);
+
+ List pets = api.findPetsByStatus(Arrays.asList("pending"));
+ assertNotNull(pets);
+
+ boolean found = false;
+ for (Pet fetched : pets) {
+ if (fetched.getId().equals(pet.getId())) {
+ found = true;
+ break;
+ }
+ }
+
+ assertTrue(found);
+
+ api.deletePet(pet.getId(), null);
+ }
+
+ @Test
+ @Disabled
+ public void testFindPetsByTags() throws Exception {
+ Pet pet = createPet();
+ pet.setName("monster");
+ pet.setStatus(Pet.StatusEnum.AVAILABLE);
+
+ List tags = new ArrayList();
+ org.openapitools.client.model.Tag tag1 = new org.openapitools.client.model.Tag();
+ tag1.setName("friendly");
+ tags.add(tag1);
+ pet.setTags(tags);
+
+ api.updatePet(pet);
+
+ List pets = api.findPetsByTags((Arrays.asList("friendly")));
+ assertNotNull(pets);
+
+ boolean found = false;
+ for (Pet fetched : pets) {
+ if (fetched.getId().equals(pet.getId())) {
+ found = true;
+ break;
+ }
+ }
+ assertTrue(found);
+
+ api.deletePet(pet.getId(), null);
+ }
+
+ @Test
+ public void testUpdatePetWithForm() throws Exception {
+ Pet pet = createPet();
+ pet.setName("frank");
+ api.addPet(pet);
+
+ Pet fetched = api.getPetById(pet.getId());
+
+ api.updatePetWithForm(fetched.getId(), "furt", null);
+ Pet updated = api.getPetById(fetched.getId());
+
+ assertEquals(updated.getName(), "furt");
+ api.deletePet(pet.getId(), null);
+ }
+
+ @Test
+ @Disabled
+ public void testDeletePet() throws Exception {
+ Pet pet = createPet();
+ api.addPet(pet);
+
+ Pet fetched = api.getPetById(pet.getId());
+ api.deletePet(pet.getId(), null);
+
+ try {
+ fetched = api.getPetById(fetched.getId());
+ fail("expected an error");
+ } catch (ApiException e) {
+ LOG.info("Code: {}. Message: {}", e.getCode(), e.getMessage());
+ assertEquals(404, e.getCode());
+ }
+ }
+
+ @Test
+ public void testUploadFile() throws Exception {
+ Pet pet = createPet();
+ api.addPet(pet);
+
+ File file = new File("hello.txt");
+ BufferedWriter writer = new BufferedWriter(new FileWriter(file));
+ writer.write("Hello world!");
+ writer.close();
+
+ api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath()));
+ api.deletePet(pet.getId(), null);
+ }
+
+ @Test
+ public void testEqualsAndHashCode() {
+ Pet pet1 = new Pet();
+ Pet pet2 = new Pet();
+ assertTrue(pet1.equals(pet2));
+ assertTrue(pet2.equals(pet1));
+ assertTrue(pet1.hashCode() == pet2.hashCode());
+ assertTrue(pet1.equals(pet1));
+ assertTrue(pet1.hashCode() == pet1.hashCode());
+
+ pet2.setName("really-happy");
+ pet2.setPhotoUrls(
+ (Arrays.asList("http://foo.bar.com/1", "http://foo.bar.com/2")));
+ assertFalse(pet1.equals(pet2));
+ assertFalse(pet2.equals(pet1));
+ assertFalse(pet1.hashCode() == (pet2.hashCode()));
+ assertTrue(pet2.equals(pet2));
+ assertTrue(pet2.hashCode() == pet2.hashCode());
+
+ pet1.setName("really-happy");
+ pet1.setPhotoUrls(
+ (Arrays.asList("http://foo.bar.com/1", "http://foo.bar.com/2")));
+ assertTrue(pet1.equals(pet2));
+ assertTrue(pet2.equals(pet1));
+ assertTrue(pet1.hashCode() == pet2.hashCode());
+ assertTrue(pet1.equals(pet1));
+ assertTrue(pet1.hashCode() == pet1.hashCode());
+ }
+
+ private Pet createPet() {
+ Pet pet = new Pet();
+ pet.setId(ThreadLocalRandom.current().nextLong(Long.MAX_VALUE));
+ pet.setName("gorilla");
+
+ Category category = new Category();
+ category.setName("really-happy");
+
+ pet.setCategory(category);
+ pet.setStatus(Pet.StatusEnum.AVAILABLE);
+ List photos =
+ (Arrays.asList("http://foo.bar.com/1", "http://foo.bar.com/2"));
+ pet.setPhotoUrls(photos);
+
+ return pet;
+ }
+
+ private String serializeJson(Object o, ApiClient apiClient) {
+ return apiClient.getJSON().serialize(o);
+ }
+
+ private T deserializeJson(String json, Type type, ApiClient apiClient) {
+ return (T) apiClient.getJSON().deserialize(json, type);
+ }
+
+ private void assertPetMatches(Pet expected, Pet actual) {
+ assertNotNull(actual);
+ assertEquals(expected.getId(), actual.getId());
+ assertNotNull(actual.getCategory());
+ assertEquals(expected.getCategory().getName(), actual.getCategory().getName());
+ }
+
+ /**
+ * Assert that the given upload/download progress list satisfies the following constraints:
+ *
+ * - List is not empty - Byte count should be nondecreasing - The last element, and only the
+ * last element, should have done=true
+ */
+ private void assertValidProgress(List