Restore unit test (#346)

* Restore test classes to commit 5340c35ce123c18daa82f62131b3d1606bd1ceab

* Fix samples/client/petstore/java/feign

* Fix samples/client/petstore/java/jersey1

* Fix samples/client/petstore/java/jersey2-java8

* Fix samples/client/petstore/java/jersey2

* Fix samples/client/petstore/java/okhttp-gson

* Fix samples/client/petstore/java/resttemplate/src/test/java

* Move "StringUtilTest.java" to "samples.ci"

and add copy command in *.sh scripts

* Fix echo line

* Move tests to 'test-manual/common/'

* Move "ApiClientTest.java" to "samples.ci"

and add copy command in *.sh scripts

* Move "ConfigurationTest.java" to "samples.ci"

and add copy command in *.sh scripts

* Move "auth/ApiKeyAuthTest.java" to "samples.ci"

and add copy command in *.sh scripts

* Move "auth/HttpBasicAuthTest.java" to "samples.ci"

and add copy command in *.sh scripts

* Move "model/EnumValueTest.java" to "samples.ci"

and add copy command in *.sh scripts

* Move "JSONTest.java" to "samples.ci"

and add copy command in *.sh scripts

* Replace "cp" => "mkdir & cp"

* JSONTest.java is java8 specific

* Run bin/java-petstore-all.sh

* "$_" does not work on Shippable
This commit is contained in:
Jérémie Bresson 2018-06-20 09:40:58 +02:00 committed by William Cheng
parent 231202d0a3
commit 3c9cf1dcd6
60 changed files with 4976 additions and 1 deletions

View File

@ -0,0 +1,15 @@
package org.openapitools.client;
import org.junit.*;
import static org.junit.Assert.*;
public class ConfigurationTest {
@Test
public void testDefaultApiClient() {
ApiClient apiClient = Configuration.getDefaultApiClient();
assertNotNull(apiClient);
assertEquals("http://petstore.swagger.io:80/v2", apiClient.getBasePath());
assertFalse(apiClient.isDebugging());
}
}

View File

@ -0,0 +1,33 @@
package org.openapitools.client;
import org.junit.*;
import static org.junit.Assert.*;
public class StringUtilTest {
@Test
public void testContainsIgnoreCase() {
assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "abc"));
assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "ABC"));
assertTrue(StringUtil.containsIgnoreCase(new String[]{"ABC"}, "abc"));
assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, "ABC"));
assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, null));
assertFalse(StringUtil.containsIgnoreCase(new String[]{"abc"}, "def"));
assertFalse(StringUtil.containsIgnoreCase(new String[]{}, "ABC"));
assertFalse(StringUtil.containsIgnoreCase(new String[]{}, null));
}
@Test
public void testJoin() {
String[] array = {"aa", "bb", "cc"};
assertEquals("aa,bb,cc", StringUtil.join(array, ","));
assertEquals("aa, bb, cc", StringUtil.join(array, ", "));
assertEquals("aabbcc", StringUtil.join(array, ""));
assertEquals("aa bb cc", StringUtil.join(array, " "));
assertEquals("aa\nbb\ncc", StringUtil.join(array, "\n"));
assertEquals("", StringUtil.join(new String[]{}, ","));
assertEquals("abc", StringUtil.join(new String[]{"abc"}, ","));
}
}

View File

@ -0,0 +1,292 @@
package org.openapitools.client;
import org.openapitools.client.auth.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import org.junit.*;
import static org.junit.Assert.*;
public class ApiClientTest {
ApiClient apiClient = null;
@Before
public void setup() {
apiClient = new ApiClient();
}
@Test
public void testParseAndFormatDate() {
// default date format
String dateStr = "2015-11-07T03:49:09.356Z";
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356+00:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356Z")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T05:49:09.356+02:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T02:49:09.356-01:00")));
// custom date format: without milli-seconds, custom time zone
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
format.setTimeZone(TimeZone.getTimeZone("GMT+10"));
apiClient.setDateFormat(format);
dateStr = "2015-11-07T13:49:09+10:00";
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09+00:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09Z")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T00:49:09-03:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T13:49:09+10:00")));
}
@Test
public void testIsJsonMime() {
assertFalse(apiClient.isJsonMime(null));
assertFalse(apiClient.isJsonMime(""));
assertFalse(apiClient.isJsonMime("text/plain"));
assertFalse(apiClient.isJsonMime("application/xml"));
assertFalse(apiClient.isJsonMime("application/jsonp"));
assertFalse(apiClient.isJsonMime("example/json"));
assertFalse(apiClient.isJsonMime("example/foo+bar+jsonx"));
assertFalse(apiClient.isJsonMime("example/foo+bar+xjson"));
assertTrue(apiClient.isJsonMime("application/json"));
assertTrue(apiClient.isJsonMime("application/json; charset=UTF8"));
assertTrue(apiClient.isJsonMime("APPLICATION/JSON"));
assertTrue(apiClient.isJsonMime("application/problem+json"));
assertTrue(apiClient.isJsonMime("APPLICATION/PROBLEM+JSON"));
assertTrue(apiClient.isJsonMime("application/json\t"));
assertTrue(apiClient.isJsonMime("example/foo+bar+json"));
assertTrue(apiClient.isJsonMime("example/foo+json;x;y"));
assertTrue(apiClient.isJsonMime("example/foo+json\t;"));
assertTrue(apiClient.isJsonMime("Example/fOO+JSON"));
}
@Test
public void testSelectHeaderAccept() {
String[] accepts = {"application/json", "application/xml"};
assertEquals("application/json", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"};
assertEquals("APPLICATION/JSON", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"application/xml", "application/json; charset=UTF8"};
assertEquals("application/json; charset=UTF8", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"text/plain", "application/xml"};
assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{};
assertNull(apiClient.selectHeaderAccept(accepts));
}
@Test
public void testSelectHeaderContentType() {
String[] contentTypes = {"application/json", "application/xml"};
assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"};
assertEquals("APPLICATION/JSON", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"};
assertEquals("application/json; charset=UTF8", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"text/plain", "application/xml"};
assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{};
assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes));
}
@Test
public void testGetAuthentications() {
Map<String, Authentication> 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<Pair> pairs_a = apiClient.parameterToPair(null, new Integer(1));
List<Pair> pairs_b = apiClient.parameterToPair("", new Integer(1));
assertTrue(pairs_a.isEmpty());
assertTrue(pairs_b.isEmpty());
}
@Test
public void testParameterToPairWhenValueIsNull() throws Exception {
List<Pair> pairs = apiClient.parameterToPair("param-a", null);
assertTrue(pairs.isEmpty());
}
@Test
public void testParameterToPairWhenValueIsEmptyString() throws Exception {
// single empty string
List<Pair> pairs = apiClient.parameterToPair("param-a", " ");
assertEquals(1, pairs.size());
}
@Test
public void testParameterToPairWhenValueIsNotCollection() throws Exception {
String name = "param-a";
Integer value = 1;
List<Pair> pairs = apiClient.parameterToPair(name, value);
assertEquals(1, pairs.size());
assertEquals(value, Integer.valueOf(pairs.get(0).getValue()));
}
@Test
public void testParameterToPairWhenValueIsCollection() throws Exception {
List<Object> values = new ArrayList<Object>();
values.add("value-a");
values.add(123);
values.add(new Date());
List<Pair> pairs = apiClient.parameterToPair("param-a", values);
assertEquals(0, pairs.size());
}
@Test
public void testParameterToPairsWhenNameIsInvalid() throws Exception {
List<Integer> objects = new ArrayList<Integer>();
objects.add(new Integer(1));
List<Pair> pairs_a = apiClient.parameterToPairs("csv", null, objects);
List<Pair> pairs_b = apiClient.parameterToPairs("csv", "", objects);
assertTrue(pairs_a.isEmpty());
assertTrue(pairs_b.isEmpty());
}
@Test
public void testParameterToPairsWhenValueIsNull() throws Exception {
List<Pair> pairs = apiClient.parameterToPairs("csv", "param-a", null);
assertTrue(pairs.isEmpty());
}
@Test
public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception {
// list of empty strings
List<String> strs = new ArrayList<String>();
strs.add(" ");
strs.add(" ");
strs.add(" ");
List<Pair> 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<String, String> collectionFormatMap = new HashMap<String, String>();
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<Object> values = new ArrayList<Object>();
values.add("value-a");
values.add(123);
values.add(new Date());
// check for multi separately
List<Pair> 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<Pair> 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]);
}
}
}
}

View File

@ -0,0 +1,47 @@
package org.openapitools.client.auth;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import org.openapitools.client.Pair;
import org.junit.*;
import static org.junit.Assert.*;
public class ApiKeyAuthTest {
@Test
public void testApplyToParamsInQuery() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
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<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
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"));
}
}

View File

@ -0,0 +1,52 @@
package org.openapitools.client.auth;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import org.openapitools.client.Pair;
import org.junit.*;
import static org.junit.Assert.*;
public class HttpBasicAuthTest {
HttpBasicAuth auth = null;
@Before
public void setup() {
auth = new HttpBasicAuth();
}
@Test
public void testApplyToParams() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
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"));
}
}

View File

@ -0,0 +1,63 @@
package org.openapitools.client.model;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class EnumValueTest {
@Test
public void testEnumClass() {
assertEquals(EnumClass._ABC.toString(), "_abc");
assertEquals(EnumClass._EFG.toString(), "-efg");
assertEquals(EnumClass._XYZ_.toString(), "(xyz)");
}
@Test
public void testEnumTest() {
// test enum value
EnumTest enumTest = new EnumTest();
enumTest.setEnumString(EnumTest.EnumStringEnum.LOWER);
enumTest.setEnumInteger(EnumTest.EnumIntegerEnum.NUMBER_1);
enumTest.setEnumNumber(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1);
assertEquals(EnumTest.EnumStringEnum.UPPER.toString(), "UPPER");
assertEquals(EnumTest.EnumStringEnum.UPPER.getValue(), "UPPER");
assertEquals(EnumTest.EnumStringEnum.LOWER.toString(), "lower");
assertEquals(EnumTest.EnumStringEnum.LOWER.getValue(), "lower");
assertEquals(EnumTest.EnumIntegerEnum.NUMBER_1.toString(), "1");
assertTrue(EnumTest.EnumIntegerEnum.NUMBER_1.getValue() == 1);
assertEquals(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.toString(), "-1");
assertTrue(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.getValue() == -1);
assertEquals(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.toString(), "1.1");
assertTrue(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.getValue() == 1.1);
assertEquals(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.toString(), "-1.2");
assertTrue(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.getValue() == -1.2);
try {
// test serialization (object => json)
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
ObjectWriter ow = mapper.writer();
String json = ow.writeValueAsString(enumTest);
assertEquals(json, "{\"enum_string\":\"lower\",\"enum_string_required\":null,\"enum_integer\":1,\"enum_number\":1.1,\"outerEnum\":null}");
// test deserialization (json => object)
EnumTest fromString = mapper.readValue(json, EnumTest.class);
assertEquals(fromString.getEnumString().toString(), "lower");
assertEquals(fromString.getEnumInteger().toString(), "1");
assertEquals(fromString.getEnumNumber().toString(), "1.1");
} catch (Exception e) {
fail("Exception thrown during serialization/deserialzation of JSON: " + e.getMessage());
}
}
}

View File

@ -0,0 +1,45 @@
package org.openapitools.client;
import org.openapitools.client.model.Order;
import java.lang.Exception;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import org.junit.*;
import static org.junit.Assert.*;
public class JSONTest {
JSON json = null;
Order order = null;
@Before
public void setup() {
json = new JSON();
order = new Order();
}
@Test
public void testDefaultDate() throws Exception {
final DateTimeFormatter dateFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
final String dateStr = "2015-11-07T14:11:05.267Z";
order.setShipDate(dateFormat.parse(dateStr, OffsetDateTime::from));
String str = json.getContext(null).writeValueAsString(order);
Order o = json.getContext(null).readValue(str, Order.class);
assertEquals(dateStr, dateFormat.format(o.getShipDate()));
}
@Test
public void testCustomDate() throws Exception {
final DateTimeFormatter dateFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.of("Etc/GMT+2"));
final String dateStr = "2015-11-07T14:11:05-02:00";
order.setShipDate(dateFormat.parse(dateStr, OffsetDateTime::from));
String str = json.getContext(null).writeValueAsString(order);
Order o = json.getContext(null).readValue(str, Order.class);
assertEquals(dateStr, dateFormat.format(o.getShipDate()));
}
}

View File

@ -0,0 +1,250 @@
package org.openapitools.client;
import org.openapitools.client.auth.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import org.junit.*;
import static org.junit.Assert.*;
public class ApiClientTest {
ApiClient apiClient = null;
@Before
public void setup() {
apiClient = new ApiClient();
}
@Test
public void testParseAndFormatDate() {
// default date format
String dateStr = "2015-11-07T03:49:09.356Z";
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356+00:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356Z")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T05:49:09.356+02:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T02:49:09.356-01:00")));
// custom date format: without milli-seconds, custom time zone
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
format.setTimeZone(TimeZone.getTimeZone("GMT+10"));
apiClient.setDateFormat(format);
dateStr = "2015-11-07T13:49:09+10:00";
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09+00:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09Z")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T00:49:09-03:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T13:49:09+10:00")));
}
@Test
public void testIsJsonMime() {
assertFalse(apiClient.isJsonMime(null));
assertFalse(apiClient.isJsonMime(""));
assertFalse(apiClient.isJsonMime("text/plain"));
assertFalse(apiClient.isJsonMime("application/xml"));
assertFalse(apiClient.isJsonMime("application/jsonp"));
assertFalse(apiClient.isJsonMime("example/json"));
assertFalse(apiClient.isJsonMime("example/foo+bar+jsonx"));
assertFalse(apiClient.isJsonMime("example/foo+bar+xjson"));
assertTrue(apiClient.isJsonMime("application/json"));
assertTrue(apiClient.isJsonMime("application/json; charset=UTF8"));
assertTrue(apiClient.isJsonMime("APPLICATION/JSON"));
assertTrue(apiClient.isJsonMime("application/problem+json"));
assertTrue(apiClient.isJsonMime("APPLICATION/PROBLEM+JSON"));
assertTrue(apiClient.isJsonMime("application/json\t"));
assertTrue(apiClient.isJsonMime("example/foo+bar+json"));
assertTrue(apiClient.isJsonMime("example/foo+json;x;y"));
assertTrue(apiClient.isJsonMime("example/foo+json\t;"));
assertTrue(apiClient.isJsonMime("Example/fOO+JSON"));
}
@Test
public void testSelectHeaderAccept() {
String[] accepts = {"application/json", "application/xml"};
assertEquals("application/json", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"};
assertEquals("APPLICATION/JSON", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"application/xml", "application/json; charset=UTF8"};
assertEquals("application/json; charset=UTF8", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"text/plain", "application/xml"};
assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{};
assertNull(apiClient.selectHeaderAccept(accepts));
}
@Test
public void testSelectHeaderContentType() {
String[] contentTypes = {"application/json", "application/xml"};
assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"};
assertEquals("APPLICATION/JSON", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"};
assertEquals("application/json; charset=UTF8", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"text/plain", "application/xml"};
assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{};
assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes));
}
@Test
public void testGetAuthentications() {
Map<String, Authentication> 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<Pair> pairs_a = apiClient.parameterToPairs("csv", null, new Integer(1));
List<Pair> pairs_b = apiClient.parameterToPairs("csv", "", new Integer(1));
assertTrue(pairs_a.isEmpty());
assertTrue(pairs_b.isEmpty());
}
@Test
public void testParameterToPairsWhenValueIsNull() throws Exception {
List<Pair> pairs = apiClient.parameterToPairs("csv", "param-a", null);
assertTrue(pairs.isEmpty());
}
@Test
public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception {
// single empty string
List<Pair> pairs = apiClient.parameterToPairs("csv", "param-a", " ");
assertEquals(1, pairs.size());
// list of empty strings
List<String> strs = new ArrayList<String>();
strs.add(" ");
strs.add(" ");
strs.add(" ");
List<Pair> 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<Pair> 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<String, String> collectionFormatMap = new HashMap<String, String>();
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<Object> values = new ArrayList<Object>();
values.add("value-a");
values.add(123);
values.add(new Date());
// check for multi separately
List<Pair> multiPairs = apiClient.parameterToPairs("multi", name, values);
assertEquals(values.size(), multiPairs.size());
// all other formats
for (String collectionFormat : collectionFormatMap.keySet()) {
List<Pair> 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);
}
}
}

View File

@ -0,0 +1,58 @@
package org.openapitools.client;
import org.openapitools.client.model.Order;
import org.junit.Before;
import org.junit.Test;
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.ZoneId;
import org.threeten.bp.format.DateTimeFormatter;
import static org.junit.Assert.*;
public class JSONTest {
private JSON json = null;
private Order order = null;
@Before
public void setup() {
json = new ApiClient().getJSON();
order = new Order();
}
@Test
public void testDefaultDate() throws Exception {
final DateTimeFormatter dateFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
final String dateStr = "2015-11-07T14:11:05.267Z";
order.setShipDate(dateFormat.parse(dateStr, OffsetDateTime.FROM));
String str = json.getContext(null).writeValueAsString(order);
Order o = json.getContext(null).readValue(str, Order.class);
assertEquals(dateStr, dateFormat.format(o.getShipDate()));
}
@Test
public void testCustomDate() throws Exception {
final DateTimeFormatter dateFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.of("Etc/GMT+2"));
final String dateStr = "2015-11-07T14:11:05-02:00";
order.setShipDate(dateFormat.parse(dateStr, OffsetDateTime.FROM));
String str = json.getContext(null).writeValueAsString(order);
Order o = json.getContext(null).readValue(str, Order.class);
assertEquals(dateStr, dateFormat.format(o.getShipDate()));
}
@Test
public void testSqlDateSerialization() throws Exception {
String str = json.getContext(null).writeValueAsString(new java.sql.Date(10));
assertEquals("\"1970-01-01\"", str);
}
@Test
public void testSqlDateDeserialization() throws Exception {
final String str = "1970-01-01";
java.sql.Date date = json.getContext(null).readValue("\"" + str + "\"", java.sql.Date.class);
assertEquals(date.toString(), str);
}
}

View File

@ -0,0 +1,47 @@
package org.openapitools.client.auth;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import org.openapitools.client.Pair;
import org.junit.*;
import static org.junit.Assert.*;
public class ApiKeyAuthTest {
@Test
public void testApplyToParamsInQuery() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
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<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
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"));
}
}

View File

@ -0,0 +1,52 @@
package org.openapitools.client.auth;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import org.openapitools.client.Pair;
import org.junit.*;
import static org.junit.Assert.*;
public class HttpBasicAuthTest {
HttpBasicAuth auth = null;
@Before
public void setup() {
auth = new HttpBasicAuth();
}
@Test
public void testApplyToParams() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
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"));
}
}

View File

@ -0,0 +1,63 @@
package org.openapitools.client.model;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class EnumValueTest {
@Test
public void testEnumClass() {
assertEquals(EnumClass._ABC.toString(), "_abc");
assertEquals(EnumClass._EFG.toString(), "-efg");
assertEquals(EnumClass._XYZ_.toString(), "(xyz)");
}
@Test
public void testEnumTest() {
// test enum value
EnumTest enumTest = new EnumTest();
enumTest.setEnumString(EnumTest.EnumStringEnum.LOWER);
enumTest.setEnumInteger(EnumTest.EnumIntegerEnum.NUMBER_1);
enumTest.setEnumNumber(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1);
assertEquals(EnumTest.EnumStringEnum.UPPER.toString(), "UPPER");
assertEquals(EnumTest.EnumStringEnum.UPPER.getValue(), "UPPER");
assertEquals(EnumTest.EnumStringEnum.LOWER.toString(), "lower");
assertEquals(EnumTest.EnumStringEnum.LOWER.getValue(), "lower");
assertEquals(EnumTest.EnumIntegerEnum.NUMBER_1.toString(), "1");
assertTrue(EnumTest.EnumIntegerEnum.NUMBER_1.getValue() == 1);
assertEquals(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.toString(), "-1");
assertTrue(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.getValue() == -1);
assertEquals(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.toString(), "1.1");
assertTrue(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.getValue() == 1.1);
assertEquals(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.toString(), "-1.2");
assertTrue(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.getValue() == -1.2);
try {
// test serialization (object => json)
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
ObjectWriter ow = mapper.writer();
String json = ow.writeValueAsString(enumTest);
assertEquals(json, "{\"enum_string\":\"lower\",\"enum_string_required\":null,\"enum_integer\":1,\"enum_number\":1.1,\"outerEnum\":null}");
// test deserialization (json => object)
EnumTest fromString = mapper.readValue(json, EnumTest.class);
assertEquals(fromString.getEnumString().toString(), "lower");
assertEquals(fromString.getEnumInteger().toString(), "1");
assertEquals(fromString.getEnumNumber().toString(), "1.1");
} catch (Exception e) {
fail("Exception thrown during serialization/deserialzation of JSON: " + e.getMessage());
}
}
}

View File

@ -0,0 +1,330 @@
package org.openapitools.client;
import org.openapitools.client.auth.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.TimeZone;
import org.junit.*;
import static org.junit.Assert.*;
public class ApiClientTest {
ApiClient apiClient;
JSON json;
@Before
public void setup() {
apiClient = new ApiClient();
json = apiClient.getJSON();
}
@Test
public void testIsJsonMime() {
assertFalse(apiClient.isJsonMime(null));
assertFalse(apiClient.isJsonMime(""));
assertFalse(apiClient.isJsonMime("text/plain"));
assertFalse(apiClient.isJsonMime("application/xml"));
assertFalse(apiClient.isJsonMime("application/jsonp"));
assertFalse(apiClient.isJsonMime("example/json"));
assertFalse(apiClient.isJsonMime("example/foo+bar+jsonx"));
assertFalse(apiClient.isJsonMime("example/foo+bar+xjson"));
assertTrue(apiClient.isJsonMime("application/json"));
assertTrue(apiClient.isJsonMime("application/json; charset=UTF8"));
assertTrue(apiClient.isJsonMime("APPLICATION/JSON"));
assertTrue(apiClient.isJsonMime("application/problem+json"));
assertTrue(apiClient.isJsonMime("APPLICATION/PROBLEM+JSON"));
assertTrue(apiClient.isJsonMime("application/json\t"));
assertTrue(apiClient.isJsonMime("example/foo+bar+json"));
assertTrue(apiClient.isJsonMime("example/foo+json;x;y"));
assertTrue(apiClient.isJsonMime("example/foo+json\t;"));
assertTrue(apiClient.isJsonMime("Example/fOO+JSON"));
assertTrue(apiClient.isJsonMime("application/json-patch+json"));
}
@Test
public void testSelectHeaderAccept() {
String[] accepts = {"application/json", "application/xml"};
assertEquals("application/json", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"};
assertEquals("APPLICATION/JSON", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"application/xml", "application/json; charset=UTF8"};
assertEquals("application/json; charset=UTF8", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"text/plain", "application/xml"};
assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{};
assertNull(apiClient.selectHeaderAccept(accepts));
}
@Test
public void testSelectHeaderContentType() {
String[] contentTypes = {"application/json", "application/xml"};
assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"};
assertEquals("APPLICATION/JSON", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"};
assertEquals("application/json; charset=UTF8", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"text/plain", "application/xml"};
assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{};
assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes));
}
@Test
public void testGetAuthentications() {
Map<String, Authentication> 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<Pair> pairs_a = apiClient.parameterToPair(null, new Integer(1));
List<Pair> pairs_b = apiClient.parameterToPair("", new Integer(1));
assertTrue(pairs_a.isEmpty());
assertTrue(pairs_b.isEmpty());
}
@Test
public void testParameterToPairWhenValueIsNull() throws Exception {
List<Pair> pairs = apiClient.parameterToPair("param-a", null);
assertTrue(pairs.isEmpty());
}
@Test
public void testParameterToPairWhenValueIsEmptyString() throws Exception {
// single empty string
List<Pair> pairs = apiClient.parameterToPair("param-a", " ");
assertEquals(1, pairs.size());
}
@Test
public void testParameterToPairWhenValueIsNotCollection() throws Exception {
String name = "param-a";
Integer value = 1;
List<Pair> pairs = apiClient.parameterToPair(name, value);
assertEquals(1, pairs.size());
assertEquals(value, Integer.valueOf(pairs.get(0).getValue()));
}
@Test
public void testParameterToPairWhenValueIsCollection() throws Exception {
List<Object> values = new ArrayList<Object>();
values.add("value-a");
values.add(123);
values.add(new Date());
List<Pair> pairs = apiClient.parameterToPair("param-a", values);
assertEquals(0, pairs.size());
}
@Test
public void testParameterToPairsWhenNameIsInvalid() throws Exception {
List<Integer> objects = new ArrayList<Integer>();
objects.add(new Integer(1));
List<Pair> pairs_a = apiClient.parameterToPairs("csv", null, objects);
List<Pair> pairs_b = apiClient.parameterToPairs("csv", "", objects);
assertTrue(pairs_a.isEmpty());
assertTrue(pairs_b.isEmpty());
}
@Test
public void testParameterToPairsWhenValueIsNull() throws Exception {
List<Pair> pairs = apiClient.parameterToPairs("csv", "param-a", null);
assertTrue(pairs.isEmpty());
}
@Test
public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception {
// list of empty strings
List<String> strs = new ArrayList<String>();
strs.add(" ");
strs.add(" ");
strs.add(" ");
List<Pair> 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<String, String> collectionFormatMap = new HashMap<String, String>();
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<Object> values = new ArrayList<Object>();
values.add("value-a");
values.add(123);
values.add(new Date());
// check for multi separately
List<Pair> 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<Pair> 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"));
}
}

View File

@ -0,0 +1,201 @@
package org.openapitools.client;
import com.google.gson.reflect.TypeToken;
import org.openapitools.client.model.Order;
import java.lang.Exception;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import okio.ByteString;
import org.junit.*;
import org.threeten.bp.LocalDate;
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.ZoneId;
import org.threeten.bp.ZoneOffset;
import org.threeten.bp.format.DateTimeFormatter;
import static org.junit.Assert.*;
public class JSONTest {
private ApiClient apiClient = null;
private JSON json = null;
private Order order = null;
@Before
public void setup() {
apiClient = new ApiClient();
json = apiClient.getJSON();
order = new Order();
}
@Test
public void testSqlDateTypeAdapter() {
final String str = "\"2015-11-07\"";
final java.sql.Date date = java.sql.Date.valueOf("2015-11-07");
assertEquals(str, json.serialize(date));
assertEquals(json.deserialize(str, java.sql.Date.class), date);
assertEquals(json.deserialize("\"2015-11-07T03:49:09.356" + getCurrentTimezoneOffset() + "\"", java.sql.Date.class).toString(), date.toString());
// custom date format: without day
DateFormat format = new SimpleDateFormat("yyyy-MM");
apiClient.setSqlDateFormat(format);
String dateStr = "\"2015-11\"";
assertEquals(dateStr, json.serialize(json.deserialize("\"2015-11-07T03:49:09Z\"", java.sql.Date.class)));
assertEquals(dateStr, json.serialize(json.deserialize("\"2015-11\"", java.sql.Date.class)));
}
@Test
public void testDateTypeAdapter() {
Calendar cal = new GregorianCalendar(2015, 10, 7, 3, 49, 9);
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
assertEquals(json.deserialize("\"2015-11-07T05:49:09+02\"", Date.class), cal.getTime());
cal.set(Calendar.MILLISECOND, 300);
assertEquals(json.deserialize("\"2015-11-07T03:49:09.3Z\"", Date.class), cal.getTime());
cal.set(Calendar.MILLISECOND, 356);
Date date = cal.getTime();
final String utcDate = "\"2015-11-07T03:49:09.356Z\"";
assertEquals(json.deserialize(utcDate, Date.class), date);
assertEquals(json.deserialize("\"2015-11-07T03:49:09.356+00:00\"", Date.class), date);
assertEquals(json.deserialize("\"2015-11-07T05:49:09.356+02:00\"", Date.class), date);
assertEquals(json.deserialize("\"2015-11-07T02:49:09.356-01:00\"", Date.class), date);
assertEquals(json.deserialize("\"2015-11-07T03:49:09.356Z\"", Date.class), date);
assertEquals(json.deserialize("\"2015-11-07T03:49:09.356+00\"", Date.class), date);
assertEquals(json.deserialize("\"2015-11-07T02:49:09.356-0100\"", Date.class), date);
assertEquals(json.deserialize("\"2015-11-07T03:49:09.356456789Z\"", Date.class), date);
assertEquals(utcDate, json.serialize(date));
// custom datetime format: without milli-seconds, custom time zone
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
format.setTimeZone(TimeZone.getTimeZone("GMT+10"));
apiClient.setDateFormat(format);
String dateStr = "\"2015-11-07T13:49:09+10:00\"";
assertEquals(dateStr, json.serialize(json.deserialize("\"2015-11-07T03:49:09+00:00\"", Date.class)));
assertEquals(dateStr, json.serialize(json.deserialize("\"2015-11-07T03:49:09Z\"", Date.class)));
assertEquals(dateStr, json.serialize(json.deserialize("\"2015-11-07T00:49:09-03:00\"", Date.class)));
try {
// invalid time zone format
json.deserialize("\"2015-11-07T03:49:09+00\"", Date.class);
fail("json parsing should fail");
} catch (RuntimeException e) {
// OK
}
try {
// unexpected miliseconds
json.deserialize("\"2015-11-07T03:49:09.000Z\"", Date.class);
fail("json parsing should fail");
} catch (RuntimeException e) {
// OK
}
}
@Test
public void testOffsetDateTimeTypeAdapter() {
final String str = "\"2016-09-09T08:02:03.123-03:00\"";
OffsetDateTime date = OffsetDateTime.of(2016, 9, 9, 8, 2, 3, 123000000, ZoneOffset.of("-3"));
assertEquals(str, json.serialize(date));
//Use toString() instead of isEqual to verify that the offset is preserved
assertEquals(json.deserialize(str, OffsetDateTime.class).toString(), date.toString());
}
@Test
public void testLocalDateTypeAdapter() {
final String str = "\"2016-09-09\"";
final LocalDate date = LocalDate.of(2016, 9, 9);
assertEquals(str, json.serialize(date));
assertEquals(json.deserialize(str, LocalDate.class), date);
}
@Test
public void testDefaultDate() throws Exception {
final DateTimeFormatter datetimeFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
final String dateStr = "2015-11-07T14:11:05.267Z";
order.setShipDate(datetimeFormat.parse(dateStr, OffsetDateTime.FROM));
String str = json.serialize(order);
Type type = new TypeToken<Order>() { }.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<Order>() { }.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<byte[]>() { }.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;
}
}

View File

@ -0,0 +1,76 @@
package org.openapitools.client.auth;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import org.openapitools.client.Pair;
import org.junit.*;
import static org.junit.Assert.*;
public class ApiKeyAuthTest {
@Test
public void testApplyToParamsInQuery() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
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<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
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<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
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<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
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());
}
}

View File

@ -0,0 +1,62 @@
package org.openapitools.client.auth;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import org.openapitools.client.Pair;
import org.junit.*;
import static org.junit.Assert.*;
public class HttpBasicAuthTest {
HttpBasicAuth auth = null;
@Before
public void setup() {
auth = new HttpBasicAuth();
}
@Test
public void testApplyToParams() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
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<Pair>();
headerParams = new HashMap<String, String>();
auth.setUsername(null);
auth.setPassword(null);
auth.applyToParams(queryParams, headerParams);
// no changes to parameters
assertEquals(0, queryParams.size());
assertEquals(0, headerParams.size());
}
}

View File

@ -0,0 +1,56 @@
package org.openapitools.client.model;
import org.junit.Test;
import com.google.gson.Gson;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class EnumValueTest {
@Test
public void testEnumClass() {
assertEquals(EnumClass._ABC.toString(), "_abc");
assertEquals(EnumClass._EFG.toString(), "-efg");
assertEquals(EnumClass._XYZ_.toString(), "(xyz)");
}
@Test
public void testEnumTest() {
// test enum value
EnumTest enumTest = new EnumTest();
enumTest.setEnumString(EnumTest.EnumStringEnum.LOWER);
enumTest.setEnumInteger(EnumTest.EnumIntegerEnum.NUMBER_1);
enumTest.setEnumNumber(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1);
assertEquals(EnumTest.EnumStringEnum.UPPER.toString(), "UPPER");
assertEquals(EnumTest.EnumStringEnum.UPPER.getValue(), "UPPER");
assertEquals(EnumTest.EnumStringEnum.LOWER.toString(), "lower");
assertEquals(EnumTest.EnumStringEnum.LOWER.getValue(), "lower");
assertEquals(EnumTest.EnumIntegerEnum.NUMBER_1.toString(), "1");
assertTrue(EnumTest.EnumIntegerEnum.NUMBER_1.getValue() == 1);
assertEquals(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.toString(), "-1");
assertTrue(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.getValue() == -1);
assertEquals(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.toString(), "1.1");
assertTrue(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.getValue() == 1.1);
assertEquals(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.toString(), "-1.2");
assertTrue(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.getValue() == -1.2);
// test serialization
Gson gson = new Gson();
String json = gson.toJson(enumTest);
assertEquals(json, "{\"enum_string\":\"lower\",\"enum_integer\":1,\"enum_number\":1.1}");
// test deserialization
EnumTest fromString = gson.fromJson(json, EnumTest.class);
assertEquals(fromString.getEnumString().toString(), "lower");
assertEquals(fromString.getEnumString().getValue(), "lower");
assertEquals(fromString.getEnumInteger().toString(), "1");
assertTrue(fromString.getEnumInteger().getValue() == 1);
assertEquals(fromString.getEnumNumber().toString(), "1.1");
assertTrue(fromString.getEnumNumber().getValue() == 1.1);
}
}

View File

@ -0,0 +1,254 @@
package org.openapitools.client;
import org.openapitools.client.auth.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import org.junit.*;
import org.springframework.http.MediaType;
import org.springframework.util.MultiValueMap;
import static org.junit.Assert.*;
public class ApiClientTest {
ApiClient apiClient = null;
@Before
public void setup() {
apiClient = new ApiClient();
}
/**
*
*/
@Test
public void testParseAndFormatDate() {
// default date format
String dateStr = "2015-11-07T03:49:09.356Z";
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356+00:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356Z")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T05:49:09.356+02:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T02:49:09.356-01:00")));
// custom date format: without milli-seconds, custom time zone
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
format.setTimeZone(TimeZone.getTimeZone("GMT+10"));
apiClient.setDateFormat(format);
dateStr = "2015-11-07T13:49:09+10:00";
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09+00:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09Z")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T00:49:09-03:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T13:49:09+10:00")));
}
@Test
public void testIsJsonMime() {
assertFalse(apiClient.isJsonMime((String) null));
assertFalse(apiClient.isJsonMime(""));
assertFalse(apiClient.isJsonMime("text/plain"));
assertFalse(apiClient.isJsonMime("application/xml"));
assertFalse(apiClient.isJsonMime("application/jsonp"));
assertFalse(apiClient.isJsonMime("example/json"));
assertFalse(apiClient.isJsonMime("example/foo+bar+jsonx"));
assertFalse(apiClient.isJsonMime("example/foo+bar+xjson"));
assertTrue(apiClient.isJsonMime("application/json"));
assertTrue(apiClient.isJsonMime("application/json; charset=UTF8"));
assertTrue(apiClient.isJsonMime("APPLICATION/JSON"));
assertTrue(apiClient.isJsonMime("application/problem+json"));
assertTrue(apiClient.isJsonMime("APPLICATION/PROBLEM+JSON"));
assertTrue(apiClient.isJsonMime("application/json\t"));
assertTrue(apiClient.isJsonMime("example/foo+bar+json"));
assertTrue(apiClient.isJsonMime("example/foo+json;x;y"));
assertTrue(apiClient.isJsonMime("example/foo+json\t;"));
assertTrue(apiClient.isJsonMime("Example/fOO+JSON"));
}
@Test
public void testSelectHeaderAccept() {
String[] accepts = {"application/json", "application/xml"};
assertEquals(Arrays.asList(MediaType.parseMediaType("application/json")), apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"};
assertEquals(Arrays.asList(MediaType.parseMediaType("APPLICATION/JSON")), apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"application/xml", "application/json; charset=UTF8"};
assertEquals(Arrays.asList(MediaType.parseMediaType("application/json; charset=UTF8")), apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"text/plain", "application/xml"};
assertEquals(Arrays.asList(MediaType.parseMediaType("text/plain"),MediaType.parseMediaType("application/xml")), apiClient.selectHeaderAccept(accepts));
accepts = new String[]{};
assertNull(apiClient.selectHeaderAccept(accepts));
}
@Test
public void testSelectHeaderContentType() {
String[] contentTypes = {"application/json", "application/xml"};
assertEquals(MediaType.parseMediaType("application/json"), apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"};
assertEquals(MediaType.parseMediaType("APPLICATION/JSON"), apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"};
assertEquals(MediaType.parseMediaType("application/json; charset=UTF8"), apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"text/plain", "application/xml"};
assertEquals(MediaType.parseMediaType("text/plain"), apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{};
assertEquals(MediaType.parseMediaType("application/json"), apiClient.selectHeaderContentType(contentTypes));
}
@Test
public void testGetAuthentications() {
Map<String, Authentication> 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<String, String> pairs_a = apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.CSV, null, new Integer(1));
MultiValueMap<String, String> 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<String, String> pairs = apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.CSV, "param-a", null);
assertTrue(pairs.isEmpty());
}
@Test
public void testParameterToMultiValueMapWhenValueIsEmptyStrings() throws Exception {
// single empty string
MultiValueMap<String, String> pairs = apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.CSV, "param-a", " ");
assertEquals(1, pairs.size());
// list of empty strings
List<String> strs = new ArrayList<String>();
strs.add(" ");
strs.add(" ");
strs.add(" ");
MultiValueMap<String, String> 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<String, String> 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<ApiClient.CollectionFormat, String> collectionFormatMap = new HashMap<ApiClient.CollectionFormat, String>();
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<Object> values = new ArrayList<Object>();
values.add("value-a");
values.add(123);
values.add(new Date());
// check for multi separately
MultiValueMap<String, String> 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<String, String> 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);
}
}
}

View File

@ -0,0 +1,47 @@
package org.openapitools.client.auth;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import org.junit.*;
import org.springframework.http.HttpHeaders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import static org.junit.Assert.*;
public class ApiKeyAuthTest {
@Test
public void testApplyToParamsInQuery() {
MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
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<String, String> queryParams = new LinkedMultiValueMap<String, String>();
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));
}
}

View File

@ -0,0 +1,54 @@
package org.openapitools.client.auth;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import org.junit.*;
import org.springframework.http.HttpHeaders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import static org.junit.Assert.*;
public class HttpBasicAuthTest {
HttpBasicAuth auth = null;
@Before
public void setup() {
auth = new HttpBasicAuth();
}
@Test
public void testApplyToParams() {
MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
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));
}
}

View File

@ -0,0 +1,63 @@
package org.openapitools.client.model;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class EnumValueTest {
@Test
public void testEnumClass() {
assertEquals(EnumClass._ABC.toString(), "_abc");
assertEquals(EnumClass._EFG.toString(), "-efg");
assertEquals(EnumClass._XYZ_.toString(), "(xyz)");
}
@Test
public void testEnumTest() {
// test enum value
EnumTest enumTest = new EnumTest();
enumTest.setEnumString(EnumTest.EnumStringEnum.LOWER);
enumTest.setEnumInteger(EnumTest.EnumIntegerEnum.NUMBER_1);
enumTest.setEnumNumber(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1);
assertEquals(EnumTest.EnumStringEnum.UPPER.toString(), "UPPER");
assertEquals(EnumTest.EnumStringEnum.UPPER.getValue(), "UPPER");
assertEquals(EnumTest.EnumStringEnum.LOWER.toString(), "lower");
assertEquals(EnumTest.EnumStringEnum.LOWER.getValue(), "lower");
assertEquals(EnumTest.EnumIntegerEnum.NUMBER_1.toString(), "1");
assertTrue(EnumTest.EnumIntegerEnum.NUMBER_1.getValue() == 1);
assertEquals(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.toString(), "-1");
assertTrue(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.getValue() == -1);
assertEquals(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.toString(), "1.1");
assertTrue(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.getValue() == 1.1);
assertEquals(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.toString(), "-1.2");
assertTrue(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.getValue() == -1.2);
try {
// test serialization (object => json)
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
ObjectWriter ow = mapper.writer();
String json = ow.writeValueAsString(enumTest);
assertEquals(json, "{\"enum_string\":\"lower\",\"enum_string_required\":null,\"enum_integer\":1,\"enum_number\":1.1,\"outerEnum\":null}");
// test deserialization (json => object)
EnumTest fromString = mapper.readValue(json, EnumTest.class);
assertEquals(fromString.getEnumString().toString(), "lower");
assertEquals(fromString.getEnumInteger().toString(), "1");
assertEquals(fromString.getEnumNumber().toString(), "1.1");
} catch (Exception e) {
fail("Exception thrown during serialization/deserialzation of JSON: " + e.getMessage());
}
}
}

View File

@ -33,3 +33,8 @@ echo "Removing files and folders under samples/client/petstore/java/feign/src/ma
rm -rf samples/client/petstore/java/feign/src/main
find samples/client/petstore/java/feign -maxdepth 1 -type f ! -name "README.md" -exec rm {} +
java $JAVA_OPTS -jar $executable $ags
# copy additional manually written unit-tests
mkdir samples/client/petstore/java/feign/src/test/java/org/openapitools/client
cp CI/samples.ci/client/petstore/java/test-manual/common/StringUtilTest.java samples/client/petstore/java/feign/src/test/java/org/openapitools/client/StringUtilTest.java

View File

@ -33,3 +33,15 @@ echo "Removing files and folders under samples/client/petstore/java/jersey1/src/
rm -rf samples/client/petstore/java/jersey1/src/main
find samples/client/petstore/java/jersey1 -maxdepth 1 -type f ! -name "README.md" -exec rm {} +
java $JAVA_OPTS -jar $executable $ags
# copy additional manually written unit-tests
mkdir samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client
mkdir samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/auth
mkdir samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/model
cp CI/samples.ci/client/petstore/java/test-manual/common/StringUtilTest.java samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/StringUtilTest.java
cp CI/samples.ci/client/petstore/java/test-manual/jersey1/ApiClientTest.java samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/ApiClientTest.java
cp CI/samples.ci/client/petstore/java/test-manual/common/ConfigurationTest.java samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/ConfigurationTest.java
cp CI/samples.ci/client/petstore/java/test-manual/jersey1/auth/ApiKeyAuthTest.java samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java
cp CI/samples.ci/client/petstore/java/test-manual/jersey1/auth/HttpBasicAuthTest.java samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java
cp CI/samples.ci/client/petstore/java/test-manual/jersey1/model/EnumValueTest.java samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/model/EnumValueTest.java

View File

@ -29,7 +29,7 @@ fi
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate --artifact-id petstore-jersey2-java6 -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g java -c bin/java-petstore-jersey2.json -o samples/client/petstore/java/jersey2-java6 -DhideGenerationTimestamp=true,supportJava6=true $@"
echo "Removing files and folders under samples/client/petstore/java/jersey2/src/main"
echo "Removing files and folders under samples/client/petstore/java/jersey2-java6/src/main"
rm -rf samples/client/petstore/java/jersey2-java6/src/main
find samples/client/petstore/java/jersey2-java6 -maxdepth 1 -type f ! -name "README.md" -exec rm {} +
java $JAVA_OPTS -jar $executable $ags

View File

@ -33,3 +33,16 @@ echo "Removing files and folders under samples/client/petstore/java/jersey2/src/
rm -rf samples/client/petstore/java/jersey2/src/main
find samples/client/petstore/java/jersey2 -maxdepth 1 -type f ! -name "README.md" -exec rm {} +
java $JAVA_OPTS -jar $executable $ags
# copy additional manually written unit-tests
mkdir samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client
mkdir samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/auth
mkdir samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/model
cp CI/samples.ci/client/petstore/java/test-manual/common/StringUtilTest.java samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/StringUtilTest.java
cp CI/samples.ci/client/petstore/java/test-manual/jersey2/ApiClientTest.java samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/ApiClientTest.java
cp CI/samples.ci/client/petstore/java/test-manual/common/ConfigurationTest.java samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/ConfigurationTest.java
cp CI/samples.ci/client/petstore/java/test-manual/jersey2/auth/ApiKeyAuthTest.java samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java
cp CI/samples.ci/client/petstore/java/test-manual/jersey2/auth/HttpBasicAuthTest.java samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java
cp CI/samples.ci/client/petstore/java/test-manual/jersey2/model/EnumValueTest.java samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/model/EnumValueTest.java
cp CI/samples.ci/client/petstore/java/test-manual/jersey2/JSONTest.java samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/JSONTest.java

View File

@ -32,3 +32,16 @@ ags="generate -t modules/openapi-generator/src/main/resources/Java/libraries/okh
rm -rf samples/client/petstore/java/okhttp-gson/src/main
find samples/client/petstore/java/okhttp-gson -maxdepth 1 -type f ! -name "README.md" -exec rm {} +
java $JAVA_OPTS -jar $executable $ags
# copy additional manually written unit-tests
mkdir samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client
mkdir samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/auth
mkdir samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model
cp CI/samples.ci/client/petstore/java/test-manual/common/StringUtilTest.java samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/StringUtilTest.java
cp CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/ApiClientTest.java samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/ApiClientTest.java
cp CI/samples.ci/client/petstore/java/test-manual/common/ConfigurationTest.java samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/ConfigurationTest.java
cp CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/auth/ApiKeyAuthTest.java samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java
cp CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/auth/HttpBasicAuthTest.java samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java
cp CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/model/EnumValueTest.java samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EnumValueTest.java
cp CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/JSONTest.java samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/JSONTest.java

View File

@ -33,3 +33,13 @@ echo "Removing files and folders under samples/client/petstore/java/resttemplate
rm -rf samples/client/petstore/java/resttemplate/src/main
find samples/client/petstore/java/resttemplate -maxdepth 1 -type f ! -name "README.md" -exec rm {} +
java $JAVA_OPTS -jar $executable $ags
# copy additional manually written unit-tests
mkdir samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client
mkdir samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/auth
mkdir samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/model
cp CI/samples.ci/client/petstore/java/test-manual/resttemplate/ApiClientTest.java samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/ApiClientTest.java
cp CI/samples.ci/client/petstore/java/test-manual/resttemplate/auth/ApiKeyAuthTest.java samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java
cp CI/samples.ci/client/petstore/java/test-manual/resttemplate/auth/HttpBasicAuthTest.java samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java
cp CI/samples.ci/client/petstore/java/test-manual/resttemplate/model/EnumValueTest.java samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/model/EnumValueTest.java

View File

@ -33,3 +33,16 @@ echo "Removing files and folders under samples/client/petstore/java/jersey2-java
rm -rf samples/client/petstore/java/jersey2-java8/src/main
find samples/client/petstore/java/jersey2-java8 -maxdepth 1 -type f ! -name "README.md" -exec rm {} +
java $JAVA_OPTS -jar $executable $ags
# copy additional manually written unit-tests
mkdir samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client
mkdir samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/auth
mkdir samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/model
cp CI/samples.ci/client/petstore/java/test-manual/common/StringUtilTest.java samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/StringUtilTest.java
cp CI/samples.ci/client/petstore/java/test-manual/jersey2/ApiClientTest.java samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/ApiClientTest.java
cp CI/samples.ci/client/petstore/java/test-manual/common/ConfigurationTest.java samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/ConfigurationTest.java
cp CI/samples.ci/client/petstore/java/test-manual/jersey2/auth/ApiKeyAuthTest.java samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java
cp CI/samples.ci/client/petstore/java/test-manual/jersey2/auth/HttpBasicAuthTest.java samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java
cp CI/samples.ci/client/petstore/java/test-manual/jersey2/model/EnumValueTest.java samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/model/EnumValueTest.java
cp CI/samples.ci/client/petstore/java/test-manual/jersey2-java8/JSONTest.java samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/JSONTest.java

View File

@ -0,0 +1,33 @@
package org.openapitools.client;
import org.junit.*;
import static org.junit.Assert.*;
public class StringUtilTest {
@Test
public void testContainsIgnoreCase() {
assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "abc"));
assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "ABC"));
assertTrue(StringUtil.containsIgnoreCase(new String[]{"ABC"}, "abc"));
assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, "ABC"));
assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, null));
assertFalse(StringUtil.containsIgnoreCase(new String[]{"abc"}, "def"));
assertFalse(StringUtil.containsIgnoreCase(new String[]{}, "ABC"));
assertFalse(StringUtil.containsIgnoreCase(new String[]{}, null));
}
@Test
public void testJoin() {
String[] array = {"aa", "bb", "cc"};
assertEquals("aa,bb,cc", StringUtil.join(array, ","));
assertEquals("aa, bb, cc", StringUtil.join(array, ", "));
assertEquals("aabbcc", StringUtil.join(array, ""));
assertEquals("aa bb cc", StringUtil.join(array, " "));
assertEquals("aa\nbb\ncc", StringUtil.join(array, "\n"));
assertEquals("", StringUtil.join(new String[]{}, ","));
assertEquals("abc", StringUtil.join(new String[]{"abc"}, ","));
}
}

View File

@ -0,0 +1,292 @@
package org.openapitools.client;
import org.openapitools.client.auth.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import org.junit.*;
import static org.junit.Assert.*;
public class ApiClientTest {
ApiClient apiClient = null;
@Before
public void setup() {
apiClient = new ApiClient();
}
@Test
public void testParseAndFormatDate() {
// default date format
String dateStr = "2015-11-07T03:49:09.356Z";
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356+00:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356Z")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T05:49:09.356+02:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T02:49:09.356-01:00")));
// custom date format: without milli-seconds, custom time zone
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
format.setTimeZone(TimeZone.getTimeZone("GMT+10"));
apiClient.setDateFormat(format);
dateStr = "2015-11-07T13:49:09+10:00";
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09+00:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09Z")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T00:49:09-03:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T13:49:09+10:00")));
}
@Test
public void testIsJsonMime() {
assertFalse(apiClient.isJsonMime(null));
assertFalse(apiClient.isJsonMime(""));
assertFalse(apiClient.isJsonMime("text/plain"));
assertFalse(apiClient.isJsonMime("application/xml"));
assertFalse(apiClient.isJsonMime("application/jsonp"));
assertFalse(apiClient.isJsonMime("example/json"));
assertFalse(apiClient.isJsonMime("example/foo+bar+jsonx"));
assertFalse(apiClient.isJsonMime("example/foo+bar+xjson"));
assertTrue(apiClient.isJsonMime("application/json"));
assertTrue(apiClient.isJsonMime("application/json; charset=UTF8"));
assertTrue(apiClient.isJsonMime("APPLICATION/JSON"));
assertTrue(apiClient.isJsonMime("application/problem+json"));
assertTrue(apiClient.isJsonMime("APPLICATION/PROBLEM+JSON"));
assertTrue(apiClient.isJsonMime("application/json\t"));
assertTrue(apiClient.isJsonMime("example/foo+bar+json"));
assertTrue(apiClient.isJsonMime("example/foo+json;x;y"));
assertTrue(apiClient.isJsonMime("example/foo+json\t;"));
assertTrue(apiClient.isJsonMime("Example/fOO+JSON"));
}
@Test
public void testSelectHeaderAccept() {
String[] accepts = {"application/json", "application/xml"};
assertEquals("application/json", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"};
assertEquals("APPLICATION/JSON", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"application/xml", "application/json; charset=UTF8"};
assertEquals("application/json; charset=UTF8", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"text/plain", "application/xml"};
assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{};
assertNull(apiClient.selectHeaderAccept(accepts));
}
@Test
public void testSelectHeaderContentType() {
String[] contentTypes = {"application/json", "application/xml"};
assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"};
assertEquals("APPLICATION/JSON", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"};
assertEquals("application/json; charset=UTF8", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"text/plain", "application/xml"};
assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{};
assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes));
}
@Test
public void testGetAuthentications() {
Map<String, Authentication> 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<Pair> pairs_a = apiClient.parameterToPair(null, new Integer(1));
List<Pair> pairs_b = apiClient.parameterToPair("", new Integer(1));
assertTrue(pairs_a.isEmpty());
assertTrue(pairs_b.isEmpty());
}
@Test
public void testParameterToPairWhenValueIsNull() throws Exception {
List<Pair> pairs = apiClient.parameterToPair("param-a", null);
assertTrue(pairs.isEmpty());
}
@Test
public void testParameterToPairWhenValueIsEmptyString() throws Exception {
// single empty string
List<Pair> pairs = apiClient.parameterToPair("param-a", " ");
assertEquals(1, pairs.size());
}
@Test
public void testParameterToPairWhenValueIsNotCollection() throws Exception {
String name = "param-a";
Integer value = 1;
List<Pair> pairs = apiClient.parameterToPair(name, value);
assertEquals(1, pairs.size());
assertEquals(value, Integer.valueOf(pairs.get(0).getValue()));
}
@Test
public void testParameterToPairWhenValueIsCollection() throws Exception {
List<Object> values = new ArrayList<Object>();
values.add("value-a");
values.add(123);
values.add(new Date());
List<Pair> pairs = apiClient.parameterToPair("param-a", values);
assertEquals(0, pairs.size());
}
@Test
public void testParameterToPairsWhenNameIsInvalid() throws Exception {
List<Integer> objects = new ArrayList<Integer>();
objects.add(new Integer(1));
List<Pair> pairs_a = apiClient.parameterToPairs("csv", null, objects);
List<Pair> pairs_b = apiClient.parameterToPairs("csv", "", objects);
assertTrue(pairs_a.isEmpty());
assertTrue(pairs_b.isEmpty());
}
@Test
public void testParameterToPairsWhenValueIsNull() throws Exception {
List<Pair> pairs = apiClient.parameterToPairs("csv", "param-a", null);
assertTrue(pairs.isEmpty());
}
@Test
public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception {
// list of empty strings
List<String> strs = new ArrayList<String>();
strs.add(" ");
strs.add(" ");
strs.add(" ");
List<Pair> 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<String, String> collectionFormatMap = new HashMap<String, String>();
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<Object> values = new ArrayList<Object>();
values.add("value-a");
values.add(123);
values.add(new Date());
// check for multi separately
List<Pair> 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<Pair> 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]);
}
}
}
}

View File

@ -0,0 +1,15 @@
package org.openapitools.client;
import org.junit.*;
import static org.junit.Assert.*;
public class ConfigurationTest {
@Test
public void testDefaultApiClient() {
ApiClient apiClient = Configuration.getDefaultApiClient();
assertNotNull(apiClient);
assertEquals("http://petstore.swagger.io:80/v2", apiClient.getBasePath());
assertFalse(apiClient.isDebugging());
}
}

View File

@ -0,0 +1,33 @@
package org.openapitools.client;
import org.junit.*;
import static org.junit.Assert.*;
public class StringUtilTest {
@Test
public void testContainsIgnoreCase() {
assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "abc"));
assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "ABC"));
assertTrue(StringUtil.containsIgnoreCase(new String[]{"ABC"}, "abc"));
assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, "ABC"));
assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, null));
assertFalse(StringUtil.containsIgnoreCase(new String[]{"abc"}, "def"));
assertFalse(StringUtil.containsIgnoreCase(new String[]{}, "ABC"));
assertFalse(StringUtil.containsIgnoreCase(new String[]{}, null));
}
@Test
public void testJoin() {
String[] array = {"aa", "bb", "cc"};
assertEquals("aa,bb,cc", StringUtil.join(array, ","));
assertEquals("aa, bb, cc", StringUtil.join(array, ", "));
assertEquals("aabbcc", StringUtil.join(array, ""));
assertEquals("aa bb cc", StringUtil.join(array, " "));
assertEquals("aa\nbb\ncc", StringUtil.join(array, "\n"));
assertEquals("", StringUtil.join(new String[]{}, ","));
assertEquals("abc", StringUtil.join(new String[]{"abc"}, ","));
}
}

View File

@ -0,0 +1,47 @@
package org.openapitools.client.auth;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import org.openapitools.client.Pair;
import org.junit.*;
import static org.junit.Assert.*;
public class ApiKeyAuthTest {
@Test
public void testApplyToParamsInQuery() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
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<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
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"));
}
}

View File

@ -0,0 +1,52 @@
package org.openapitools.client.auth;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import org.openapitools.client.Pair;
import org.junit.*;
import static org.junit.Assert.*;
public class HttpBasicAuthTest {
HttpBasicAuth auth = null;
@Before
public void setup() {
auth = new HttpBasicAuth();
}
@Test
public void testApplyToParams() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
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"));
}
}

View File

@ -0,0 +1,63 @@
package org.openapitools.client.model;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class EnumValueTest {
@Test
public void testEnumClass() {
assertEquals(EnumClass._ABC.toString(), "_abc");
assertEquals(EnumClass._EFG.toString(), "-efg");
assertEquals(EnumClass._XYZ_.toString(), "(xyz)");
}
@Test
public void testEnumTest() {
// test enum value
EnumTest enumTest = new EnumTest();
enumTest.setEnumString(EnumTest.EnumStringEnum.LOWER);
enumTest.setEnumInteger(EnumTest.EnumIntegerEnum.NUMBER_1);
enumTest.setEnumNumber(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1);
assertEquals(EnumTest.EnumStringEnum.UPPER.toString(), "UPPER");
assertEquals(EnumTest.EnumStringEnum.UPPER.getValue(), "UPPER");
assertEquals(EnumTest.EnumStringEnum.LOWER.toString(), "lower");
assertEquals(EnumTest.EnumStringEnum.LOWER.getValue(), "lower");
assertEquals(EnumTest.EnumIntegerEnum.NUMBER_1.toString(), "1");
assertTrue(EnumTest.EnumIntegerEnum.NUMBER_1.getValue() == 1);
assertEquals(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.toString(), "-1");
assertTrue(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.getValue() == -1);
assertEquals(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.toString(), "1.1");
assertTrue(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.getValue() == 1.1);
assertEquals(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.toString(), "-1.2");
assertTrue(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.getValue() == -1.2);
try {
// test serialization (object => json)
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
ObjectWriter ow = mapper.writer();
String json = ow.writeValueAsString(enumTest);
assertEquals(json, "{\"enum_string\":\"lower\",\"enum_string_required\":null,\"enum_integer\":1,\"enum_number\":1.1,\"outerEnum\":null}");
// test deserialization (json => object)
EnumTest fromString = mapper.readValue(json, EnumTest.class);
assertEquals(fromString.getEnumString().toString(), "lower");
assertEquals(fromString.getEnumInteger().toString(), "1");
assertEquals(fromString.getEnumNumber().toString(), "1.1");
} catch (Exception e) {
fail("Exception thrown during serialization/deserialzation of JSON: " + e.getMessage());
}
}
}

View File

@ -0,0 +1,250 @@
package org.openapitools.client;
import org.openapitools.client.auth.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import org.junit.*;
import static org.junit.Assert.*;
public class ApiClientTest {
ApiClient apiClient = null;
@Before
public void setup() {
apiClient = new ApiClient();
}
@Test
public void testParseAndFormatDate() {
// default date format
String dateStr = "2015-11-07T03:49:09.356Z";
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356+00:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356Z")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T05:49:09.356+02:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T02:49:09.356-01:00")));
// custom date format: without milli-seconds, custom time zone
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
format.setTimeZone(TimeZone.getTimeZone("GMT+10"));
apiClient.setDateFormat(format);
dateStr = "2015-11-07T13:49:09+10:00";
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09+00:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09Z")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T00:49:09-03:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T13:49:09+10:00")));
}
@Test
public void testIsJsonMime() {
assertFalse(apiClient.isJsonMime(null));
assertFalse(apiClient.isJsonMime(""));
assertFalse(apiClient.isJsonMime("text/plain"));
assertFalse(apiClient.isJsonMime("application/xml"));
assertFalse(apiClient.isJsonMime("application/jsonp"));
assertFalse(apiClient.isJsonMime("example/json"));
assertFalse(apiClient.isJsonMime("example/foo+bar+jsonx"));
assertFalse(apiClient.isJsonMime("example/foo+bar+xjson"));
assertTrue(apiClient.isJsonMime("application/json"));
assertTrue(apiClient.isJsonMime("application/json; charset=UTF8"));
assertTrue(apiClient.isJsonMime("APPLICATION/JSON"));
assertTrue(apiClient.isJsonMime("application/problem+json"));
assertTrue(apiClient.isJsonMime("APPLICATION/PROBLEM+JSON"));
assertTrue(apiClient.isJsonMime("application/json\t"));
assertTrue(apiClient.isJsonMime("example/foo+bar+json"));
assertTrue(apiClient.isJsonMime("example/foo+json;x;y"));
assertTrue(apiClient.isJsonMime("example/foo+json\t;"));
assertTrue(apiClient.isJsonMime("Example/fOO+JSON"));
}
@Test
public void testSelectHeaderAccept() {
String[] accepts = {"application/json", "application/xml"};
assertEquals("application/json", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"};
assertEquals("APPLICATION/JSON", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"application/xml", "application/json; charset=UTF8"};
assertEquals("application/json; charset=UTF8", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"text/plain", "application/xml"};
assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{};
assertNull(apiClient.selectHeaderAccept(accepts));
}
@Test
public void testSelectHeaderContentType() {
String[] contentTypes = {"application/json", "application/xml"};
assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"};
assertEquals("APPLICATION/JSON", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"};
assertEquals("application/json; charset=UTF8", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"text/plain", "application/xml"};
assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{};
assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes));
}
@Test
public void testGetAuthentications() {
Map<String, Authentication> 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<Pair> pairs_a = apiClient.parameterToPairs("csv", null, new Integer(1));
List<Pair> pairs_b = apiClient.parameterToPairs("csv", "", new Integer(1));
assertTrue(pairs_a.isEmpty());
assertTrue(pairs_b.isEmpty());
}
@Test
public void testParameterToPairsWhenValueIsNull() throws Exception {
List<Pair> pairs = apiClient.parameterToPairs("csv", "param-a", null);
assertTrue(pairs.isEmpty());
}
@Test
public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception {
// single empty string
List<Pair> pairs = apiClient.parameterToPairs("csv", "param-a", " ");
assertEquals(1, pairs.size());
// list of empty strings
List<String> strs = new ArrayList<String>();
strs.add(" ");
strs.add(" ");
strs.add(" ");
List<Pair> 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<Pair> 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<String, String> collectionFormatMap = new HashMap<String, String>();
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<Object> values = new ArrayList<Object>();
values.add("value-a");
values.add(123);
values.add(new Date());
// check for multi separately
List<Pair> multiPairs = apiClient.parameterToPairs("multi", name, values);
assertEquals(values.size(), multiPairs.size());
// all other formats
for (String collectionFormat : collectionFormatMap.keySet()) {
List<Pair> 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);
}
}
}

View File

@ -0,0 +1,15 @@
package org.openapitools.client;
import org.junit.*;
import static org.junit.Assert.*;
public class ConfigurationTest {
@Test
public void testDefaultApiClient() {
ApiClient apiClient = Configuration.getDefaultApiClient();
assertNotNull(apiClient);
assertEquals("http://petstore.swagger.io:80/v2", apiClient.getBasePath());
assertFalse(apiClient.isDebugging());
}
}

View File

@ -0,0 +1,45 @@
package org.openapitools.client;
import org.openapitools.client.model.Order;
import java.lang.Exception;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import org.junit.*;
import static org.junit.Assert.*;
public class JSONTest {
JSON json = null;
Order order = null;
@Before
public void setup() {
json = new JSON();
order = new Order();
}
@Test
public void testDefaultDate() throws Exception {
final DateTimeFormatter dateFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
final String dateStr = "2015-11-07T14:11:05.267Z";
order.setShipDate(dateFormat.parse(dateStr, OffsetDateTime::from));
String str = json.getContext(null).writeValueAsString(order);
Order o = json.getContext(null).readValue(str, Order.class);
assertEquals(dateStr, dateFormat.format(o.getShipDate()));
}
@Test
public void testCustomDate() throws Exception {
final DateTimeFormatter dateFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.of("Etc/GMT+2"));
final String dateStr = "2015-11-07T14:11:05-02:00";
order.setShipDate(dateFormat.parse(dateStr, OffsetDateTime::from));
String str = json.getContext(null).writeValueAsString(order);
Order o = json.getContext(null).readValue(str, Order.class);
assertEquals(dateStr, dateFormat.format(o.getShipDate()));
}
}

View File

@ -0,0 +1,33 @@
package org.openapitools.client;
import org.junit.*;
import static org.junit.Assert.*;
public class StringUtilTest {
@Test
public void testContainsIgnoreCase() {
assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "abc"));
assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "ABC"));
assertTrue(StringUtil.containsIgnoreCase(new String[]{"ABC"}, "abc"));
assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, "ABC"));
assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, null));
assertFalse(StringUtil.containsIgnoreCase(new String[]{"abc"}, "def"));
assertFalse(StringUtil.containsIgnoreCase(new String[]{}, "ABC"));
assertFalse(StringUtil.containsIgnoreCase(new String[]{}, null));
}
@Test
public void testJoin() {
String[] array = {"aa", "bb", "cc"};
assertEquals("aa,bb,cc", StringUtil.join(array, ","));
assertEquals("aa, bb, cc", StringUtil.join(array, ", "));
assertEquals("aabbcc", StringUtil.join(array, ""));
assertEquals("aa bb cc", StringUtil.join(array, " "));
assertEquals("aa\nbb\ncc", StringUtil.join(array, "\n"));
assertEquals("", StringUtil.join(new String[]{}, ","));
assertEquals("abc", StringUtil.join(new String[]{"abc"}, ","));
}
}

View File

@ -0,0 +1,47 @@
package org.openapitools.client.auth;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import org.openapitools.client.Pair;
import org.junit.*;
import static org.junit.Assert.*;
public class ApiKeyAuthTest {
@Test
public void testApplyToParamsInQuery() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
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<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
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"));
}
}

View File

@ -0,0 +1,52 @@
package org.openapitools.client.auth;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import org.openapitools.client.Pair;
import org.junit.*;
import static org.junit.Assert.*;
public class HttpBasicAuthTest {
HttpBasicAuth auth = null;
@Before
public void setup() {
auth = new HttpBasicAuth();
}
@Test
public void testApplyToParams() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
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"));
}
}

View File

@ -0,0 +1,63 @@
package org.openapitools.client.model;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class EnumValueTest {
@Test
public void testEnumClass() {
assertEquals(EnumClass._ABC.toString(), "_abc");
assertEquals(EnumClass._EFG.toString(), "-efg");
assertEquals(EnumClass._XYZ_.toString(), "(xyz)");
}
@Test
public void testEnumTest() {
// test enum value
EnumTest enumTest = new EnumTest();
enumTest.setEnumString(EnumTest.EnumStringEnum.LOWER);
enumTest.setEnumInteger(EnumTest.EnumIntegerEnum.NUMBER_1);
enumTest.setEnumNumber(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1);
assertEquals(EnumTest.EnumStringEnum.UPPER.toString(), "UPPER");
assertEquals(EnumTest.EnumStringEnum.UPPER.getValue(), "UPPER");
assertEquals(EnumTest.EnumStringEnum.LOWER.toString(), "lower");
assertEquals(EnumTest.EnumStringEnum.LOWER.getValue(), "lower");
assertEquals(EnumTest.EnumIntegerEnum.NUMBER_1.toString(), "1");
assertTrue(EnumTest.EnumIntegerEnum.NUMBER_1.getValue() == 1);
assertEquals(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.toString(), "-1");
assertTrue(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.getValue() == -1);
assertEquals(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.toString(), "1.1");
assertTrue(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.getValue() == 1.1);
assertEquals(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.toString(), "-1.2");
assertTrue(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.getValue() == -1.2);
try {
// test serialization (object => json)
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
ObjectWriter ow = mapper.writer();
String json = ow.writeValueAsString(enumTest);
assertEquals(json, "{\"enum_string\":\"lower\",\"enum_string_required\":null,\"enum_integer\":1,\"enum_number\":1.1,\"outerEnum\":null}");
// test deserialization (json => object)
EnumTest fromString = mapper.readValue(json, EnumTest.class);
assertEquals(fromString.getEnumString().toString(), "lower");
assertEquals(fromString.getEnumInteger().toString(), "1");
assertEquals(fromString.getEnumNumber().toString(), "1.1");
} catch (Exception e) {
fail("Exception thrown during serialization/deserialzation of JSON: " + e.getMessage());
}
}
}

View File

@ -0,0 +1,250 @@
package org.openapitools.client;
import org.openapitools.client.auth.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import org.junit.*;
import static org.junit.Assert.*;
public class ApiClientTest {
ApiClient apiClient = null;
@Before
public void setup() {
apiClient = new ApiClient();
}
@Test
public void testParseAndFormatDate() {
// default date format
String dateStr = "2015-11-07T03:49:09.356Z";
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356+00:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356Z")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T05:49:09.356+02:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T02:49:09.356-01:00")));
// custom date format: without milli-seconds, custom time zone
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
format.setTimeZone(TimeZone.getTimeZone("GMT+10"));
apiClient.setDateFormat(format);
dateStr = "2015-11-07T13:49:09+10:00";
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09+00:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09Z")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T00:49:09-03:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T13:49:09+10:00")));
}
@Test
public void testIsJsonMime() {
assertFalse(apiClient.isJsonMime(null));
assertFalse(apiClient.isJsonMime(""));
assertFalse(apiClient.isJsonMime("text/plain"));
assertFalse(apiClient.isJsonMime("application/xml"));
assertFalse(apiClient.isJsonMime("application/jsonp"));
assertFalse(apiClient.isJsonMime("example/json"));
assertFalse(apiClient.isJsonMime("example/foo+bar+jsonx"));
assertFalse(apiClient.isJsonMime("example/foo+bar+xjson"));
assertTrue(apiClient.isJsonMime("application/json"));
assertTrue(apiClient.isJsonMime("application/json; charset=UTF8"));
assertTrue(apiClient.isJsonMime("APPLICATION/JSON"));
assertTrue(apiClient.isJsonMime("application/problem+json"));
assertTrue(apiClient.isJsonMime("APPLICATION/PROBLEM+JSON"));
assertTrue(apiClient.isJsonMime("application/json\t"));
assertTrue(apiClient.isJsonMime("example/foo+bar+json"));
assertTrue(apiClient.isJsonMime("example/foo+json;x;y"));
assertTrue(apiClient.isJsonMime("example/foo+json\t;"));
assertTrue(apiClient.isJsonMime("Example/fOO+JSON"));
}
@Test
public void testSelectHeaderAccept() {
String[] accepts = {"application/json", "application/xml"};
assertEquals("application/json", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"};
assertEquals("APPLICATION/JSON", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"application/xml", "application/json; charset=UTF8"};
assertEquals("application/json; charset=UTF8", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"text/plain", "application/xml"};
assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{};
assertNull(apiClient.selectHeaderAccept(accepts));
}
@Test
public void testSelectHeaderContentType() {
String[] contentTypes = {"application/json", "application/xml"};
assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"};
assertEquals("APPLICATION/JSON", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"};
assertEquals("application/json; charset=UTF8", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"text/plain", "application/xml"};
assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{};
assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes));
}
@Test
public void testGetAuthentications() {
Map<String, Authentication> 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<Pair> pairs_a = apiClient.parameterToPairs("csv", null, new Integer(1));
List<Pair> pairs_b = apiClient.parameterToPairs("csv", "", new Integer(1));
assertTrue(pairs_a.isEmpty());
assertTrue(pairs_b.isEmpty());
}
@Test
public void testParameterToPairsWhenValueIsNull() throws Exception {
List<Pair> pairs = apiClient.parameterToPairs("csv", "param-a", null);
assertTrue(pairs.isEmpty());
}
@Test
public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception {
// single empty string
List<Pair> pairs = apiClient.parameterToPairs("csv", "param-a", " ");
assertEquals(1, pairs.size());
// list of empty strings
List<String> strs = new ArrayList<String>();
strs.add(" ");
strs.add(" ");
strs.add(" ");
List<Pair> 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<Pair> 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<String, String> collectionFormatMap = new HashMap<String, String>();
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<Object> values = new ArrayList<Object>();
values.add("value-a");
values.add(123);
values.add(new Date());
// check for multi separately
List<Pair> multiPairs = apiClient.parameterToPairs("multi", name, values);
assertEquals(values.size(), multiPairs.size());
// all other formats
for (String collectionFormat : collectionFormatMap.keySet()) {
List<Pair> 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);
}
}
}

View File

@ -0,0 +1,15 @@
package org.openapitools.client;
import org.junit.*;
import static org.junit.Assert.*;
public class ConfigurationTest {
@Test
public void testDefaultApiClient() {
ApiClient apiClient = Configuration.getDefaultApiClient();
assertNotNull(apiClient);
assertEquals("http://petstore.swagger.io:80/v2", apiClient.getBasePath());
assertFalse(apiClient.isDebugging());
}
}

View File

@ -0,0 +1,58 @@
package org.openapitools.client;
import org.openapitools.client.model.Order;
import org.junit.Before;
import org.junit.Test;
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.ZoneId;
import org.threeten.bp.format.DateTimeFormatter;
import static org.junit.Assert.*;
public class JSONTest {
private JSON json = null;
private Order order = null;
@Before
public void setup() {
json = new ApiClient().getJSON();
order = new Order();
}
@Test
public void testDefaultDate() throws Exception {
final DateTimeFormatter dateFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
final String dateStr = "2015-11-07T14:11:05.267Z";
order.setShipDate(dateFormat.parse(dateStr, OffsetDateTime.FROM));
String str = json.getContext(null).writeValueAsString(order);
Order o = json.getContext(null).readValue(str, Order.class);
assertEquals(dateStr, dateFormat.format(o.getShipDate()));
}
@Test
public void testCustomDate() throws Exception {
final DateTimeFormatter dateFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.of("Etc/GMT+2"));
final String dateStr = "2015-11-07T14:11:05-02:00";
order.setShipDate(dateFormat.parse(dateStr, OffsetDateTime.FROM));
String str = json.getContext(null).writeValueAsString(order);
Order o = json.getContext(null).readValue(str, Order.class);
assertEquals(dateStr, dateFormat.format(o.getShipDate()));
}
@Test
public void testSqlDateSerialization() throws Exception {
String str = json.getContext(null).writeValueAsString(new java.sql.Date(10));
assertEquals("\"1970-01-01\"", str);
}
@Test
public void testSqlDateDeserialization() throws Exception {
final String str = "1970-01-01";
java.sql.Date date = json.getContext(null).readValue("\"" + str + "\"", java.sql.Date.class);
assertEquals(date.toString(), str);
}
}

View File

@ -0,0 +1,33 @@
package org.openapitools.client;
import org.junit.*;
import static org.junit.Assert.*;
public class StringUtilTest {
@Test
public void testContainsIgnoreCase() {
assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "abc"));
assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "ABC"));
assertTrue(StringUtil.containsIgnoreCase(new String[]{"ABC"}, "abc"));
assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, "ABC"));
assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, null));
assertFalse(StringUtil.containsIgnoreCase(new String[]{"abc"}, "def"));
assertFalse(StringUtil.containsIgnoreCase(new String[]{}, "ABC"));
assertFalse(StringUtil.containsIgnoreCase(new String[]{}, null));
}
@Test
public void testJoin() {
String[] array = {"aa", "bb", "cc"};
assertEquals("aa,bb,cc", StringUtil.join(array, ","));
assertEquals("aa, bb, cc", StringUtil.join(array, ", "));
assertEquals("aabbcc", StringUtil.join(array, ""));
assertEquals("aa bb cc", StringUtil.join(array, " "));
assertEquals("aa\nbb\ncc", StringUtil.join(array, "\n"));
assertEquals("", StringUtil.join(new String[]{}, ","));
assertEquals("abc", StringUtil.join(new String[]{"abc"}, ","));
}
}

View File

@ -0,0 +1,47 @@
package org.openapitools.client.auth;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import org.openapitools.client.Pair;
import org.junit.*;
import static org.junit.Assert.*;
public class ApiKeyAuthTest {
@Test
public void testApplyToParamsInQuery() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
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<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
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"));
}
}

View File

@ -0,0 +1,52 @@
package org.openapitools.client.auth;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import org.openapitools.client.Pair;
import org.junit.*;
import static org.junit.Assert.*;
public class HttpBasicAuthTest {
HttpBasicAuth auth = null;
@Before
public void setup() {
auth = new HttpBasicAuth();
}
@Test
public void testApplyToParams() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
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"));
}
}

View File

@ -0,0 +1,63 @@
package org.openapitools.client.model;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class EnumValueTest {
@Test
public void testEnumClass() {
assertEquals(EnumClass._ABC.toString(), "_abc");
assertEquals(EnumClass._EFG.toString(), "-efg");
assertEquals(EnumClass._XYZ_.toString(), "(xyz)");
}
@Test
public void testEnumTest() {
// test enum value
EnumTest enumTest = new EnumTest();
enumTest.setEnumString(EnumTest.EnumStringEnum.LOWER);
enumTest.setEnumInteger(EnumTest.EnumIntegerEnum.NUMBER_1);
enumTest.setEnumNumber(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1);
assertEquals(EnumTest.EnumStringEnum.UPPER.toString(), "UPPER");
assertEquals(EnumTest.EnumStringEnum.UPPER.getValue(), "UPPER");
assertEquals(EnumTest.EnumStringEnum.LOWER.toString(), "lower");
assertEquals(EnumTest.EnumStringEnum.LOWER.getValue(), "lower");
assertEquals(EnumTest.EnumIntegerEnum.NUMBER_1.toString(), "1");
assertTrue(EnumTest.EnumIntegerEnum.NUMBER_1.getValue() == 1);
assertEquals(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.toString(), "-1");
assertTrue(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.getValue() == -1);
assertEquals(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.toString(), "1.1");
assertTrue(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.getValue() == 1.1);
assertEquals(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.toString(), "-1.2");
assertTrue(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.getValue() == -1.2);
try {
// test serialization (object => json)
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
ObjectWriter ow = mapper.writer();
String json = ow.writeValueAsString(enumTest);
assertEquals(json, "{\"enum_string\":\"lower\",\"enum_string_required\":null,\"enum_integer\":1,\"enum_number\":1.1,\"outerEnum\":null}");
// test deserialization (json => object)
EnumTest fromString = mapper.readValue(json, EnumTest.class);
assertEquals(fromString.getEnumString().toString(), "lower");
assertEquals(fromString.getEnumInteger().toString(), "1");
assertEquals(fromString.getEnumNumber().toString(), "1.1");
} catch (Exception e) {
fail("Exception thrown during serialization/deserialzation of JSON: " + e.getMessage());
}
}
}

View File

@ -0,0 +1,330 @@
package org.openapitools.client;
import org.openapitools.client.auth.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.TimeZone;
import org.junit.*;
import static org.junit.Assert.*;
public class ApiClientTest {
ApiClient apiClient;
JSON json;
@Before
public void setup() {
apiClient = new ApiClient();
json = apiClient.getJSON();
}
@Test
public void testIsJsonMime() {
assertFalse(apiClient.isJsonMime(null));
assertFalse(apiClient.isJsonMime(""));
assertFalse(apiClient.isJsonMime("text/plain"));
assertFalse(apiClient.isJsonMime("application/xml"));
assertFalse(apiClient.isJsonMime("application/jsonp"));
assertFalse(apiClient.isJsonMime("example/json"));
assertFalse(apiClient.isJsonMime("example/foo+bar+jsonx"));
assertFalse(apiClient.isJsonMime("example/foo+bar+xjson"));
assertTrue(apiClient.isJsonMime("application/json"));
assertTrue(apiClient.isJsonMime("application/json; charset=UTF8"));
assertTrue(apiClient.isJsonMime("APPLICATION/JSON"));
assertTrue(apiClient.isJsonMime("application/problem+json"));
assertTrue(apiClient.isJsonMime("APPLICATION/PROBLEM+JSON"));
assertTrue(apiClient.isJsonMime("application/json\t"));
assertTrue(apiClient.isJsonMime("example/foo+bar+json"));
assertTrue(apiClient.isJsonMime("example/foo+json;x;y"));
assertTrue(apiClient.isJsonMime("example/foo+json\t;"));
assertTrue(apiClient.isJsonMime("Example/fOO+JSON"));
assertTrue(apiClient.isJsonMime("application/json-patch+json"));
}
@Test
public void testSelectHeaderAccept() {
String[] accepts = {"application/json", "application/xml"};
assertEquals("application/json", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"};
assertEquals("APPLICATION/JSON", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"application/xml", "application/json; charset=UTF8"};
assertEquals("application/json; charset=UTF8", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"text/plain", "application/xml"};
assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{};
assertNull(apiClient.selectHeaderAccept(accepts));
}
@Test
public void testSelectHeaderContentType() {
String[] contentTypes = {"application/json", "application/xml"};
assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"};
assertEquals("APPLICATION/JSON", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"};
assertEquals("application/json; charset=UTF8", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"text/plain", "application/xml"};
assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{};
assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes));
}
@Test
public void testGetAuthentications() {
Map<String, Authentication> 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<Pair> pairs_a = apiClient.parameterToPair(null, new Integer(1));
List<Pair> pairs_b = apiClient.parameterToPair("", new Integer(1));
assertTrue(pairs_a.isEmpty());
assertTrue(pairs_b.isEmpty());
}
@Test
public void testParameterToPairWhenValueIsNull() throws Exception {
List<Pair> pairs = apiClient.parameterToPair("param-a", null);
assertTrue(pairs.isEmpty());
}
@Test
public void testParameterToPairWhenValueIsEmptyString() throws Exception {
// single empty string
List<Pair> pairs = apiClient.parameterToPair("param-a", " ");
assertEquals(1, pairs.size());
}
@Test
public void testParameterToPairWhenValueIsNotCollection() throws Exception {
String name = "param-a";
Integer value = 1;
List<Pair> pairs = apiClient.parameterToPair(name, value);
assertEquals(1, pairs.size());
assertEquals(value, Integer.valueOf(pairs.get(0).getValue()));
}
@Test
public void testParameterToPairWhenValueIsCollection() throws Exception {
List<Object> values = new ArrayList<Object>();
values.add("value-a");
values.add(123);
values.add(new Date());
List<Pair> pairs = apiClient.parameterToPair("param-a", values);
assertEquals(0, pairs.size());
}
@Test
public void testParameterToPairsWhenNameIsInvalid() throws Exception {
List<Integer> objects = new ArrayList<Integer>();
objects.add(new Integer(1));
List<Pair> pairs_a = apiClient.parameterToPairs("csv", null, objects);
List<Pair> pairs_b = apiClient.parameterToPairs("csv", "", objects);
assertTrue(pairs_a.isEmpty());
assertTrue(pairs_b.isEmpty());
}
@Test
public void testParameterToPairsWhenValueIsNull() throws Exception {
List<Pair> pairs = apiClient.parameterToPairs("csv", "param-a", null);
assertTrue(pairs.isEmpty());
}
@Test
public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception {
// list of empty strings
List<String> strs = new ArrayList<String>();
strs.add(" ");
strs.add(" ");
strs.add(" ");
List<Pair> 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<String, String> collectionFormatMap = new HashMap<String, String>();
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<Object> values = new ArrayList<Object>();
values.add("value-a");
values.add(123);
values.add(new Date());
// check for multi separately
List<Pair> 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<Pair> 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"));
}
}

View File

@ -0,0 +1,15 @@
package org.openapitools.client;
import org.junit.*;
import static org.junit.Assert.*;
public class ConfigurationTest {
@Test
public void testDefaultApiClient() {
ApiClient apiClient = Configuration.getDefaultApiClient();
assertNotNull(apiClient);
assertEquals("http://petstore.swagger.io:80/v2", apiClient.getBasePath());
assertFalse(apiClient.isDebugging());
}
}

View File

@ -0,0 +1,201 @@
package org.openapitools.client;
import com.google.gson.reflect.TypeToken;
import org.openapitools.client.model.Order;
import java.lang.Exception;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import okio.ByteString;
import org.junit.*;
import org.threeten.bp.LocalDate;
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.ZoneId;
import org.threeten.bp.ZoneOffset;
import org.threeten.bp.format.DateTimeFormatter;
import static org.junit.Assert.*;
public class JSONTest {
private ApiClient apiClient = null;
private JSON json = null;
private Order order = null;
@Before
public void setup() {
apiClient = new ApiClient();
json = apiClient.getJSON();
order = new Order();
}
@Test
public void testSqlDateTypeAdapter() {
final String str = "\"2015-11-07\"";
final java.sql.Date date = java.sql.Date.valueOf("2015-11-07");
assertEquals(str, json.serialize(date));
assertEquals(json.deserialize(str, java.sql.Date.class), date);
assertEquals(json.deserialize("\"2015-11-07T03:49:09.356" + getCurrentTimezoneOffset() + "\"", java.sql.Date.class).toString(), date.toString());
// custom date format: without day
DateFormat format = new SimpleDateFormat("yyyy-MM");
apiClient.setSqlDateFormat(format);
String dateStr = "\"2015-11\"";
assertEquals(dateStr, json.serialize(json.deserialize("\"2015-11-07T03:49:09Z\"", java.sql.Date.class)));
assertEquals(dateStr, json.serialize(json.deserialize("\"2015-11\"", java.sql.Date.class)));
}
@Test
public void testDateTypeAdapter() {
Calendar cal = new GregorianCalendar(2015, 10, 7, 3, 49, 9);
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
assertEquals(json.deserialize("\"2015-11-07T05:49:09+02\"", Date.class), cal.getTime());
cal.set(Calendar.MILLISECOND, 300);
assertEquals(json.deserialize("\"2015-11-07T03:49:09.3Z\"", Date.class), cal.getTime());
cal.set(Calendar.MILLISECOND, 356);
Date date = cal.getTime();
final String utcDate = "\"2015-11-07T03:49:09.356Z\"";
assertEquals(json.deserialize(utcDate, Date.class), date);
assertEquals(json.deserialize("\"2015-11-07T03:49:09.356+00:00\"", Date.class), date);
assertEquals(json.deserialize("\"2015-11-07T05:49:09.356+02:00\"", Date.class), date);
assertEquals(json.deserialize("\"2015-11-07T02:49:09.356-01:00\"", Date.class), date);
assertEquals(json.deserialize("\"2015-11-07T03:49:09.356Z\"", Date.class), date);
assertEquals(json.deserialize("\"2015-11-07T03:49:09.356+00\"", Date.class), date);
assertEquals(json.deserialize("\"2015-11-07T02:49:09.356-0100\"", Date.class), date);
assertEquals(json.deserialize("\"2015-11-07T03:49:09.356456789Z\"", Date.class), date);
assertEquals(utcDate, json.serialize(date));
// custom datetime format: without milli-seconds, custom time zone
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
format.setTimeZone(TimeZone.getTimeZone("GMT+10"));
apiClient.setDateFormat(format);
String dateStr = "\"2015-11-07T13:49:09+10:00\"";
assertEquals(dateStr, json.serialize(json.deserialize("\"2015-11-07T03:49:09+00:00\"", Date.class)));
assertEquals(dateStr, json.serialize(json.deserialize("\"2015-11-07T03:49:09Z\"", Date.class)));
assertEquals(dateStr, json.serialize(json.deserialize("\"2015-11-07T00:49:09-03:00\"", Date.class)));
try {
// invalid time zone format
json.deserialize("\"2015-11-07T03:49:09+00\"", Date.class);
fail("json parsing should fail");
} catch (RuntimeException e) {
// OK
}
try {
// unexpected miliseconds
json.deserialize("\"2015-11-07T03:49:09.000Z\"", Date.class);
fail("json parsing should fail");
} catch (RuntimeException e) {
// OK
}
}
@Test
public void testOffsetDateTimeTypeAdapter() {
final String str = "\"2016-09-09T08:02:03.123-03:00\"";
OffsetDateTime date = OffsetDateTime.of(2016, 9, 9, 8, 2, 3, 123000000, ZoneOffset.of("-3"));
assertEquals(str, json.serialize(date));
//Use toString() instead of isEqual to verify that the offset is preserved
assertEquals(json.deserialize(str, OffsetDateTime.class).toString(), date.toString());
}
@Test
public void testLocalDateTypeAdapter() {
final String str = "\"2016-09-09\"";
final LocalDate date = LocalDate.of(2016, 9, 9);
assertEquals(str, json.serialize(date));
assertEquals(json.deserialize(str, LocalDate.class), date);
}
@Test
public void testDefaultDate() throws Exception {
final DateTimeFormatter datetimeFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
final String dateStr = "2015-11-07T14:11:05.267Z";
order.setShipDate(datetimeFormat.parse(dateStr, OffsetDateTime.FROM));
String str = json.serialize(order);
Type type = new TypeToken<Order>() { }.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<Order>() { }.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<byte[]>() { }.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;
}
}

View File

@ -0,0 +1,33 @@
package org.openapitools.client;
import org.junit.*;
import static org.junit.Assert.*;
public class StringUtilTest {
@Test
public void testContainsIgnoreCase() {
assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "abc"));
assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "ABC"));
assertTrue(StringUtil.containsIgnoreCase(new String[]{"ABC"}, "abc"));
assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, "ABC"));
assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, null));
assertFalse(StringUtil.containsIgnoreCase(new String[]{"abc"}, "def"));
assertFalse(StringUtil.containsIgnoreCase(new String[]{}, "ABC"));
assertFalse(StringUtil.containsIgnoreCase(new String[]{}, null));
}
@Test
public void testJoin() {
String[] array = {"aa", "bb", "cc"};
assertEquals("aa,bb,cc", StringUtil.join(array, ","));
assertEquals("aa, bb, cc", StringUtil.join(array, ", "));
assertEquals("aabbcc", StringUtil.join(array, ""));
assertEquals("aa bb cc", StringUtil.join(array, " "));
assertEquals("aa\nbb\ncc", StringUtil.join(array, "\n"));
assertEquals("", StringUtil.join(new String[]{}, ","));
assertEquals("abc", StringUtil.join(new String[]{"abc"}, ","));
}
}

View File

@ -0,0 +1,76 @@
package org.openapitools.client.auth;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import org.openapitools.client.Pair;
import org.junit.*;
import static org.junit.Assert.*;
public class ApiKeyAuthTest {
@Test
public void testApplyToParamsInQuery() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
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<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
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<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
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<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
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());
}
}

View File

@ -0,0 +1,62 @@
package org.openapitools.client.auth;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import org.openapitools.client.Pair;
import org.junit.*;
import static org.junit.Assert.*;
public class HttpBasicAuthTest {
HttpBasicAuth auth = null;
@Before
public void setup() {
auth = new HttpBasicAuth();
}
@Test
public void testApplyToParams() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
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<Pair>();
headerParams = new HashMap<String, String>();
auth.setUsername(null);
auth.setPassword(null);
auth.applyToParams(queryParams, headerParams);
// no changes to parameters
assertEquals(0, queryParams.size());
assertEquals(0, headerParams.size());
}
}

View File

@ -0,0 +1,56 @@
package org.openapitools.client.model;
import org.junit.Test;
import com.google.gson.Gson;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class EnumValueTest {
@Test
public void testEnumClass() {
assertEquals(EnumClass._ABC.toString(), "_abc");
assertEquals(EnumClass._EFG.toString(), "-efg");
assertEquals(EnumClass._XYZ_.toString(), "(xyz)");
}
@Test
public void testEnumTest() {
// test enum value
EnumTest enumTest = new EnumTest();
enumTest.setEnumString(EnumTest.EnumStringEnum.LOWER);
enumTest.setEnumInteger(EnumTest.EnumIntegerEnum.NUMBER_1);
enumTest.setEnumNumber(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1);
assertEquals(EnumTest.EnumStringEnum.UPPER.toString(), "UPPER");
assertEquals(EnumTest.EnumStringEnum.UPPER.getValue(), "UPPER");
assertEquals(EnumTest.EnumStringEnum.LOWER.toString(), "lower");
assertEquals(EnumTest.EnumStringEnum.LOWER.getValue(), "lower");
assertEquals(EnumTest.EnumIntegerEnum.NUMBER_1.toString(), "1");
assertTrue(EnumTest.EnumIntegerEnum.NUMBER_1.getValue() == 1);
assertEquals(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.toString(), "-1");
assertTrue(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.getValue() == -1);
assertEquals(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.toString(), "1.1");
assertTrue(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.getValue() == 1.1);
assertEquals(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.toString(), "-1.2");
assertTrue(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.getValue() == -1.2);
// test serialization
Gson gson = new Gson();
String json = gson.toJson(enumTest);
assertEquals(json, "{\"enum_string\":\"lower\",\"enum_integer\":1,\"enum_number\":1.1}");
// test deserialization
EnumTest fromString = gson.fromJson(json, EnumTest.class);
assertEquals(fromString.getEnumString().toString(), "lower");
assertEquals(fromString.getEnumString().getValue(), "lower");
assertEquals(fromString.getEnumInteger().toString(), "1");
assertTrue(fromString.getEnumInteger().getValue() == 1);
assertEquals(fromString.getEnumNumber().toString(), "1.1");
assertTrue(fromString.getEnumNumber().getValue() == 1.1);
}
}

View File

@ -0,0 +1,254 @@
package org.openapitools.client;
import org.openapitools.client.auth.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import org.junit.*;
import org.springframework.http.MediaType;
import org.springframework.util.MultiValueMap;
import static org.junit.Assert.*;
public class ApiClientTest {
ApiClient apiClient = null;
@Before
public void setup() {
apiClient = new ApiClient();
}
/**
*
*/
@Test
public void testParseAndFormatDate() {
// default date format
String dateStr = "2015-11-07T03:49:09.356Z";
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356+00:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356Z")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T05:49:09.356+02:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T02:49:09.356-01:00")));
// custom date format: without milli-seconds, custom time zone
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
format.setTimeZone(TimeZone.getTimeZone("GMT+10"));
apiClient.setDateFormat(format);
dateStr = "2015-11-07T13:49:09+10:00";
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09+00:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09Z")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T00:49:09-03:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T13:49:09+10:00")));
}
@Test
public void testIsJsonMime() {
assertFalse(apiClient.isJsonMime((String) null));
assertFalse(apiClient.isJsonMime(""));
assertFalse(apiClient.isJsonMime("text/plain"));
assertFalse(apiClient.isJsonMime("application/xml"));
assertFalse(apiClient.isJsonMime("application/jsonp"));
assertFalse(apiClient.isJsonMime("example/json"));
assertFalse(apiClient.isJsonMime("example/foo+bar+jsonx"));
assertFalse(apiClient.isJsonMime("example/foo+bar+xjson"));
assertTrue(apiClient.isJsonMime("application/json"));
assertTrue(apiClient.isJsonMime("application/json; charset=UTF8"));
assertTrue(apiClient.isJsonMime("APPLICATION/JSON"));
assertTrue(apiClient.isJsonMime("application/problem+json"));
assertTrue(apiClient.isJsonMime("APPLICATION/PROBLEM+JSON"));
assertTrue(apiClient.isJsonMime("application/json\t"));
assertTrue(apiClient.isJsonMime("example/foo+bar+json"));
assertTrue(apiClient.isJsonMime("example/foo+json;x;y"));
assertTrue(apiClient.isJsonMime("example/foo+json\t;"));
assertTrue(apiClient.isJsonMime("Example/fOO+JSON"));
}
@Test
public void testSelectHeaderAccept() {
String[] accepts = {"application/json", "application/xml"};
assertEquals(Arrays.asList(MediaType.parseMediaType("application/json")), apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"};
assertEquals(Arrays.asList(MediaType.parseMediaType("APPLICATION/JSON")), apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"application/xml", "application/json; charset=UTF8"};
assertEquals(Arrays.asList(MediaType.parseMediaType("application/json; charset=UTF8")), apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"text/plain", "application/xml"};
assertEquals(Arrays.asList(MediaType.parseMediaType("text/plain"),MediaType.parseMediaType("application/xml")), apiClient.selectHeaderAccept(accepts));
accepts = new String[]{};
assertNull(apiClient.selectHeaderAccept(accepts));
}
@Test
public void testSelectHeaderContentType() {
String[] contentTypes = {"application/json", "application/xml"};
assertEquals(MediaType.parseMediaType("application/json"), apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"};
assertEquals(MediaType.parseMediaType("APPLICATION/JSON"), apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"};
assertEquals(MediaType.parseMediaType("application/json; charset=UTF8"), apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"text/plain", "application/xml"};
assertEquals(MediaType.parseMediaType("text/plain"), apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{};
assertEquals(MediaType.parseMediaType("application/json"), apiClient.selectHeaderContentType(contentTypes));
}
@Test
public void testGetAuthentications() {
Map<String, Authentication> 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<String, String> pairs_a = apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.CSV, null, new Integer(1));
MultiValueMap<String, String> 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<String, String> pairs = apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.CSV, "param-a", null);
assertTrue(pairs.isEmpty());
}
@Test
public void testParameterToMultiValueMapWhenValueIsEmptyStrings() throws Exception {
// single empty string
MultiValueMap<String, String> pairs = apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.CSV, "param-a", " ");
assertEquals(1, pairs.size());
// list of empty strings
List<String> strs = new ArrayList<String>();
strs.add(" ");
strs.add(" ");
strs.add(" ");
MultiValueMap<String, String> 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<String, String> 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<ApiClient.CollectionFormat, String> collectionFormatMap = new HashMap<ApiClient.CollectionFormat, String>();
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<Object> values = new ArrayList<Object>();
values.add("value-a");
values.add(123);
values.add(new Date());
// check for multi separately
MultiValueMap<String, String> 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<String, String> 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);
}
}
}

View File

@ -0,0 +1,47 @@
package org.openapitools.client.auth;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import org.junit.*;
import org.springframework.http.HttpHeaders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import static org.junit.Assert.*;
public class ApiKeyAuthTest {
@Test
public void testApplyToParamsInQuery() {
MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
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<String, String> queryParams = new LinkedMultiValueMap<String, String>();
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));
}
}

View File

@ -0,0 +1,54 @@
package org.openapitools.client.auth;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import org.junit.*;
import org.springframework.http.HttpHeaders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import static org.junit.Assert.*;
public class HttpBasicAuthTest {
HttpBasicAuth auth = null;
@Before
public void setup() {
auth = new HttpBasicAuth();
}
@Test
public void testApplyToParams() {
MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
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));
}
}

View File

@ -0,0 +1,63 @@
package org.openapitools.client.model;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class EnumValueTest {
@Test
public void testEnumClass() {
assertEquals(EnumClass._ABC.toString(), "_abc");
assertEquals(EnumClass._EFG.toString(), "-efg");
assertEquals(EnumClass._XYZ_.toString(), "(xyz)");
}
@Test
public void testEnumTest() {
// test enum value
EnumTest enumTest = new EnumTest();
enumTest.setEnumString(EnumTest.EnumStringEnum.LOWER);
enumTest.setEnumInteger(EnumTest.EnumIntegerEnum.NUMBER_1);
enumTest.setEnumNumber(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1);
assertEquals(EnumTest.EnumStringEnum.UPPER.toString(), "UPPER");
assertEquals(EnumTest.EnumStringEnum.UPPER.getValue(), "UPPER");
assertEquals(EnumTest.EnumStringEnum.LOWER.toString(), "lower");
assertEquals(EnumTest.EnumStringEnum.LOWER.getValue(), "lower");
assertEquals(EnumTest.EnumIntegerEnum.NUMBER_1.toString(), "1");
assertTrue(EnumTest.EnumIntegerEnum.NUMBER_1.getValue() == 1);
assertEquals(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.toString(), "-1");
assertTrue(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.getValue() == -1);
assertEquals(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.toString(), "1.1");
assertTrue(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.getValue() == 1.1);
assertEquals(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.toString(), "-1.2");
assertTrue(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.getValue() == -1.2);
try {
// test serialization (object => json)
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
ObjectWriter ow = mapper.writer();
String json = ow.writeValueAsString(enumTest);
assertEquals(json, "{\"enum_string\":\"lower\",\"enum_string_required\":null,\"enum_integer\":1,\"enum_number\":1.1,\"outerEnum\":null}");
// test deserialization (json => object)
EnumTest fromString = mapper.readValue(json, EnumTest.class);
assertEquals(fromString.getEnumString().toString(), "lower");
assertEquals(fromString.getEnumInteger().toString(), "1");
assertEquals(fromString.getEnumNumber().toString(), "1.1");
} catch (Exception e) {
fail("Exception thrown during serialization/deserialzation of JSON: " + e.getMessage());
}
}
}