diff --git a/CI/samples.ci/client/petstore/java/test-manual/common/ConfigurationTest.java b/CI/samples.ci/client/petstore/java/test-manual/common/ConfigurationTest.java new file mode 100644 index 0000000000..f05c230dc7 --- /dev/null +++ b/CI/samples.ci/client/petstore/java/test-manual/common/ConfigurationTest.java @@ -0,0 +1,15 @@ +package org.openapitools.client; + +import org.junit.*; +import static org.junit.Assert.*; + + +public class ConfigurationTest { + @Test + public void testDefaultApiClient() { + ApiClient apiClient = Configuration.getDefaultApiClient(); + assertNotNull(apiClient); + assertEquals("http://petstore.swagger.io:80/v2", apiClient.getBasePath()); + assertFalse(apiClient.isDebugging()); + } +} diff --git a/CI/samples.ci/client/petstore/java/test-manual/common/StringUtilTest.java b/CI/samples.ci/client/petstore/java/test-manual/common/StringUtilTest.java new file mode 100644 index 0000000000..aa7c81759e --- /dev/null +++ b/CI/samples.ci/client/petstore/java/test-manual/common/StringUtilTest.java @@ -0,0 +1,33 @@ +package org.openapitools.client; + +import org.junit.*; +import static org.junit.Assert.*; + + +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/CI/samples.ci/client/petstore/java/test-manual/jersey1/ApiClientTest.java b/CI/samples.ci/client/petstore/java/test-manual/jersey1/ApiClientTest.java new file mode 100644 index 0000000000..a890ead935 --- /dev/null +++ b/CI/samples.ci/client/petstore/java/test-manual/jersey1/ApiClientTest.java @@ -0,0 +1,292 @@ +package org.openapitools.client; + +import org.openapitools.client.auth.*; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.*; + +import org.junit.*; +import static org.junit.Assert.*; + + +public class ApiClientTest { + ApiClient apiClient = null; + + @Before + public void setup() { + apiClient = new ApiClient(); + } + + @Test + public void testParseAndFormatDate() { + // default date format + String dateStr = "2015-11-07T03:49:09.356Z"; + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356+00:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356Z"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T05:49:09.356+02:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T02:49:09.356-01:00"))); + + // custom date format: without milli-seconds, custom time zone + DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); + format.setTimeZone(TimeZone.getTimeZone("GMT+10")); + apiClient.setDateFormat(format); + dateStr = "2015-11-07T13:49:09+10:00"; + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09+00:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09Z"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T00:49:09-03:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T13:49:09+10:00"))); + } + + @Test + public void testIsJsonMime() { + assertFalse(apiClient.isJsonMime(null)); + assertFalse(apiClient.isJsonMime("")); + assertFalse(apiClient.isJsonMime("text/plain")); + assertFalse(apiClient.isJsonMime("application/xml")); + assertFalse(apiClient.isJsonMime("application/jsonp")); + assertFalse(apiClient.isJsonMime("example/json")); + assertFalse(apiClient.isJsonMime("example/foo+bar+jsonx")); + assertFalse(apiClient.isJsonMime("example/foo+bar+xjson")); + + assertTrue(apiClient.isJsonMime("application/json")); + assertTrue(apiClient.isJsonMime("application/json; charset=UTF8")); + assertTrue(apiClient.isJsonMime("APPLICATION/JSON")); + + assertTrue(apiClient.isJsonMime("application/problem+json")); + assertTrue(apiClient.isJsonMime("APPLICATION/PROBLEM+JSON")); + assertTrue(apiClient.isJsonMime("application/json\t")); + assertTrue(apiClient.isJsonMime("example/foo+bar+json")); + assertTrue(apiClient.isJsonMime("example/foo+json;x;y")); + assertTrue(apiClient.isJsonMime("example/foo+json\t;")); + assertTrue(apiClient.isJsonMime("Example/fOO+JSON")); + } + + @Test + public void testSelectHeaderAccept() { + String[] accepts = {"application/json", "application/xml"}; + assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"text/plain", "application/xml"}; + assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{}; + assertNull(apiClient.selectHeaderAccept(accepts)); + } + + @Test + public void testSelectHeaderContentType() { + String[] contentTypes = {"application/json", "application/xml"}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"text/plain", "application/xml"}; + assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + } + + @Test + public void testGetAuthentications() { + Map auths = apiClient.getAuthentications(); + + Authentication auth = auths.get("api_key"); + assertNotNull(auth); + assertTrue(auth instanceof ApiKeyAuth); + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) auth; + assertEquals("header", apiKeyAuth.getLocation()); + assertEquals("api_key", apiKeyAuth.getParamName()); + + auth = auths.get("petstore_auth"); + assertTrue(auth instanceof OAuth); + assertSame(auth, apiClient.getAuthentication("petstore_auth")); + + assertNull(auths.get("unknown")); + + try { + auths.put("my_auth", new HttpBasicAuth()); + fail("the authentications returned should not be modifiable"); + } catch (UnsupportedOperationException e) { + } + } + + @Ignore("There is no more basic auth in petstore security definitions") + @Test + public void testSetUsernameAndPassword() { + HttpBasicAuth auth = null; + for (Authentication _auth : apiClient.getAuthentications().values()) { + if (_auth instanceof HttpBasicAuth) { + auth = (HttpBasicAuth) _auth; + break; + } + } + auth.setUsername(null); + auth.setPassword(null); + + apiClient.setUsername("my-username"); + apiClient.setPassword("my-password"); + assertEquals("my-username", auth.getUsername()); + assertEquals("my-password", auth.getPassword()); + + // reset values + auth.setUsername(null); + auth.setPassword(null); + } + + @Test + public void testSetApiKeyAndPrefix() { + ApiKeyAuth auth = null; + for (Authentication _auth : apiClient.getAuthentications().values()) { + if (_auth instanceof ApiKeyAuth) { + auth = (ApiKeyAuth) _auth; + break; + } + } + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + + apiClient.setApiKey("my-api-key"); + apiClient.setApiKeyPrefix("Token"); + assertEquals("my-api-key", auth.getApiKey()); + assertEquals("Token", auth.getApiKeyPrefix()); + + // reset values + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + } + + @Test + public void testParameterToPairWhenNameIsInvalid() throws Exception { + List pairs_a = apiClient.parameterToPair(null, new Integer(1)); + List pairs_b = apiClient.parameterToPair("", new Integer(1)); + + assertTrue(pairs_a.isEmpty()); + assertTrue(pairs_b.isEmpty()); + } + + @Test + public void testParameterToPairWhenValueIsNull() throws Exception { + List pairs = apiClient.parameterToPair("param-a", null); + + assertTrue(pairs.isEmpty()); + } + + @Test + public void testParameterToPairWhenValueIsEmptyString() throws Exception { + // single empty string + List pairs = apiClient.parameterToPair("param-a", " "); + assertEquals(1, pairs.size()); + } + + @Test + public void testParameterToPairWhenValueIsNotCollection() throws Exception { + String name = "param-a"; + Integer value = 1; + + List pairs = apiClient.parameterToPair(name, value); + + assertEquals(1, pairs.size()); + assertEquals(value, Integer.valueOf(pairs.get(0).getValue())); + } + + @Test + public void testParameterToPairWhenValueIsCollection() throws Exception { + List values = new ArrayList(); + values.add("value-a"); + values.add(123); + values.add(new Date()); + + List pairs = apiClient.parameterToPair("param-a", values); + assertEquals(0, pairs.size()); + } + + @Test + public void testParameterToPairsWhenNameIsInvalid() throws Exception { + List objects = new ArrayList(); + objects.add(new Integer(1)); + + List pairs_a = apiClient.parameterToPairs("csv", null, objects); + List pairs_b = apiClient.parameterToPairs("csv", "", objects); + + assertTrue(pairs_a.isEmpty()); + assertTrue(pairs_b.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsNull() throws Exception { + List pairs = apiClient.parameterToPairs("csv", "param-a", null); + + assertTrue(pairs.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception { + // list of empty strings + List strs = new ArrayList(); + strs.add(" "); + strs.add(" "); + strs.add(" "); + + List concatStrings = apiClient.parameterToPairs("csv", "param-a", strs); + + assertEquals(1, concatStrings.size()); + assertFalse(concatStrings.get(0).getValue().isEmpty()); // should contain some delimiters + } + + @Test + public void testParameterToPairsWhenValueIsCollection() throws Exception { + Map collectionFormatMap = new HashMap(); + collectionFormatMap.put("csv", ","); + collectionFormatMap.put("tsv", "\t"); + collectionFormatMap.put("ssv", " "); + collectionFormatMap.put("pipes", "|"); + collectionFormatMap.put("", ","); // no format, must default to csv + collectionFormatMap.put("unknown", ","); // all other formats, must default to csv + + String name = "param-a"; + + List values = new ArrayList(); + values.add("value-a"); + values.add(123); + values.add(new Date()); + + // check for multi separately + List multiPairs = apiClient.parameterToPairs("multi", name, values); + assertEquals(values.size(), multiPairs.size()); + for (int i = 0; i < values.size(); i++) { + assertEquals(apiClient.escapeString(apiClient.parameterToString(values.get(i))), multiPairs.get(i).getValue()); + } + + // all other formats + for (String collectionFormat : collectionFormatMap.keySet()) { + List pairs = apiClient.parameterToPairs(collectionFormat, name, values); + + assertEquals(1, pairs.size()); + + String delimiter = collectionFormatMap.get(collectionFormat); + if (!delimiter.equals(",")) { + // commas are not escaped because they are reserved characters in URIs + delimiter = apiClient.escapeString(delimiter); + } + String[] pairValueSplit = pairs.get(0).getValue().split(delimiter); + + // must equal input values + assertEquals(values.size(), pairValueSplit.length); + for (int i = 0; i < values.size(); i++) { + assertEquals(apiClient.escapeString(apiClient.parameterToString(values.get(i))), pairValueSplit[i]); + } + } + } +} diff --git a/CI/samples.ci/client/petstore/java/test-manual/jersey1/auth/ApiKeyAuthTest.java b/CI/samples.ci/client/petstore/java/test-manual/jersey1/auth/ApiKeyAuthTest.java new file mode 100644 index 0000000000..d9b17065f7 --- /dev/null +++ b/CI/samples.ci/client/petstore/java/test-manual/jersey1/auth/ApiKeyAuthTest.java @@ -0,0 +1,47 @@ +package org.openapitools.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import org.openapitools.client.Pair; +import org.junit.*; +import static org.junit.Assert.*; + + +public class ApiKeyAuthTest { + @Test + public void testApplyToParamsInQuery() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); + auth.setApiKey("my-api-key"); + auth.applyToParams(queryParams, headerParams); + + assertEquals(1, queryParams.size()); + for (Pair queryParam : queryParams) { + assertEquals("my-api-key", queryParam.getValue()); + } + + // no changes to header parameters + assertEquals(0, headerParams.size()); + } + + @Test + public void testApplyToParamsInHeaderWithPrefix() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); + auth.setApiKey("my-api-token"); + auth.setApiKeyPrefix("Token"); + auth.applyToParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN")); + } +} diff --git a/CI/samples.ci/client/petstore/java/test-manual/jersey1/auth/HttpBasicAuthTest.java b/CI/samples.ci/client/petstore/java/test-manual/jersey1/auth/HttpBasicAuthTest.java new file mode 100644 index 0000000000..668342d96d --- /dev/null +++ b/CI/samples.ci/client/petstore/java/test-manual/jersey1/auth/HttpBasicAuthTest.java @@ -0,0 +1,52 @@ +package org.openapitools.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import org.openapitools.client.Pair; +import org.junit.*; +import static org.junit.Assert.*; + + +public class HttpBasicAuthTest { + HttpBasicAuth auth = null; + + @Before + public void setup() { + auth = new HttpBasicAuth(); + } + + @Test + public void testApplyToParams() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + auth.setUsername("my-username"); + auth.setPassword("my-password"); + auth.applyToParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + // the string below is base64-encoded result of "my-username:my-password" with the "Basic " prefix + String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ="; + assertEquals(expected, headerParams.get("Authorization")); + + // null username should be treated as empty string + auth.setUsername(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of ":my-password" with the "Basic " prefix + expected = "Basic Om15LXBhc3N3b3Jk"; + assertEquals(expected, headerParams.get("Authorization")); + + // null password should be treated as empty string + auth.setUsername("my-username"); + auth.setPassword(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of "my-username:" with the "Basic " prefix + expected = "Basic bXktdXNlcm5hbWU6"; + assertEquals(expected, headerParams.get("Authorization")); + } +} diff --git a/CI/samples.ci/client/petstore/java/test-manual/jersey1/model/EnumValueTest.java b/CI/samples.ci/client/petstore/java/test-manual/jersey1/model/EnumValueTest.java new file mode 100644 index 0000000000..47bfe940d3 --- /dev/null +++ b/CI/samples.ci/client/petstore/java/test-manual/jersey1/model/EnumValueTest.java @@ -0,0 +1,63 @@ +package org.openapitools.client.model; + +import org.junit.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.fasterxml.jackson.databind.SerializationFeature; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class EnumValueTest { + + @Test + public void testEnumClass() { + assertEquals(EnumClass._ABC.toString(), "_abc"); + assertEquals(EnumClass._EFG.toString(), "-efg"); + assertEquals(EnumClass._XYZ_.toString(), "(xyz)"); + } + + @Test + public void testEnumTest() { + // test enum value + EnumTest enumTest = new EnumTest(); + enumTest.setEnumString(EnumTest.EnumStringEnum.LOWER); + enumTest.setEnumInteger(EnumTest.EnumIntegerEnum.NUMBER_1); + enumTest.setEnumNumber(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1); + + assertEquals(EnumTest.EnumStringEnum.UPPER.toString(), "UPPER"); + assertEquals(EnumTest.EnumStringEnum.UPPER.getValue(), "UPPER"); + assertEquals(EnumTest.EnumStringEnum.LOWER.toString(), "lower"); + assertEquals(EnumTest.EnumStringEnum.LOWER.getValue(), "lower"); + + assertEquals(EnumTest.EnumIntegerEnum.NUMBER_1.toString(), "1"); + assertTrue(EnumTest.EnumIntegerEnum.NUMBER_1.getValue() == 1); + assertEquals(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.toString(), "-1"); + assertTrue(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.getValue() == -1); + + assertEquals(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.toString(), "1.1"); + assertTrue(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.getValue() == 1.1); + assertEquals(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.toString(), "-1.2"); + assertTrue(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.getValue() == -1.2); + + try { + // test serialization (object => json) + ObjectMapper mapper = new ObjectMapper(); + mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + ObjectWriter ow = mapper.writer(); + String json = ow.writeValueAsString(enumTest); + assertEquals(json, "{\"enum_string\":\"lower\",\"enum_string_required\":null,\"enum_integer\":1,\"enum_number\":1.1,\"outerEnum\":null}"); + + // test deserialization (json => object) + EnumTest fromString = mapper.readValue(json, EnumTest.class); + assertEquals(fromString.getEnumString().toString(), "lower"); + assertEquals(fromString.getEnumInteger().toString(), "1"); + assertEquals(fromString.getEnumNumber().toString(), "1.1"); + + } catch (Exception e) { + fail("Exception thrown during serialization/deserialzation of JSON: " + e.getMessage()); + } + } +} diff --git a/CI/samples.ci/client/petstore/java/test-manual/jersey2-java8/JSONTest.java b/CI/samples.ci/client/petstore/java/test-manual/jersey2-java8/JSONTest.java new file mode 100644 index 0000000000..7fb307a3df --- /dev/null +++ b/CI/samples.ci/client/petstore/java/test-manual/jersey2-java8/JSONTest.java @@ -0,0 +1,45 @@ +package org.openapitools.client; + +import org.openapitools.client.model.Order; + +import java.lang.Exception; + +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import org.junit.*; +import static org.junit.Assert.*; + + +public class JSONTest { + JSON json = null; + Order order = null; + + @Before + public void setup() { + json = new JSON(); + order = new Order(); + } + + @Test + public void testDefaultDate() throws Exception { + final DateTimeFormatter dateFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME; + final String dateStr = "2015-11-07T14:11:05.267Z"; + order.setShipDate(dateFormat.parse(dateStr, OffsetDateTime::from)); + + String str = json.getContext(null).writeValueAsString(order); + Order o = json.getContext(null).readValue(str, Order.class); + assertEquals(dateStr, dateFormat.format(o.getShipDate())); + } + + @Test + public void testCustomDate() throws Exception { + final DateTimeFormatter dateFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.of("Etc/GMT+2")); + final String dateStr = "2015-11-07T14:11:05-02:00"; + order.setShipDate(dateFormat.parse(dateStr, OffsetDateTime::from)); + + String str = json.getContext(null).writeValueAsString(order); + Order o = json.getContext(null).readValue(str, Order.class); + assertEquals(dateStr, dateFormat.format(o.getShipDate())); + } +} \ No newline at end of file diff --git a/CI/samples.ci/client/petstore/java/test-manual/jersey2/ApiClientTest.java b/CI/samples.ci/client/petstore/java/test-manual/jersey2/ApiClientTest.java new file mode 100644 index 0000000000..6fb1e54b67 --- /dev/null +++ b/CI/samples.ci/client/petstore/java/test-manual/jersey2/ApiClientTest.java @@ -0,0 +1,250 @@ +package org.openapitools.client; + +import org.openapitools.client.auth.*; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.*; + +import org.junit.*; +import static org.junit.Assert.*; + + +public class ApiClientTest { + ApiClient apiClient = null; + + @Before + public void setup() { + apiClient = new ApiClient(); + } + + @Test + public void testParseAndFormatDate() { + // default date format + String dateStr = "2015-11-07T03:49:09.356Z"; + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356+00:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356Z"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T05:49:09.356+02:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T02:49:09.356-01:00"))); + + // custom date format: without milli-seconds, custom time zone + DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); + format.setTimeZone(TimeZone.getTimeZone("GMT+10")); + apiClient.setDateFormat(format); + dateStr = "2015-11-07T13:49:09+10:00"; + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09+00:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09Z"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T00:49:09-03:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T13:49:09+10:00"))); + } + + @Test + public void testIsJsonMime() { + assertFalse(apiClient.isJsonMime(null)); + assertFalse(apiClient.isJsonMime("")); + assertFalse(apiClient.isJsonMime("text/plain")); + assertFalse(apiClient.isJsonMime("application/xml")); + assertFalse(apiClient.isJsonMime("application/jsonp")); + assertFalse(apiClient.isJsonMime("example/json")); + assertFalse(apiClient.isJsonMime("example/foo+bar+jsonx")); + assertFalse(apiClient.isJsonMime("example/foo+bar+xjson")); + + assertTrue(apiClient.isJsonMime("application/json")); + assertTrue(apiClient.isJsonMime("application/json; charset=UTF8")); + assertTrue(apiClient.isJsonMime("APPLICATION/JSON")); + + assertTrue(apiClient.isJsonMime("application/problem+json")); + assertTrue(apiClient.isJsonMime("APPLICATION/PROBLEM+JSON")); + assertTrue(apiClient.isJsonMime("application/json\t")); + assertTrue(apiClient.isJsonMime("example/foo+bar+json")); + assertTrue(apiClient.isJsonMime("example/foo+json;x;y")); + assertTrue(apiClient.isJsonMime("example/foo+json\t;")); + assertTrue(apiClient.isJsonMime("Example/fOO+JSON")); + } + + @Test + public void testSelectHeaderAccept() { + String[] accepts = {"application/json", "application/xml"}; + assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"text/plain", "application/xml"}; + assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{}; + assertNull(apiClient.selectHeaderAccept(accepts)); + } + + @Test + public void testSelectHeaderContentType() { + String[] contentTypes = {"application/json", "application/xml"}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"text/plain", "application/xml"}; + assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + } + + @Test + public void testGetAuthentications() { + Map auths = apiClient.getAuthentications(); + + Authentication auth = auths.get("api_key"); + assertNotNull(auth); + assertTrue(auth instanceof ApiKeyAuth); + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) auth; + assertEquals("header", apiKeyAuth.getLocation()); + assertEquals("api_key", apiKeyAuth.getParamName()); + + auth = auths.get("petstore_auth"); + assertTrue(auth instanceof OAuth); + assertSame(auth, apiClient.getAuthentication("petstore_auth")); + + assertNull(auths.get("unknown")); + + try { + auths.put("my_auth", new HttpBasicAuth()); + fail("the authentications returned should not be modifiable"); + } catch (UnsupportedOperationException e) { + } + } + + @Ignore("There is no more basic auth in petstore security definitions") + @Test + public void testSetUsernameAndPassword() { + HttpBasicAuth auth = null; + for (Authentication _auth : apiClient.getAuthentications().values()) { + if (_auth instanceof HttpBasicAuth) { + auth = (HttpBasicAuth) _auth; + break; + } + } + auth.setUsername(null); + auth.setPassword(null); + + apiClient.setUsername("my-username"); + apiClient.setPassword("my-password"); + assertEquals("my-username", auth.getUsername()); + assertEquals("my-password", auth.getPassword()); + + // reset values + auth.setUsername(null); + auth.setPassword(null); + } + + @Test + public void testSetApiKeyAndPrefix() { + ApiKeyAuth auth = null; + for (Authentication _auth : apiClient.getAuthentications().values()) { + if (_auth instanceof ApiKeyAuth) { + auth = (ApiKeyAuth) _auth; + break; + } + } + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + + apiClient.setApiKey("my-api-key"); + apiClient.setApiKeyPrefix("Token"); + assertEquals("my-api-key", auth.getApiKey()); + assertEquals("Token", auth.getApiKeyPrefix()); + + // reset values + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + } + + @Test + public void testParameterToPairsWhenNameIsInvalid() throws Exception { + List pairs_a = apiClient.parameterToPairs("csv", null, new Integer(1)); + List pairs_b = apiClient.parameterToPairs("csv", "", new Integer(1)); + + assertTrue(pairs_a.isEmpty()); + assertTrue(pairs_b.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsNull() throws Exception { + List pairs = apiClient.parameterToPairs("csv", "param-a", null); + + assertTrue(pairs.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception { + + // single empty string + List pairs = apiClient.parameterToPairs("csv", "param-a", " "); + assertEquals(1, pairs.size()); + + // list of empty strings + List strs = new ArrayList(); + strs.add(" "); + strs.add(" "); + strs.add(" "); + + List concatStrings = apiClient.parameterToPairs("csv", "param-a", strs); + + assertEquals(1, concatStrings.size()); + assertFalse(concatStrings.get(0).getValue().isEmpty()); // should contain some delimiters + } + + @Test + public void testParameterToPairsWhenValueIsNotCollection() throws Exception { + String name = "param-a"; + Integer value = 1; + + List pairs = apiClient.parameterToPairs("csv", name, value); + + assertEquals(1, pairs.size()); + assertEquals(value, Integer.valueOf(pairs.get(0).getValue())); + } + + @Test + public void testParameterToPairsWhenValueIsCollection() throws Exception { + Map collectionFormatMap = new HashMap(); + collectionFormatMap.put("csv", ","); + collectionFormatMap.put("tsv", "\t"); + collectionFormatMap.put("ssv", " "); + collectionFormatMap.put("pipes", "\\|"); + collectionFormatMap.put("", ","); // no format, must default to csv + collectionFormatMap.put("unknown", ","); // all other formats, must default to csv + + String name = "param-a"; + + List values = new ArrayList(); + values.add("value-a"); + values.add(123); + values.add(new Date()); + + // check for multi separately + List multiPairs = apiClient.parameterToPairs("multi", name, values); + assertEquals(values.size(), multiPairs.size()); + + // all other formats + for (String collectionFormat : collectionFormatMap.keySet()) { + List pairs = apiClient.parameterToPairs(collectionFormat, name, values); + + assertEquals(1, pairs.size()); + + String delimiter = collectionFormatMap.get(collectionFormat); + String[] pairValueSplit = pairs.get(0).getValue().split(delimiter); + + // must equal input values + assertEquals(values.size(), pairValueSplit.length); + } + } +} diff --git a/CI/samples.ci/client/petstore/java/test-manual/jersey2/JSONTest.java b/CI/samples.ci/client/petstore/java/test-manual/jersey2/JSONTest.java new file mode 100644 index 0000000000..f21b852065 --- /dev/null +++ b/CI/samples.ci/client/petstore/java/test-manual/jersey2/JSONTest.java @@ -0,0 +1,58 @@ +package org.openapitools.client; + +import org.openapitools.client.model.Order; +import org.junit.Before; +import org.junit.Test; +import org.threeten.bp.OffsetDateTime; +import org.threeten.bp.ZoneId; +import org.threeten.bp.format.DateTimeFormatter; + +import static org.junit.Assert.*; + + +public class JSONTest { + private JSON json = null; + private Order order = null; + + @Before + public void setup() { + json = new ApiClient().getJSON(); + order = new Order(); + } + + @Test + public void testDefaultDate() throws Exception { + final DateTimeFormatter dateFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME; + final String dateStr = "2015-11-07T14:11:05.267Z"; + order.setShipDate(dateFormat.parse(dateStr, OffsetDateTime.FROM)); + + String str = json.getContext(null).writeValueAsString(order); + Order o = json.getContext(null).readValue(str, Order.class); + assertEquals(dateStr, dateFormat.format(o.getShipDate())); + } + + @Test + public void testCustomDate() throws Exception { + final DateTimeFormatter dateFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.of("Etc/GMT+2")); + final String dateStr = "2015-11-07T14:11:05-02:00"; + order.setShipDate(dateFormat.parse(dateStr, OffsetDateTime.FROM)); + + String str = json.getContext(null).writeValueAsString(order); + Order o = json.getContext(null).readValue(str, Order.class); + assertEquals(dateStr, dateFormat.format(o.getShipDate())); + } + + @Test + public void testSqlDateSerialization() throws Exception { + String str = json.getContext(null).writeValueAsString(new java.sql.Date(10)); + assertEquals("\"1970-01-01\"", str); + } + + @Test + public void testSqlDateDeserialization() throws Exception { + final String str = "1970-01-01"; + java.sql.Date date = json.getContext(null).readValue("\"" + str + "\"", java.sql.Date.class); + assertEquals(date.toString(), str); + } + +} \ No newline at end of file diff --git a/CI/samples.ci/client/petstore/java/test-manual/jersey2/auth/ApiKeyAuthTest.java b/CI/samples.ci/client/petstore/java/test-manual/jersey2/auth/ApiKeyAuthTest.java new file mode 100644 index 0000000000..d9b17065f7 --- /dev/null +++ b/CI/samples.ci/client/petstore/java/test-manual/jersey2/auth/ApiKeyAuthTest.java @@ -0,0 +1,47 @@ +package org.openapitools.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import org.openapitools.client.Pair; +import org.junit.*; +import static org.junit.Assert.*; + + +public class ApiKeyAuthTest { + @Test + public void testApplyToParamsInQuery() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); + auth.setApiKey("my-api-key"); + auth.applyToParams(queryParams, headerParams); + + assertEquals(1, queryParams.size()); + for (Pair queryParam : queryParams) { + assertEquals("my-api-key", queryParam.getValue()); + } + + // no changes to header parameters + assertEquals(0, headerParams.size()); + } + + @Test + public void testApplyToParamsInHeaderWithPrefix() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); + auth.setApiKey("my-api-token"); + auth.setApiKeyPrefix("Token"); + auth.applyToParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN")); + } +} diff --git a/CI/samples.ci/client/petstore/java/test-manual/jersey2/auth/HttpBasicAuthTest.java b/CI/samples.ci/client/petstore/java/test-manual/jersey2/auth/HttpBasicAuthTest.java new file mode 100644 index 0000000000..668342d96d --- /dev/null +++ b/CI/samples.ci/client/petstore/java/test-manual/jersey2/auth/HttpBasicAuthTest.java @@ -0,0 +1,52 @@ +package org.openapitools.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import org.openapitools.client.Pair; +import org.junit.*; +import static org.junit.Assert.*; + + +public class HttpBasicAuthTest { + HttpBasicAuth auth = null; + + @Before + public void setup() { + auth = new HttpBasicAuth(); + } + + @Test + public void testApplyToParams() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + auth.setUsername("my-username"); + auth.setPassword("my-password"); + auth.applyToParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + // the string below is base64-encoded result of "my-username:my-password" with the "Basic " prefix + String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ="; + assertEquals(expected, headerParams.get("Authorization")); + + // null username should be treated as empty string + auth.setUsername(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of ":my-password" with the "Basic " prefix + expected = "Basic Om15LXBhc3N3b3Jk"; + assertEquals(expected, headerParams.get("Authorization")); + + // null password should be treated as empty string + auth.setUsername("my-username"); + auth.setPassword(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of "my-username:" with the "Basic " prefix + expected = "Basic bXktdXNlcm5hbWU6"; + assertEquals(expected, headerParams.get("Authorization")); + } +} diff --git a/CI/samples.ci/client/petstore/java/test-manual/jersey2/model/EnumValueTest.java b/CI/samples.ci/client/petstore/java/test-manual/jersey2/model/EnumValueTest.java new file mode 100644 index 0000000000..47bfe940d3 --- /dev/null +++ b/CI/samples.ci/client/petstore/java/test-manual/jersey2/model/EnumValueTest.java @@ -0,0 +1,63 @@ +package org.openapitools.client.model; + +import org.junit.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.fasterxml.jackson.databind.SerializationFeature; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class EnumValueTest { + + @Test + public void testEnumClass() { + assertEquals(EnumClass._ABC.toString(), "_abc"); + assertEquals(EnumClass._EFG.toString(), "-efg"); + assertEquals(EnumClass._XYZ_.toString(), "(xyz)"); + } + + @Test + public void testEnumTest() { + // test enum value + EnumTest enumTest = new EnumTest(); + enumTest.setEnumString(EnumTest.EnumStringEnum.LOWER); + enumTest.setEnumInteger(EnumTest.EnumIntegerEnum.NUMBER_1); + enumTest.setEnumNumber(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1); + + assertEquals(EnumTest.EnumStringEnum.UPPER.toString(), "UPPER"); + assertEquals(EnumTest.EnumStringEnum.UPPER.getValue(), "UPPER"); + assertEquals(EnumTest.EnumStringEnum.LOWER.toString(), "lower"); + assertEquals(EnumTest.EnumStringEnum.LOWER.getValue(), "lower"); + + assertEquals(EnumTest.EnumIntegerEnum.NUMBER_1.toString(), "1"); + assertTrue(EnumTest.EnumIntegerEnum.NUMBER_1.getValue() == 1); + assertEquals(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.toString(), "-1"); + assertTrue(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.getValue() == -1); + + assertEquals(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.toString(), "1.1"); + assertTrue(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.getValue() == 1.1); + assertEquals(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.toString(), "-1.2"); + assertTrue(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.getValue() == -1.2); + + try { + // test serialization (object => json) + ObjectMapper mapper = new ObjectMapper(); + mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + ObjectWriter ow = mapper.writer(); + String json = ow.writeValueAsString(enumTest); + assertEquals(json, "{\"enum_string\":\"lower\",\"enum_string_required\":null,\"enum_integer\":1,\"enum_number\":1.1,\"outerEnum\":null}"); + + // test deserialization (json => object) + EnumTest fromString = mapper.readValue(json, EnumTest.class); + assertEquals(fromString.getEnumString().toString(), "lower"); + assertEquals(fromString.getEnumInteger().toString(), "1"); + assertEquals(fromString.getEnumNumber().toString(), "1.1"); + + } catch (Exception e) { + fail("Exception thrown during serialization/deserialzation of JSON: " + e.getMessage()); + } + } +} diff --git a/CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/ApiClientTest.java b/CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/ApiClientTest.java new file mode 100644 index 0000000000..5167afc326 --- /dev/null +++ b/CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/ApiClientTest.java @@ -0,0 +1,330 @@ +package org.openapitools.client; + +import org.openapitools.client.auth.*; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.TimeZone; + +import org.junit.*; +import static org.junit.Assert.*; + + +public class ApiClientTest { + ApiClient apiClient; + JSON json; + + @Before + public void setup() { + apiClient = new ApiClient(); + json = apiClient.getJSON(); + } + + @Test + public void testIsJsonMime() { + assertFalse(apiClient.isJsonMime(null)); + assertFalse(apiClient.isJsonMime("")); + assertFalse(apiClient.isJsonMime("text/plain")); + assertFalse(apiClient.isJsonMime("application/xml")); + assertFalse(apiClient.isJsonMime("application/jsonp")); + assertFalse(apiClient.isJsonMime("example/json")); + assertFalse(apiClient.isJsonMime("example/foo+bar+jsonx")); + assertFalse(apiClient.isJsonMime("example/foo+bar+xjson")); + + assertTrue(apiClient.isJsonMime("application/json")); + assertTrue(apiClient.isJsonMime("application/json; charset=UTF8")); + assertTrue(apiClient.isJsonMime("APPLICATION/JSON")); + + assertTrue(apiClient.isJsonMime("application/problem+json")); + assertTrue(apiClient.isJsonMime("APPLICATION/PROBLEM+JSON")); + assertTrue(apiClient.isJsonMime("application/json\t")); + assertTrue(apiClient.isJsonMime("example/foo+bar+json")); + assertTrue(apiClient.isJsonMime("example/foo+json;x;y")); + assertTrue(apiClient.isJsonMime("example/foo+json\t;")); + assertTrue(apiClient.isJsonMime("Example/fOO+JSON")); + + assertTrue(apiClient.isJsonMime("application/json-patch+json")); + } + + @Test + public void testSelectHeaderAccept() { + String[] accepts = {"application/json", "application/xml"}; + assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"text/plain", "application/xml"}; + assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{}; + assertNull(apiClient.selectHeaderAccept(accepts)); + } + + @Test + public void testSelectHeaderContentType() { + String[] contentTypes = {"application/json", "application/xml"}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"text/plain", "application/xml"}; + assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + } + + @Test + public void testGetAuthentications() { + Map auths = apiClient.getAuthentications(); + + Authentication auth = auths.get("api_key"); + assertNotNull(auth); + assertTrue(auth instanceof ApiKeyAuth); + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) auth; + assertEquals("header", apiKeyAuth.getLocation()); + assertEquals("api_key", apiKeyAuth.getParamName()); + + auth = auths.get("petstore_auth"); + assertTrue(auth instanceof OAuth); + assertSame(auth, apiClient.getAuthentication("petstore_auth")); + + assertNull(auths.get("unknown")); + + try { + auths.put("my_auth", new HttpBasicAuth()); + fail("the authentications returned should not be modifiable"); + } catch (UnsupportedOperationException e) { + } + } + + /* + @Test + public void testSetUsernameAndPassword() { + HttpBasicAuth auth = null; + for (Authentication _auth : apiClient.getAuthentications().values()) { + if (_auth instanceof HttpBasicAuth) { + auth = (HttpBasicAuth) _auth; + break; + } + } + auth.setUsername(null); + auth.setPassword(null); + + apiClient.setUsername("my-username"); + apiClient.setPassword("my-password"); + assertEquals("my-username", auth.getUsername()); + assertEquals("my-password", auth.getPassword()); + + // reset values + auth.setUsername(null); + auth.setPassword(null); + } + */ + + @Test + public void testSetApiKeyAndPrefix() { + ApiKeyAuth auth = null; + for (Authentication _auth : apiClient.getAuthentications().values()) { + if (_auth instanceof ApiKeyAuth) { + auth = (ApiKeyAuth) _auth; + break; + } + } + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + + apiClient.setApiKey("my-api-key"); + apiClient.setApiKeyPrefix("Token"); + assertEquals("my-api-key", auth.getApiKey()); + assertEquals("Token", auth.getApiKeyPrefix()); + + // reset values + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + } + + @Test + public void testGetAndSetConnectTimeout() { + // connect timeout defaults to 10 seconds + assertEquals(10000, apiClient.getConnectTimeout()); + assertEquals(10000, apiClient.getHttpClient().getConnectTimeout()); + + apiClient.setConnectTimeout(0); + assertEquals(0, apiClient.getConnectTimeout()); + assertEquals(0, apiClient.getHttpClient().getConnectTimeout()); + + apiClient.setConnectTimeout(10000); + } + + @Test + public void testGetAndSetReadTimeout() { + // read timeout defaults to 10 seconds + assertEquals(10000, apiClient.getReadTimeout()); + assertEquals(10000, apiClient.getHttpClient().getReadTimeout()); + + apiClient.setReadTimeout(0); + assertEquals(0, apiClient.getReadTimeout()); + assertEquals(0, apiClient.getHttpClient().getReadTimeout()); + + apiClient.setReadTimeout(10000); + } + + @Test + public void testGetAndSetWriteTimeout() { + // write timeout defaults to 10 seconds + assertEquals(10000, apiClient.getWriteTimeout()); + assertEquals(10000, apiClient.getHttpClient().getWriteTimeout()); + + apiClient.setWriteTimeout(0); + assertEquals(0, apiClient.getWriteTimeout()); + assertEquals(0, apiClient.getHttpClient().getWriteTimeout()); + + apiClient.setWriteTimeout(10000); + } + + @Test + public void testParameterToPairWhenNameIsInvalid() throws Exception { + List pairs_a = apiClient.parameterToPair(null, new Integer(1)); + List pairs_b = apiClient.parameterToPair("", new Integer(1)); + + assertTrue(pairs_a.isEmpty()); + assertTrue(pairs_b.isEmpty()); + } + + @Test + public void testParameterToPairWhenValueIsNull() throws Exception { + List pairs = apiClient.parameterToPair("param-a", null); + + assertTrue(pairs.isEmpty()); + } + + @Test + public void testParameterToPairWhenValueIsEmptyString() throws Exception { + // single empty string + List pairs = apiClient.parameterToPair("param-a", " "); + assertEquals(1, pairs.size()); + } + + @Test + public void testParameterToPairWhenValueIsNotCollection() throws Exception { + String name = "param-a"; + Integer value = 1; + + List pairs = apiClient.parameterToPair(name, value); + + assertEquals(1, pairs.size()); + assertEquals(value, Integer.valueOf(pairs.get(0).getValue())); + } + + @Test + public void testParameterToPairWhenValueIsCollection() throws Exception { + List values = new ArrayList(); + values.add("value-a"); + values.add(123); + values.add(new Date()); + + List pairs = apiClient.parameterToPair("param-a", values); + assertEquals(0, pairs.size()); + } + + @Test + public void testParameterToPairsWhenNameIsInvalid() throws Exception { + List objects = new ArrayList(); + objects.add(new Integer(1)); + + List pairs_a = apiClient.parameterToPairs("csv", null, objects); + List pairs_b = apiClient.parameterToPairs("csv", "", objects); + + assertTrue(pairs_a.isEmpty()); + assertTrue(pairs_b.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsNull() throws Exception { + List pairs = apiClient.parameterToPairs("csv", "param-a", null); + + assertTrue(pairs.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception { + // list of empty strings + List strs = new ArrayList(); + strs.add(" "); + strs.add(" "); + strs.add(" "); + + List concatStrings = apiClient.parameterToPairs("csv", "param-a", strs); + + assertEquals(1, concatStrings.size()); + assertFalse(concatStrings.get(0).getValue().isEmpty()); // should contain some delimiters + } + + @Test + public void testParameterToPairsWhenValueIsCollection() throws Exception { + Map collectionFormatMap = new HashMap(); + collectionFormatMap.put("csv", ","); + collectionFormatMap.put("tsv", "\t"); + collectionFormatMap.put("ssv", " "); + collectionFormatMap.put("pipes", "|"); + collectionFormatMap.put("", ","); // no format, must default to csv + collectionFormatMap.put("unknown", ","); // all other formats, must default to csv + + String name = "param-a"; + + List values = new ArrayList(); + values.add("value-a"); + values.add(123); + values.add(new Date()); + + // check for multi separately + List multiPairs = apiClient.parameterToPairs("multi", name, values); + assertEquals(values.size(), multiPairs.size()); + for (int i = 0; i < values.size(); i++) { + assertEquals(apiClient.escapeString(apiClient.parameterToString(values.get(i))), multiPairs.get(i).getValue()); + } + + // all other formats + for (String collectionFormat : collectionFormatMap.keySet()) { + List pairs = apiClient.parameterToPairs(collectionFormat, name, values); + + assertEquals(1, pairs.size()); + + String delimiter = collectionFormatMap.get(collectionFormat); + if (!delimiter.equals(",")) { + // commas are not escaped because they are reserved characters in URIs + delimiter = apiClient.escapeString(delimiter); + } + String[] pairValueSplit = pairs.get(0).getValue().split(delimiter); + + // must equal input values + assertEquals(values.size(), pairValueSplit.length); + for (int i = 0; i < values.size(); i++) { + assertEquals(apiClient.escapeString(apiClient.parameterToString(values.get(i))), pairValueSplit[i]); + } + } + } + + @Test + public void testSanitizeFilename() { + assertEquals("sun", apiClient.sanitizeFilename("sun")); + assertEquals("sun.gif", apiClient.sanitizeFilename("sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("../sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("/var/tmp/sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("./sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("..\\sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("\\var\\tmp\\sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("c:\\var\\tmp\\sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename(".\\sun.gif")); + } +} diff --git a/CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/JSONTest.java b/CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/JSONTest.java new file mode 100644 index 0000000000..e7687d0b33 --- /dev/null +++ b/CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/JSONTest.java @@ -0,0 +1,201 @@ +package org.openapitools.client; + +import com.google.gson.reflect.TypeToken; + +import org.openapitools.client.model.Order; + +import java.lang.Exception; +import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; + +import okio.ByteString; +import org.junit.*; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; +import org.threeten.bp.ZoneId; +import org.threeten.bp.ZoneOffset; +import org.threeten.bp.format.DateTimeFormatter; + +import static org.junit.Assert.*; + +public class JSONTest { + private ApiClient apiClient = null; + private JSON json = null; + private Order order = null; + + @Before + public void setup() { + apiClient = new ApiClient(); + json = apiClient.getJSON(); + order = new Order(); + } + + @Test + public void testSqlDateTypeAdapter() { + final String str = "\"2015-11-07\""; + final java.sql.Date date = java.sql.Date.valueOf("2015-11-07"); + + assertEquals(str, json.serialize(date)); + assertEquals(json.deserialize(str, java.sql.Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T03:49:09.356" + getCurrentTimezoneOffset() + "\"", java.sql.Date.class).toString(), date.toString()); + + // custom date format: without day + DateFormat format = new SimpleDateFormat("yyyy-MM"); + apiClient.setSqlDateFormat(format); + String dateStr = "\"2015-11\""; + assertEquals(dateStr, json.serialize(json.deserialize("\"2015-11-07T03:49:09Z\"", java.sql.Date.class))); + assertEquals(dateStr, json.serialize(json.deserialize("\"2015-11\"", java.sql.Date.class))); + } + + @Test + public void testDateTypeAdapter() { + Calendar cal = new GregorianCalendar(2015, 10, 7, 3, 49, 9); + cal.setTimeZone(TimeZone.getTimeZone("UTC")); + + assertEquals(json.deserialize("\"2015-11-07T05:49:09+02\"", Date.class), cal.getTime()); + + cal.set(Calendar.MILLISECOND, 300); + assertEquals(json.deserialize("\"2015-11-07T03:49:09.3Z\"", Date.class), cal.getTime()); + + cal.set(Calendar.MILLISECOND, 356); + Date date = cal.getTime(); + + final String utcDate = "\"2015-11-07T03:49:09.356Z\""; + assertEquals(json.deserialize(utcDate, Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T03:49:09.356+00:00\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T05:49:09.356+02:00\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T02:49:09.356-01:00\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T03:49:09.356Z\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T03:49:09.356+00\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T02:49:09.356-0100\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T03:49:09.356456789Z\"", Date.class), date); + + assertEquals(utcDate, json.serialize(date)); + + // custom datetime format: without milli-seconds, custom time zone + DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); + format.setTimeZone(TimeZone.getTimeZone("GMT+10")); + apiClient.setDateFormat(format); + + String dateStr = "\"2015-11-07T13:49:09+10:00\""; + assertEquals(dateStr, json.serialize(json.deserialize("\"2015-11-07T03:49:09+00:00\"", Date.class))); + assertEquals(dateStr, json.serialize(json.deserialize("\"2015-11-07T03:49:09Z\"", Date.class))); + assertEquals(dateStr, json.serialize(json.deserialize("\"2015-11-07T00:49:09-03:00\"", Date.class))); + + try { + // invalid time zone format + json.deserialize("\"2015-11-07T03:49:09+00\"", Date.class); + fail("json parsing should fail"); + } catch (RuntimeException e) { + // OK + } + try { + // unexpected miliseconds + json.deserialize("\"2015-11-07T03:49:09.000Z\"", Date.class); + fail("json parsing should fail"); + } catch (RuntimeException e) { + // OK + } + + } + + @Test + public void testOffsetDateTimeTypeAdapter() { + final String str = "\"2016-09-09T08:02:03.123-03:00\""; + OffsetDateTime date = OffsetDateTime.of(2016, 9, 9, 8, 2, 3, 123000000, ZoneOffset.of("-3")); + + assertEquals(str, json.serialize(date)); + //Use toString() instead of isEqual to verify that the offset is preserved + assertEquals(json.deserialize(str, OffsetDateTime.class).toString(), date.toString()); + } + + @Test + public void testLocalDateTypeAdapter() { + final String str = "\"2016-09-09\""; + final LocalDate date = LocalDate.of(2016, 9, 9); + + assertEquals(str, json.serialize(date)); + assertEquals(json.deserialize(str, LocalDate.class), date); + } + + + @Test + public void testDefaultDate() throws Exception { + final DateTimeFormatter datetimeFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME; + final String dateStr = "2015-11-07T14:11:05.267Z"; + order.setShipDate(datetimeFormat.parse(dateStr, OffsetDateTime.FROM)); + + String str = json.serialize(order); + Type type = new TypeToken() { }.getType(); + Order o = json.deserialize(str, type); + assertEquals(dateStr, datetimeFormat.format(o.getShipDate())); + } + + @Test + public void testCustomDate() throws Exception { + final DateTimeFormatter datetimeFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.of("Etc/GMT+2")); + final String dateStr = "2015-11-07T14:11:05-02:00"; + order.setShipDate(datetimeFormat.parse(dateStr, OffsetDateTime.FROM)); + + String str = json.serialize(order); + Type type = new TypeToken() { }.getType(); + Order o = json.deserialize(str, type); + assertEquals(dateStr, datetimeFormat.format(o.getShipDate())); + } + + @Test + public void testByteArrayTypeAdapterSerialization() { + // Arrange + final String expectedBytesAsString = "Let's pretend this a jpg or something"; + final byte[] expectedBytes = expectedBytesAsString.getBytes(StandardCharsets.UTF_8); + + // Act + String serializedBytesWithQuotes = json.serialize(expectedBytes); + + // Assert + String serializedBytes = serializedBytesWithQuotes.substring(1, serializedBytesWithQuotes.length() - 1); + if (json.getGson().htmlSafe()) { + serializedBytes = serializedBytes.replaceAll("\\\\u003d", "="); + } + ByteString actualAsByteString = ByteString.decodeBase64(serializedBytes); + byte[] actualBytes = actualAsByteString.toByteArray(); + assertEquals(expectedBytesAsString, new String(actualBytes, StandardCharsets.UTF_8)); + } + + @Test + public void testByteArrayTypeAdapterDeserialization() { + // Arrange + final String expectedBytesAsString = "Let's pretend this a jpg or something"; + final byte[] expectedBytes = expectedBytesAsString.getBytes(StandardCharsets.UTF_8); + final ByteString expectedByteString = ByteString.of(expectedBytes); + final String serializedBytes = expectedByteString.base64(); + final String serializedBytesWithQuotes = "\"" + serializedBytes + "\""; + Type type = new TypeToken() { }.getType(); + + // Act + byte[] actualDeserializedBytes = json.deserialize(serializedBytesWithQuotes, type); + + // Assert + assertEquals(expectedBytesAsString, new String(actualDeserializedBytes, StandardCharsets.UTF_8)); + } + + // 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); + int offsetInMillis = tz.getOffset(cal.getTimeInMillis()); + + String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60)); + offset = (offsetInMillis >= 0 ? "+" : "-") + offset; + + return offset; + } +} \ No newline at end of file diff --git a/CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/auth/ApiKeyAuthTest.java b/CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/auth/ApiKeyAuthTest.java new file mode 100644 index 0000000000..d5a8813230 --- /dev/null +++ b/CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/auth/ApiKeyAuthTest.java @@ -0,0 +1,76 @@ +package org.openapitools.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import org.openapitools.client.Pair; +import org.junit.*; +import static org.junit.Assert.*; + + +public class ApiKeyAuthTest { + @Test + public void testApplyToParamsInQuery() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); + auth.setApiKey("my-api-key"); + auth.applyToParams(queryParams, headerParams); + + assertEquals(1, queryParams.size()); + for (Pair queryParam : queryParams) { + assertEquals("my-api-key", queryParam.getValue()); + } + + // no changes to header parameters + assertEquals(0, headerParams.size()); + } + + @Test + public void testApplyToParamsInQueryWithNullValue() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); + auth.setApiKey(null); + auth.applyToParams(queryParams, headerParams); + + // no changes to parameters + assertEquals(0, queryParams.size()); + assertEquals(0, headerParams.size()); + } + + @Test + public void testApplyToParamsInHeaderWithPrefix() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); + auth.setApiKey("my-api-token"); + auth.setApiKeyPrefix("Token"); + auth.applyToParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN")); + } + + @Test + public void testApplyToParamsInHeaderWithNullValue() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); + auth.setApiKey(null); + auth.setApiKeyPrefix("Token"); + auth.applyToParams(queryParams, headerParams); + + // no changes to parameters + assertEquals(0, queryParams.size()); + assertEquals(0, headerParams.size()); + } +} diff --git a/CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/auth/HttpBasicAuthTest.java b/CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/auth/HttpBasicAuthTest.java new file mode 100644 index 0000000000..d27a15f4dc --- /dev/null +++ b/CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/auth/HttpBasicAuthTest.java @@ -0,0 +1,62 @@ +package org.openapitools.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import org.openapitools.client.Pair; +import org.junit.*; +import static org.junit.Assert.*; + + +public class HttpBasicAuthTest { + HttpBasicAuth auth = null; + + @Before + public void setup() { + auth = new HttpBasicAuth(); + } + + @Test + public void testApplyToParams() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + auth.setUsername("my-username"); + auth.setPassword("my-password"); + auth.applyToParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + // the string below is base64-encoded result of "my-username:my-password" with the "Basic " prefix + String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ="; + assertEquals(expected, headerParams.get("Authorization")); + + // null username should be treated as empty string + auth.setUsername(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of ":my-password" with the "Basic " prefix + expected = "Basic Om15LXBhc3N3b3Jk"; + assertEquals(expected, headerParams.get("Authorization")); + + // null password should be treated as empty string + auth.setUsername("my-username"); + auth.setPassword(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of "my-username:" with the "Basic " prefix + expected = "Basic bXktdXNlcm5hbWU6"; + assertEquals(expected, headerParams.get("Authorization")); + + // null username and password should be ignored + queryParams = new ArrayList(); + headerParams = new HashMap(); + auth.setUsername(null); + auth.setPassword(null); + auth.applyToParams(queryParams, headerParams); + // no changes to parameters + assertEquals(0, queryParams.size()); + assertEquals(0, headerParams.size()); + } +} diff --git a/CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/model/EnumValueTest.java b/CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/model/EnumValueTest.java new file mode 100644 index 0000000000..73440e547b --- /dev/null +++ b/CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/model/EnumValueTest.java @@ -0,0 +1,56 @@ +package org.openapitools.client.model; + +import org.junit.Test; + +import com.google.gson.Gson; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class EnumValueTest { + + @Test + public void testEnumClass() { + assertEquals(EnumClass._ABC.toString(), "_abc"); + assertEquals(EnumClass._EFG.toString(), "-efg"); + assertEquals(EnumClass._XYZ_.toString(), "(xyz)"); + } + + @Test + public void testEnumTest() { + // test enum value + EnumTest enumTest = new EnumTest(); + enumTest.setEnumString(EnumTest.EnumStringEnum.LOWER); + enumTest.setEnumInteger(EnumTest.EnumIntegerEnum.NUMBER_1); + enumTest.setEnumNumber(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1); + + assertEquals(EnumTest.EnumStringEnum.UPPER.toString(), "UPPER"); + assertEquals(EnumTest.EnumStringEnum.UPPER.getValue(), "UPPER"); + assertEquals(EnumTest.EnumStringEnum.LOWER.toString(), "lower"); + assertEquals(EnumTest.EnumStringEnum.LOWER.getValue(), "lower"); + + assertEquals(EnumTest.EnumIntegerEnum.NUMBER_1.toString(), "1"); + assertTrue(EnumTest.EnumIntegerEnum.NUMBER_1.getValue() == 1); + assertEquals(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.toString(), "-1"); + assertTrue(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.getValue() == -1); + + assertEquals(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.toString(), "1.1"); + assertTrue(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.getValue() == 1.1); + assertEquals(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.toString(), "-1.2"); + assertTrue(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.getValue() == -1.2); + + // test serialization + Gson gson = new Gson(); + String json = gson.toJson(enumTest); + assertEquals(json, "{\"enum_string\":\"lower\",\"enum_integer\":1,\"enum_number\":1.1}"); + + // test deserialization + EnumTest fromString = gson.fromJson(json, EnumTest.class); + assertEquals(fromString.getEnumString().toString(), "lower"); + assertEquals(fromString.getEnumString().getValue(), "lower"); + assertEquals(fromString.getEnumInteger().toString(), "1"); + assertTrue(fromString.getEnumInteger().getValue() == 1); + assertEquals(fromString.getEnumNumber().toString(), "1.1"); + assertTrue(fromString.getEnumNumber().getValue() == 1.1); + } +} diff --git a/CI/samples.ci/client/petstore/java/test-manual/resttemplate/ApiClientTest.java b/CI/samples.ci/client/petstore/java/test-manual/resttemplate/ApiClientTest.java new file mode 100644 index 0000000000..2113f5d245 --- /dev/null +++ b/CI/samples.ci/client/petstore/java/test-manual/resttemplate/ApiClientTest.java @@ -0,0 +1,254 @@ +package org.openapitools.client; + +import org.openapitools.client.auth.*; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.*; + +import org.junit.*; +import org.springframework.http.MediaType; +import org.springframework.util.MultiValueMap; + +import static org.junit.Assert.*; + + +public class ApiClientTest { + ApiClient apiClient = null; + + @Before + public void setup() { + apiClient = new ApiClient(); + } + + /** + * + */ + @Test + public void testParseAndFormatDate() { + // default date format + String dateStr = "2015-11-07T03:49:09.356Z"; + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356+00:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356Z"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T05:49:09.356+02:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T02:49:09.356-01:00"))); + + // custom date format: without milli-seconds, custom time zone + DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); + format.setTimeZone(TimeZone.getTimeZone("GMT+10")); + apiClient.setDateFormat(format); + dateStr = "2015-11-07T13:49:09+10:00"; + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09+00:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09Z"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T00:49:09-03:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T13:49:09+10:00"))); + } + + @Test + public void testIsJsonMime() { + assertFalse(apiClient.isJsonMime((String) null)); + assertFalse(apiClient.isJsonMime("")); + assertFalse(apiClient.isJsonMime("text/plain")); + assertFalse(apiClient.isJsonMime("application/xml")); + assertFalse(apiClient.isJsonMime("application/jsonp")); + assertFalse(apiClient.isJsonMime("example/json")); + assertFalse(apiClient.isJsonMime("example/foo+bar+jsonx")); + assertFalse(apiClient.isJsonMime("example/foo+bar+xjson")); + + assertTrue(apiClient.isJsonMime("application/json")); + assertTrue(apiClient.isJsonMime("application/json; charset=UTF8")); + assertTrue(apiClient.isJsonMime("APPLICATION/JSON")); + + assertTrue(apiClient.isJsonMime("application/problem+json")); + assertTrue(apiClient.isJsonMime("APPLICATION/PROBLEM+JSON")); + assertTrue(apiClient.isJsonMime("application/json\t")); + assertTrue(apiClient.isJsonMime("example/foo+bar+json")); + assertTrue(apiClient.isJsonMime("example/foo+json;x;y")); + assertTrue(apiClient.isJsonMime("example/foo+json\t;")); + assertTrue(apiClient.isJsonMime("Example/fOO+JSON")); + } + + @Test + public void testSelectHeaderAccept() { + String[] accepts = {"application/json", "application/xml"}; + assertEquals(Arrays.asList(MediaType.parseMediaType("application/json")), apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"}; + assertEquals(Arrays.asList(MediaType.parseMediaType("APPLICATION/JSON")), apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals(Arrays.asList(MediaType.parseMediaType("application/json; charset=UTF8")), apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"text/plain", "application/xml"}; + assertEquals(Arrays.asList(MediaType.parseMediaType("text/plain"),MediaType.parseMediaType("application/xml")), apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{}; + assertNull(apiClient.selectHeaderAccept(accepts)); + } + + @Test + public void testSelectHeaderContentType() { + String[] contentTypes = {"application/json", "application/xml"}; + assertEquals(MediaType.parseMediaType("application/json"), apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"}; + assertEquals(MediaType.parseMediaType("APPLICATION/JSON"), apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals(MediaType.parseMediaType("application/json; charset=UTF8"), apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"text/plain", "application/xml"}; + assertEquals(MediaType.parseMediaType("text/plain"), apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{}; + assertEquals(MediaType.parseMediaType("application/json"), apiClient.selectHeaderContentType(contentTypes)); + } + + @Test + public void testGetAuthentications() { + Map auths = apiClient.getAuthentications(); + + Authentication auth = auths.get("api_key"); + assertNotNull(auth); + assertTrue(auth instanceof ApiKeyAuth); + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) auth; + assertEquals("header", apiKeyAuth.getLocation()); + assertEquals("api_key", apiKeyAuth.getParamName()); + + auth = auths.get("petstore_auth"); + assertTrue(auth instanceof OAuth); + assertSame(auth, apiClient.getAuthentication("petstore_auth")); + + assertNull(auths.get("unknown")); + + try { + auths.put("my_auth", new HttpBasicAuth()); + fail("the authentications returned should not be modifiable"); + } catch (UnsupportedOperationException e) { + } + } + + @Ignore("There is no more basic auth in petstore security definitions") + @Test + public void testSetUsernameAndPassword() { + HttpBasicAuth auth = null; + for (Authentication _auth : apiClient.getAuthentications().values()) { + if (_auth instanceof HttpBasicAuth) { + auth = (HttpBasicAuth) _auth; + break; + } + } + auth.setUsername(null); + auth.setPassword(null); + + apiClient.setUsername("my-username"); + apiClient.setPassword("my-password"); + assertEquals("my-username", auth.getUsername()); + assertEquals("my-password", auth.getPassword()); + + // reset values + auth.setUsername(null); + auth.setPassword(null); + } + + @Test + public void testSetApiKeyAndPrefix() { + ApiKeyAuth auth = null; + for (Authentication _auth : apiClient.getAuthentications().values()) { + if (_auth instanceof ApiKeyAuth) { + auth = (ApiKeyAuth) _auth; + break; + } + } + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + + apiClient.setApiKey("my-api-key"); + apiClient.setApiKeyPrefix("Token"); + assertEquals("my-api-key", auth.getApiKey()); + assertEquals("Token", auth.getApiKeyPrefix()); + + // reset values + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + } + + @Test + public void testParameterToMultiValueMapWhenNameIsInvalid() throws Exception { + MultiValueMap pairs_a = apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.CSV, null, new Integer(1)); + MultiValueMap pairs_b = apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.CSV, "", new Integer(1)); + + assertTrue(pairs_a.isEmpty()); + assertTrue(pairs_b.isEmpty()); + } + + @Test + public void testParameterToMultiValueMapWhenValueIsNull() throws Exception { + MultiValueMap pairs = apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.CSV, "param-a", null); + + assertTrue(pairs.isEmpty()); + } + + @Test + public void testParameterToMultiValueMapWhenValueIsEmptyStrings() throws Exception { + + // single empty string + MultiValueMap pairs = apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.CSV, "param-a", " "); + assertEquals(1, pairs.size()); + + // list of empty strings + List strs = new ArrayList(); + strs.add(" "); + strs.add(" "); + strs.add(" "); + + MultiValueMap concatStrings = apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.CSV, "param-a", strs); + + assertEquals(1, concatStrings.get("param-a").size()); + assertFalse(concatStrings.get("param-a").isEmpty()); // should contain some delimiters + } + + @Test + public void testParameterToMultiValueMapWhenValueIsNotCollection() throws Exception { + String name = "param-a"; + Integer value = 1; + + MultiValueMap pairs = apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.CSV, name, value); + + assertEquals(1, pairs.get(name).size()); + assertEquals(value, Integer.valueOf(pairs.get(name).get(0))); + } + + @Test + public void testParameterToMultiValueMapWhenValueIsCollection() throws Exception { + Map collectionFormatMap = new HashMap(); + collectionFormatMap.put(ApiClient.CollectionFormat.CSV, ","); + collectionFormatMap.put(ApiClient.CollectionFormat.TSV, "\t"); + collectionFormatMap.put(ApiClient.CollectionFormat.SSV, " "); + collectionFormatMap.put(ApiClient.CollectionFormat.PIPES, "\\|"); + collectionFormatMap.put(null, ","); // no format, must default to csv + + String name = "param-a"; + + List values = new ArrayList(); + values.add("value-a"); + values.add(123); + values.add(new Date()); + + // check for multi separately + MultiValueMap multiValueMap = apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.MULTI, name, values); + assertEquals(values.size(), multiValueMap.get(name).size()); + + // all other formats + for (ApiClient.CollectionFormat collectionFormat : collectionFormatMap.keySet()) { + MultiValueMap pairs = apiClient.parameterToMultiValueMap(collectionFormat, name, values); + + assertEquals(1, pairs.size()); + + String delimiter = collectionFormatMap.get(collectionFormat); + String[] pairValueSplit = pairs.get(name).get(0).split(delimiter); + + assertEquals(values.size(), pairValueSplit.length); + } + } +} diff --git a/CI/samples.ci/client/petstore/java/test-manual/resttemplate/auth/ApiKeyAuthTest.java b/CI/samples.ci/client/petstore/java/test-manual/resttemplate/auth/ApiKeyAuthTest.java new file mode 100644 index 0000000000..eef07a5309 --- /dev/null +++ b/CI/samples.ci/client/petstore/java/test-manual/resttemplate/auth/ApiKeyAuthTest.java @@ -0,0 +1,47 @@ +package org.openapitools.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import org.junit.*; +import org.springframework.http.HttpHeaders; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; + +import static org.junit.Assert.*; + +public class ApiKeyAuthTest { + @Test + public void testApplyToParamsInQuery() { + MultiValueMap queryParams = new LinkedMultiValueMap(); + HttpHeaders headerParams = new HttpHeaders(); + + ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); + auth.setApiKey("my-api-key"); + auth.applyToParams(queryParams, headerParams); + + assertEquals(1, queryParams.size()); + assertEquals("my-api-key", queryParams.get("api_key").get(0)); + + // no changes to header parameters + assertEquals(0, headerParams.size()); + } + + @Test + public void testApplyToParamsInHeaderWithPrefix() { + MultiValueMap queryParams = new LinkedMultiValueMap(); + HttpHeaders headerParams = new HttpHeaders(); + + ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); + auth.setApiKey("my-api-token"); + auth.setApiKeyPrefix("Token"); + auth.applyToParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN").get(0)); + } +} diff --git a/CI/samples.ci/client/petstore/java/test-manual/resttemplate/auth/HttpBasicAuthTest.java b/CI/samples.ci/client/petstore/java/test-manual/resttemplate/auth/HttpBasicAuthTest.java new file mode 100644 index 0000000000..04522ec56c --- /dev/null +++ b/CI/samples.ci/client/petstore/java/test-manual/resttemplate/auth/HttpBasicAuthTest.java @@ -0,0 +1,54 @@ +package org.openapitools.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import org.junit.*; +import org.springframework.http.HttpHeaders; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; + +import static org.junit.Assert.*; + +public class HttpBasicAuthTest { + HttpBasicAuth auth = null; + + @Before + public void setup() { + auth = new HttpBasicAuth(); + } + + @Test + public void testApplyToParams() { + MultiValueMap queryParams = new LinkedMultiValueMap(); + HttpHeaders headerParams = new HttpHeaders(); + + auth.setUsername("my-username"); + auth.setPassword("my-password"); + auth.applyToParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + // the string below is base64-encoded result of "my-username:my-password" with the "Basic " prefix + String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ="; + assertEquals(expected, headerParams.get("Authorization").get(0)); + + // null username should be treated as empty string + auth.setUsername(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of ":my-password" with the "Basic " prefix + expected = "Basic Om15LXBhc3N3b3Jk"; + assertEquals(expected, headerParams.get("Authorization").get(1)); + + // null password should be treated as empty string + auth.setUsername("my-username"); + auth.setPassword(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of "my-username:" with the "Basic " prefix + expected = "Basic bXktdXNlcm5hbWU6"; + assertEquals(expected, headerParams.get("Authorization").get(2)); + } +} diff --git a/CI/samples.ci/client/petstore/java/test-manual/resttemplate/model/EnumValueTest.java b/CI/samples.ci/client/petstore/java/test-manual/resttemplate/model/EnumValueTest.java new file mode 100644 index 0000000000..47bfe940d3 --- /dev/null +++ b/CI/samples.ci/client/petstore/java/test-manual/resttemplate/model/EnumValueTest.java @@ -0,0 +1,63 @@ +package org.openapitools.client.model; + +import org.junit.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.fasterxml.jackson.databind.SerializationFeature; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class EnumValueTest { + + @Test + public void testEnumClass() { + assertEquals(EnumClass._ABC.toString(), "_abc"); + assertEquals(EnumClass._EFG.toString(), "-efg"); + assertEquals(EnumClass._XYZ_.toString(), "(xyz)"); + } + + @Test + public void testEnumTest() { + // test enum value + EnumTest enumTest = new EnumTest(); + enumTest.setEnumString(EnumTest.EnumStringEnum.LOWER); + enumTest.setEnumInteger(EnumTest.EnumIntegerEnum.NUMBER_1); + enumTest.setEnumNumber(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1); + + assertEquals(EnumTest.EnumStringEnum.UPPER.toString(), "UPPER"); + assertEquals(EnumTest.EnumStringEnum.UPPER.getValue(), "UPPER"); + assertEquals(EnumTest.EnumStringEnum.LOWER.toString(), "lower"); + assertEquals(EnumTest.EnumStringEnum.LOWER.getValue(), "lower"); + + assertEquals(EnumTest.EnumIntegerEnum.NUMBER_1.toString(), "1"); + assertTrue(EnumTest.EnumIntegerEnum.NUMBER_1.getValue() == 1); + assertEquals(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.toString(), "-1"); + assertTrue(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.getValue() == -1); + + assertEquals(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.toString(), "1.1"); + assertTrue(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.getValue() == 1.1); + assertEquals(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.toString(), "-1.2"); + assertTrue(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.getValue() == -1.2); + + try { + // test serialization (object => json) + ObjectMapper mapper = new ObjectMapper(); + mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + ObjectWriter ow = mapper.writer(); + String json = ow.writeValueAsString(enumTest); + assertEquals(json, "{\"enum_string\":\"lower\",\"enum_string_required\":null,\"enum_integer\":1,\"enum_number\":1.1,\"outerEnum\":null}"); + + // test deserialization (json => object) + EnumTest fromString = mapper.readValue(json, EnumTest.class); + assertEquals(fromString.getEnumString().toString(), "lower"); + assertEquals(fromString.getEnumInteger().toString(), "1"); + assertEquals(fromString.getEnumNumber().toString(), "1.1"); + + } catch (Exception e) { + fail("Exception thrown during serialization/deserialzation of JSON: " + e.getMessage()); + } + } +} diff --git a/README.md b/README.md index e0b0a1e43c..02e6c8e33c 100644 --- a/README.md +++ b/README.md @@ -413,6 +413,7 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in - [GMO Pepabo](https://pepabo.com/en/) - [Raiffeisen Schweiz Genossenschaft](https://www.raiffeisen.ch) - [REST United](https://restunited.com) +- [Telstra](https://dev.telstra.com) - [unblu inc.](https://www.unblu.com/) diff --git a/bin/java-petstore-feign.sh b/bin/java-petstore-feign.sh index 5acd593dfc..d60d977be7 100755 --- a/bin/java-petstore-feign.sh +++ b/bin/java-petstore-feign.sh @@ -33,3 +33,8 @@ echo "Removing files and folders under samples/client/petstore/java/feign/src/ma rm -rf samples/client/petstore/java/feign/src/main find samples/client/petstore/java/feign -maxdepth 1 -type f ! -name "README.md" -exec rm {} + java $JAVA_OPTS -jar $executable $ags + +# copy additional manually written unit-tests +mkdir samples/client/petstore/java/feign/src/test/java/org/openapitools/client + +cp CI/samples.ci/client/petstore/java/test-manual/common/StringUtilTest.java samples/client/petstore/java/feign/src/test/java/org/openapitools/client/StringUtilTest.java \ No newline at end of file diff --git a/bin/java-petstore-jersey1.sh b/bin/java-petstore-jersey1.sh index 5ea0947fc6..caa69adfaf 100755 --- a/bin/java-petstore-jersey1.sh +++ b/bin/java-petstore-jersey1.sh @@ -33,3 +33,15 @@ echo "Removing files and folders under samples/client/petstore/java/jersey1/src/ rm -rf samples/client/petstore/java/jersey1/src/main find samples/client/petstore/java/jersey1 -maxdepth 1 -type f ! -name "README.md" -exec rm {} + java $JAVA_OPTS -jar $executable $ags + +# copy additional manually written unit-tests +mkdir samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client +mkdir samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/auth +mkdir samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/model + +cp CI/samples.ci/client/petstore/java/test-manual/common/StringUtilTest.java samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/StringUtilTest.java +cp CI/samples.ci/client/petstore/java/test-manual/jersey1/ApiClientTest.java samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/ApiClientTest.java +cp CI/samples.ci/client/petstore/java/test-manual/common/ConfigurationTest.java samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/ConfigurationTest.java +cp CI/samples.ci/client/petstore/java/test-manual/jersey1/auth/ApiKeyAuthTest.java samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java +cp CI/samples.ci/client/petstore/java/test-manual/jersey1/auth/HttpBasicAuthTest.java samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java +cp CI/samples.ci/client/petstore/java/test-manual/jersey1/model/EnumValueTest.java samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/model/EnumValueTest.java diff --git a/bin/java-petstore-jersey2-java6.sh b/bin/java-petstore-jersey2-java6.sh index fb887669a2..c9e71d722c 100755 --- a/bin/java-petstore-jersey2-java6.sh +++ b/bin/java-petstore-jersey2-java6.sh @@ -29,7 +29,7 @@ fi export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" ags="generate --artifact-id petstore-jersey2-java6 -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g java -c bin/java-petstore-jersey2.json -o samples/client/petstore/java/jersey2-java6 -DhideGenerationTimestamp=true,supportJava6=true $@" -echo "Removing files and folders under samples/client/petstore/java/jersey2/src/main" +echo "Removing files and folders under samples/client/petstore/java/jersey2-java6/src/main" rm -rf samples/client/petstore/java/jersey2-java6/src/main find samples/client/petstore/java/jersey2-java6 -maxdepth 1 -type f ! -name "README.md" -exec rm {} + java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore-jersey2.sh b/bin/java-petstore-jersey2.sh index 6b37fa3194..dda1a2da8c 100755 --- a/bin/java-petstore-jersey2.sh +++ b/bin/java-petstore-jersey2.sh @@ -33,3 +33,16 @@ echo "Removing files and folders under samples/client/petstore/java/jersey2/src/ rm -rf samples/client/petstore/java/jersey2/src/main find samples/client/petstore/java/jersey2 -maxdepth 1 -type f ! -name "README.md" -exec rm {} + java $JAVA_OPTS -jar $executable $ags + +# copy additional manually written unit-tests +mkdir samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client +mkdir samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/auth +mkdir samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/model + +cp CI/samples.ci/client/petstore/java/test-manual/common/StringUtilTest.java samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/StringUtilTest.java +cp CI/samples.ci/client/petstore/java/test-manual/jersey2/ApiClientTest.java samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/ApiClientTest.java +cp CI/samples.ci/client/petstore/java/test-manual/common/ConfigurationTest.java samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/ConfigurationTest.java +cp CI/samples.ci/client/petstore/java/test-manual/jersey2/auth/ApiKeyAuthTest.java samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java +cp CI/samples.ci/client/petstore/java/test-manual/jersey2/auth/HttpBasicAuthTest.java samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java +cp CI/samples.ci/client/petstore/java/test-manual/jersey2/model/EnumValueTest.java samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/model/EnumValueTest.java +cp CI/samples.ci/client/petstore/java/test-manual/jersey2/JSONTest.java samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/JSONTest.java diff --git a/bin/java-petstore-okhttp-gson.sh b/bin/java-petstore-okhttp-gson.sh index 755267573f..33a3c1903d 100755 --- a/bin/java-petstore-okhttp-gson.sh +++ b/bin/java-petstore-okhttp-gson.sh @@ -32,3 +32,16 @@ ags="generate -t modules/openapi-generator/src/main/resources/Java/libraries/okh rm -rf samples/client/petstore/java/okhttp-gson/src/main find samples/client/petstore/java/okhttp-gson -maxdepth 1 -type f ! -name "README.md" -exec rm {} + java $JAVA_OPTS -jar $executable $ags + +# copy additional manually written unit-tests +mkdir samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client +mkdir samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/auth +mkdir samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model + +cp CI/samples.ci/client/petstore/java/test-manual/common/StringUtilTest.java samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/StringUtilTest.java +cp CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/ApiClientTest.java samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/ApiClientTest.java +cp CI/samples.ci/client/petstore/java/test-manual/common/ConfigurationTest.java samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/ConfigurationTest.java +cp CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/auth/ApiKeyAuthTest.java samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java +cp CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/auth/HttpBasicAuthTest.java samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java +cp CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/model/EnumValueTest.java samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EnumValueTest.java +cp CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/JSONTest.java samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/JSONTest.java diff --git a/bin/java-petstore-resttemplate.sh b/bin/java-petstore-resttemplate.sh index 3ff4a22189..dbf04c44cc 100755 --- a/bin/java-petstore-resttemplate.sh +++ b/bin/java-petstore-resttemplate.sh @@ -33,3 +33,13 @@ echo "Removing files and folders under samples/client/petstore/java/resttemplate rm -rf samples/client/petstore/java/resttemplate/src/main find samples/client/petstore/java/resttemplate -maxdepth 1 -type f ! -name "README.md" -exec rm {} + java $JAVA_OPTS -jar $executable $ags + +# copy additional manually written unit-tests +mkdir samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client +mkdir samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/auth +mkdir samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/model + +cp CI/samples.ci/client/petstore/java/test-manual/resttemplate/ApiClientTest.java samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/ApiClientTest.java +cp CI/samples.ci/client/petstore/java/test-manual/resttemplate/auth/ApiKeyAuthTest.java samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java +cp CI/samples.ci/client/petstore/java/test-manual/resttemplate/auth/HttpBasicAuthTest.java samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java +cp CI/samples.ci/client/petstore/java/test-manual/resttemplate/model/EnumValueTest.java samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/model/EnumValueTest.java diff --git a/bin/java8-petstore-jersey2.sh b/bin/java8-petstore-jersey2.sh index 93338d9ad6..8f32b34120 100755 --- a/bin/java8-petstore-jersey2.sh +++ b/bin/java8-petstore-jersey2.sh @@ -33,3 +33,16 @@ echo "Removing files and folders under samples/client/petstore/java/jersey2-java rm -rf samples/client/petstore/java/jersey2-java8/src/main find samples/client/petstore/java/jersey2-java8 -maxdepth 1 -type f ! -name "README.md" -exec rm {} + java $JAVA_OPTS -jar $executable $ags + +# copy additional manually written unit-tests +mkdir samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client +mkdir samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/auth +mkdir samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/model + +cp CI/samples.ci/client/petstore/java/test-manual/common/StringUtilTest.java samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/StringUtilTest.java +cp CI/samples.ci/client/petstore/java/test-manual/jersey2/ApiClientTest.java samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/ApiClientTest.java +cp CI/samples.ci/client/petstore/java/test-manual/common/ConfigurationTest.java samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/ConfigurationTest.java +cp CI/samples.ci/client/petstore/java/test-manual/jersey2/auth/ApiKeyAuthTest.java samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java +cp CI/samples.ci/client/petstore/java/test-manual/jersey2/auth/HttpBasicAuthTest.java samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java +cp CI/samples.ci/client/petstore/java/test-manual/jersey2/model/EnumValueTest.java samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/model/EnumValueTest.java +cp CI/samples.ci/client/petstore/java/test-manual/jersey2-java8/JSONTest.java samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/JSONTest.java \ No newline at end of file diff --git a/docs/roadmap.adoc b/docs/roadmap.adoc new file mode 100644 index 0000000000..e6d1a0af6a --- /dev/null +++ b/docs/roadmap.adoc @@ -0,0 +1,79 @@ +== Roadmap + +This document lists short-term, medium-term, and long-term goals for the project. + +[NOTE] +==== +These are goals, not necessarily commitments. The sections are not intended to represent exclusive focus during these terms. For example, when you start at a college or university you may have a long-term goal to graduate and a short-term goal to find a job for supplemental income. We will similarly work toward many of our medium-term and long-term goals in the near future as we move toward meeting our short-term goals. +==== + +=== Short-term + +> Usability, stability, and marketing. + +Short term are focused on improving contributor and user productivity (part of this is getting the word out). + +* CLI improvements +** Search functionality (e.g. what generators support retrofit, what generators are available for kotlin) +* Build automation improvements +** Discuss consolidating current third-party build systems +** Investigate custom docker containerization for prepared build environments +** Automated release stability +* General +** OAS3.0 features support: anyOf, oneOf, callbacks, etc +** Consider opt-in telemetry about generators being used, limited to a counter of invocations by generator name). This would allow us to make prioritization decisions based on statistics. +** Code clean up +*** centralize build scripts +*** organize samples/bin scripts according to new generator names +*** consolidate typescript generators +*** jaxrs => use Swagger core v3 (see https://github.com/OpenAPITools/openapi-generator/issues/27[#27]) +* Documentation +** Static pages, preferably on gh-pages, devoted to each generator +** Explain generator options +** Centralized docs on generated code usage/examples/configuration + +=== Medium-term + +> Feature set, well-defined API (code and templates), and extensibility improvements. + +* API +** Typed representation of the model bound to our templates. As it is, everything is treated an an Object, and this can lead to changes in the interface which might be unexpected from the template perspective. +* Feature set (potential generators to add; not an exhaustive list) +** Azure functions (node.js, server) +** Finagle HTTP Client (Scala, client) +** Finagle Http Server (Scala, server) +** Finatra (Scala, server) +** Kotlin Spring MVC/Springboot (server) +** C++ Server, any framework (server) +* General +** Migrate from Maven to Gradle +** Java 9+ support +* Feature set (other options to investigate) +** SPI plugins +*** Templating engine +*** Language extensions +*** Custom extensions (e.g. allowing users to load support for https://github.com/Azure/azure-rest-api-specs[azure-rest-api-specs]) +** Customizable templating engines (handlebars support) +** Unit-testing templates (to previously mentioned explicit type as an interface to the template) +* Reduce coupling +** Make types extending `CodegenConfig` become the generation entrypoint +** Allow current `CodegenConfig` types to define templating engine +** Allow current `CodegenConfig` types to modify workflow (currently encapsulated in `DefaultGenerator` and tightly coupled to the template engine +** Clearer reuse of "language" features, outside of "generator" types. That is, rather than enforcing polymorphic sharing of "language" which currently allows the super type to redefine framework-specific mapping functionality, generators could compose one or more language support types. +* Define template deprecation/removal process + +=== Long-term + +> Expanding tooling offered, integrations, potentially SaaS offering to partially fund efforts. + +* Generator UI wrappers +** Move jimschubert/intellij-swagger-codegen plugin under the org, and rename +** Look into an Eclipse UI wrapper around the generator +** Look at Visual Studio Code (and/or Atom, sublime text) integration +* Provide a native GUI for viewing/editing specs. Most tools are currently geared toward developers, but often times it may be non-technical business users who are interested in an API. +* A paid service (SaaS) for generation may be enticing for some users. Such a service would allow for statistics (mentioned earlier in telemetry) +* Additional tools +** node.js build system(s) integration (grunt/gulp/webpack/etc) +** ruby gem +** others (which may require previously mentioned SaaS API) + diff --git a/modules/openapi-generator/src/main/resources/php/api.mustache b/modules/openapi-generator/src/main/resources/php/api.mustache index 15a18da56b..776ebc1420 100644 --- a/modules/openapi-generator/src/main/resources/php/api.mustache +++ b/modules/openapi-generator/src/main/resources/php/api.mustache @@ -95,7 +95,7 @@ use {{invokerPackage}}\ObjectSerializer; * * @throws \{{invokerPackage}}\ApiException on non-2xx response * @throws \InvalidArgumentException - * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} + * @return {{#returnType}}{{#responses}}{{#dataType}}{{^-first}}|{{/-first}}{{/dataType}}{{{dataType}}}{{/responses}}{{/returnType}}{{^returnType}}void{{/returnType}} */ public function {{operationId}}({{#allParams}}${{paramName}}{{^required}} = {{#defaultValue}}{{{.}}}{{/defaultValue}}{{^defaultValue}}null{{/defaultValue}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { @@ -120,11 +120,10 @@ use {{invokerPackage}}\ObjectSerializer; * * @throws \{{invokerPackage}}\ApiException on non-2xx response * @throws \InvalidArgumentException - * @return array of {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}null{{/returnType}}, HTTP status code, HTTP response headers (array of strings) + * @return array of {{#returnType}}{{#responses}}{{#dataType}}{{^-first}}|{{/-first}}{{/dataType}}{{{dataType}}}{{/responses}}{{/returnType}}{{^returnType}}null{{/returnType}}, HTTP status code, HTTP response headers (array of strings) */ public function {{operationId}}WithHttpInfo({{#allParams}}${{paramName}}{{^required}} = {{#defaultValue}}{{{.}}}{{/defaultValue}}{{^defaultValue}}null{{/defaultValue}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { - $returnType = '{{returnType}}'; $request = $this->{{operationId}}Request({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); try { @@ -154,8 +153,36 @@ use {{invokerPackage}}\ObjectSerializer; $response->getBody() ); } - {{#returnType}} + {{#responses}} + {{#-first}} + + $responseBody = $response->getBody(); + switch($statusCode) { + {{/-first}} + {{#dataType}} + {{^isWildcard}}case {{code}}:{{/isWildcard}}{{#isWildcard}}default:{{/isWildcard}} + if ('{{dataType}}' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('{{dataType}}' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, '{{dataType}}', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + {{/dataType}} + {{#-last}} + } + {{/-last}} + {{/responses}} + + $returnType = '{{returnType}}'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer @@ -173,6 +200,7 @@ use {{invokerPackage}}\ObjectSerializer; ]; {{/returnType}} {{^returnType}} + return [null, $statusCode, $response->getHeaders()]; {{/returnType}} diff --git a/samples/client/petstore-security-test/php/OpenAPIClient-php/lib/Api/FakeApi.php b/samples/client/petstore-security-test/php/OpenAPIClient-php/lib/Api/FakeApi.php index 3043c1e097..e7c29a0121 100644 --- a/samples/client/petstore-security-test/php/OpenAPIClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore-security-test/php/OpenAPIClient-php/lib/Api/FakeApi.php @@ -116,7 +116,6 @@ class FakeApi */ public function testCodeInjectEndRnNRWithHttpInfo($unknown_base_type = null) { - $returnType = ''; $request = $this->testCodeInjectEndRnNRRequest($unknown_base_type); try { diff --git a/samples/client/petstore/java/feign/src/test/java/org/openapitools/client/StringUtilTest.java b/samples/client/petstore/java/feign/src/test/java/org/openapitools/client/StringUtilTest.java new file mode 100644 index 0000000000..aa7c81759e --- /dev/null +++ b/samples/client/petstore/java/feign/src/test/java/org/openapitools/client/StringUtilTest.java @@ -0,0 +1,33 @@ +package org.openapitools.client; + +import org.junit.*; +import static org.junit.Assert.*; + + +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/jersey1/src/test/java/org/openapitools/client/ApiClientTest.java b/samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/ApiClientTest.java new file mode 100644 index 0000000000..a890ead935 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/ApiClientTest.java @@ -0,0 +1,292 @@ +package org.openapitools.client; + +import org.openapitools.client.auth.*; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.*; + +import org.junit.*; +import static org.junit.Assert.*; + + +public class ApiClientTest { + ApiClient apiClient = null; + + @Before + public void setup() { + apiClient = new ApiClient(); + } + + @Test + public void testParseAndFormatDate() { + // default date format + String dateStr = "2015-11-07T03:49:09.356Z"; + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356+00:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356Z"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T05:49:09.356+02:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T02:49:09.356-01:00"))); + + // custom date format: without milli-seconds, custom time zone + DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); + format.setTimeZone(TimeZone.getTimeZone("GMT+10")); + apiClient.setDateFormat(format); + dateStr = "2015-11-07T13:49:09+10:00"; + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09+00:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09Z"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T00:49:09-03:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T13:49:09+10:00"))); + } + + @Test + public void testIsJsonMime() { + assertFalse(apiClient.isJsonMime(null)); + assertFalse(apiClient.isJsonMime("")); + assertFalse(apiClient.isJsonMime("text/plain")); + assertFalse(apiClient.isJsonMime("application/xml")); + assertFalse(apiClient.isJsonMime("application/jsonp")); + assertFalse(apiClient.isJsonMime("example/json")); + assertFalse(apiClient.isJsonMime("example/foo+bar+jsonx")); + assertFalse(apiClient.isJsonMime("example/foo+bar+xjson")); + + assertTrue(apiClient.isJsonMime("application/json")); + assertTrue(apiClient.isJsonMime("application/json; charset=UTF8")); + assertTrue(apiClient.isJsonMime("APPLICATION/JSON")); + + assertTrue(apiClient.isJsonMime("application/problem+json")); + assertTrue(apiClient.isJsonMime("APPLICATION/PROBLEM+JSON")); + assertTrue(apiClient.isJsonMime("application/json\t")); + assertTrue(apiClient.isJsonMime("example/foo+bar+json")); + assertTrue(apiClient.isJsonMime("example/foo+json;x;y")); + assertTrue(apiClient.isJsonMime("example/foo+json\t;")); + assertTrue(apiClient.isJsonMime("Example/fOO+JSON")); + } + + @Test + public void testSelectHeaderAccept() { + String[] accepts = {"application/json", "application/xml"}; + assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"text/plain", "application/xml"}; + assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{}; + assertNull(apiClient.selectHeaderAccept(accepts)); + } + + @Test + public void testSelectHeaderContentType() { + String[] contentTypes = {"application/json", "application/xml"}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"text/plain", "application/xml"}; + assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + } + + @Test + public void testGetAuthentications() { + Map auths = apiClient.getAuthentications(); + + Authentication auth = auths.get("api_key"); + assertNotNull(auth); + assertTrue(auth instanceof ApiKeyAuth); + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) auth; + assertEquals("header", apiKeyAuth.getLocation()); + assertEquals("api_key", apiKeyAuth.getParamName()); + + auth = auths.get("petstore_auth"); + assertTrue(auth instanceof OAuth); + assertSame(auth, apiClient.getAuthentication("petstore_auth")); + + assertNull(auths.get("unknown")); + + try { + auths.put("my_auth", new HttpBasicAuth()); + fail("the authentications returned should not be modifiable"); + } catch (UnsupportedOperationException e) { + } + } + + @Ignore("There is no more basic auth in petstore security definitions") + @Test + public void testSetUsernameAndPassword() { + HttpBasicAuth auth = null; + for (Authentication _auth : apiClient.getAuthentications().values()) { + if (_auth instanceof HttpBasicAuth) { + auth = (HttpBasicAuth) _auth; + break; + } + } + auth.setUsername(null); + auth.setPassword(null); + + apiClient.setUsername("my-username"); + apiClient.setPassword("my-password"); + assertEquals("my-username", auth.getUsername()); + assertEquals("my-password", auth.getPassword()); + + // reset values + auth.setUsername(null); + auth.setPassword(null); + } + + @Test + public void testSetApiKeyAndPrefix() { + ApiKeyAuth auth = null; + for (Authentication _auth : apiClient.getAuthentications().values()) { + if (_auth instanceof ApiKeyAuth) { + auth = (ApiKeyAuth) _auth; + break; + } + } + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + + apiClient.setApiKey("my-api-key"); + apiClient.setApiKeyPrefix("Token"); + assertEquals("my-api-key", auth.getApiKey()); + assertEquals("Token", auth.getApiKeyPrefix()); + + // reset values + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + } + + @Test + public void testParameterToPairWhenNameIsInvalid() throws Exception { + List pairs_a = apiClient.parameterToPair(null, new Integer(1)); + List pairs_b = apiClient.parameterToPair("", new Integer(1)); + + assertTrue(pairs_a.isEmpty()); + assertTrue(pairs_b.isEmpty()); + } + + @Test + public void testParameterToPairWhenValueIsNull() throws Exception { + List pairs = apiClient.parameterToPair("param-a", null); + + assertTrue(pairs.isEmpty()); + } + + @Test + public void testParameterToPairWhenValueIsEmptyString() throws Exception { + // single empty string + List pairs = apiClient.parameterToPair("param-a", " "); + assertEquals(1, pairs.size()); + } + + @Test + public void testParameterToPairWhenValueIsNotCollection() throws Exception { + String name = "param-a"; + Integer value = 1; + + List pairs = apiClient.parameterToPair(name, value); + + assertEquals(1, pairs.size()); + assertEquals(value, Integer.valueOf(pairs.get(0).getValue())); + } + + @Test + public void testParameterToPairWhenValueIsCollection() throws Exception { + List values = new ArrayList(); + values.add("value-a"); + values.add(123); + values.add(new Date()); + + List pairs = apiClient.parameterToPair("param-a", values); + assertEquals(0, pairs.size()); + } + + @Test + public void testParameterToPairsWhenNameIsInvalid() throws Exception { + List objects = new ArrayList(); + objects.add(new Integer(1)); + + List pairs_a = apiClient.parameterToPairs("csv", null, objects); + List pairs_b = apiClient.parameterToPairs("csv", "", objects); + + assertTrue(pairs_a.isEmpty()); + assertTrue(pairs_b.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsNull() throws Exception { + List pairs = apiClient.parameterToPairs("csv", "param-a", null); + + assertTrue(pairs.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception { + // list of empty strings + List strs = new ArrayList(); + strs.add(" "); + strs.add(" "); + strs.add(" "); + + List concatStrings = apiClient.parameterToPairs("csv", "param-a", strs); + + assertEquals(1, concatStrings.size()); + assertFalse(concatStrings.get(0).getValue().isEmpty()); // should contain some delimiters + } + + @Test + public void testParameterToPairsWhenValueIsCollection() throws Exception { + Map collectionFormatMap = new HashMap(); + collectionFormatMap.put("csv", ","); + collectionFormatMap.put("tsv", "\t"); + collectionFormatMap.put("ssv", " "); + collectionFormatMap.put("pipes", "|"); + collectionFormatMap.put("", ","); // no format, must default to csv + collectionFormatMap.put("unknown", ","); // all other formats, must default to csv + + String name = "param-a"; + + List values = new ArrayList(); + values.add("value-a"); + values.add(123); + values.add(new Date()); + + // check for multi separately + List multiPairs = apiClient.parameterToPairs("multi", name, values); + assertEquals(values.size(), multiPairs.size()); + for (int i = 0; i < values.size(); i++) { + assertEquals(apiClient.escapeString(apiClient.parameterToString(values.get(i))), multiPairs.get(i).getValue()); + } + + // all other formats + for (String collectionFormat : collectionFormatMap.keySet()) { + List pairs = apiClient.parameterToPairs(collectionFormat, name, values); + + assertEquals(1, pairs.size()); + + String delimiter = collectionFormatMap.get(collectionFormat); + if (!delimiter.equals(",")) { + // commas are not escaped because they are reserved characters in URIs + delimiter = apiClient.escapeString(delimiter); + } + String[] pairValueSplit = pairs.get(0).getValue().split(delimiter); + + // must equal input values + assertEquals(values.size(), pairValueSplit.length); + for (int i = 0; i < values.size(); i++) { + assertEquals(apiClient.escapeString(apiClient.parameterToString(values.get(i))), pairValueSplit[i]); + } + } + } +} diff --git a/samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/ConfigurationTest.java b/samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/ConfigurationTest.java new file mode 100644 index 0000000000..f05c230dc7 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/ConfigurationTest.java @@ -0,0 +1,15 @@ +package org.openapitools.client; + +import org.junit.*; +import static org.junit.Assert.*; + + +public class ConfigurationTest { + @Test + public void testDefaultApiClient() { + ApiClient apiClient = Configuration.getDefaultApiClient(); + assertNotNull(apiClient); + assertEquals("http://petstore.swagger.io:80/v2", apiClient.getBasePath()); + assertFalse(apiClient.isDebugging()); + } +} diff --git a/samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/StringUtilTest.java b/samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/StringUtilTest.java new file mode 100644 index 0000000000..aa7c81759e --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/StringUtilTest.java @@ -0,0 +1,33 @@ +package org.openapitools.client; + +import org.junit.*; +import static org.junit.Assert.*; + + +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/jersey1/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java new file mode 100644 index 0000000000..d9b17065f7 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java @@ -0,0 +1,47 @@ +package org.openapitools.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import org.openapitools.client.Pair; +import org.junit.*; +import static org.junit.Assert.*; + + +public class ApiKeyAuthTest { + @Test + public void testApplyToParamsInQuery() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); + auth.setApiKey("my-api-key"); + auth.applyToParams(queryParams, headerParams); + + assertEquals(1, queryParams.size()); + for (Pair queryParam : queryParams) { + assertEquals("my-api-key", queryParam.getValue()); + } + + // no changes to header parameters + assertEquals(0, headerParams.size()); + } + + @Test + public void testApplyToParamsInHeaderWithPrefix() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); + auth.setApiKey("my-api-token"); + auth.setApiKeyPrefix("Token"); + auth.applyToParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN")); + } +} diff --git a/samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java new file mode 100644 index 0000000000..668342d96d --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java @@ -0,0 +1,52 @@ +package org.openapitools.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import org.openapitools.client.Pair; +import org.junit.*; +import static org.junit.Assert.*; + + +public class HttpBasicAuthTest { + HttpBasicAuth auth = null; + + @Before + public void setup() { + auth = new HttpBasicAuth(); + } + + @Test + public void testApplyToParams() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + auth.setUsername("my-username"); + auth.setPassword("my-password"); + auth.applyToParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + // the string below is base64-encoded result of "my-username:my-password" with the "Basic " prefix + String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ="; + assertEquals(expected, headerParams.get("Authorization")); + + // null username should be treated as empty string + auth.setUsername(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of ":my-password" with the "Basic " prefix + expected = "Basic Om15LXBhc3N3b3Jk"; + assertEquals(expected, headerParams.get("Authorization")); + + // null password should be treated as empty string + auth.setUsername("my-username"); + auth.setPassword(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of "my-username:" with the "Basic " prefix + expected = "Basic bXktdXNlcm5hbWU6"; + assertEquals(expected, headerParams.get("Authorization")); + } +} diff --git a/samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/model/EnumValueTest.java b/samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/model/EnumValueTest.java new file mode 100644 index 0000000000..47bfe940d3 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/model/EnumValueTest.java @@ -0,0 +1,63 @@ +package org.openapitools.client.model; + +import org.junit.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.fasterxml.jackson.databind.SerializationFeature; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class EnumValueTest { + + @Test + public void testEnumClass() { + assertEquals(EnumClass._ABC.toString(), "_abc"); + assertEquals(EnumClass._EFG.toString(), "-efg"); + assertEquals(EnumClass._XYZ_.toString(), "(xyz)"); + } + + @Test + public void testEnumTest() { + // test enum value + EnumTest enumTest = new EnumTest(); + enumTest.setEnumString(EnumTest.EnumStringEnum.LOWER); + enumTest.setEnumInteger(EnumTest.EnumIntegerEnum.NUMBER_1); + enumTest.setEnumNumber(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1); + + assertEquals(EnumTest.EnumStringEnum.UPPER.toString(), "UPPER"); + assertEquals(EnumTest.EnumStringEnum.UPPER.getValue(), "UPPER"); + assertEquals(EnumTest.EnumStringEnum.LOWER.toString(), "lower"); + assertEquals(EnumTest.EnumStringEnum.LOWER.getValue(), "lower"); + + assertEquals(EnumTest.EnumIntegerEnum.NUMBER_1.toString(), "1"); + assertTrue(EnumTest.EnumIntegerEnum.NUMBER_1.getValue() == 1); + assertEquals(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.toString(), "-1"); + assertTrue(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.getValue() == -1); + + assertEquals(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.toString(), "1.1"); + assertTrue(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.getValue() == 1.1); + assertEquals(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.toString(), "-1.2"); + assertTrue(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.getValue() == -1.2); + + try { + // test serialization (object => json) + ObjectMapper mapper = new ObjectMapper(); + mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + ObjectWriter ow = mapper.writer(); + String json = ow.writeValueAsString(enumTest); + assertEquals(json, "{\"enum_string\":\"lower\",\"enum_string_required\":null,\"enum_integer\":1,\"enum_number\":1.1,\"outerEnum\":null}"); + + // test deserialization (json => object) + EnumTest fromString = mapper.readValue(json, EnumTest.class); + assertEquals(fromString.getEnumString().toString(), "lower"); + assertEquals(fromString.getEnumInteger().toString(), "1"); + assertEquals(fromString.getEnumNumber().toString(), "1.1"); + + } catch (Exception e) { + fail("Exception thrown during serialization/deserialzation of JSON: " + e.getMessage()); + } + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/ApiClientTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/ApiClientTest.java new file mode 100644 index 0000000000..6fb1e54b67 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/ApiClientTest.java @@ -0,0 +1,250 @@ +package org.openapitools.client; + +import org.openapitools.client.auth.*; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.*; + +import org.junit.*; +import static org.junit.Assert.*; + + +public class ApiClientTest { + ApiClient apiClient = null; + + @Before + public void setup() { + apiClient = new ApiClient(); + } + + @Test + public void testParseAndFormatDate() { + // default date format + String dateStr = "2015-11-07T03:49:09.356Z"; + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356+00:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356Z"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T05:49:09.356+02:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T02:49:09.356-01:00"))); + + // custom date format: without milli-seconds, custom time zone + DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); + format.setTimeZone(TimeZone.getTimeZone("GMT+10")); + apiClient.setDateFormat(format); + dateStr = "2015-11-07T13:49:09+10:00"; + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09+00:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09Z"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T00:49:09-03:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T13:49:09+10:00"))); + } + + @Test + public void testIsJsonMime() { + assertFalse(apiClient.isJsonMime(null)); + assertFalse(apiClient.isJsonMime("")); + assertFalse(apiClient.isJsonMime("text/plain")); + assertFalse(apiClient.isJsonMime("application/xml")); + assertFalse(apiClient.isJsonMime("application/jsonp")); + assertFalse(apiClient.isJsonMime("example/json")); + assertFalse(apiClient.isJsonMime("example/foo+bar+jsonx")); + assertFalse(apiClient.isJsonMime("example/foo+bar+xjson")); + + assertTrue(apiClient.isJsonMime("application/json")); + assertTrue(apiClient.isJsonMime("application/json; charset=UTF8")); + assertTrue(apiClient.isJsonMime("APPLICATION/JSON")); + + assertTrue(apiClient.isJsonMime("application/problem+json")); + assertTrue(apiClient.isJsonMime("APPLICATION/PROBLEM+JSON")); + assertTrue(apiClient.isJsonMime("application/json\t")); + assertTrue(apiClient.isJsonMime("example/foo+bar+json")); + assertTrue(apiClient.isJsonMime("example/foo+json;x;y")); + assertTrue(apiClient.isJsonMime("example/foo+json\t;")); + assertTrue(apiClient.isJsonMime("Example/fOO+JSON")); + } + + @Test + public void testSelectHeaderAccept() { + String[] accepts = {"application/json", "application/xml"}; + assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"text/plain", "application/xml"}; + assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{}; + assertNull(apiClient.selectHeaderAccept(accepts)); + } + + @Test + public void testSelectHeaderContentType() { + String[] contentTypes = {"application/json", "application/xml"}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"text/plain", "application/xml"}; + assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + } + + @Test + public void testGetAuthentications() { + Map auths = apiClient.getAuthentications(); + + Authentication auth = auths.get("api_key"); + assertNotNull(auth); + assertTrue(auth instanceof ApiKeyAuth); + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) auth; + assertEquals("header", apiKeyAuth.getLocation()); + assertEquals("api_key", apiKeyAuth.getParamName()); + + auth = auths.get("petstore_auth"); + assertTrue(auth instanceof OAuth); + assertSame(auth, apiClient.getAuthentication("petstore_auth")); + + assertNull(auths.get("unknown")); + + try { + auths.put("my_auth", new HttpBasicAuth()); + fail("the authentications returned should not be modifiable"); + } catch (UnsupportedOperationException e) { + } + } + + @Ignore("There is no more basic auth in petstore security definitions") + @Test + public void testSetUsernameAndPassword() { + HttpBasicAuth auth = null; + for (Authentication _auth : apiClient.getAuthentications().values()) { + if (_auth instanceof HttpBasicAuth) { + auth = (HttpBasicAuth) _auth; + break; + } + } + auth.setUsername(null); + auth.setPassword(null); + + apiClient.setUsername("my-username"); + apiClient.setPassword("my-password"); + assertEquals("my-username", auth.getUsername()); + assertEquals("my-password", auth.getPassword()); + + // reset values + auth.setUsername(null); + auth.setPassword(null); + } + + @Test + public void testSetApiKeyAndPrefix() { + ApiKeyAuth auth = null; + for (Authentication _auth : apiClient.getAuthentications().values()) { + if (_auth instanceof ApiKeyAuth) { + auth = (ApiKeyAuth) _auth; + break; + } + } + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + + apiClient.setApiKey("my-api-key"); + apiClient.setApiKeyPrefix("Token"); + assertEquals("my-api-key", auth.getApiKey()); + assertEquals("Token", auth.getApiKeyPrefix()); + + // reset values + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + } + + @Test + public void testParameterToPairsWhenNameIsInvalid() throws Exception { + List pairs_a = apiClient.parameterToPairs("csv", null, new Integer(1)); + List pairs_b = apiClient.parameterToPairs("csv", "", new Integer(1)); + + assertTrue(pairs_a.isEmpty()); + assertTrue(pairs_b.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsNull() throws Exception { + List pairs = apiClient.parameterToPairs("csv", "param-a", null); + + assertTrue(pairs.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception { + + // single empty string + List pairs = apiClient.parameterToPairs("csv", "param-a", " "); + assertEquals(1, pairs.size()); + + // list of empty strings + List strs = new ArrayList(); + strs.add(" "); + strs.add(" "); + strs.add(" "); + + List concatStrings = apiClient.parameterToPairs("csv", "param-a", strs); + + assertEquals(1, concatStrings.size()); + assertFalse(concatStrings.get(0).getValue().isEmpty()); // should contain some delimiters + } + + @Test + public void testParameterToPairsWhenValueIsNotCollection() throws Exception { + String name = "param-a"; + Integer value = 1; + + List pairs = apiClient.parameterToPairs("csv", name, value); + + assertEquals(1, pairs.size()); + assertEquals(value, Integer.valueOf(pairs.get(0).getValue())); + } + + @Test + public void testParameterToPairsWhenValueIsCollection() throws Exception { + Map collectionFormatMap = new HashMap(); + collectionFormatMap.put("csv", ","); + collectionFormatMap.put("tsv", "\t"); + collectionFormatMap.put("ssv", " "); + collectionFormatMap.put("pipes", "\\|"); + collectionFormatMap.put("", ","); // no format, must default to csv + collectionFormatMap.put("unknown", ","); // all other formats, must default to csv + + String name = "param-a"; + + List values = new ArrayList(); + values.add("value-a"); + values.add(123); + values.add(new Date()); + + // check for multi separately + List multiPairs = apiClient.parameterToPairs("multi", name, values); + assertEquals(values.size(), multiPairs.size()); + + // all other formats + for (String collectionFormat : collectionFormatMap.keySet()) { + List pairs = apiClient.parameterToPairs(collectionFormat, name, values); + + assertEquals(1, pairs.size()); + + String delimiter = collectionFormatMap.get(collectionFormat); + String[] pairValueSplit = pairs.get(0).getValue().split(delimiter); + + // must equal input values + assertEquals(values.size(), pairValueSplit.length); + } + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/ConfigurationTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/ConfigurationTest.java new file mode 100644 index 0000000000..f05c230dc7 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/ConfigurationTest.java @@ -0,0 +1,15 @@ +package org.openapitools.client; + +import org.junit.*; +import static org.junit.Assert.*; + + +public class ConfigurationTest { + @Test + public void testDefaultApiClient() { + ApiClient apiClient = Configuration.getDefaultApiClient(); + assertNotNull(apiClient); + assertEquals("http://petstore.swagger.io:80/v2", apiClient.getBasePath()); + assertFalse(apiClient.isDebugging()); + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/JSONTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/JSONTest.java new file mode 100644 index 0000000000..7fb307a3df --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/JSONTest.java @@ -0,0 +1,45 @@ +package org.openapitools.client; + +import org.openapitools.client.model.Order; + +import java.lang.Exception; + +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import org.junit.*; +import static org.junit.Assert.*; + + +public class JSONTest { + JSON json = null; + Order order = null; + + @Before + public void setup() { + json = new JSON(); + order = new Order(); + } + + @Test + public void testDefaultDate() throws Exception { + final DateTimeFormatter dateFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME; + final String dateStr = "2015-11-07T14:11:05.267Z"; + order.setShipDate(dateFormat.parse(dateStr, OffsetDateTime::from)); + + String str = json.getContext(null).writeValueAsString(order); + Order o = json.getContext(null).readValue(str, Order.class); + assertEquals(dateStr, dateFormat.format(o.getShipDate())); + } + + @Test + public void testCustomDate() throws Exception { + final DateTimeFormatter dateFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.of("Etc/GMT+2")); + final String dateStr = "2015-11-07T14:11:05-02:00"; + order.setShipDate(dateFormat.parse(dateStr, OffsetDateTime::from)); + + String str = json.getContext(null).writeValueAsString(order); + Order o = json.getContext(null).readValue(str, Order.class); + assertEquals(dateStr, dateFormat.format(o.getShipDate())); + } +} \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/StringUtilTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/StringUtilTest.java new file mode 100644 index 0000000000..aa7c81759e --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/StringUtilTest.java @@ -0,0 +1,33 @@ +package org.openapitools.client; + +import org.junit.*; +import static org.junit.Assert.*; + + +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/jersey2-java8/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java new file mode 100644 index 0000000000..d9b17065f7 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java @@ -0,0 +1,47 @@ +package org.openapitools.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import org.openapitools.client.Pair; +import org.junit.*; +import static org.junit.Assert.*; + + +public class ApiKeyAuthTest { + @Test + public void testApplyToParamsInQuery() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); + auth.setApiKey("my-api-key"); + auth.applyToParams(queryParams, headerParams); + + assertEquals(1, queryParams.size()); + for (Pair queryParam : queryParams) { + assertEquals("my-api-key", queryParam.getValue()); + } + + // no changes to header parameters + assertEquals(0, headerParams.size()); + } + + @Test + public void testApplyToParamsInHeaderWithPrefix() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); + auth.setApiKey("my-api-token"); + auth.setApiKeyPrefix("Token"); + auth.applyToParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN")); + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java new file mode 100644 index 0000000000..668342d96d --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java @@ -0,0 +1,52 @@ +package org.openapitools.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import org.openapitools.client.Pair; +import org.junit.*; +import static org.junit.Assert.*; + + +public class HttpBasicAuthTest { + HttpBasicAuth auth = null; + + @Before + public void setup() { + auth = new HttpBasicAuth(); + } + + @Test + public void testApplyToParams() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + auth.setUsername("my-username"); + auth.setPassword("my-password"); + auth.applyToParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + // the string below is base64-encoded result of "my-username:my-password" with the "Basic " prefix + String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ="; + assertEquals(expected, headerParams.get("Authorization")); + + // null username should be treated as empty string + auth.setUsername(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of ":my-password" with the "Basic " prefix + expected = "Basic Om15LXBhc3N3b3Jk"; + assertEquals(expected, headerParams.get("Authorization")); + + // null password should be treated as empty string + auth.setUsername("my-username"); + auth.setPassword(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of "my-username:" with the "Basic " prefix + expected = "Basic bXktdXNlcm5hbWU6"; + assertEquals(expected, headerParams.get("Authorization")); + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/model/EnumValueTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/model/EnumValueTest.java new file mode 100644 index 0000000000..47bfe940d3 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/model/EnumValueTest.java @@ -0,0 +1,63 @@ +package org.openapitools.client.model; + +import org.junit.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.fasterxml.jackson.databind.SerializationFeature; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class EnumValueTest { + + @Test + public void testEnumClass() { + assertEquals(EnumClass._ABC.toString(), "_abc"); + assertEquals(EnumClass._EFG.toString(), "-efg"); + assertEquals(EnumClass._XYZ_.toString(), "(xyz)"); + } + + @Test + public void testEnumTest() { + // test enum value + EnumTest enumTest = new EnumTest(); + enumTest.setEnumString(EnumTest.EnumStringEnum.LOWER); + enumTest.setEnumInteger(EnumTest.EnumIntegerEnum.NUMBER_1); + enumTest.setEnumNumber(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1); + + assertEquals(EnumTest.EnumStringEnum.UPPER.toString(), "UPPER"); + assertEquals(EnumTest.EnumStringEnum.UPPER.getValue(), "UPPER"); + assertEquals(EnumTest.EnumStringEnum.LOWER.toString(), "lower"); + assertEquals(EnumTest.EnumStringEnum.LOWER.getValue(), "lower"); + + assertEquals(EnumTest.EnumIntegerEnum.NUMBER_1.toString(), "1"); + assertTrue(EnumTest.EnumIntegerEnum.NUMBER_1.getValue() == 1); + assertEquals(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.toString(), "-1"); + assertTrue(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.getValue() == -1); + + assertEquals(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.toString(), "1.1"); + assertTrue(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.getValue() == 1.1); + assertEquals(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.toString(), "-1.2"); + assertTrue(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.getValue() == -1.2); + + try { + // test serialization (object => json) + ObjectMapper mapper = new ObjectMapper(); + mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + ObjectWriter ow = mapper.writer(); + String json = ow.writeValueAsString(enumTest); + assertEquals(json, "{\"enum_string\":\"lower\",\"enum_string_required\":null,\"enum_integer\":1,\"enum_number\":1.1,\"outerEnum\":null}"); + + // test deserialization (json => object) + EnumTest fromString = mapper.readValue(json, EnumTest.class); + assertEquals(fromString.getEnumString().toString(), "lower"); + assertEquals(fromString.getEnumInteger().toString(), "1"); + assertEquals(fromString.getEnumNumber().toString(), "1.1"); + + } catch (Exception e) { + fail("Exception thrown during serialization/deserialzation of JSON: " + e.getMessage()); + } + } +} diff --git a/samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/ApiClientTest.java b/samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/ApiClientTest.java new file mode 100644 index 0000000000..6fb1e54b67 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/ApiClientTest.java @@ -0,0 +1,250 @@ +package org.openapitools.client; + +import org.openapitools.client.auth.*; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.*; + +import org.junit.*; +import static org.junit.Assert.*; + + +public class ApiClientTest { + ApiClient apiClient = null; + + @Before + public void setup() { + apiClient = new ApiClient(); + } + + @Test + public void testParseAndFormatDate() { + // default date format + String dateStr = "2015-11-07T03:49:09.356Z"; + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356+00:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356Z"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T05:49:09.356+02:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T02:49:09.356-01:00"))); + + // custom date format: without milli-seconds, custom time zone + DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); + format.setTimeZone(TimeZone.getTimeZone("GMT+10")); + apiClient.setDateFormat(format); + dateStr = "2015-11-07T13:49:09+10:00"; + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09+00:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09Z"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T00:49:09-03:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T13:49:09+10:00"))); + } + + @Test + public void testIsJsonMime() { + assertFalse(apiClient.isJsonMime(null)); + assertFalse(apiClient.isJsonMime("")); + assertFalse(apiClient.isJsonMime("text/plain")); + assertFalse(apiClient.isJsonMime("application/xml")); + assertFalse(apiClient.isJsonMime("application/jsonp")); + assertFalse(apiClient.isJsonMime("example/json")); + assertFalse(apiClient.isJsonMime("example/foo+bar+jsonx")); + assertFalse(apiClient.isJsonMime("example/foo+bar+xjson")); + + assertTrue(apiClient.isJsonMime("application/json")); + assertTrue(apiClient.isJsonMime("application/json; charset=UTF8")); + assertTrue(apiClient.isJsonMime("APPLICATION/JSON")); + + assertTrue(apiClient.isJsonMime("application/problem+json")); + assertTrue(apiClient.isJsonMime("APPLICATION/PROBLEM+JSON")); + assertTrue(apiClient.isJsonMime("application/json\t")); + assertTrue(apiClient.isJsonMime("example/foo+bar+json")); + assertTrue(apiClient.isJsonMime("example/foo+json;x;y")); + assertTrue(apiClient.isJsonMime("example/foo+json\t;")); + assertTrue(apiClient.isJsonMime("Example/fOO+JSON")); + } + + @Test + public void testSelectHeaderAccept() { + String[] accepts = {"application/json", "application/xml"}; + assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"text/plain", "application/xml"}; + assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{}; + assertNull(apiClient.selectHeaderAccept(accepts)); + } + + @Test + public void testSelectHeaderContentType() { + String[] contentTypes = {"application/json", "application/xml"}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"text/plain", "application/xml"}; + assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + } + + @Test + public void testGetAuthentications() { + Map auths = apiClient.getAuthentications(); + + Authentication auth = auths.get("api_key"); + assertNotNull(auth); + assertTrue(auth instanceof ApiKeyAuth); + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) auth; + assertEquals("header", apiKeyAuth.getLocation()); + assertEquals("api_key", apiKeyAuth.getParamName()); + + auth = auths.get("petstore_auth"); + assertTrue(auth instanceof OAuth); + assertSame(auth, apiClient.getAuthentication("petstore_auth")); + + assertNull(auths.get("unknown")); + + try { + auths.put("my_auth", new HttpBasicAuth()); + fail("the authentications returned should not be modifiable"); + } catch (UnsupportedOperationException e) { + } + } + + @Ignore("There is no more basic auth in petstore security definitions") + @Test + public void testSetUsernameAndPassword() { + HttpBasicAuth auth = null; + for (Authentication _auth : apiClient.getAuthentications().values()) { + if (_auth instanceof HttpBasicAuth) { + auth = (HttpBasicAuth) _auth; + break; + } + } + auth.setUsername(null); + auth.setPassword(null); + + apiClient.setUsername("my-username"); + apiClient.setPassword("my-password"); + assertEquals("my-username", auth.getUsername()); + assertEquals("my-password", auth.getPassword()); + + // reset values + auth.setUsername(null); + auth.setPassword(null); + } + + @Test + public void testSetApiKeyAndPrefix() { + ApiKeyAuth auth = null; + for (Authentication _auth : apiClient.getAuthentications().values()) { + if (_auth instanceof ApiKeyAuth) { + auth = (ApiKeyAuth) _auth; + break; + } + } + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + + apiClient.setApiKey("my-api-key"); + apiClient.setApiKeyPrefix("Token"); + assertEquals("my-api-key", auth.getApiKey()); + assertEquals("Token", auth.getApiKeyPrefix()); + + // reset values + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + } + + @Test + public void testParameterToPairsWhenNameIsInvalid() throws Exception { + List pairs_a = apiClient.parameterToPairs("csv", null, new Integer(1)); + List pairs_b = apiClient.parameterToPairs("csv", "", new Integer(1)); + + assertTrue(pairs_a.isEmpty()); + assertTrue(pairs_b.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsNull() throws Exception { + List pairs = apiClient.parameterToPairs("csv", "param-a", null); + + assertTrue(pairs.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception { + + // single empty string + List pairs = apiClient.parameterToPairs("csv", "param-a", " "); + assertEquals(1, pairs.size()); + + // list of empty strings + List strs = new ArrayList(); + strs.add(" "); + strs.add(" "); + strs.add(" "); + + List concatStrings = apiClient.parameterToPairs("csv", "param-a", strs); + + assertEquals(1, concatStrings.size()); + assertFalse(concatStrings.get(0).getValue().isEmpty()); // should contain some delimiters + } + + @Test + public void testParameterToPairsWhenValueIsNotCollection() throws Exception { + String name = "param-a"; + Integer value = 1; + + List pairs = apiClient.parameterToPairs("csv", name, value); + + assertEquals(1, pairs.size()); + assertEquals(value, Integer.valueOf(pairs.get(0).getValue())); + } + + @Test + public void testParameterToPairsWhenValueIsCollection() throws Exception { + Map collectionFormatMap = new HashMap(); + collectionFormatMap.put("csv", ","); + collectionFormatMap.put("tsv", "\t"); + collectionFormatMap.put("ssv", " "); + collectionFormatMap.put("pipes", "\\|"); + collectionFormatMap.put("", ","); // no format, must default to csv + collectionFormatMap.put("unknown", ","); // all other formats, must default to csv + + String name = "param-a"; + + List values = new ArrayList(); + values.add("value-a"); + values.add(123); + values.add(new Date()); + + // check for multi separately + List multiPairs = apiClient.parameterToPairs("multi", name, values); + assertEquals(values.size(), multiPairs.size()); + + // all other formats + for (String collectionFormat : collectionFormatMap.keySet()) { + List pairs = apiClient.parameterToPairs(collectionFormat, name, values); + + assertEquals(1, pairs.size()); + + String delimiter = collectionFormatMap.get(collectionFormat); + String[] pairValueSplit = pairs.get(0).getValue().split(delimiter); + + // must equal input values + assertEquals(values.size(), pairValueSplit.length); + } + } +} diff --git a/samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/ConfigurationTest.java b/samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/ConfigurationTest.java new file mode 100644 index 0000000000..f05c230dc7 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/ConfigurationTest.java @@ -0,0 +1,15 @@ +package org.openapitools.client; + +import org.junit.*; +import static org.junit.Assert.*; + + +public class ConfigurationTest { + @Test + public void testDefaultApiClient() { + ApiClient apiClient = Configuration.getDefaultApiClient(); + assertNotNull(apiClient); + assertEquals("http://petstore.swagger.io:80/v2", apiClient.getBasePath()); + assertFalse(apiClient.isDebugging()); + } +} diff --git a/samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/JSONTest.java b/samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/JSONTest.java new file mode 100644 index 0000000000..f21b852065 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/JSONTest.java @@ -0,0 +1,58 @@ +package org.openapitools.client; + +import org.openapitools.client.model.Order; +import org.junit.Before; +import org.junit.Test; +import org.threeten.bp.OffsetDateTime; +import org.threeten.bp.ZoneId; +import org.threeten.bp.format.DateTimeFormatter; + +import static org.junit.Assert.*; + + +public class JSONTest { + private JSON json = null; + private Order order = null; + + @Before + public void setup() { + json = new ApiClient().getJSON(); + order = new Order(); + } + + @Test + public void testDefaultDate() throws Exception { + final DateTimeFormatter dateFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME; + final String dateStr = "2015-11-07T14:11:05.267Z"; + order.setShipDate(dateFormat.parse(dateStr, OffsetDateTime.FROM)); + + String str = json.getContext(null).writeValueAsString(order); + Order o = json.getContext(null).readValue(str, Order.class); + assertEquals(dateStr, dateFormat.format(o.getShipDate())); + } + + @Test + public void testCustomDate() throws Exception { + final DateTimeFormatter dateFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.of("Etc/GMT+2")); + final String dateStr = "2015-11-07T14:11:05-02:00"; + order.setShipDate(dateFormat.parse(dateStr, OffsetDateTime.FROM)); + + String str = json.getContext(null).writeValueAsString(order); + Order o = json.getContext(null).readValue(str, Order.class); + assertEquals(dateStr, dateFormat.format(o.getShipDate())); + } + + @Test + public void testSqlDateSerialization() throws Exception { + String str = json.getContext(null).writeValueAsString(new java.sql.Date(10)); + assertEquals("\"1970-01-01\"", str); + } + + @Test + public void testSqlDateDeserialization() throws Exception { + final String str = "1970-01-01"; + java.sql.Date date = json.getContext(null).readValue("\"" + str + "\"", java.sql.Date.class); + assertEquals(date.toString(), str); + } + +} \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/StringUtilTest.java b/samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/StringUtilTest.java new file mode 100644 index 0000000000..aa7c81759e --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/StringUtilTest.java @@ -0,0 +1,33 @@ +package org.openapitools.client; + +import org.junit.*; +import static org.junit.Assert.*; + + +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/jersey2/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java new file mode 100644 index 0000000000..d9b17065f7 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java @@ -0,0 +1,47 @@ +package org.openapitools.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import org.openapitools.client.Pair; +import org.junit.*; +import static org.junit.Assert.*; + + +public class ApiKeyAuthTest { + @Test + public void testApplyToParamsInQuery() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); + auth.setApiKey("my-api-key"); + auth.applyToParams(queryParams, headerParams); + + assertEquals(1, queryParams.size()); + for (Pair queryParam : queryParams) { + assertEquals("my-api-key", queryParam.getValue()); + } + + // no changes to header parameters + assertEquals(0, headerParams.size()); + } + + @Test + public void testApplyToParamsInHeaderWithPrefix() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); + auth.setApiKey("my-api-token"); + auth.setApiKeyPrefix("Token"); + auth.applyToParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN")); + } +} diff --git a/samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java new file mode 100644 index 0000000000..668342d96d --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java @@ -0,0 +1,52 @@ +package org.openapitools.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import org.openapitools.client.Pair; +import org.junit.*; +import static org.junit.Assert.*; + + +public class HttpBasicAuthTest { + HttpBasicAuth auth = null; + + @Before + public void setup() { + auth = new HttpBasicAuth(); + } + + @Test + public void testApplyToParams() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + auth.setUsername("my-username"); + auth.setPassword("my-password"); + auth.applyToParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + // the string below is base64-encoded result of "my-username:my-password" with the "Basic " prefix + String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ="; + assertEquals(expected, headerParams.get("Authorization")); + + // null username should be treated as empty string + auth.setUsername(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of ":my-password" with the "Basic " prefix + expected = "Basic Om15LXBhc3N3b3Jk"; + assertEquals(expected, headerParams.get("Authorization")); + + // null password should be treated as empty string + auth.setUsername("my-username"); + auth.setPassword(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of "my-username:" with the "Basic " prefix + expected = "Basic bXktdXNlcm5hbWU6"; + assertEquals(expected, headerParams.get("Authorization")); + } +} diff --git a/samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/model/EnumValueTest.java b/samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/model/EnumValueTest.java new file mode 100644 index 0000000000..47bfe940d3 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/model/EnumValueTest.java @@ -0,0 +1,63 @@ +package org.openapitools.client.model; + +import org.junit.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.fasterxml.jackson.databind.SerializationFeature; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class EnumValueTest { + + @Test + public void testEnumClass() { + assertEquals(EnumClass._ABC.toString(), "_abc"); + assertEquals(EnumClass._EFG.toString(), "-efg"); + assertEquals(EnumClass._XYZ_.toString(), "(xyz)"); + } + + @Test + public void testEnumTest() { + // test enum value + EnumTest enumTest = new EnumTest(); + enumTest.setEnumString(EnumTest.EnumStringEnum.LOWER); + enumTest.setEnumInteger(EnumTest.EnumIntegerEnum.NUMBER_1); + enumTest.setEnumNumber(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1); + + assertEquals(EnumTest.EnumStringEnum.UPPER.toString(), "UPPER"); + assertEquals(EnumTest.EnumStringEnum.UPPER.getValue(), "UPPER"); + assertEquals(EnumTest.EnumStringEnum.LOWER.toString(), "lower"); + assertEquals(EnumTest.EnumStringEnum.LOWER.getValue(), "lower"); + + assertEquals(EnumTest.EnumIntegerEnum.NUMBER_1.toString(), "1"); + assertTrue(EnumTest.EnumIntegerEnum.NUMBER_1.getValue() == 1); + assertEquals(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.toString(), "-1"); + assertTrue(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.getValue() == -1); + + assertEquals(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.toString(), "1.1"); + assertTrue(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.getValue() == 1.1); + assertEquals(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.toString(), "-1.2"); + assertTrue(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.getValue() == -1.2); + + try { + // test serialization (object => json) + ObjectMapper mapper = new ObjectMapper(); + mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + ObjectWriter ow = mapper.writer(); + String json = ow.writeValueAsString(enumTest); + assertEquals(json, "{\"enum_string\":\"lower\",\"enum_string_required\":null,\"enum_integer\":1,\"enum_number\":1.1,\"outerEnum\":null}"); + + // test deserialization (json => object) + EnumTest fromString = mapper.readValue(json, EnumTest.class); + assertEquals(fromString.getEnumString().toString(), "lower"); + assertEquals(fromString.getEnumInteger().toString(), "1"); + assertEquals(fromString.getEnumNumber().toString(), "1.1"); + + } catch (Exception e) { + fail("Exception thrown during serialization/deserialzation of JSON: " + e.getMessage()); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/ApiClientTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/ApiClientTest.java new file mode 100644 index 0000000000..5167afc326 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/ApiClientTest.java @@ -0,0 +1,330 @@ +package org.openapitools.client; + +import org.openapitools.client.auth.*; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.TimeZone; + +import org.junit.*; +import static org.junit.Assert.*; + + +public class ApiClientTest { + ApiClient apiClient; + JSON json; + + @Before + public void setup() { + apiClient = new ApiClient(); + json = apiClient.getJSON(); + } + + @Test + public void testIsJsonMime() { + assertFalse(apiClient.isJsonMime(null)); + assertFalse(apiClient.isJsonMime("")); + assertFalse(apiClient.isJsonMime("text/plain")); + assertFalse(apiClient.isJsonMime("application/xml")); + assertFalse(apiClient.isJsonMime("application/jsonp")); + assertFalse(apiClient.isJsonMime("example/json")); + assertFalse(apiClient.isJsonMime("example/foo+bar+jsonx")); + assertFalse(apiClient.isJsonMime("example/foo+bar+xjson")); + + assertTrue(apiClient.isJsonMime("application/json")); + assertTrue(apiClient.isJsonMime("application/json; charset=UTF8")); + assertTrue(apiClient.isJsonMime("APPLICATION/JSON")); + + assertTrue(apiClient.isJsonMime("application/problem+json")); + assertTrue(apiClient.isJsonMime("APPLICATION/PROBLEM+JSON")); + assertTrue(apiClient.isJsonMime("application/json\t")); + assertTrue(apiClient.isJsonMime("example/foo+bar+json")); + assertTrue(apiClient.isJsonMime("example/foo+json;x;y")); + assertTrue(apiClient.isJsonMime("example/foo+json\t;")); + assertTrue(apiClient.isJsonMime("Example/fOO+JSON")); + + assertTrue(apiClient.isJsonMime("application/json-patch+json")); + } + + @Test + public void testSelectHeaderAccept() { + String[] accepts = {"application/json", "application/xml"}; + assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"text/plain", "application/xml"}; + assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{}; + assertNull(apiClient.selectHeaderAccept(accepts)); + } + + @Test + public void testSelectHeaderContentType() { + String[] contentTypes = {"application/json", "application/xml"}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"text/plain", "application/xml"}; + assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + } + + @Test + public void testGetAuthentications() { + Map auths = apiClient.getAuthentications(); + + Authentication auth = auths.get("api_key"); + assertNotNull(auth); + assertTrue(auth instanceof ApiKeyAuth); + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) auth; + assertEquals("header", apiKeyAuth.getLocation()); + assertEquals("api_key", apiKeyAuth.getParamName()); + + auth = auths.get("petstore_auth"); + assertTrue(auth instanceof OAuth); + assertSame(auth, apiClient.getAuthentication("petstore_auth")); + + assertNull(auths.get("unknown")); + + try { + auths.put("my_auth", new HttpBasicAuth()); + fail("the authentications returned should not be modifiable"); + } catch (UnsupportedOperationException e) { + } + } + + /* + @Test + public void testSetUsernameAndPassword() { + HttpBasicAuth auth = null; + for (Authentication _auth : apiClient.getAuthentications().values()) { + if (_auth instanceof HttpBasicAuth) { + auth = (HttpBasicAuth) _auth; + break; + } + } + auth.setUsername(null); + auth.setPassword(null); + + apiClient.setUsername("my-username"); + apiClient.setPassword("my-password"); + assertEquals("my-username", auth.getUsername()); + assertEquals("my-password", auth.getPassword()); + + // reset values + auth.setUsername(null); + auth.setPassword(null); + } + */ + + @Test + public void testSetApiKeyAndPrefix() { + ApiKeyAuth auth = null; + for (Authentication _auth : apiClient.getAuthentications().values()) { + if (_auth instanceof ApiKeyAuth) { + auth = (ApiKeyAuth) _auth; + break; + } + } + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + + apiClient.setApiKey("my-api-key"); + apiClient.setApiKeyPrefix("Token"); + assertEquals("my-api-key", auth.getApiKey()); + assertEquals("Token", auth.getApiKeyPrefix()); + + // reset values + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + } + + @Test + public void testGetAndSetConnectTimeout() { + // connect timeout defaults to 10 seconds + assertEquals(10000, apiClient.getConnectTimeout()); + assertEquals(10000, apiClient.getHttpClient().getConnectTimeout()); + + apiClient.setConnectTimeout(0); + assertEquals(0, apiClient.getConnectTimeout()); + assertEquals(0, apiClient.getHttpClient().getConnectTimeout()); + + apiClient.setConnectTimeout(10000); + } + + @Test + public void testGetAndSetReadTimeout() { + // read timeout defaults to 10 seconds + assertEquals(10000, apiClient.getReadTimeout()); + assertEquals(10000, apiClient.getHttpClient().getReadTimeout()); + + apiClient.setReadTimeout(0); + assertEquals(0, apiClient.getReadTimeout()); + assertEquals(0, apiClient.getHttpClient().getReadTimeout()); + + apiClient.setReadTimeout(10000); + } + + @Test + public void testGetAndSetWriteTimeout() { + // write timeout defaults to 10 seconds + assertEquals(10000, apiClient.getWriteTimeout()); + assertEquals(10000, apiClient.getHttpClient().getWriteTimeout()); + + apiClient.setWriteTimeout(0); + assertEquals(0, apiClient.getWriteTimeout()); + assertEquals(0, apiClient.getHttpClient().getWriteTimeout()); + + apiClient.setWriteTimeout(10000); + } + + @Test + public void testParameterToPairWhenNameIsInvalid() throws Exception { + List pairs_a = apiClient.parameterToPair(null, new Integer(1)); + List pairs_b = apiClient.parameterToPair("", new Integer(1)); + + assertTrue(pairs_a.isEmpty()); + assertTrue(pairs_b.isEmpty()); + } + + @Test + public void testParameterToPairWhenValueIsNull() throws Exception { + List pairs = apiClient.parameterToPair("param-a", null); + + assertTrue(pairs.isEmpty()); + } + + @Test + public void testParameterToPairWhenValueIsEmptyString() throws Exception { + // single empty string + List pairs = apiClient.parameterToPair("param-a", " "); + assertEquals(1, pairs.size()); + } + + @Test + public void testParameterToPairWhenValueIsNotCollection() throws Exception { + String name = "param-a"; + Integer value = 1; + + List pairs = apiClient.parameterToPair(name, value); + + assertEquals(1, pairs.size()); + assertEquals(value, Integer.valueOf(pairs.get(0).getValue())); + } + + @Test + public void testParameterToPairWhenValueIsCollection() throws Exception { + List values = new ArrayList(); + values.add("value-a"); + values.add(123); + values.add(new Date()); + + List pairs = apiClient.parameterToPair("param-a", values); + assertEquals(0, pairs.size()); + } + + @Test + public void testParameterToPairsWhenNameIsInvalid() throws Exception { + List objects = new ArrayList(); + objects.add(new Integer(1)); + + List pairs_a = apiClient.parameterToPairs("csv", null, objects); + List pairs_b = apiClient.parameterToPairs("csv", "", objects); + + assertTrue(pairs_a.isEmpty()); + assertTrue(pairs_b.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsNull() throws Exception { + List pairs = apiClient.parameterToPairs("csv", "param-a", null); + + assertTrue(pairs.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception { + // list of empty strings + List strs = new ArrayList(); + strs.add(" "); + strs.add(" "); + strs.add(" "); + + List concatStrings = apiClient.parameterToPairs("csv", "param-a", strs); + + assertEquals(1, concatStrings.size()); + assertFalse(concatStrings.get(0).getValue().isEmpty()); // should contain some delimiters + } + + @Test + public void testParameterToPairsWhenValueIsCollection() throws Exception { + Map collectionFormatMap = new HashMap(); + collectionFormatMap.put("csv", ","); + collectionFormatMap.put("tsv", "\t"); + collectionFormatMap.put("ssv", " "); + collectionFormatMap.put("pipes", "|"); + collectionFormatMap.put("", ","); // no format, must default to csv + collectionFormatMap.put("unknown", ","); // all other formats, must default to csv + + String name = "param-a"; + + List values = new ArrayList(); + values.add("value-a"); + values.add(123); + values.add(new Date()); + + // check for multi separately + List multiPairs = apiClient.parameterToPairs("multi", name, values); + assertEquals(values.size(), multiPairs.size()); + for (int i = 0; i < values.size(); i++) { + assertEquals(apiClient.escapeString(apiClient.parameterToString(values.get(i))), multiPairs.get(i).getValue()); + } + + // all other formats + for (String collectionFormat : collectionFormatMap.keySet()) { + List pairs = apiClient.parameterToPairs(collectionFormat, name, values); + + assertEquals(1, pairs.size()); + + String delimiter = collectionFormatMap.get(collectionFormat); + if (!delimiter.equals(",")) { + // commas are not escaped because they are reserved characters in URIs + delimiter = apiClient.escapeString(delimiter); + } + String[] pairValueSplit = pairs.get(0).getValue().split(delimiter); + + // must equal input values + assertEquals(values.size(), pairValueSplit.length); + for (int i = 0; i < values.size(); i++) { + assertEquals(apiClient.escapeString(apiClient.parameterToString(values.get(i))), pairValueSplit[i]); + } + } + } + + @Test + public void testSanitizeFilename() { + assertEquals("sun", apiClient.sanitizeFilename("sun")); + assertEquals("sun.gif", apiClient.sanitizeFilename("sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("../sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("/var/tmp/sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("./sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("..\\sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("\\var\\tmp\\sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("c:\\var\\tmp\\sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename(".\\sun.gif")); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/ConfigurationTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/ConfigurationTest.java new file mode 100644 index 0000000000..f05c230dc7 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/ConfigurationTest.java @@ -0,0 +1,15 @@ +package org.openapitools.client; + +import org.junit.*; +import static org.junit.Assert.*; + + +public class ConfigurationTest { + @Test + public void testDefaultApiClient() { + ApiClient apiClient = Configuration.getDefaultApiClient(); + assertNotNull(apiClient); + assertEquals("http://petstore.swagger.io:80/v2", apiClient.getBasePath()); + assertFalse(apiClient.isDebugging()); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/JSONTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/JSONTest.java new file mode 100644 index 0000000000..e7687d0b33 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/JSONTest.java @@ -0,0 +1,201 @@ +package org.openapitools.client; + +import com.google.gson.reflect.TypeToken; + +import org.openapitools.client.model.Order; + +import java.lang.Exception; +import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; + +import okio.ByteString; +import org.junit.*; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; +import org.threeten.bp.ZoneId; +import org.threeten.bp.ZoneOffset; +import org.threeten.bp.format.DateTimeFormatter; + +import static org.junit.Assert.*; + +public class JSONTest { + private ApiClient apiClient = null; + private JSON json = null; + private Order order = null; + + @Before + public void setup() { + apiClient = new ApiClient(); + json = apiClient.getJSON(); + order = new Order(); + } + + @Test + public void testSqlDateTypeAdapter() { + final String str = "\"2015-11-07\""; + final java.sql.Date date = java.sql.Date.valueOf("2015-11-07"); + + assertEquals(str, json.serialize(date)); + assertEquals(json.deserialize(str, java.sql.Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T03:49:09.356" + getCurrentTimezoneOffset() + "\"", java.sql.Date.class).toString(), date.toString()); + + // custom date format: without day + DateFormat format = new SimpleDateFormat("yyyy-MM"); + apiClient.setSqlDateFormat(format); + String dateStr = "\"2015-11\""; + assertEquals(dateStr, json.serialize(json.deserialize("\"2015-11-07T03:49:09Z\"", java.sql.Date.class))); + assertEquals(dateStr, json.serialize(json.deserialize("\"2015-11\"", java.sql.Date.class))); + } + + @Test + public void testDateTypeAdapter() { + Calendar cal = new GregorianCalendar(2015, 10, 7, 3, 49, 9); + cal.setTimeZone(TimeZone.getTimeZone("UTC")); + + assertEquals(json.deserialize("\"2015-11-07T05:49:09+02\"", Date.class), cal.getTime()); + + cal.set(Calendar.MILLISECOND, 300); + assertEquals(json.deserialize("\"2015-11-07T03:49:09.3Z\"", Date.class), cal.getTime()); + + cal.set(Calendar.MILLISECOND, 356); + Date date = cal.getTime(); + + final String utcDate = "\"2015-11-07T03:49:09.356Z\""; + assertEquals(json.deserialize(utcDate, Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T03:49:09.356+00:00\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T05:49:09.356+02:00\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T02:49:09.356-01:00\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T03:49:09.356Z\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T03:49:09.356+00\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T02:49:09.356-0100\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T03:49:09.356456789Z\"", Date.class), date); + + assertEquals(utcDate, json.serialize(date)); + + // custom datetime format: without milli-seconds, custom time zone + DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); + format.setTimeZone(TimeZone.getTimeZone("GMT+10")); + apiClient.setDateFormat(format); + + String dateStr = "\"2015-11-07T13:49:09+10:00\""; + assertEquals(dateStr, json.serialize(json.deserialize("\"2015-11-07T03:49:09+00:00\"", Date.class))); + assertEquals(dateStr, json.serialize(json.deserialize("\"2015-11-07T03:49:09Z\"", Date.class))); + assertEquals(dateStr, json.serialize(json.deserialize("\"2015-11-07T00:49:09-03:00\"", Date.class))); + + try { + // invalid time zone format + json.deserialize("\"2015-11-07T03:49:09+00\"", Date.class); + fail("json parsing should fail"); + } catch (RuntimeException e) { + // OK + } + try { + // unexpected miliseconds + json.deserialize("\"2015-11-07T03:49:09.000Z\"", Date.class); + fail("json parsing should fail"); + } catch (RuntimeException e) { + // OK + } + + } + + @Test + public void testOffsetDateTimeTypeAdapter() { + final String str = "\"2016-09-09T08:02:03.123-03:00\""; + OffsetDateTime date = OffsetDateTime.of(2016, 9, 9, 8, 2, 3, 123000000, ZoneOffset.of("-3")); + + assertEquals(str, json.serialize(date)); + //Use toString() instead of isEqual to verify that the offset is preserved + assertEquals(json.deserialize(str, OffsetDateTime.class).toString(), date.toString()); + } + + @Test + public void testLocalDateTypeAdapter() { + final String str = "\"2016-09-09\""; + final LocalDate date = LocalDate.of(2016, 9, 9); + + assertEquals(str, json.serialize(date)); + assertEquals(json.deserialize(str, LocalDate.class), date); + } + + + @Test + public void testDefaultDate() throws Exception { + final DateTimeFormatter datetimeFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME; + final String dateStr = "2015-11-07T14:11:05.267Z"; + order.setShipDate(datetimeFormat.parse(dateStr, OffsetDateTime.FROM)); + + String str = json.serialize(order); + Type type = new TypeToken() { }.getType(); + Order o = json.deserialize(str, type); + assertEquals(dateStr, datetimeFormat.format(o.getShipDate())); + } + + @Test + public void testCustomDate() throws Exception { + final DateTimeFormatter datetimeFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.of("Etc/GMT+2")); + final String dateStr = "2015-11-07T14:11:05-02:00"; + order.setShipDate(datetimeFormat.parse(dateStr, OffsetDateTime.FROM)); + + String str = json.serialize(order); + Type type = new TypeToken() { }.getType(); + Order o = json.deserialize(str, type); + assertEquals(dateStr, datetimeFormat.format(o.getShipDate())); + } + + @Test + public void testByteArrayTypeAdapterSerialization() { + // Arrange + final String expectedBytesAsString = "Let's pretend this a jpg or something"; + final byte[] expectedBytes = expectedBytesAsString.getBytes(StandardCharsets.UTF_8); + + // Act + String serializedBytesWithQuotes = json.serialize(expectedBytes); + + // Assert + String serializedBytes = serializedBytesWithQuotes.substring(1, serializedBytesWithQuotes.length() - 1); + if (json.getGson().htmlSafe()) { + serializedBytes = serializedBytes.replaceAll("\\\\u003d", "="); + } + ByteString actualAsByteString = ByteString.decodeBase64(serializedBytes); + byte[] actualBytes = actualAsByteString.toByteArray(); + assertEquals(expectedBytesAsString, new String(actualBytes, StandardCharsets.UTF_8)); + } + + @Test + public void testByteArrayTypeAdapterDeserialization() { + // Arrange + final String expectedBytesAsString = "Let's pretend this a jpg or something"; + final byte[] expectedBytes = expectedBytesAsString.getBytes(StandardCharsets.UTF_8); + final ByteString expectedByteString = ByteString.of(expectedBytes); + final String serializedBytes = expectedByteString.base64(); + final String serializedBytesWithQuotes = "\"" + serializedBytes + "\""; + Type type = new TypeToken() { }.getType(); + + // Act + byte[] actualDeserializedBytes = json.deserialize(serializedBytesWithQuotes, type); + + // Assert + assertEquals(expectedBytesAsString, new String(actualDeserializedBytes, StandardCharsets.UTF_8)); + } + + // 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); + int offsetInMillis = tz.getOffset(cal.getTimeInMillis()); + + String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60)); + offset = (offsetInMillis >= 0 ? "+" : "-") + offset; + + return offset; + } +} \ No newline at end of file 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 0000000000..aa7c81759e --- /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 org.junit.*; +import static org.junit.Assert.*; + + +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/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java new file mode 100644 index 0000000000..d5a8813230 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java @@ -0,0 +1,76 @@ +package org.openapitools.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import org.openapitools.client.Pair; +import org.junit.*; +import static org.junit.Assert.*; + + +public class ApiKeyAuthTest { + @Test + public void testApplyToParamsInQuery() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); + auth.setApiKey("my-api-key"); + auth.applyToParams(queryParams, headerParams); + + assertEquals(1, queryParams.size()); + for (Pair queryParam : queryParams) { + assertEquals("my-api-key", queryParam.getValue()); + } + + // no changes to header parameters + assertEquals(0, headerParams.size()); + } + + @Test + public void testApplyToParamsInQueryWithNullValue() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); + auth.setApiKey(null); + auth.applyToParams(queryParams, headerParams); + + // no changes to parameters + assertEquals(0, queryParams.size()); + assertEquals(0, headerParams.size()); + } + + @Test + public void testApplyToParamsInHeaderWithPrefix() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); + auth.setApiKey("my-api-token"); + auth.setApiKeyPrefix("Token"); + auth.applyToParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN")); + } + + @Test + public void testApplyToParamsInHeaderWithNullValue() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); + auth.setApiKey(null); + auth.setApiKeyPrefix("Token"); + auth.applyToParams(queryParams, headerParams); + + // no changes to parameters + assertEquals(0, queryParams.size()); + assertEquals(0, headerParams.size()); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java new file mode 100644 index 0000000000..d27a15f4dc --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java @@ -0,0 +1,62 @@ +package org.openapitools.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import org.openapitools.client.Pair; +import org.junit.*; +import static org.junit.Assert.*; + + +public class HttpBasicAuthTest { + HttpBasicAuth auth = null; + + @Before + public void setup() { + auth = new HttpBasicAuth(); + } + + @Test + public void testApplyToParams() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + auth.setUsername("my-username"); + auth.setPassword("my-password"); + auth.applyToParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + // the string below is base64-encoded result of "my-username:my-password" with the "Basic " prefix + String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ="; + assertEquals(expected, headerParams.get("Authorization")); + + // null username should be treated as empty string + auth.setUsername(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of ":my-password" with the "Basic " prefix + expected = "Basic Om15LXBhc3N3b3Jk"; + assertEquals(expected, headerParams.get("Authorization")); + + // null password should be treated as empty string + auth.setUsername("my-username"); + auth.setPassword(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of "my-username:" with the "Basic " prefix + expected = "Basic bXktdXNlcm5hbWU6"; + assertEquals(expected, headerParams.get("Authorization")); + + // null username and password should be ignored + queryParams = new ArrayList(); + headerParams = new HashMap(); + auth.setUsername(null); + auth.setPassword(null); + auth.applyToParams(queryParams, headerParams); + // no changes to parameters + assertEquals(0, queryParams.size()); + assertEquals(0, headerParams.size()); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EnumValueTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EnumValueTest.java new file mode 100644 index 0000000000..73440e547b --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EnumValueTest.java @@ -0,0 +1,56 @@ +package org.openapitools.client.model; + +import org.junit.Test; + +import com.google.gson.Gson; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class EnumValueTest { + + @Test + public void testEnumClass() { + assertEquals(EnumClass._ABC.toString(), "_abc"); + assertEquals(EnumClass._EFG.toString(), "-efg"); + assertEquals(EnumClass._XYZ_.toString(), "(xyz)"); + } + + @Test + public void testEnumTest() { + // test enum value + EnumTest enumTest = new EnumTest(); + enumTest.setEnumString(EnumTest.EnumStringEnum.LOWER); + enumTest.setEnumInteger(EnumTest.EnumIntegerEnum.NUMBER_1); + enumTest.setEnumNumber(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1); + + assertEquals(EnumTest.EnumStringEnum.UPPER.toString(), "UPPER"); + assertEquals(EnumTest.EnumStringEnum.UPPER.getValue(), "UPPER"); + assertEquals(EnumTest.EnumStringEnum.LOWER.toString(), "lower"); + assertEquals(EnumTest.EnumStringEnum.LOWER.getValue(), "lower"); + + assertEquals(EnumTest.EnumIntegerEnum.NUMBER_1.toString(), "1"); + assertTrue(EnumTest.EnumIntegerEnum.NUMBER_1.getValue() == 1); + assertEquals(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.toString(), "-1"); + assertTrue(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.getValue() == -1); + + assertEquals(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.toString(), "1.1"); + assertTrue(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.getValue() == 1.1); + assertEquals(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.toString(), "-1.2"); + assertTrue(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.getValue() == -1.2); + + // test serialization + Gson gson = new Gson(); + String json = gson.toJson(enumTest); + assertEquals(json, "{\"enum_string\":\"lower\",\"enum_integer\":1,\"enum_number\":1.1}"); + + // test deserialization + EnumTest fromString = gson.fromJson(json, EnumTest.class); + assertEquals(fromString.getEnumString().toString(), "lower"); + assertEquals(fromString.getEnumString().getValue(), "lower"); + assertEquals(fromString.getEnumInteger().toString(), "1"); + assertTrue(fromString.getEnumInteger().getValue() == 1); + assertEquals(fromString.getEnumNumber().toString(), "1.1"); + assertTrue(fromString.getEnumNumber().getValue() == 1.1); + } +} diff --git a/samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/ApiClientTest.java b/samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/ApiClientTest.java new file mode 100644 index 0000000000..2113f5d245 --- /dev/null +++ b/samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/ApiClientTest.java @@ -0,0 +1,254 @@ +package org.openapitools.client; + +import org.openapitools.client.auth.*; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.*; + +import org.junit.*; +import org.springframework.http.MediaType; +import org.springframework.util.MultiValueMap; + +import static org.junit.Assert.*; + + +public class ApiClientTest { + ApiClient apiClient = null; + + @Before + public void setup() { + apiClient = new ApiClient(); + } + + /** + * + */ + @Test + public void testParseAndFormatDate() { + // default date format + String dateStr = "2015-11-07T03:49:09.356Z"; + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356+00:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356Z"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T05:49:09.356+02:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T02:49:09.356-01:00"))); + + // custom date format: without milli-seconds, custom time zone + DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); + format.setTimeZone(TimeZone.getTimeZone("GMT+10")); + apiClient.setDateFormat(format); + dateStr = "2015-11-07T13:49:09+10:00"; + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09+00:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09Z"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T00:49:09-03:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T13:49:09+10:00"))); + } + + @Test + public void testIsJsonMime() { + assertFalse(apiClient.isJsonMime((String) null)); + assertFalse(apiClient.isJsonMime("")); + assertFalse(apiClient.isJsonMime("text/plain")); + assertFalse(apiClient.isJsonMime("application/xml")); + assertFalse(apiClient.isJsonMime("application/jsonp")); + assertFalse(apiClient.isJsonMime("example/json")); + assertFalse(apiClient.isJsonMime("example/foo+bar+jsonx")); + assertFalse(apiClient.isJsonMime("example/foo+bar+xjson")); + + assertTrue(apiClient.isJsonMime("application/json")); + assertTrue(apiClient.isJsonMime("application/json; charset=UTF8")); + assertTrue(apiClient.isJsonMime("APPLICATION/JSON")); + + assertTrue(apiClient.isJsonMime("application/problem+json")); + assertTrue(apiClient.isJsonMime("APPLICATION/PROBLEM+JSON")); + assertTrue(apiClient.isJsonMime("application/json\t")); + assertTrue(apiClient.isJsonMime("example/foo+bar+json")); + assertTrue(apiClient.isJsonMime("example/foo+json;x;y")); + assertTrue(apiClient.isJsonMime("example/foo+json\t;")); + assertTrue(apiClient.isJsonMime("Example/fOO+JSON")); + } + + @Test + public void testSelectHeaderAccept() { + String[] accepts = {"application/json", "application/xml"}; + assertEquals(Arrays.asList(MediaType.parseMediaType("application/json")), apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"}; + assertEquals(Arrays.asList(MediaType.parseMediaType("APPLICATION/JSON")), apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals(Arrays.asList(MediaType.parseMediaType("application/json; charset=UTF8")), apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"text/plain", "application/xml"}; + assertEquals(Arrays.asList(MediaType.parseMediaType("text/plain"),MediaType.parseMediaType("application/xml")), apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{}; + assertNull(apiClient.selectHeaderAccept(accepts)); + } + + @Test + public void testSelectHeaderContentType() { + String[] contentTypes = {"application/json", "application/xml"}; + assertEquals(MediaType.parseMediaType("application/json"), apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"}; + assertEquals(MediaType.parseMediaType("APPLICATION/JSON"), apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals(MediaType.parseMediaType("application/json; charset=UTF8"), apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"text/plain", "application/xml"}; + assertEquals(MediaType.parseMediaType("text/plain"), apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{}; + assertEquals(MediaType.parseMediaType("application/json"), apiClient.selectHeaderContentType(contentTypes)); + } + + @Test + public void testGetAuthentications() { + Map auths = apiClient.getAuthentications(); + + Authentication auth = auths.get("api_key"); + assertNotNull(auth); + assertTrue(auth instanceof ApiKeyAuth); + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) auth; + assertEquals("header", apiKeyAuth.getLocation()); + assertEquals("api_key", apiKeyAuth.getParamName()); + + auth = auths.get("petstore_auth"); + assertTrue(auth instanceof OAuth); + assertSame(auth, apiClient.getAuthentication("petstore_auth")); + + assertNull(auths.get("unknown")); + + try { + auths.put("my_auth", new HttpBasicAuth()); + fail("the authentications returned should not be modifiable"); + } catch (UnsupportedOperationException e) { + } + } + + @Ignore("There is no more basic auth in petstore security definitions") + @Test + public void testSetUsernameAndPassword() { + HttpBasicAuth auth = null; + for (Authentication _auth : apiClient.getAuthentications().values()) { + if (_auth instanceof HttpBasicAuth) { + auth = (HttpBasicAuth) _auth; + break; + } + } + auth.setUsername(null); + auth.setPassword(null); + + apiClient.setUsername("my-username"); + apiClient.setPassword("my-password"); + assertEquals("my-username", auth.getUsername()); + assertEquals("my-password", auth.getPassword()); + + // reset values + auth.setUsername(null); + auth.setPassword(null); + } + + @Test + public void testSetApiKeyAndPrefix() { + ApiKeyAuth auth = null; + for (Authentication _auth : apiClient.getAuthentications().values()) { + if (_auth instanceof ApiKeyAuth) { + auth = (ApiKeyAuth) _auth; + break; + } + } + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + + apiClient.setApiKey("my-api-key"); + apiClient.setApiKeyPrefix("Token"); + assertEquals("my-api-key", auth.getApiKey()); + assertEquals("Token", auth.getApiKeyPrefix()); + + // reset values + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + } + + @Test + public void testParameterToMultiValueMapWhenNameIsInvalid() throws Exception { + MultiValueMap pairs_a = apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.CSV, null, new Integer(1)); + MultiValueMap pairs_b = apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.CSV, "", new Integer(1)); + + assertTrue(pairs_a.isEmpty()); + assertTrue(pairs_b.isEmpty()); + } + + @Test + public void testParameterToMultiValueMapWhenValueIsNull() throws Exception { + MultiValueMap pairs = apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.CSV, "param-a", null); + + assertTrue(pairs.isEmpty()); + } + + @Test + public void testParameterToMultiValueMapWhenValueIsEmptyStrings() throws Exception { + + // single empty string + MultiValueMap pairs = apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.CSV, "param-a", " "); + assertEquals(1, pairs.size()); + + // list of empty strings + List strs = new ArrayList(); + strs.add(" "); + strs.add(" "); + strs.add(" "); + + MultiValueMap concatStrings = apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.CSV, "param-a", strs); + + assertEquals(1, concatStrings.get("param-a").size()); + assertFalse(concatStrings.get("param-a").isEmpty()); // should contain some delimiters + } + + @Test + public void testParameterToMultiValueMapWhenValueIsNotCollection() throws Exception { + String name = "param-a"; + Integer value = 1; + + MultiValueMap pairs = apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.CSV, name, value); + + assertEquals(1, pairs.get(name).size()); + assertEquals(value, Integer.valueOf(pairs.get(name).get(0))); + } + + @Test + public void testParameterToMultiValueMapWhenValueIsCollection() throws Exception { + Map collectionFormatMap = new HashMap(); + collectionFormatMap.put(ApiClient.CollectionFormat.CSV, ","); + collectionFormatMap.put(ApiClient.CollectionFormat.TSV, "\t"); + collectionFormatMap.put(ApiClient.CollectionFormat.SSV, " "); + collectionFormatMap.put(ApiClient.CollectionFormat.PIPES, "\\|"); + collectionFormatMap.put(null, ","); // no format, must default to csv + + String name = "param-a"; + + List values = new ArrayList(); + values.add("value-a"); + values.add(123); + values.add(new Date()); + + // check for multi separately + MultiValueMap multiValueMap = apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.MULTI, name, values); + assertEquals(values.size(), multiValueMap.get(name).size()); + + // all other formats + for (ApiClient.CollectionFormat collectionFormat : collectionFormatMap.keySet()) { + MultiValueMap pairs = apiClient.parameterToMultiValueMap(collectionFormat, name, values); + + assertEquals(1, pairs.size()); + + String delimiter = collectionFormatMap.get(collectionFormat); + String[] pairValueSplit = pairs.get(name).get(0).split(delimiter); + + assertEquals(values.size(), pairValueSplit.length); + } + } +} diff --git a/samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java new file mode 100644 index 0000000000..eef07a5309 --- /dev/null +++ b/samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java @@ -0,0 +1,47 @@ +package org.openapitools.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import org.junit.*; +import org.springframework.http.HttpHeaders; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; + +import static org.junit.Assert.*; + +public class ApiKeyAuthTest { + @Test + public void testApplyToParamsInQuery() { + MultiValueMap queryParams = new LinkedMultiValueMap(); + HttpHeaders headerParams = new HttpHeaders(); + + ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); + auth.setApiKey("my-api-key"); + auth.applyToParams(queryParams, headerParams); + + assertEquals(1, queryParams.size()); + assertEquals("my-api-key", queryParams.get("api_key").get(0)); + + // no changes to header parameters + assertEquals(0, headerParams.size()); + } + + @Test + public void testApplyToParamsInHeaderWithPrefix() { + MultiValueMap queryParams = new LinkedMultiValueMap(); + HttpHeaders headerParams = new HttpHeaders(); + + ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); + auth.setApiKey("my-api-token"); + auth.setApiKeyPrefix("Token"); + auth.applyToParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN").get(0)); + } +} diff --git a/samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java new file mode 100644 index 0000000000..04522ec56c --- /dev/null +++ b/samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java @@ -0,0 +1,54 @@ +package org.openapitools.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import org.junit.*; +import org.springframework.http.HttpHeaders; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; + +import static org.junit.Assert.*; + +public class HttpBasicAuthTest { + HttpBasicAuth auth = null; + + @Before + public void setup() { + auth = new HttpBasicAuth(); + } + + @Test + public void testApplyToParams() { + MultiValueMap queryParams = new LinkedMultiValueMap(); + HttpHeaders headerParams = new HttpHeaders(); + + auth.setUsername("my-username"); + auth.setPassword("my-password"); + auth.applyToParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + // the string below is base64-encoded result of "my-username:my-password" with the "Basic " prefix + String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ="; + assertEquals(expected, headerParams.get("Authorization").get(0)); + + // null username should be treated as empty string + auth.setUsername(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of ":my-password" with the "Basic " prefix + expected = "Basic Om15LXBhc3N3b3Jk"; + assertEquals(expected, headerParams.get("Authorization").get(1)); + + // null password should be treated as empty string + auth.setUsername("my-username"); + auth.setPassword(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of "my-username:" with the "Basic " prefix + expected = "Basic bXktdXNlcm5hbWU6"; + assertEquals(expected, headerParams.get("Authorization").get(2)); + } +} diff --git a/samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/model/EnumValueTest.java b/samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/model/EnumValueTest.java new file mode 100644 index 0000000000..47bfe940d3 --- /dev/null +++ b/samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/model/EnumValueTest.java @@ -0,0 +1,63 @@ +package org.openapitools.client.model; + +import org.junit.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.fasterxml.jackson.databind.SerializationFeature; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class EnumValueTest { + + @Test + public void testEnumClass() { + assertEquals(EnumClass._ABC.toString(), "_abc"); + assertEquals(EnumClass._EFG.toString(), "-efg"); + assertEquals(EnumClass._XYZ_.toString(), "(xyz)"); + } + + @Test + public void testEnumTest() { + // test enum value + EnumTest enumTest = new EnumTest(); + enumTest.setEnumString(EnumTest.EnumStringEnum.LOWER); + enumTest.setEnumInteger(EnumTest.EnumIntegerEnum.NUMBER_1); + enumTest.setEnumNumber(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1); + + assertEquals(EnumTest.EnumStringEnum.UPPER.toString(), "UPPER"); + assertEquals(EnumTest.EnumStringEnum.UPPER.getValue(), "UPPER"); + assertEquals(EnumTest.EnumStringEnum.LOWER.toString(), "lower"); + assertEquals(EnumTest.EnumStringEnum.LOWER.getValue(), "lower"); + + assertEquals(EnumTest.EnumIntegerEnum.NUMBER_1.toString(), "1"); + assertTrue(EnumTest.EnumIntegerEnum.NUMBER_1.getValue() == 1); + assertEquals(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.toString(), "-1"); + assertTrue(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.getValue() == -1); + + assertEquals(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.toString(), "1.1"); + assertTrue(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.getValue() == 1.1); + assertEquals(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.toString(), "-1.2"); + assertTrue(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.getValue() == -1.2); + + try { + // test serialization (object => json) + ObjectMapper mapper = new ObjectMapper(); + mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + ObjectWriter ow = mapper.writer(); + String json = ow.writeValueAsString(enumTest); + assertEquals(json, "{\"enum_string\":\"lower\",\"enum_string_required\":null,\"enum_integer\":1,\"enum_number\":1.1,\"outerEnum\":null}"); + + // test deserialization (json => object) + EnumTest fromString = mapper.readValue(json, EnumTest.class); + assertEquals(fromString.getEnumString().toString(), "lower"); + assertEquals(fromString.getEnumInteger().toString(), "1"); + assertEquals(fromString.getEnumNumber().toString(), "1.1"); + + } catch (Exception e) { + fail("Exception thrown during serialization/deserialzation of JSON: " + e.getMessage()); + } + } +} diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/AnotherFakeApi.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/AnotherFakeApi.php index ceca2c17b4..62e71d99fa 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/AnotherFakeApi.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/AnotherFakeApi.php @@ -117,7 +117,6 @@ class AnotherFakeApi */ public function testSpecialTagsWithHttpInfo($client) { - $returnType = '\OpenAPI\Client\Model\Client'; $request = $this->testSpecialTagsRequest($client); try { @@ -148,6 +147,26 @@ class AnotherFakeApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('\OpenAPI\Client\Model\Client' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('\OpenAPI\Client\Model\Client' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\Client', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = '\OpenAPI\Client\Model\Client'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeApi.php index 8bb2297361..aa02caf338 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeApi.php @@ -113,7 +113,6 @@ class FakeApi */ public function fakeOuterBooleanSerializeWithHttpInfo($body = null) { - $returnType = 'bool'; $request = $this->fakeOuterBooleanSerializeRequest($body); try { @@ -144,6 +143,26 @@ class FakeApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('bool' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('bool' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, 'bool', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = 'bool'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer @@ -360,7 +379,6 @@ class FakeApi */ public function fakeOuterCompositeSerializeWithHttpInfo($outer_composite = null) { - $returnType = '\OpenAPI\Client\Model\OuterComposite'; $request = $this->fakeOuterCompositeSerializeRequest($outer_composite); try { @@ -391,6 +409,26 @@ class FakeApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('\OpenAPI\Client\Model\OuterComposite' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('\OpenAPI\Client\Model\OuterComposite' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\OuterComposite', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = '\OpenAPI\Client\Model\OuterComposite'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer @@ -607,7 +645,6 @@ class FakeApi */ public function fakeOuterNumberSerializeWithHttpInfo($body = null) { - $returnType = 'float'; $request = $this->fakeOuterNumberSerializeRequest($body); try { @@ -638,6 +675,26 @@ class FakeApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('float' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('float' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, 'float', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = 'float'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer @@ -854,7 +911,6 @@ class FakeApi */ public function fakeOuterStringSerializeWithHttpInfo($body = null) { - $returnType = 'string'; $request = $this->fakeOuterStringSerializeRequest($body); try { @@ -885,6 +941,26 @@ class FakeApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('string' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('string' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, 'string', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = 'string'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer @@ -1102,7 +1178,6 @@ class FakeApi */ public function testBodyWithQueryParamsWithHttpInfo($query, $user) { - $returnType = ''; $request = $this->testBodyWithQueryParamsRequest($query, $user); try { @@ -1336,7 +1411,6 @@ class FakeApi */ public function testClientModelWithHttpInfo($client) { - $returnType = '\OpenAPI\Client\Model\Client'; $request = $this->testClientModelRequest($client); try { @@ -1367,6 +1441,26 @@ class FakeApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('\OpenAPI\Client\Model\Client' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('\OpenAPI\Client\Model\Client' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\Client', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = '\OpenAPI\Client\Model\Client'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer @@ -1618,7 +1712,6 @@ class FakeApi */ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_without_delimiter, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $string = null, $binary = null, $date = null, $date_time = null, $password = null, $callback = null) { - $returnType = ''; $request = $this->testEndpointParametersRequest($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password, $callback); try { @@ -2014,7 +2107,6 @@ class FakeApi */ public function testEnumParametersWithHttpInfo($enum_header_string_array = null, $enum_header_string = '-efg', $enum_query_string_array = null, $enum_query_string = '-efg', $enum_query_integer = null, $enum_query_double = null, $enum_form_string_array = '$', $enum_form_string = '-efg') { - $returnType = ''; $request = $this->testEnumParametersRequest($enum_header_string_array, $enum_header_string, $enum_query_string_array, $enum_query_string, $enum_query_integer, $enum_query_double, $enum_form_string_array, $enum_form_string); try { @@ -2284,7 +2376,6 @@ class FakeApi */ public function testInlineAdditionalPropertiesWithHttpInfo($request_body) { - $returnType = ''; $request = $this->testInlineAdditionalPropertiesRequest($request_body); try { @@ -2506,7 +2597,6 @@ class FakeApi */ public function testJsonFormDataWithHttpInfo($param, $param2) { - $returnType = ''; $request = $this->testJsonFormDataRequest($param, $param2); try { diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeClassnameTags123Api.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeClassnameTags123Api.php index b108e2ca02..bf52434107 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeClassnameTags123Api.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeClassnameTags123Api.php @@ -117,7 +117,6 @@ class FakeClassnameTags123Api */ public function testClassnameWithHttpInfo($client) { - $returnType = '\OpenAPI\Client\Model\Client'; $request = $this->testClassnameRequest($client); try { @@ -148,6 +147,26 @@ class FakeClassnameTags123Api ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('\OpenAPI\Client\Model\Client' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('\OpenAPI\Client\Model\Client' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\Client', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = '\OpenAPI\Client\Model\Client'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/PetApi.php index 790a258b52..6326bfb40a 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/PetApi.php @@ -116,7 +116,6 @@ class PetApi */ public function addPetWithHttpInfo($pet) { - $returnType = ''; $request = $this->addPetRequest($pet); try { @@ -342,7 +341,6 @@ class PetApi */ public function deletePetWithHttpInfo($pet_id, $api_key = null) { - $returnType = ''; $request = $this->deletePetRequest($pet_id, $api_key); try { @@ -579,7 +577,6 @@ class PetApi */ public function findPetsByStatusWithHttpInfo($status) { - $returnType = '\OpenAPI\Client\Model\Pet[]'; $request = $this->findPetsByStatusRequest($status); try { @@ -610,6 +607,26 @@ class PetApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('\OpenAPI\Client\Model\Pet[]' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('\OpenAPI\Client\Model\Pet[]' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\Pet[]', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = '\OpenAPI\Client\Model\Pet[]'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer @@ -844,7 +861,6 @@ class PetApi */ public function findPetsByTagsWithHttpInfo($tags) { - $returnType = '\OpenAPI\Client\Model\Pet[]'; $request = $this->findPetsByTagsRequest($tags); try { @@ -875,6 +891,26 @@ class PetApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('\OpenAPI\Client\Model\Pet[]' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('\OpenAPI\Client\Model\Pet[]' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\Pet[]', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = '\OpenAPI\Client\Model\Pet[]'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer @@ -1109,7 +1145,6 @@ class PetApi */ public function getPetByIdWithHttpInfo($pet_id) { - $returnType = '\OpenAPI\Client\Model\Pet'; $request = $this->getPetByIdRequest($pet_id); try { @@ -1140,6 +1175,26 @@ class PetApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('\OpenAPI\Client\Model\Pet' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('\OpenAPI\Client\Model\Pet' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\Pet', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = '\OpenAPI\Client\Model\Pet'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer @@ -1375,7 +1430,6 @@ class PetApi */ public function updatePetWithHttpInfo($pet) { - $returnType = ''; $request = $this->updatePetRequest($pet); try { @@ -1603,7 +1657,6 @@ class PetApi */ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = null) { - $returnType = ''; $request = $this->updatePetWithFormRequest($pet_id, $name, $status); try { @@ -1851,7 +1904,6 @@ class PetApi */ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $file = null) { - $returnType = '\OpenAPI\Client\Model\ApiResponse'; $request = $this->uploadFileRequest($pet_id, $additional_metadata, $file); try { @@ -1882,6 +1934,26 @@ class PetApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('\OpenAPI\Client\Model\ApiResponse' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('\OpenAPI\Client\Model\ApiResponse' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\ApiResponse', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = '\OpenAPI\Client\Model\ApiResponse'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/StoreApi.php index c85be4bc8b..01636e3356 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/StoreApi.php @@ -116,7 +116,6 @@ class StoreApi */ public function deleteOrderWithHttpInfo($order_id) { - $returnType = ''; $request = $this->deleteOrderRequest($order_id); try { @@ -340,7 +339,6 @@ class StoreApi */ public function getInventoryWithHttpInfo() { - $returnType = 'map[string,int]'; $request = $this->getInventoryRequest(); try { @@ -371,6 +369,26 @@ class StoreApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('map[string,int]' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('map[string,int]' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, 'map[string,int]', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = 'map[string,int]'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer @@ -590,7 +608,6 @@ class StoreApi */ public function getOrderByIdWithHttpInfo($order_id) { - $returnType = '\OpenAPI\Client\Model\Order'; $request = $this->getOrderByIdRequest($order_id); try { @@ -621,6 +638,26 @@ class StoreApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('\OpenAPI\Client\Model\Order' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('\OpenAPI\Client\Model\Order' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\Order', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = '\OpenAPI\Client\Model\Order'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer @@ -859,7 +896,6 @@ class StoreApi */ public function placeOrderWithHttpInfo($order) { - $returnType = '\OpenAPI\Client\Model\Order'; $request = $this->placeOrderRequest($order); try { @@ -890,6 +926,26 @@ class StoreApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('\OpenAPI\Client\Model\Order' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('\OpenAPI\Client\Model\Order' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\Order', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = '\OpenAPI\Client\Model\Order'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/UserApi.php index 3557f26b66..54849c59c9 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/UserApi.php @@ -116,7 +116,6 @@ class UserApi */ public function createUserWithHttpInfo($user) { - $returnType = ''; $request = $this->createUserRequest($user); try { @@ -336,7 +335,6 @@ class UserApi */ public function createUsersWithArrayInputWithHttpInfo($user) { - $returnType = ''; $request = $this->createUsersWithArrayInputRequest($user); try { @@ -556,7 +554,6 @@ class UserApi */ public function createUsersWithListInputWithHttpInfo($user) { - $returnType = ''; $request = $this->createUsersWithListInputRequest($user); try { @@ -776,7 +773,6 @@ class UserApi */ public function deleteUserWithHttpInfo($username) { - $returnType = ''; $request = $this->deleteUserRequest($username); try { @@ -1002,7 +998,6 @@ class UserApi */ public function getUserByNameWithHttpInfo($username) { - $returnType = '\OpenAPI\Client\Model\User'; $request = $this->getUserByNameRequest($username); try { @@ -1033,6 +1028,26 @@ class UserApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('\OpenAPI\Client\Model\User' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('\OpenAPI\Client\Model\User' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\User', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = '\OpenAPI\Client\Model\User'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer @@ -1266,7 +1281,6 @@ class UserApi */ public function loginUserWithHttpInfo($username, $password) { - $returnType = 'string'; $request = $this->loginUserRequest($username, $password); try { @@ -1297,6 +1311,26 @@ class UserApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('string' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('string' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, 'string', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = 'string'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer @@ -1534,7 +1568,6 @@ class UserApi */ public function logoutUserWithHttpInfo() { - $returnType = ''; $request = $this->logoutUserRequest(); try { @@ -1744,7 +1777,6 @@ class UserApi */ public function updateUserWithHttpInfo($username, $user) { - $returnType = ''; $request = $this->updateUserRequest($username, $user); try { diff --git a/samples/openapi3/client/petstore/php/OpenAPIClient-php/lib/Api/AnotherFakeApi.php b/samples/openapi3/client/petstore/php/OpenAPIClient-php/lib/Api/AnotherFakeApi.php index ceca2c17b4..62e71d99fa 100644 --- a/samples/openapi3/client/petstore/php/OpenAPIClient-php/lib/Api/AnotherFakeApi.php +++ b/samples/openapi3/client/petstore/php/OpenAPIClient-php/lib/Api/AnotherFakeApi.php @@ -117,7 +117,6 @@ class AnotherFakeApi */ public function testSpecialTagsWithHttpInfo($client) { - $returnType = '\OpenAPI\Client\Model\Client'; $request = $this->testSpecialTagsRequest($client); try { @@ -148,6 +147,26 @@ class AnotherFakeApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('\OpenAPI\Client\Model\Client' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('\OpenAPI\Client\Model\Client' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\Client', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = '\OpenAPI\Client\Model\Client'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer diff --git a/samples/openapi3/client/petstore/php/OpenAPIClient-php/lib/Api/FakeApi.php b/samples/openapi3/client/petstore/php/OpenAPIClient-php/lib/Api/FakeApi.php index ad70a4f885..9ef029ccea 100644 --- a/samples/openapi3/client/petstore/php/OpenAPIClient-php/lib/Api/FakeApi.php +++ b/samples/openapi3/client/petstore/php/OpenAPIClient-php/lib/Api/FakeApi.php @@ -113,7 +113,6 @@ class FakeApi */ public function fakeOuterBooleanSerializeWithHttpInfo($body = null) { - $returnType = 'bool'; $request = $this->fakeOuterBooleanSerializeRequest($body); try { @@ -144,6 +143,26 @@ class FakeApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('bool' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('bool' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, 'bool', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = 'bool'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer @@ -360,7 +379,6 @@ class FakeApi */ public function fakeOuterCompositeSerializeWithHttpInfo($outer_composite = null) { - $returnType = '\OpenAPI\Client\Model\OuterComposite'; $request = $this->fakeOuterCompositeSerializeRequest($outer_composite); try { @@ -391,6 +409,26 @@ class FakeApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('\OpenAPI\Client\Model\OuterComposite' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('\OpenAPI\Client\Model\OuterComposite' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\OuterComposite', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = '\OpenAPI\Client\Model\OuterComposite'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer @@ -607,7 +645,6 @@ class FakeApi */ public function fakeOuterNumberSerializeWithHttpInfo($body = null) { - $returnType = 'float'; $request = $this->fakeOuterNumberSerializeRequest($body); try { @@ -638,6 +675,26 @@ class FakeApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('float' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('float' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, 'float', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = 'float'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer @@ -854,7 +911,6 @@ class FakeApi */ public function fakeOuterStringSerializeWithHttpInfo($body = null) { - $returnType = 'string'; $request = $this->fakeOuterStringSerializeRequest($body); try { @@ -885,6 +941,26 @@ class FakeApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('string' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('string' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, 'string', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = 'string'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer @@ -1105,7 +1181,6 @@ class FakeApi */ public function testClientModelWithHttpInfo($client) { - $returnType = '\OpenAPI\Client\Model\Client'; $request = $this->testClientModelRequest($client); try { @@ -1136,6 +1211,26 @@ class FakeApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('\OpenAPI\Client\Model\Client' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('\OpenAPI\Client\Model\Client' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\Client', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = '\OpenAPI\Client\Model\Client'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer @@ -1387,7 +1482,6 @@ class FakeApi */ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_without_delimiter, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $string = null, $binary = null, $date = null, $date_time = null, $password = null, $callback = null) { - $returnType = ''; $request = $this->testEndpointParametersRequest($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password, $callback); try { @@ -1783,7 +1877,6 @@ class FakeApi */ public function testEnumParametersWithHttpInfo($enum_header_string_array = null, $enum_header_string = '-efg', $enum_query_string_array = null, $enum_query_string = '-efg', $enum_query_integer = null, $enum_query_double = null, $enum_form_string_array = '$', $enum_form_string = '-efg') { - $returnType = ''; $request = $this->testEnumParametersRequest($enum_header_string_array, $enum_header_string, $enum_query_string_array, $enum_query_string, $enum_query_integer, $enum_query_double, $enum_form_string_array, $enum_form_string); try { @@ -2053,7 +2146,6 @@ class FakeApi */ public function testInlineAdditionalPropertiesWithHttpInfo($request_body) { - $returnType = ''; $request = $this->testInlineAdditionalPropertiesRequest($request_body); try { @@ -2275,7 +2367,6 @@ class FakeApi */ public function testJsonFormDataWithHttpInfo($param, $param2) { - $returnType = ''; $request = $this->testJsonFormDataRequest($param, $param2); try { diff --git a/samples/openapi3/client/petstore/php/OpenAPIClient-php/lib/Api/FakeClassnameTags123Api.php b/samples/openapi3/client/petstore/php/OpenAPIClient-php/lib/Api/FakeClassnameTags123Api.php index b108e2ca02..bf52434107 100644 --- a/samples/openapi3/client/petstore/php/OpenAPIClient-php/lib/Api/FakeClassnameTags123Api.php +++ b/samples/openapi3/client/petstore/php/OpenAPIClient-php/lib/Api/FakeClassnameTags123Api.php @@ -117,7 +117,6 @@ class FakeClassnameTags123Api */ public function testClassnameWithHttpInfo($client) { - $returnType = '\OpenAPI\Client\Model\Client'; $request = $this->testClassnameRequest($client); try { @@ -148,6 +147,26 @@ class FakeClassnameTags123Api ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('\OpenAPI\Client\Model\Client' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('\OpenAPI\Client\Model\Client' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\Client', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = '\OpenAPI\Client\Model\Client'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer diff --git a/samples/openapi3/client/petstore/php/OpenAPIClient-php/lib/Api/PetApi.php b/samples/openapi3/client/petstore/php/OpenAPIClient-php/lib/Api/PetApi.php index 790a258b52..6326bfb40a 100644 --- a/samples/openapi3/client/petstore/php/OpenAPIClient-php/lib/Api/PetApi.php +++ b/samples/openapi3/client/petstore/php/OpenAPIClient-php/lib/Api/PetApi.php @@ -116,7 +116,6 @@ class PetApi */ public function addPetWithHttpInfo($pet) { - $returnType = ''; $request = $this->addPetRequest($pet); try { @@ -342,7 +341,6 @@ class PetApi */ public function deletePetWithHttpInfo($pet_id, $api_key = null) { - $returnType = ''; $request = $this->deletePetRequest($pet_id, $api_key); try { @@ -579,7 +577,6 @@ class PetApi */ public function findPetsByStatusWithHttpInfo($status) { - $returnType = '\OpenAPI\Client\Model\Pet[]'; $request = $this->findPetsByStatusRequest($status); try { @@ -610,6 +607,26 @@ class PetApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('\OpenAPI\Client\Model\Pet[]' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('\OpenAPI\Client\Model\Pet[]' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\Pet[]', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = '\OpenAPI\Client\Model\Pet[]'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer @@ -844,7 +861,6 @@ class PetApi */ public function findPetsByTagsWithHttpInfo($tags) { - $returnType = '\OpenAPI\Client\Model\Pet[]'; $request = $this->findPetsByTagsRequest($tags); try { @@ -875,6 +891,26 @@ class PetApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('\OpenAPI\Client\Model\Pet[]' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('\OpenAPI\Client\Model\Pet[]' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\Pet[]', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = '\OpenAPI\Client\Model\Pet[]'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer @@ -1109,7 +1145,6 @@ class PetApi */ public function getPetByIdWithHttpInfo($pet_id) { - $returnType = '\OpenAPI\Client\Model\Pet'; $request = $this->getPetByIdRequest($pet_id); try { @@ -1140,6 +1175,26 @@ class PetApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('\OpenAPI\Client\Model\Pet' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('\OpenAPI\Client\Model\Pet' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\Pet', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = '\OpenAPI\Client\Model\Pet'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer @@ -1375,7 +1430,6 @@ class PetApi */ public function updatePetWithHttpInfo($pet) { - $returnType = ''; $request = $this->updatePetRequest($pet); try { @@ -1603,7 +1657,6 @@ class PetApi */ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = null) { - $returnType = ''; $request = $this->updatePetWithFormRequest($pet_id, $name, $status); try { @@ -1851,7 +1904,6 @@ class PetApi */ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $file = null) { - $returnType = '\OpenAPI\Client\Model\ApiResponse'; $request = $this->uploadFileRequest($pet_id, $additional_metadata, $file); try { @@ -1882,6 +1934,26 @@ class PetApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('\OpenAPI\Client\Model\ApiResponse' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('\OpenAPI\Client\Model\ApiResponse' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\ApiResponse', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = '\OpenAPI\Client\Model\ApiResponse'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer diff --git a/samples/openapi3/client/petstore/php/OpenAPIClient-php/lib/Api/StoreApi.php b/samples/openapi3/client/petstore/php/OpenAPIClient-php/lib/Api/StoreApi.php index 6eee204284..f534e9e924 100644 --- a/samples/openapi3/client/petstore/php/OpenAPIClient-php/lib/Api/StoreApi.php +++ b/samples/openapi3/client/petstore/php/OpenAPIClient-php/lib/Api/StoreApi.php @@ -116,7 +116,6 @@ class StoreApi */ public function deleteOrderWithHttpInfo($order_id) { - $returnType = ''; $request = $this->deleteOrderRequest($order_id); try { @@ -340,7 +339,6 @@ class StoreApi */ public function getInventoryWithHttpInfo() { - $returnType = 'map[string,int]'; $request = $this->getInventoryRequest(); try { @@ -371,6 +369,26 @@ class StoreApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('map[string,int]' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('map[string,int]' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, 'map[string,int]', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = 'map[string,int]'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer @@ -590,7 +608,6 @@ class StoreApi */ public function getOrderByIdWithHttpInfo($order_id) { - $returnType = '\OpenAPI\Client\Model\Order'; $request = $this->getOrderByIdRequest($order_id); try { @@ -621,6 +638,26 @@ class StoreApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('\OpenAPI\Client\Model\Order' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('\OpenAPI\Client\Model\Order' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\Order', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = '\OpenAPI\Client\Model\Order'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer @@ -859,7 +896,6 @@ class StoreApi */ public function placeOrderWithHttpInfo($order) { - $returnType = '\OpenAPI\Client\Model\Order'; $request = $this->placeOrderRequest($order); try { @@ -890,6 +926,26 @@ class StoreApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('\OpenAPI\Client\Model\Order' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('\OpenAPI\Client\Model\Order' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\Order', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = '\OpenAPI\Client\Model\Order'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer diff --git a/samples/openapi3/client/petstore/php/OpenAPIClient-php/lib/Api/UserApi.php b/samples/openapi3/client/petstore/php/OpenAPIClient-php/lib/Api/UserApi.php index f0dfc74709..abff4105f7 100644 --- a/samples/openapi3/client/petstore/php/OpenAPIClient-php/lib/Api/UserApi.php +++ b/samples/openapi3/client/petstore/php/OpenAPIClient-php/lib/Api/UserApi.php @@ -116,7 +116,6 @@ class UserApi */ public function createUserWithHttpInfo($user) { - $returnType = ''; $request = $this->createUserRequest($user); try { @@ -336,7 +335,6 @@ class UserApi */ public function createUsersWithArrayInputWithHttpInfo($user) { - $returnType = ''; $request = $this->createUsersWithArrayInputRequest($user); try { @@ -556,7 +554,6 @@ class UserApi */ public function createUsersWithListInputWithHttpInfo($user) { - $returnType = ''; $request = $this->createUsersWithListInputRequest($user); try { @@ -776,7 +773,6 @@ class UserApi */ public function deleteUserWithHttpInfo($username) { - $returnType = ''; $request = $this->deleteUserRequest($username); try { @@ -1002,7 +998,6 @@ class UserApi */ public function getUserByNameWithHttpInfo($username) { - $returnType = '\OpenAPI\Client\Model\User'; $request = $this->getUserByNameRequest($username); try { @@ -1033,6 +1028,26 @@ class UserApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('\OpenAPI\Client\Model\User' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('\OpenAPI\Client\Model\User' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\User', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = '\OpenAPI\Client\Model\User'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer @@ -1266,7 +1281,6 @@ class UserApi */ public function loginUserWithHttpInfo($username, $password) { - $returnType = 'string'; $request = $this->loginUserRequest($username, $password); try { @@ -1297,6 +1311,26 @@ class UserApi ); } + $responseBody = $response->getBody(); + switch($statusCode) { + case 200: + if ('string' === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ('string' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, 'string', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = 'string'; $responseBody = $response->getBody(); if ($returnType === '\SplFileObject') { $content = $responseBody; //stream goes to serializer @@ -1534,7 +1568,6 @@ class UserApi */ public function logoutUserWithHttpInfo() { - $returnType = ''; $request = $this->logoutUserRequest(); try { @@ -1744,7 +1777,6 @@ class UserApi */ public function updateUserWithHttpInfo($username, $user) { - $returnType = ''; $request = $this->updateUserRequest($username, $user); try {