diff --git a/samples/client/petstore/java/feign/src/test/java/io/swagger/client/StringUtilTest.java b/samples/client/petstore/java/feign/src/test/java/io/swagger/client/StringUtilTest.java new file mode 100644 index 000000000000..c93908b84821 --- /dev/null +++ b/samples/client/petstore/java/feign/src/test/java/io/swagger/client/StringUtilTest.java @@ -0,0 +1,32 @@ +package io.swagger.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"}, ",")); + } +} \ No newline at end of file diff --git a/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/ApiClientTest.java new file mode 100644 index 000000000000..02a895dd0923 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/ApiClientTest.java @@ -0,0 +1,292 @@ +package io.swagger.client; + +import io.swagger.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/io/swagger/client/ConfigurationTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/ConfigurationTest.java new file mode 100644 index 000000000000..ccdf25feb301 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/ConfigurationTest.java @@ -0,0 +1,15 @@ +package io.swagger.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/io/swagger/client/StringUtilTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/StringUtilTest.java new file mode 100644 index 000000000000..4b03c7a98120 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/StringUtilTest.java @@ -0,0 +1,33 @@ +package io.swagger.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/io/swagger/client/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java new file mode 100644 index 000000000000..5bdb4fb78fba --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java @@ -0,0 +1,47 @@ +package io.swagger.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import io.swagger.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/io/swagger/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java new file mode 100644 index 000000000000..52c5497ba83e --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java @@ -0,0 +1,52 @@ +package io.swagger.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import io.swagger.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/io/swagger/client/model/EnumValueTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/model/EnumValueTest.java new file mode 100644 index 000000000000..e2ce8e1f1e53 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/model/EnumValueTest.java @@ -0,0 +1,63 @@ +package io.swagger.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_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/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/ApiClientTest.java new file mode 100644 index 000000000000..c88245473033 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/ApiClientTest.java @@ -0,0 +1,250 @@ +package io.swagger.client; + +import io.swagger.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/io/swagger/client/ConfigurationTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/ConfigurationTest.java new file mode 100644 index 000000000000..ccdf25feb301 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/ConfigurationTest.java @@ -0,0 +1,15 @@ +package io.swagger.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/io/swagger/client/JSONTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/JSONTest.java new file mode 100644 index 000000000000..5286976a8198 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/JSONTest.java @@ -0,0 +1,45 @@ +package io.swagger.client; + +import io.swagger.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/io/swagger/client/StringUtilTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/StringUtilTest.java new file mode 100644 index 000000000000..4b03c7a98120 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/StringUtilTest.java @@ -0,0 +1,33 @@ +package io.swagger.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/io/swagger/client/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java new file mode 100644 index 000000000000..5bdb4fb78fba --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java @@ -0,0 +1,47 @@ +package io.swagger.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import io.swagger.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/io/swagger/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java new file mode 100644 index 000000000000..52c5497ba83e --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java @@ -0,0 +1,52 @@ +package io.swagger.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import io.swagger.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/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java new file mode 100644 index 000000000000..c88245473033 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java @@ -0,0 +1,250 @@ +package io.swagger.client; + +import io.swagger.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/io/swagger/client/ConfigurationTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ConfigurationTest.java new file mode 100644 index 000000000000..ccdf25feb301 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ConfigurationTest.java @@ -0,0 +1,15 @@ +package io.swagger.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/io/swagger/client/JSONTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java new file mode 100644 index 000000000000..2cce6e7ddd5e --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java @@ -0,0 +1,58 @@ +package io.swagger.client; + +import io.swagger.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/io/swagger/client/StringUtilTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/StringUtilTest.java new file mode 100644 index 000000000000..4b03c7a98120 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/StringUtilTest.java @@ -0,0 +1,33 @@ +package io.swagger.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/io/swagger/client/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java new file mode 100644 index 000000000000..5bdb4fb78fba --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java @@ -0,0 +1,47 @@ +package io.swagger.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import io.swagger.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/io/swagger/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java new file mode 100644 index 000000000000..52c5497ba83e --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java @@ -0,0 +1,52 @@ +package io.swagger.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import io.swagger.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/io/swagger/client/model/EnumValueTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/model/EnumValueTest.java new file mode 100644 index 000000000000..e2ce8e1f1e53 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/model/EnumValueTest.java @@ -0,0 +1,63 @@ +package io.swagger.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_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/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ApiClientTest.java new file mode 100644 index 000000000000..e793075224be --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ApiClientTest.java @@ -0,0 +1,330 @@ +package io.swagger.client; + +import io.swagger.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/io/swagger/client/ConfigurationTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ConfigurationTest.java new file mode 100644 index 000000000000..ccdf25feb301 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ConfigurationTest.java @@ -0,0 +1,15 @@ +package io.swagger.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/io/swagger/client/JSONTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/JSONTest.java new file mode 100644 index 000000000000..a3fefc968952 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/JSONTest.java @@ -0,0 +1,201 @@ +package io.swagger.client; + +import com.google.gson.reflect.TypeToken; + +import io.swagger.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/io/swagger/client/StringUtilTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/StringUtilTest.java new file mode 100644 index 000000000000..4b03c7a98120 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/StringUtilTest.java @@ -0,0 +1,33 @@ +package io.swagger.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/io/swagger/client/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java new file mode 100644 index 000000000000..3715e9724e69 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java @@ -0,0 +1,76 @@ +package io.swagger.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import io.swagger.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/io/swagger/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java new file mode 100644 index 000000000000..ddee04f57fcb --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java @@ -0,0 +1,62 @@ +package io.swagger.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import io.swagger.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/io/swagger/client/model/EnumValueTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/model/EnumValueTest.java new file mode 100644 index 000000000000..a74a4a31b663 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/model/EnumValueTest.java @@ -0,0 +1,56 @@ +package io.swagger.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/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/resttemplate/src/test/java/io/swagger/client/ApiClientTest.java new file mode 100644 index 000000000000..17953e3401ad --- /dev/null +++ b/samples/client/petstore/java/resttemplate/src/test/java/io/swagger/client/ApiClientTest.java @@ -0,0 +1,254 @@ +package io.swagger.client; + +import io.swagger.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/io/swagger/client/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/resttemplate/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java new file mode 100644 index 000000000000..c1eabc2fd089 --- /dev/null +++ b/samples/client/petstore/java/resttemplate/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java @@ -0,0 +1,47 @@ +package io.swagger.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/io/swagger/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/resttemplate/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java new file mode 100644 index 000000000000..877c6cfc77c3 --- /dev/null +++ b/samples/client/petstore/java/resttemplate/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java @@ -0,0 +1,54 @@ +package io.swagger.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/io/swagger/client/model/EnumValueTest.java b/samples/client/petstore/java/resttemplate/src/test/java/io/swagger/client/model/EnumValueTest.java new file mode 100644 index 000000000000..e2ce8e1f1e53 --- /dev/null +++ b/samples/client/petstore/java/resttemplate/src/test/java/io/swagger/client/model/EnumValueTest.java @@ -0,0 +1,63 @@ +package io.swagger.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_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()); + } + } +}