add joda support to okhttp-gson and use it in the samples

This commit is contained in:
cbornet 2016-06-09 18:09:02 +02:00
parent bd705a49d6
commit 61884211bb
28 changed files with 714 additions and 997 deletions

View File

@ -26,6 +26,8 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-okhttp-gson.json -o samples/client/petstore/java/okhttp-gson -DhideGenerationTimestamp=true"
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-okhttp-gson.json -o samples/client/petstore/java/okhttp-gson -DdateLibrary=joda,hideGenerationTimestamp=true"
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

View File

@ -5,6 +5,6 @@ If Not Exist %executable% (
)
set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -t modules\swagger-codegen\src\main\resources\java -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l java -o samples\client\petstore\java --library=okhttp-gson -DhideGenerationTimestamp=true
set ags=generate -t modules\swagger-codegen\src\main\resources\java -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l java -o samples\client\petstore\java --library=okhttp-gson -DdateLibrary=joda,hideGenerationTimestamp=true
java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -12,12 +12,20 @@ import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Type;
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
public class JSON {
private ApiClient apiClient;
private Gson gson;
@ -31,6 +39,8 @@ public class JSON {
this.apiClient = apiClient;
gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateAdapter(apiClient))
.registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter())
.registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter())
.create();
}
@ -143,3 +153,62 @@ class DateAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
}
}
}
/**
* Gson TypeAdapter for Joda DateTime type
*/
class DateTimeTypeAdapter extends TypeAdapter<DateTime> {
private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
@Override
public void write(JsonWriter out, DateTime date) throws IOException {
if (date == null) {
out.nullValue();
} else {
out.value(formatter.print(date));
}
}
@Override
public DateTime read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
return formatter.parseDateTime(date);
}
}
}
/**
* Gson TypeAdapter for Joda LocalDate type
*/
class LocalDateTypeAdapter extends TypeAdapter<LocalDate> {
private final DateTimeFormatter formatter = ISODateTimeFormat.date();
@Override
public void write(JsonWriter out, LocalDate date) throws IOException {
if (date == null) {
out.nullValue();
} else {
out.value(formatter.print(date));
}
}
@Override
public LocalDate read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
return formatter.parseLocalDate(date);
}
}
}

View File

@ -98,5 +98,6 @@ dependencies {
compile 'com.squareup.okhttp:okhttp:2.7.5'
compile 'com.squareup.okhttp:logging-interceptor:2.7.5'
compile 'com.google.code.gson:gson:2.6.2'
compile 'joda-time:joda-time:2.9.3'
testCompile 'junit:junit:4.12'
}

View File

@ -13,6 +13,7 @@ lazy val root = (project in file(".")).
"com.squareup.okhttp" % "okhttp" % "2.7.5",
"com.squareup.okhttp" % "logging-interceptor" % "2.7.5",
"com.google.code.gson" % "gson" % "2.6.2",
"joda-time" % "joda-time" % "2.9.3" % "compile",
"junit" % "junit" % "4.12" % "test",
"com.novocode" % "junit-interface" % "0.10" % "test"
)

View File

@ -128,6 +128,11 @@
<artifactId>gson</artifactId>
<version>${gson-version}</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${jodatime-version}</version>
</dependency>
<!-- test dependencies -->
<dependency>
@ -141,6 +146,7 @@
<swagger-core-version>1.5.9</swagger-core-version>
<okhttp-version>2.7.5</okhttp-version>
<gson-version>2.6.2</gson-version>
<jodatime-version>2.9.3</jodatime-version>
<maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.12</junit-version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

View File

@ -98,5 +98,6 @@ dependencies {
compile 'com.squareup.okhttp:okhttp:2.7.5'
compile 'com.squareup.okhttp:logging-interceptor:2.7.5'
compile 'com.google.code.gson:gson:2.6.2'
compile 'joda-time:joda-time:2.9.3'
testCompile 'junit:junit:4.12'
}

View File

@ -13,6 +13,7 @@ lazy val root = (project in file(".")).
"com.squareup.okhttp" % "okhttp" % "2.7.5",
"com.squareup.okhttp" % "logging-interceptor" % "2.7.5",
"com.google.code.gson" % "gson" % "2.6.2",
"joda-time" % "joda-time" % "2.9.3" % "compile",
"junit" % "junit" % "4.12" % "test",
"com.novocode" % "junit-interface" % "0.10" % "test"
)

View File

@ -32,8 +32,8 @@ Integer int32 = 56; // Integer | None
Long int64 = 789L; // Long | None
Float _float = 3.4F; // Float | None
byte[] binary = B; // byte[] | None
Date date = new Date(); // Date | None
Date dateTime = new Date(); // Date | None
LocalDate date = new LocalDate(); // LocalDate | None
DateTime dateTime = new DateTime(); // DateTime | None
String password = "password_example"; // String | None
try {
apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password);
@ -56,8 +56,8 @@ Name | Type | Description | Notes
**int64** | **Long**| None | [optional]
**_float** | **Float**| None | [optional]
**binary** | **byte[]**| None | [optional]
**date** | **Date**| None | [optional]
**dateTime** | **Date**| None | [optional]
**date** | **LocalDate**| None | [optional]
**dateTime** | **DateTime**| None | [optional]
**password** | **String**| None | [optional]
### Return type

View File

@ -13,8 +13,8 @@ Name | Type | Description | Notes
**string** | **String** | | [optional]
**_byte** | **byte[]** | |
**binary** | **byte[]** | | [optional]
**date** | [**Date**](Date.md) | |
**dateTime** | [**Date**](Date.md) | | [optional]
**date** | [**LocalDate**](LocalDate.md) | |
**dateTime** | [**DateTime**](DateTime.md) | | [optional]
**uuid** | **String** | | [optional]
**password** | **String** | |

View File

@ -5,7 +5,7 @@
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**uuid** | **String** | | [optional]
**dateTime** | [**Date**](Date.md) | | [optional]
**dateTime** | [**DateTime**](DateTime.md) | | [optional]
**map** | [**Map&lt;String, Animal&gt;**](Animal.md) | | [optional]

View File

@ -7,7 +7,7 @@ Name | Type | Description | Notes
**id** | **Long** | | [optional]
**petId** | **Long** | | [optional]
**quantity** | **Integer** | | [optional]
**shipDate** | [**Date**](Date.md) | | [optional]
**shipDate** | [**DateTime**](DateTime.md) | | [optional]
**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional]
**complete** | **Boolean** | | [optional]

0
samples/client/petstore/java/okhttp-gson/gradlew vendored Executable file → Normal file
View File

View File

@ -105,53 +105,6 @@
<target>1.7</target>
</configuration>
</plugin>
<!-- For testing build.gradle, build.sbt, mvn javadoc:javadoc -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<id>gradle-test</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>gradle</executable>
<arguments>
<argument>check</argument>
</arguments>
</configuration>
</execution>
<execution>
<id>sbt-test</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>sbt</executable>
<arguments>
<argument>publishLocal</argument>
</arguments>
</configuration>
</execution>
<execution>
<id>mvn-javadoc-test</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>mvn</executable>
<arguments>
<argument>javadoc:javadoc</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
@ -175,6 +128,11 @@
<artifactId>gson</artifactId>
<version>${gson-version}</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${jodatime-version}</version>
</dependency>
<!-- test dependencies -->
<dependency>
@ -188,6 +146,7 @@
<swagger-core-version>1.5.9</swagger-core-version>
<okhttp-version>2.7.5</okhttp-version>
<gson-version>2.6.2</gson-version>
<jodatime-version>2.9.3</jodatime-version>
<maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.12</junit-version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

View File

@ -173,8 +173,8 @@ public class ApiClient {
// Setup authentications (key: authentication name, value: authentication).
authentications = new HashMap<String, Authentication>();
authentications.put("api_key", new ApiKeyAuth("header", "api_key"));
authentications.put("petstore_auth", new OAuth());
authentications.put("api_key", new ApiKeyAuth("header", "api_key"));
// Prevent the authentications from being modified.
authentications = Collections.unmodifiableMap(authentications);
}

View File

@ -35,12 +35,20 @@ import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Type;
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
public class JSON {
private ApiClient apiClient;
private Gson gson;
@ -54,6 +62,8 @@ public class JSON {
this.apiClient = apiClient;
gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateAdapter(apiClient))
.registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter())
.registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter())
.create();
}
@ -166,3 +176,62 @@ class DateAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
}
}
}
/**
* Gson TypeAdapter for Joda DateTime type
*/
class DateTimeTypeAdapter extends TypeAdapter<DateTime> {
private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
@Override
public void write(JsonWriter out, DateTime date) throws IOException {
if (date == null) {
out.nullValue();
} else {
out.value(formatter.print(date));
}
}
@Override
public DateTime read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
return formatter.parseDateTime(date);
}
}
}
/**
* Gson TypeAdapter for Joda LocalDate type
*/
class LocalDateTypeAdapter extends TypeAdapter<LocalDate> {
private final DateTimeFormatter formatter = ISODateTimeFormat.date();
@Override
public void write(JsonWriter out, LocalDate date) throws IOException {
if (date == null) {
out.nullValue();
} else {
out.value(formatter.print(date));
}
}
@Override
public LocalDate read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
return formatter.parseLocalDate(date);
}
}
}

View File

@ -38,8 +38,9 @@ import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.util.Date;
import org.joda.time.LocalDate;
import java.math.BigDecimal;
import org.joda.time.DateTime;
import java.lang.reflect.Type;
import java.util.ArrayList;
@ -67,7 +68,7 @@ public class FakeApi {
}
/* Build call for testEndpointParameters */
private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, Date date, Date dateTime, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// verify the required parameter 'number' is set
@ -169,7 +170,7 @@ public class FakeApi {
* @param password None (optional)
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, Date date, Date dateTime, String password) throws ApiException {
public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException {
testEndpointParametersWithHttpInfo(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password);
}
@ -191,7 +192,7 @@ public class FakeApi {
* @return ApiResponse&lt;Void&gt;
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<Void> testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, Date date, Date dateTime, String password) throws ApiException {
public ApiResponse<Void> testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException {
com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, null, null);
return apiClient.execute(call);
}
@ -215,7 +216,7 @@ public class FakeApi {
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call testEndpointParametersAsync(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, Date date, Date dateTime, String password, final ApiCallback<Void> callback) throws ApiException {
public com.squareup.okhttp.Call testEndpointParametersAsync(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password, final ApiCallback<Void> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;

View File

@ -39,8 +39,8 @@ import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import io.swagger.client.model.Pet;
import java.io.File;
import io.swagger.client.model.ModelApiResponse;
import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;

View File

@ -29,7 +29,8 @@ import java.util.Objects;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.math.BigDecimal;
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import com.google.gson.annotations.SerializedName;
@ -57,9 +58,9 @@ public class FormatTest {
@SerializedName("binary")
private byte[] binary = null;
@SerializedName("date")
private Date date = null;
private LocalDate date = null;
@SerializedName("dateTime")
private Date dateTime = null;
private DateTime dateTime = null;
@SerializedName("uuid")
private String uuid = null;
@SerializedName("password")
@ -242,7 +243,7 @@ public class FormatTest {
* @return date
**/
@ApiModelProperty(required = true, value = "")
public Date getDate() {
public LocalDate getDate() {
return date;
}
@ -251,7 +252,7 @@ public class FormatTest {
*
* @param date date
*/
public void setDate(Date date) {
public void setDate(LocalDate date) {
this.date = date;
}
@ -260,7 +261,7 @@ public class FormatTest {
* @return dateTime
**/
@ApiModelProperty(value = "")
public Date getDateTime() {
public DateTime getDateTime() {
return dateTime;
}
@ -269,7 +270,7 @@ public class FormatTest {
*
* @param dateTime dateTime
*/
public void setDateTime(Date dateTime) {
public void setDateTime(DateTime dateTime) {
this.dateTime = dateTime;
}

View File

@ -29,10 +29,10 @@ import java.util.Objects;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.client.model.Animal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.joda.time.DateTime;
import com.google.gson.annotations.SerializedName;
@ -44,7 +44,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass {
@SerializedName("uuid")
private String uuid = null;
@SerializedName("dateTime")
private Date dateTime = null;
private DateTime dateTime = null;
@SerializedName("map")
private Map<String, Animal> map = new HashMap<String, Animal>();
@ -71,7 +71,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass {
* @return dateTime
**/
@ApiModelProperty(value = "")
public Date getDateTime() {
public DateTime getDateTime() {
return dateTime;
}
@ -80,7 +80,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass {
*
* @param dateTime dateTime
*/
public void setDateTime(Date dateTime) {
public void setDateTime(DateTime dateTime) {
this.dateTime = dateTime;
}

View File

@ -28,7 +28,7 @@ package io.swagger.client.model;
import java.util.Objects;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.Date;
import org.joda.time.DateTime;
import com.google.gson.annotations.SerializedName;
@ -44,7 +44,7 @@ public class Order {
@SerializedName("quantity")
private Integer quantity = null;
@SerializedName("shipDate")
private Date shipDate = null;
private DateTime shipDate = null;
/**
* Order Status
*/
@ -134,7 +134,7 @@ public class Order {
* @return shipDate
**/
@ApiModelProperty(value = "")
public Date getShipDate() {
public DateTime getShipDate() {
return shipDate;
}
@ -143,7 +143,7 @@ public class Order {
*
* @param shipDate shipDate
*/
public void setShipDate(Date shipDate) {
public void setShipDate(DateTime shipDate) {
this.shipDate = shipDate;
}

View File

@ -6,10 +6,10 @@ import io.swagger.client.model.Order;
import java.lang.Exception;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.*;
import static org.junit.Assert.*;
@ -27,29 +27,25 @@ public class JSONTest {
@Test
public void testDefaultDate() throws Exception {
final DateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
final DateTimeFormatter datetimeFormat = ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC);
final String dateStr = "2015-11-07T14:11:05.267Z";
order.setShipDate(datetimeFormat.parse(dateStr));
order.setShipDate(datetimeFormat.parseDateTime(dateStr));
String str = json.serialize(order);
Type type = new TypeToken<Order>() { }.getType();
Order o = json.deserialize(str, type);
assertEquals(dateStr, datetimeFormat.format(o.getShipDate()));
assertEquals(dateStr, datetimeFormat.print(o.getShipDate()));
}
@Test
public void testCustomDate() throws Exception {
final DateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
datetimeFormat.setTimeZone(TimeZone.getTimeZone("GMT-2"));
final DateTimeFormatter datetimeFormat = ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.forID("Etc/GMT+2"));
final String dateStr = "2015-11-07T14:11:05-02:00";
order.setShipDate(datetimeFormat.parse(dateStr));
order.setShipDate(datetimeFormat.parseDateTime(dateStr));
apiClient.setDatetimeFormat(datetimeFormat);
apiClient.setLenientDatetimeFormat(false);
String str = json.serialize(order);
Type type = new TypeToken<Order>() { }.getType();
Order o = json.deserialize(str, type);
assertEquals(dateStr, datetimeFormat.format(o.getShipDate()));
assertEquals(dateStr, datetimeFormat.print(o.getShipDate()));
}
}

View File

@ -1,155 +1,395 @@
package io.swagger.client.api;
import io.swagger.client.ApiException;
import io.swagger.client.model.Pet;
import io.swagger.client.model.ModelApiResponse;
import java.io.File;
import org.junit.Test;
import io.swagger.TestUtils;
import io.swagger.client.*;
import io.swagger.client.auth.*;
import io.swagger.client.model.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* API tests for PetApi
*/
import org.junit.*;
import static org.junit.Assert.*;
public class PetApiTest {
PetApi api = null;
private final PetApi api = new PetApi();
/**
* Add a new pet to the store
*
*
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void addPetTest() throws ApiException {
Pet body = null;
// api.addPet(body);
// TODO: test validations
@Before
public void setup() {
api = new PetApi();
// setup authentication
ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key");
apiKeyAuth.setApiKey("special-key");
}
/**
* Deletes a pet
*
*
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void deletePetTest() throws ApiException {
Long petId = null;
String apiKey = null;
// api.deletePet(petId, apiKey);
// TODO: test validations
}
/**
* Finds Pets by status
*
* Multiple status values can be provided with comma separated strings
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void findPetsByStatusTest() throws ApiException {
List<String> status = null;
// List<Pet> response = api.findPetsByStatus(status);
public void testApiClient() {
// the default api client is used
assertEquals(Configuration.getDefaultApiClient(), api.getApiClient());
assertNotNull(api.getApiClient());
assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath());
assertFalse(api.getApiClient().isDebugging());
// TODO: test validations
ApiClient oldClient = api.getApiClient();
ApiClient newClient = new ApiClient();
newClient.setBasePath("http://example.com");
newClient.setDebugging(true);
// set api client via constructor
api = new PetApi(newClient);
assertNotNull(api.getApiClient());
assertEquals("http://example.com", api.getApiClient().getBasePath());
assertTrue(api.getApiClient().isDebugging());
// set api client via setter method
api.setApiClient(oldClient);
assertNotNull(api.getApiClient());
assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath());
assertFalse(api.getApiClient().isDebugging());
}
/**
* Finds Pets by tags
*
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void findPetsByTagsTest() throws ApiException {
List<String> tags = null;
// List<Pet> response = api.findPetsByTags(tags);
public void testCreateAndGetPet() throws Exception {
Pet pet = createRandomPet();
api.addPet(pet);
// TODO: test validations
Pet fetched = api.getPetById(pet.getId());
assertNotNull(fetched);
assertEquals(pet.getId(), fetched.getId());
assertNotNull(fetched.getCategory());
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
}
/**
* Find pet by ID
*
* Returns a single pet
*
* @throws ApiException
* if the Api call fails
*/
/*
@Test
public void getPetByIdTest() throws ApiException {
Long petId = null;
// Pet response = api.getPetById(petId);
public void testCreateAndGetPetWithByteArray() throws Exception {
Pet pet = createRandomPet();
byte[] bytes = serializeJson(pet, api.getApiClient()).getBytes();
api.addPetUsingByteArray(bytes);
// TODO: test validations
byte[] fetchedBytes = api.petPetIdtestingByteArraytrueGet(pet.getId());
Type type = new TypeToken<Pet>(){}.getType();
Pet fetched = deserializeJson(new String(fetchedBytes), type, api.getApiClient());
assertNotNull(fetched);
assertEquals(pet.getId(), fetched.getId());
assertNotNull(fetched.getCategory());
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
}
/**
* Update an existing pet
*
*
*
* @throws ApiException
* if the Api call fails
*/
*/
@Test
public void updatePetTest() throws ApiException {
Pet body = null;
// api.updatePet(body);
public void testCreateAndGetPetWithHttpInfo() throws Exception {
Pet pet = createRandomPet();
api.addPetWithHttpInfo(pet);
// TODO: test validations
ApiResponse<Pet> resp = api.getPetByIdWithHttpInfo(pet.getId());
assertEquals(200, resp.getStatusCode());
assertEquals("application/json", resp.getHeaders().get("Content-Type").get(0));
Pet fetched = resp.getData();
assertNotNull(fetched);
assertEquals(pet.getId(), fetched.getId());
assertNotNull(fetched.getCategory());
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
}
/**
* Updates a pet in the store with form data
*
*
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void updatePetWithFormTest() throws ApiException {
Long petId = null;
String name = null;
String status = null;
// api.updatePetWithForm(petId, name, status);
public void testCreateAndGetPetAsync() throws Exception {
Pet pet = createRandomPet();
api.addPet(pet);
// to store returned Pet or error message/exception
final Map<String, Object> result = new HashMap<String, Object>();
// TODO: test validations
api.getPetByIdAsync(pet.getId(), new ApiCallback<Pet>() {
@Override
public void onFailure(ApiException e, int statusCode, Map<String, List<String>> responseHeaders) {
result.put("error", e.getMessage());
}
@Override
public void onSuccess(Pet pet, int statusCode, Map<String, List<String>> responseHeaders) {
result.put("pet", pet);
}
@Override
public void onUploadProgress(long bytesWritten, long contentLength, boolean done) {
//empty
}
@Override
public void onDownloadProgress(long bytesRead, long contentLength, boolean done) {
//empty
}
});
// the API call should be executed asynchronously, so result should be empty at the moment
assertTrue(result.isEmpty());
// wait for the asynchronous call to finish (at most 10 seconds)
final int maxTry = 10;
int tryCount = 1;
Pet fetched = null;
do {
if (tryCount > maxTry) fail("have not got result of getPetByIdAsync after 10 seconds");
Thread.sleep(1000);
tryCount += 1;
if (result.get("error") != null) fail((String) result.get("error"));
if (result.get("pet") != null) {
fetched = (Pet) result.get("pet");
break;
}
} while (result.isEmpty());
assertNotNull(fetched);
assertEquals(pet.getId(), fetched.getId());
assertNotNull(fetched.getCategory());
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
// test getting a nonexistent pet
result.clear();
api.getPetByIdAsync(new Long(-10000), new ApiCallback<Pet>() {
@Override
public void onFailure(ApiException e, int statusCode, Map<String, List<String>> responseHeaders) {
result.put("exception", e);
}
@Override
public void onSuccess(Pet pet, int statusCode, Map<String, List<String>> responseHeaders) {
result.put("pet", pet);
}
@Override
public void onUploadProgress(long bytesWritten, long contentLength, boolean done) {
//empty
}
@Override
public void onDownloadProgress(long bytesRead, long contentLength, boolean done) {
//empty
}
});
// the API call should be executed asynchronously, so result should be empty at the moment
assertTrue(result.isEmpty());
// wait for the asynchronous call to finish (at most 10 seconds)
tryCount = 1;
ApiException exception = null;
do {
if (tryCount > maxTry) fail("have not got result of getPetByIdAsync after 10 seconds");
Thread.sleep(1000);
tryCount += 1;
if (result.get("pet") != null) fail("expected an error");
if (result.get("exception") != null) {
exception = (ApiException) result.get("exception");
break;
}
} while (result.isEmpty());
assertNotNull(exception);
assertEquals(404, exception.getCode());
assertEquals("Not Found", exception.getMessage());
assertEquals("application/json", exception.getResponseHeaders().get("Content-Type").get(0));
}
/**
* uploads an image
*
*
*
* @throws ApiException
* if the Api call fails
*/
/*
@Test
public void uploadFileTest() throws ApiException {
Long petId = null;
String additionalMetadata = null;
File file = null;
// ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file);
public void testGetPetByIdInObject() throws Exception {
Pet pet = new Pet();
pet.setId(TestUtils.nextId());
pet.setName("pet " + pet.getId());
// TODO: test validations
Category category = new Category();
category.setId(TestUtils.nextId());
category.setName("category " + category.getId());
pet.setCategory(category);
pet.setStatus(Pet.StatusEnum.PENDING);
List<String> photos = Arrays.asList(new String[]{"http://foo.bar.com/1"});
pet.setPhotoUrls(photos);
api.addPet(pet);
InlineResponse200 fetched = api.getPetByIdInObject(pet.getId());
assertEquals(pet.getId(), fetched.getId());
assertEquals(pet.getName(), fetched.getName());
Object categoryObj = fetched.getCategory();
assertNotNull(categoryObj);
assertTrue(categoryObj instanceof Map);
Map categoryMap = (Map) categoryObj;
Object categoryIdObj = categoryMap.get("id");
// NOTE: Gson parses integer value to double.
assertTrue(categoryIdObj instanceof Double);
Long categoryIdLong = ((Double) categoryIdObj).longValue();
assertEquals(category.getId(), categoryIdLong);
assertEquals(category.getName(), categoryMap.get("name"));
}
*/
@Test
public void testUpdatePet() throws Exception {
Pet pet = createRandomPet();
pet.setName("programmer");
api.updatePet(pet);
Pet fetched = api.getPetById(pet.getId());
assertNotNull(fetched);
assertEquals(pet.getId(), fetched.getId());
assertNotNull(fetched.getCategory());
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
}
@Test
public void testFindPetsByStatus() throws Exception {
Pet pet = createRandomPet();
pet.setName("programmer");
pet.setStatus(Pet.StatusEnum.PENDING);
api.updatePet(pet);
List<Pet> pets = api.findPetsByStatus(Arrays.asList(new String[]{"pending"}));
assertNotNull(pets);
boolean found = false;
for (Pet fetched : pets) {
if (fetched.getId().equals(pet.getId())) {
found = true;
break;
}
}
assertTrue(found);
api.deletePet(pet.getId(), null);
}
@Test
public void testFindPetsByTags() throws Exception {
Pet pet = createRandomPet();
pet.setName("monster");
pet.setStatus(Pet.StatusEnum.AVAILABLE);
List<Tag> tags = new ArrayList<Tag>();
Tag tag1 = new Tag();
tag1.setName("friendly");
tags.add(tag1);
pet.setTags(tags);
api.updatePet(pet);
List<Pet> pets = api.findPetsByTags(Arrays.asList(new String[]{"friendly"}));
assertNotNull(pets);
boolean found = false;
for (Pet fetched : pets) {
if (fetched.getId().equals(pet.getId())) {
found = true;
break;
}
}
assertTrue(found);
api.deletePet(pet.getId(), null);
}
@Test
public void testUpdatePetWithForm() throws Exception {
Pet pet = createRandomPet();
pet.setName("frank");
api.addPet(pet);
Pet fetched = api.getPetById(pet.getId());
api.updatePetWithForm(fetched.getId(), "furt", null);
Pet updated = api.getPetById(fetched.getId());
assertEquals(updated.getName(), "furt");
}
@Test
public void testDeletePet() throws Exception {
Pet pet = createRandomPet();
api.addPet(pet);
Pet fetched = api.getPetById(pet.getId());
api.deletePet(fetched.getId(), null);
try {
fetched = api.getPetById(fetched.getId());
fail("expected an error");
} catch (ApiException e) {
assertEquals(404, e.getCode());
}
}
@Test
public void testUploadFile() throws Exception {
Pet pet = createRandomPet();
api.addPet(pet);
File file = new File("hello.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write("Hello world!");
writer.close();
api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath()));
}
@Test
public void testEqualsAndHashCode() {
Pet pet1 = new Pet();
Pet pet2 = new Pet();
assertTrue(pet1.equals(pet2));
assertTrue(pet2.equals(pet1));
assertTrue(pet1.hashCode() == pet2.hashCode());
assertTrue(pet1.equals(pet1));
assertTrue(pet1.hashCode() == pet1.hashCode());
pet2.setName("really-happy");
pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}));
assertFalse(pet1.equals(pet2));
assertFalse(pet2.equals(pet1));
assertFalse(pet1.hashCode() == (pet2.hashCode()));
assertTrue(pet2.equals(pet2));
assertTrue(pet2.hashCode() == pet2.hashCode());
pet1.setName("really-happy");
pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}));
assertTrue(pet1.equals(pet2));
assertTrue(pet2.equals(pet1));
assertTrue(pet1.hashCode() == pet2.hashCode());
assertTrue(pet1.equals(pet1));
assertTrue(pet1.hashCode() == pet1.hashCode());
}
private Pet createRandomPet() {
Pet pet = new Pet();
pet.setId(TestUtils.nextId());
pet.setName("gorilla");
Category category = new Category();
category.setName("really-happy");
pet.setCategory(category);
pet.setStatus(Pet.StatusEnum.AVAILABLE);
List<String> photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"});
pet.setPhotoUrls(photos);
return pet;
}
private String serializeJson(Object o, ApiClient apiClient) {
return apiClient.getJSON().serialize(o);
}
private <T> T deserializeJson(String json, Type type, ApiClient apiClient) {
return (T) apiClient.getJSON().deserialize(json, type);
}
}

View File

@ -1,83 +1,105 @@
package io.swagger.client.api;
import io.swagger.TestUtils;
import io.swagger.client.ApiException;
import io.swagger.client.model.Order;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import io.swagger.client.auth.*;
import io.swagger.client.model.*;
import java.lang.reflect.Field;
import java.util.Map;
import java.text.SimpleDateFormat;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.*;
import static org.junit.Assert.*;
/**
* API tests for StoreApi
*/
public class StoreApiTest {
StoreApi api = null;
private final StoreApi api = new StoreApi();
/**
* Delete purchase order by ID
*
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void deleteOrderTest() throws ApiException {
String orderId = null;
// api.deleteOrder(orderId);
// TODO: test validations
@Before
public void setup() {
api = new StoreApi();
// setup authentication
ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key");
apiKeyAuth.setApiKey("special-key");
// set custom date format that is used by the petstore server
// Note: it would still work without this setting as okhttp-gson Java client supports
// various date formats by default (with lenientDatetimeFormat enabled), including
// the one used by petstore server
api.getApiClient().setDatetimeFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"));
api.getApiClient().setLenientDatetimeFormat(false);
}
/**
* Returns pet inventories by status
*
* Returns a map of status codes to quantities
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getInventoryTest() throws ApiException {
// Map<String, Integer> response = api.getInventory();
// TODO: test validations
}
/**
* Find purchase order by ID
*
* For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generated exceptions
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getOrderByIdTest() throws ApiException {
Long orderId = null;
// Order response = api.getOrderById(orderId);
// TODO: test validations
public void testGetInventory() throws Exception {
Map<String, Integer> inventory = api.getInventory();
assertTrue(inventory.keySet().size() > 0);
}
/**
* Place an order for a pet
*
*
*
* @throws ApiException
* if the Api call fails
*/
/*
@Test
public void placeOrderTest() throws ApiException {
Order body = null;
// Order response = api.placeOrder(body);
public void testGetInventoryInObject() throws Exception {
Object inventoryObj = api.getInventoryInObject();
assertTrue(inventoryObj instanceof Map);
// TODO: test validations
Map inventoryMap = (Map) inventoryObj;
assertTrue(inventoryMap.keySet().size() > 0);
Map.Entry firstEntry = (Map.Entry) inventoryMap.entrySet().iterator().next();
assertTrue(firstEntry.getKey() instanceof String);
// NOTE: Gson parses integer value to double.
assertTrue(firstEntry.getValue() instanceof Double);
}
*/
@Test
public void testPlaceOrder() throws Exception {
Order order = createOrder();
api.placeOrder(order);
Order fetched = api.getOrderById(order.getId());
assertEquals(order.getId(), fetched.getId());
assertEquals(order.getPetId(), fetched.getPetId());
assertEquals(order.getQuantity(), fetched.getQuantity());
assertEquals(order.getShipDate().withZone(DateTimeZone.UTC), fetched.getShipDate().withZone(DateTimeZone.UTC));
}
@Test
public void testDeleteOrder() throws Exception {
Order order = createOrder();
api.placeOrder(order);
Order fetched = api.getOrderById(order.getId());
assertEquals(fetched.getId(), order.getId());
api.deleteOrder(String.valueOf(order.getId()));
try {
api.getOrderById(order.getId());
// fail("expected an error");
} catch (ApiException e) {
// ok
}
}
private Order createOrder() {
Order order = new Order();
order.setPetId(new Long(200));
order.setQuantity(new Integer(13));
order.setShipDate(DateTime.now());
order.setStatus(Order.StatusEnum.PLACED);
order.setComplete(true);
try {
Field idField = Order.class.getDeclaredField("id");
idField.setAccessible(true);
idField.set(order, TestUtils.nextId());
} catch (Exception e) {
throw new RuntimeException(e);
}
return order;
}
}

View File

@ -1,149 +1,87 @@
package io.swagger.client.api;
import io.swagger.client.ApiException;
import io.swagger.client.model.User;
import org.junit.Test;
import io.swagger.TestUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.swagger.client.auth.*;
import io.swagger.client.model.*;
import java.util.Arrays;
import org.junit.*;
import static org.junit.Assert.*;
/**
* API tests for UserApi
*/
public class UserApiTest {
UserApi api = null;
private final UserApi api = new UserApi();
/**
* Create user
*
* This can only be done by the logged in user.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void createUserTest() throws ApiException {
User body = null;
// api.createUser(body);
// TODO: test validations
@Before
public void setup() {
api = new UserApi();
// setup authentication
ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key");
apiKeyAuth.setApiKey("special-key");
}
/**
* Creates list of users with given input array
*
*
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void createUsersWithArrayInputTest() throws ApiException {
List<User> body = null;
// api.createUsersWithArrayInput(body);
// TODO: test validations
}
/**
* Creates list of users with given input array
*
*
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void createUsersWithListInputTest() throws ApiException {
List<User> body = null;
// api.createUsersWithListInput(body);
public void testCreateUser() throws Exception {
User user = createUser();
// TODO: test validations
api.createUser(user);
User fetched = api.getUserByName(user.getUsername());
assertEquals(user.getId(), fetched.getId());
}
/**
* Delete user
*
* This can only be done by the logged in user.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void deleteUserTest() throws ApiException {
String username = null;
// api.deleteUser(username);
public void testCreateUsersWithArray() throws Exception {
User user1 = createUser();
user1.setUsername("user" + user1.getId());
User user2 = createUser();
user2.setUsername("user" + user2.getId());
// TODO: test validations
api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2}));
User fetched = api.getUserByName(user1.getUsername());
assertEquals(user1.getId(), fetched.getId());
}
/**
* Get user by user name
*
*
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getUserByNameTest() throws ApiException {
String username = null;
// User response = api.getUserByName(username);
public void testCreateUsersWithList() throws Exception {
User user1 = createUser();
user1.setUsername("user" + user1.getId());
User user2 = createUser();
user2.setUsername("user" + user2.getId());
// TODO: test validations
api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2}));
User fetched = api.getUserByName(user1.getUsername());
assertEquals(user1.getId(), fetched.getId());
}
/**
* Logs user into the system
*
*
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void loginUserTest() throws ApiException {
String username = null;
String password = null;
// String response = api.loginUser(username, password);
public void testLoginUser() throws Exception {
User user = createUser();
api.createUser(user);
// TODO: test validations
String token = api.loginUser(user.getUsername(), user.getPassword());
assertTrue(token.startsWith("logged in user session:"));
}
/**
* Logs out current logged in user session
*
*
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void logoutUserTest() throws ApiException {
// api.logoutUser();
// TODO: test validations
public void logoutUser() throws Exception {
api.logoutUser();
}
/**
* Updated user
*
* This can only be done by the logged in user.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void updateUserTest() throws ApiException {
String username = null;
User body = null;
// api.updateUser(username, body);
// TODO: test validations
private User createUser() {
User user = new User();
user.setId(TestUtils.nextId());
user.setUsername("fred" + user.getId());
user.setFirstName("Fred");
user.setLastName("Meyer");
user.setEmail("fred@fredmeyer.com");
user.setPassword("xxXXxx");
user.setPhone("408-867-5309");
user.setUserStatus(123);
return user;
}
}

View File

@ -1,398 +0,0 @@
package io.swagger.petstore.test;
import com.google.gson.reflect.TypeToken;
import io.swagger.TestUtils;
import io.swagger.client.*;
import io.swagger.client.api.*;
import io.swagger.client.auth.*;
import io.swagger.client.model.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.*;
import static org.junit.Assert.*;
public class PetApiTest {
PetApi api = null;
@Before
public void setup() {
api = new PetApi();
// setup authentication
ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key");
apiKeyAuth.setApiKey("special-key");
}
@Test
public void testApiClient() {
// the default api client is used
assertEquals(Configuration.getDefaultApiClient(), api.getApiClient());
assertNotNull(api.getApiClient());
assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath());
assertFalse(api.getApiClient().isDebugging());
ApiClient oldClient = api.getApiClient();
ApiClient newClient = new ApiClient();
newClient.setBasePath("http://example.com");
newClient.setDebugging(true);
// set api client via constructor
api = new PetApi(newClient);
assertNotNull(api.getApiClient());
assertEquals("http://example.com", api.getApiClient().getBasePath());
assertTrue(api.getApiClient().isDebugging());
// set api client via setter method
api.setApiClient(oldClient);
assertNotNull(api.getApiClient());
assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath());
assertFalse(api.getApiClient().isDebugging());
}
@Test
public void testCreateAndGetPet() throws Exception {
Pet pet = createRandomPet();
api.addPet(pet);
Pet fetched = api.getPetById(pet.getId());
assertNotNull(fetched);
assertEquals(pet.getId(), fetched.getId());
assertNotNull(fetched.getCategory());
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
}
/*
@Test
public void testCreateAndGetPetWithByteArray() throws Exception {
Pet pet = createRandomPet();
byte[] bytes = serializeJson(pet, api.getApiClient()).getBytes();
api.addPetUsingByteArray(bytes);
byte[] fetchedBytes = api.petPetIdtestingByteArraytrueGet(pet.getId());
Type type = new TypeToken<Pet>(){}.getType();
Pet fetched = deserializeJson(new String(fetchedBytes), type, api.getApiClient());
assertNotNull(fetched);
assertEquals(pet.getId(), fetched.getId());
assertNotNull(fetched.getCategory());
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
}
*/
@Test
public void testCreateAndGetPetWithHttpInfo() throws Exception {
Pet pet = createRandomPet();
api.addPetWithHttpInfo(pet);
ApiResponse<Pet> resp = api.getPetByIdWithHttpInfo(pet.getId());
assertEquals(200, resp.getStatusCode());
assertEquals("application/json", resp.getHeaders().get("Content-Type").get(0));
Pet fetched = resp.getData();
assertNotNull(fetched);
assertEquals(pet.getId(), fetched.getId());
assertNotNull(fetched.getCategory());
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
}
@Test
public void testCreateAndGetPetAsync() throws Exception {
Pet pet = createRandomPet();
api.addPet(pet);
// to store returned Pet or error message/exception
final Map<String, Object> result = new HashMap<String, Object>();
api.getPetByIdAsync(pet.getId(), new ApiCallback<Pet>() {
@Override
public void onFailure(ApiException e, int statusCode, Map<String, List<String>> responseHeaders) {
result.put("error", e.getMessage());
}
@Override
public void onSuccess(Pet pet, int statusCode, Map<String, List<String>> responseHeaders) {
result.put("pet", pet);
}
@Override
public void onUploadProgress(long bytesWritten, long contentLength, boolean done) {
//empty
}
@Override
public void onDownloadProgress(long bytesRead, long contentLength, boolean done) {
//empty
}
});
// the API call should be executed asynchronously, so result should be empty at the moment
assertTrue(result.isEmpty());
// wait for the asynchronous call to finish (at most 10 seconds)
final int maxTry = 10;
int tryCount = 1;
Pet fetched = null;
do {
if (tryCount > maxTry) fail("have not got result of getPetByIdAsync after 10 seconds");
Thread.sleep(1000);
tryCount += 1;
if (result.get("error") != null) fail((String) result.get("error"));
if (result.get("pet") != null) {
fetched = (Pet) result.get("pet");
break;
}
} while (result.isEmpty());
assertNotNull(fetched);
assertEquals(pet.getId(), fetched.getId());
assertNotNull(fetched.getCategory());
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
// test getting a nonexistent pet
result.clear();
api.getPetByIdAsync(new Long(-10000), new ApiCallback<Pet>() {
@Override
public void onFailure(ApiException e, int statusCode, Map<String, List<String>> responseHeaders) {
result.put("exception", e);
}
@Override
public void onSuccess(Pet pet, int statusCode, Map<String, List<String>> responseHeaders) {
result.put("pet", pet);
}
@Override
public void onUploadProgress(long bytesWritten, long contentLength, boolean done) {
//empty
}
@Override
public void onDownloadProgress(long bytesRead, long contentLength, boolean done) {
//empty
}
});
// the API call should be executed asynchronously, so result should be empty at the moment
assertTrue(result.isEmpty());
// wait for the asynchronous call to finish (at most 10 seconds)
tryCount = 1;
ApiException exception = null;
do {
if (tryCount > maxTry) fail("have not got result of getPetByIdAsync after 10 seconds");
Thread.sleep(1000);
tryCount += 1;
if (result.get("pet") != null) fail("expected an error");
if (result.get("exception") != null) {
exception = (ApiException) result.get("exception");
break;
}
} while (result.isEmpty());
assertNotNull(exception);
assertEquals(404, exception.getCode());
assertEquals("Not Found", exception.getMessage());
assertEquals("application/json", exception.getResponseHeaders().get("Content-Type").get(0));
}
/*
@Test
public void testGetPetByIdInObject() throws Exception {
Pet pet = new Pet();
pet.setId(TestUtils.nextId());
pet.setName("pet " + pet.getId());
Category category = new Category();
category.setId(TestUtils.nextId());
category.setName("category " + category.getId());
pet.setCategory(category);
pet.setStatus(Pet.StatusEnum.PENDING);
List<String> photos = Arrays.asList(new String[]{"http://foo.bar.com/1"});
pet.setPhotoUrls(photos);
api.addPet(pet);
InlineResponse200 fetched = api.getPetByIdInObject(pet.getId());
assertEquals(pet.getId(), fetched.getId());
assertEquals(pet.getName(), fetched.getName());
Object categoryObj = fetched.getCategory();
assertNotNull(categoryObj);
assertTrue(categoryObj instanceof Map);
Map categoryMap = (Map) categoryObj;
Object categoryIdObj = categoryMap.get("id");
// NOTE: Gson parses integer value to double.
assertTrue(categoryIdObj instanceof Double);
Long categoryIdLong = ((Double) categoryIdObj).longValue();
assertEquals(category.getId(), categoryIdLong);
assertEquals(category.getName(), categoryMap.get("name"));
}
*/
@Test
public void testUpdatePet() throws Exception {
Pet pet = createRandomPet();
pet.setName("programmer");
api.updatePet(pet);
Pet fetched = api.getPetById(pet.getId());
assertNotNull(fetched);
assertEquals(pet.getId(), fetched.getId());
assertNotNull(fetched.getCategory());
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
}
@Test
public void testFindPetsByStatus() throws Exception {
Pet pet = createRandomPet();
pet.setName("programmer");
pet.setStatus(Pet.StatusEnum.PENDING);
api.updatePet(pet);
List<Pet> pets = api.findPetsByStatus(Arrays.asList(new String[]{"pending"}));
assertNotNull(pets);
boolean found = false;
for (Pet fetched : pets) {
if (fetched.getId().equals(pet.getId())) {
found = true;
break;
}
}
assertTrue(found);
api.deletePet(pet.getId(), null);
}
@Test
public void testFindPetsByTags() throws Exception {
Pet pet = createRandomPet();
pet.setName("monster");
pet.setStatus(Pet.StatusEnum.AVAILABLE);
List<Tag> tags = new ArrayList<Tag>();
Tag tag1 = new Tag();
tag1.setName("friendly");
tags.add(tag1);
pet.setTags(tags);
api.updatePet(pet);
List<Pet> pets = api.findPetsByTags(Arrays.asList(new String[]{"friendly"}));
assertNotNull(pets);
boolean found = false;
for (Pet fetched : pets) {
if (fetched.getId().equals(pet.getId())) {
found = true;
break;
}
}
assertTrue(found);
api.deletePet(pet.getId(), null);
}
@Test
public void testUpdatePetWithForm() throws Exception {
Pet pet = createRandomPet();
pet.setName("frank");
api.addPet(pet);
Pet fetched = api.getPetById(pet.getId());
api.updatePetWithForm(fetched.getId(), "furt", null);
Pet updated = api.getPetById(fetched.getId());
assertEquals(updated.getName(), "furt");
}
@Test
public void testDeletePet() throws Exception {
Pet pet = createRandomPet();
api.addPet(pet);
Pet fetched = api.getPetById(pet.getId());
api.deletePet(fetched.getId(), null);
try {
fetched = api.getPetById(fetched.getId());
fail("expected an error");
} catch (ApiException e) {
assertEquals(404, e.getCode());
}
}
@Test
public void testUploadFile() throws Exception {
Pet pet = createRandomPet();
api.addPet(pet);
File file = new File("hello.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write("Hello world!");
writer.close();
api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath()));
}
@Test
public void testEqualsAndHashCode() {
Pet pet1 = new Pet();
Pet pet2 = new Pet();
assertTrue(pet1.equals(pet2));
assertTrue(pet2.equals(pet1));
assertTrue(pet1.hashCode() == pet2.hashCode());
assertTrue(pet1.equals(pet1));
assertTrue(pet1.hashCode() == pet1.hashCode());
pet2.setName("really-happy");
pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}));
assertFalse(pet1.equals(pet2));
assertFalse(pet2.equals(pet1));
assertFalse(pet1.hashCode() == (pet2.hashCode()));
assertTrue(pet2.equals(pet2));
assertTrue(pet2.hashCode() == pet2.hashCode());
pet1.setName("really-happy");
pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}));
assertTrue(pet1.equals(pet2));
assertTrue(pet2.equals(pet1));
assertTrue(pet1.hashCode() == pet2.hashCode());
assertTrue(pet1.equals(pet1));
assertTrue(pet1.hashCode() == pet1.hashCode());
}
private Pet createRandomPet() {
Pet pet = new Pet();
pet.setId(TestUtils.nextId());
pet.setName("gorilla");
Category category = new Category();
category.setName("really-happy");
pet.setCategory(category);
pet.setStatus(Pet.StatusEnum.AVAILABLE);
List<String> photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"});
pet.setPhotoUrls(photos);
return pet;
}
private String serializeJson(Object o, ApiClient apiClient) {
return apiClient.getJSON().serialize(o);
}
private <T> T deserializeJson(String json, Type type, ApiClient apiClient) {
return (T) apiClient.getJSON().deserialize(json, type);
}
}

View File

@ -1,104 +0,0 @@
package io.swagger.petstore.test;
import io.swagger.TestUtils;
import io.swagger.client.ApiException;
import io.swagger.client.*;
import io.swagger.client.api.*;
import io.swagger.client.auth.*;
import io.swagger.client.model.*;
import java.lang.reflect.Field;
import java.util.Map;
import java.text.SimpleDateFormat;
import org.junit.*;
import static org.junit.Assert.*;
public class StoreApiTest {
StoreApi api = null;
@Before
public void setup() {
api = new StoreApi();
// setup authentication
ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key");
apiKeyAuth.setApiKey("special-key");
// set custom date format that is used by the petstore server
// Note: it would still work without this setting as okhttp-gson Java client supports
// various date formats by default (with lenientDatetimeFormat enabled), including
// the one used by petstore server
api.getApiClient().setDatetimeFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"));
api.getApiClient().setLenientDatetimeFormat(false);
}
@Test
public void testGetInventory() throws Exception {
Map<String, Integer> inventory = api.getInventory();
assertTrue(inventory.keySet().size() > 0);
}
/*
@Test
public void testGetInventoryInObject() throws Exception {
Object inventoryObj = api.getInventoryInObject();
assertTrue(inventoryObj instanceof Map);
Map inventoryMap = (Map) inventoryObj;
assertTrue(inventoryMap.keySet().size() > 0);
Map.Entry firstEntry = (Map.Entry) inventoryMap.entrySet().iterator().next();
assertTrue(firstEntry.getKey() instanceof String);
// NOTE: Gson parses integer value to double.
assertTrue(firstEntry.getValue() instanceof Double);
}
*/
@Test
public void testPlaceOrder() throws Exception {
Order order = createOrder();
api.placeOrder(order);
Order fetched = api.getOrderById(order.getId());
assertEquals(order.getId(), fetched.getId());
assertEquals(order.getPetId(), fetched.getPetId());
assertEquals(order.getQuantity(), fetched.getQuantity());
}
@Test
public void testDeleteOrder() throws Exception {
Order order = createOrder();
api.placeOrder(order);
Order fetched = api.getOrderById(order.getId());
assertEquals(fetched.getId(), order.getId());
api.deleteOrder(String.valueOf(order.getId()));
try {
api.getOrderById(order.getId());
// fail("expected an error");
} catch (ApiException e) {
// ok
}
}
private Order createOrder() {
Order order = new Order();
order.setPetId(new Long(200));
order.setQuantity(new Integer(13));
order.setShipDate(new java.util.Date());
order.setStatus(Order.StatusEnum.PLACED);
order.setComplete(true);
try {
Field idField = Order.class.getDeclaredField("id");
idField.setAccessible(true);
idField.set(order, TestUtils.nextId());
} catch (Exception e) {
throw new RuntimeException(e);
}
return order;
}
}

View File

@ -1,88 +0,0 @@
package io.swagger.petstore.test;
import io.swagger.TestUtils;
import io.swagger.client.api.*;
import io.swagger.client.auth.*;
import io.swagger.client.model.*;
import java.util.Arrays;
import org.junit.*;
import static org.junit.Assert.*;
public class UserApiTest {
UserApi api = null;
@Before
public void setup() {
api = new UserApi();
// setup authentication
ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key");
apiKeyAuth.setApiKey("special-key");
}
@Test
public void testCreateUser() throws Exception {
User user = createUser();
api.createUser(user);
User fetched = api.getUserByName(user.getUsername());
assertEquals(user.getId(), fetched.getId());
}
@Test
public void testCreateUsersWithArray() throws Exception {
User user1 = createUser();
user1.setUsername("user" + user1.getId());
User user2 = createUser();
user2.setUsername("user" + user2.getId());
api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2}));
User fetched = api.getUserByName(user1.getUsername());
assertEquals(user1.getId(), fetched.getId());
}
@Test
public void testCreateUsersWithList() throws Exception {
User user1 = createUser();
user1.setUsername("user" + user1.getId());
User user2 = createUser();
user2.setUsername("user" + user2.getId());
api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2}));
User fetched = api.getUserByName(user1.getUsername());
assertEquals(user1.getId(), fetched.getId());
}
@Test
public void testLoginUser() throws Exception {
User user = createUser();
api.createUser(user);
String token = api.loginUser(user.getUsername(), user.getPassword());
assertTrue(token.startsWith("logged in user session:"));
}
@Test
public void logoutUser() throws Exception {
api.logoutUser();
}
private User createUser() {
User user = new User();
user.setId(TestUtils.nextId());
user.setUsername("fred" + user.getId());
user.setFirstName("Fred");
user.setLastName("Meyer");
user.setEmail("fred@fredmeyer.com");
user.setPassword("xxXXxx");
user.setPhone("408-867-5309");
user.setUserStatus(123);
return user;
}
}