add joda support to retrofit 1 clients

This commit is contained in:
cbornet 2016-06-09 18:41:44 +02:00
parent bd705a49d6
commit 2fe9cd2ba0
22 changed files with 492 additions and 631 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-retrofit.json -o samples/client/petstore/java/retrofit"
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-retrofit.json -o samples/client/petstore/java/retrofit -DdateLibrary=joda,hideGenerationTimestamp=true"
rm -rf samples/client/petstore/java/retrofit/src/main
find samples/client/petstore/java/retrofit -maxdepth 1 -type f ! -name "README.md" -exec rm {} +
java $JAVA_OPTS -jar $executable $ags

View File

@ -9,6 +9,10 @@ import java.util.Map;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import retrofit.RestAdapter;
import retrofit.client.OkClient;
@ -22,6 +26,9 @@ import retrofit.mime.TypedOutput;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
@ -108,6 +115,8 @@ public class ApiClient {
public void createDefaultAdapter() {
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
.registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter())
.registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter())
.create();
okClient = new OkHttpClient();
@ -339,3 +348,61 @@ class GsonConverterWrapper implements Converter {
}
}
/**
* 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 DateTime 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

@ -99,6 +99,7 @@ ext {
retrofit_version = "1.9.0"
swagger_annotations_version = "1.5.8"
junit_version = "4.12"
jodatime_version = "2.9.3"
}
dependencies {
@ -106,5 +107,6 @@ dependencies {
compile "com.squareup.retrofit:retrofit:$retrofit_version"
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version"
compile "joda-time:joda-time:$jodatime_version"
testCompile "junit:junit:$junit_version"
}

View File

@ -13,6 +13,7 @@ lazy val root = (project in file(".")).
"com.squareup.retrofit" % "retrofit" % "1.9.0" % "compile",
"io.swagger" % "swagger-annotations" % "1.5.8" % "compile",
"org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile",
"joda-time" % "joda-time" % "2.9.3" % "compile",
"junit" % "junit" % "4.12" % "test",
"com.novocode" % "junit-interface" % "0.10" % "test"
)

View File

@ -127,6 +127,11 @@
<artifactId>okhttp</artifactId>
<version>${okhttp-version}</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${jodatime-version}</version>
</dependency>
<!-- test dependencies -->
<dependency>
@ -140,6 +145,7 @@
<swagger-core-version>1.5.8</swagger-core-version>
<retrofit-version>1.9.0</retrofit-version>
<okhttp-version>2.7.5</okhttp-version>
<jodatime-version>2.9.3</jodatime-version>
<oltu-version>1.0.1</oltu-version>
<maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.12</junit-version>

View File

@ -99,6 +99,7 @@ ext {
retrofit_version = "1.9.0"
swagger_annotations_version = "1.5.8"
junit_version = "4.12"
jodatime_version = "2.9.3"
}
dependencies {
@ -106,5 +107,6 @@ dependencies {
compile "com.squareup.retrofit:retrofit:$retrofit_version"
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version"
compile "joda-time:joda-time:$jodatime_version"
testCompile "junit:junit:$junit_version"
}

View File

@ -13,6 +13,7 @@ lazy val root = (project in file(".")).
"com.squareup.retrofit" % "retrofit" % "1.9.0" % "compile",
"io.swagger" % "swagger-annotations" % "1.5.8" % "compile",
"org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile",
"joda-time" % "joda-time" % "2.9.3" % "compile",
"junit" % "junit" % "4.12" % "test",
"com.novocode" % "junit-interface" % "0.10" % "test"
)

0
samples/client/petstore/java/retrofit/gradlew vendored Executable file → Normal file
View File

View File

@ -127,6 +127,11 @@
<artifactId>okhttp</artifactId>
<version>${okhttp-version}</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${jodatime-version}</version>
</dependency>
<!-- test dependencies -->
<dependency>
@ -140,6 +145,7 @@
<swagger-core-version>1.5.8</swagger-core-version>
<retrofit-version>1.9.0</retrofit-version>
<okhttp-version>2.7.5</okhttp-version>
<jodatime-version>2.9.3</jodatime-version>
<oltu-version>1.0.1</oltu-version>
<maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.12</junit-version>

View File

@ -9,6 +9,10 @@ import java.util.Map;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import retrofit.RestAdapter;
import retrofit.client.OkClient;
@ -22,6 +26,9 @@ import retrofit.mime.TypedOutput;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
@ -107,6 +114,8 @@ public class ApiClient {
public void createDefaultAdapter() {
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
.registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter())
.registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter())
.create();
okClient = new OkHttpClient();
@ -338,3 +347,61 @@ class GsonConverterWrapper implements Converter {
}
}
/**
* 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 DateTime 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

@ -1,6 +1,31 @@
/**
* Swagger Petstore
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.swagger.client;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-04T20:43:54.025+08:00")
public class StringUtil {
/**
* Check if the given array contains the given value (with case-insensitive comparison).

View File

@ -6,8 +6,9 @@ import retrofit.Callback;
import retrofit.http.*;
import retrofit.mime.*;
import org.joda.time.LocalDate;
import java.math.BigDecimal;
import java.util.Date;
import org.joda.time.DateTime;
import java.util.ArrayList;
import java.util.HashMap;
@ -37,7 +38,7 @@ public interface FakeApi {
@FormUrlEncoded
@POST("/fake")
Void testEndpointParameters(
@Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") Date date, @Field("dateTime") Date dateTime, @Field("password") String password
@Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password
);
/**
@ -62,6 +63,6 @@ public interface FakeApi {
@FormUrlEncoded
@POST("/fake")
void testEndpointParameters(
@Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") Date date, @Field("dateTime") Date dateTime, @Field("password") String password, Callback<Void> cb
@Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password, Callback<Void> cb
);
}

View File

@ -1,5 +1,30 @@
/**
* Swagger Petstore
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.swagger.client.auth;
public enum OAuthFlow {
accessCode, implicit, password, application
}
}

View File

@ -4,7 +4,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;
@ -42,10 +43,10 @@ public class FormatTest {
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;
@ -156,20 +157,20 @@ public class FormatTest {
/**
**/
@ApiModelProperty(required = true, value = "")
public Date getDate() {
public LocalDate getDate() {
return date;
}
public void setDate(Date date) {
public void setDate(LocalDate date) {
this.date = date;
}
/**
**/
@ApiModelProperty(value = "")
public Date getDateTime() {
public DateTime getDateTime() {
return dateTime;
}
public void setDateTime(Date dateTime) {
public void setDateTime(DateTime dateTime) {
this.dateTime = dateTime;
}

View File

@ -4,10 +4,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;
@ -21,7 +21,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass {
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>();
@ -39,10 +39,10 @@ public class MixedPropertiesAndAdditionalPropertiesClass {
/**
**/
@ApiModelProperty(value = "")
public Date getDateTime() {
public DateTime getDateTime() {
return dateTime;
}
public void setDateTime(Date dateTime) {
public void setDateTime(DateTime dateTime) {
this.dateTime = dateTime;
}

View File

@ -3,7 +3,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;
@ -23,7 +23,7 @@ public class Order {
private Integer quantity = null;
@SerializedName("shipDate")
private Date shipDate = null;
private DateTime shipDate = null;
/**
@ -90,10 +90,10 @@ public class Order {
/**
**/
@ApiModelProperty(value = "")
public Date getShipDate() {
public DateTime getShipDate() {
return shipDate;
}
public void setShipDate(Date shipDate) {
public void setShipDate(DateTime shipDate) {
this.shipDate = shipDate;
}

View File

@ -1,137 +1,190 @@
package io.swagger.client.api;
import io.swagger.client.ApiClient;
import io.swagger.client.model.Pet;
import io.swagger.client.model.ModelApiResponse;
import io.swagger.TestUtils;
import io.swagger.client.*;
import io.swagger.client.CollectionFormats.*;
import io.swagger.client.model.*;
import retrofit.RetrofitError;
import retrofit.mime.TypedFile;
import java.io.BufferedWriter;
import java.io.File;
import org.junit.Before;
import org.junit.Test;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* API tests for PetApi
*/
import org.junit.*;
import static org.junit.Assert.*;
public class PetApiTest {
private PetApi api;
PetApi api = null;
@Before
public void setup() {
api = new ApiClient().createService(PetApi.class);
}
/**
* Add a new pet to the store
*
*
*/
@Test
public void addPetTest() {
Pet body = null;
// Void response = api.addPet(body);
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());
}
/**
* Deletes a pet
*
*
*/
@Test
public void deletePetTest() {
Long petId = null;
String apiKey = null;
// Void response = api.deletePet(petId, apiKey);
public void testUpdatePet() throws Exception {
Pet pet = createRandomPet();
pet.setName("programmer");
// TODO: test validations
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());
}
/**
* Finds Pets by status
*
* Multiple status values can be provided with comma separated strings
*/
@Test
public void findPetsByStatusTest() {
List<String> status = null;
// List<Pet> response = api.findPetsByStatus(status);
public void testFindPetsByStatus() throws Exception {
Pet pet = createRandomPet();
pet.setName("programmer");
pet.setStatus(Pet.StatusEnum.AVAILABLE);
// TODO: test validations
api.updatePet(pet);
List<Pet> pets = api.findPetsByStatus(new CSVParams("available"));
assertNotNull(pets);
boolean found = false;
for (Pet fetched : pets) {
if (fetched.getId().equals(pet.getId())) {
found = true;
break;
}
}
assertTrue(found);
}
/**
* Finds Pets by tags
*
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
*/
@Test
public void findPetsByTagsTest() {
List<String> tags = null;
// List<Pet> response = api.findPetsByTags(tags);
public void testFindPetsByTags() throws Exception {
Pet pet = createRandomPet();
pet.setName("monster");
pet.setStatus(Pet.StatusEnum.AVAILABLE);
// TODO: test validations
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(new CSVParams("friendly"));
assertNotNull(pets);
boolean found = false;
for (Pet fetched : pets) {
if (fetched.getId().equals(pet.getId())) {
found = true;
break;
}
}
assertTrue(found);
}
/**
* Find pet by ID
*
* Returns a single pet
*/
@Test
public void getPetByIdTest() {
Long petId = null;
// Pet response = api.getPetById(petId);
public void testUpdatePetWithForm() throws Exception {
Pet pet = createRandomPet();
pet.setName("frank");
api.addPet(pet);
// TODO: test validations
Pet fetched = api.getPetById(pet.getId());
api.updatePetWithForm(fetched.getId(), "furt", null);
Pet updated = api.getPetById(fetched.getId());
assertEquals(updated.getName(), "furt");
}
/**
* Update an existing pet
*
*
*/
@Test
public void updatePetTest() {
Pet body = null;
// Void response = api.updatePet(body);
public void testDeletePet() throws Exception {
Pet pet = createRandomPet();
api.addPet(pet);
// TODO: test validations
Pet fetched = api.getPetById(pet.getId());
api.deletePet(fetched.getId(), null);
try {
fetched = api.getPetById(fetched.getId());
fail("expected an error");
} catch (RetrofitError e) {
assertEquals(404, e.getResponse().getStatus());
}
}
/**
* Updates a pet in the store with form data
*
*
*/
@Test
public void updatePetWithFormTest() {
Long petId = null;
String name = null;
String status = null;
// Void response = api.updatePetWithForm(petId, name, status);
public void testUploadFile() throws Exception {
Pet pet = createRandomPet();
api.addPet(pet);
// TODO: test validations
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 TypedFile("text/plain", file));
}
/**
* uploads an image
*
*
*/
@Test
public void uploadFileTest() {
Long petId = null;
String additionalMetadata = null;
File file = null;
// ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file);
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());
// TODO: test validations
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;
}
}

View File

@ -1,77 +1,80 @@
package io.swagger.client.api;
import io.swagger.client.ApiClient;
import io.swagger.client.model.Order;
import org.junit.Before;
import org.junit.Test;
import io.swagger.TestUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import io.swagger.client.ApiClient;
import io.swagger.client.model.*;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import retrofit.RetrofitError;
import java.lang.reflect.Field;
import java.util.Map;
/**
* API tests for StoreApi
*/
public class StoreApiTest {
import org.junit.*;
import static org.junit.Assert.*;
private StoreApi api;
public class StoreApiTest {
StoreApi api = null;
@Before
public void setup() {
api = new ApiClient().createService(StoreApi.class);
}
/**
* Delete purchase order by ID
*
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
*/
@Test
public void deleteOrderTest() {
String orderId = null;
// Void response = api.deleteOrder(orderId);
// TODO: test validations
public void testGetInventory() throws Exception {
Map<String, Integer> inventory = api.getInventory();
assertTrue(inventory.keySet().size() > 0);
}
/**
* Returns pet inventories by status
*
* Returns a map of status codes to quantities
*/
@Test
public void getInventoryTest() {
// Map<String, Integer> response = api.getInventory();
public void testPlaceOrder() throws Exception {
Order order = createOrder();
api.placeOrder(order);
// TODO: test validations
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));
}
/**
* Find purchase order by ID
*
* For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generated exceptions
*/
@Test
public void getOrderByIdTest() {
Long orderId = null;
// Order response = api.getOrderById(orderId);
public void testDeleteOrder() throws Exception {
Order order = createOrder();
api.placeOrder(order);
// TODO: test validations
}
/**
* Place an order for a pet
*
*
*/
@Test
public void placeOrderTest() {
Order body = null;
// Order response = api.placeOrder(body);
Order fetched = api.getOrderById(order.getId());
assertEquals(fetched.getId(), order.getId());
// TODO: test validations
api.deleteOrder(String.valueOf(order.getId()));
try {
api.getOrderById(order.getId());
// fail("expected an error");
} catch (RetrofitError 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,131 +1,85 @@
package io.swagger.client.api;
import io.swagger.TestUtils;
import io.swagger.client.ApiClient;
import io.swagger.client.model.User;
import org.junit.Before;
import org.junit.Test;
import io.swagger.client.model.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* API tests for UserApi
*/
import java.util.Arrays;
import org.junit.*;
import static org.junit.Assert.*;
public class UserApiTest {
private UserApi api;
UserApi api = null;
@Before
public void setup() {
api = new ApiClient().createService(UserApi.class);
}
/**
* Create user
*
* This can only be done by the logged in user.
*/
@Test
public void createUserTest() {
User body = null;
// Void response = api.createUser(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());
}
/**
* Creates list of users with given input array
*
*
*/
@Test
public void createUsersWithArrayInputTest() {
List<User> body = null;
// Void response = api.createUsersWithArrayInput(body);
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());
}
/**
* Creates list of users with given input array
*
*
*/
@Test
public void createUsersWithListInputTest() {
List<User> body = null;
// Void response = api.createUsersWithListInput(body);
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());
}
/**
* Delete user
*
* This can only be done by the logged in user.
*/
@Test
public void deleteUserTest() {
String username = null;
// Void response = api.deleteUser(username);
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:"));
}
/**
* Get user by user name
*
*
*/
@Test
public void getUserByNameTest() {
String username = null;
// User response = api.getUserByName(username);
// TODO: test validations
public void logoutUser() throws Exception {
api.logoutUser();
}
/**
* Logs user into the system
*
*
*/
@Test
public void loginUserTest() {
String username = null;
String password = null;
// String response = api.loginUser(username, password);
// TODO: test validations
}
/**
* Logs out current logged in user session
*
*
*/
@Test
public void logoutUserTest() {
// Void response = 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);
// TODO: test validations
return user;
}
/**
* Updated user
*
* This can only be done by the logged in user.
*/
@Test
public void updateUserTest() {
String username = null;
User body = null;
// Void response = api.updateUser(username, body);
// TODO: test validations
}
}

View File

@ -1,191 +0,0 @@
package io.swagger.petstore.test;
import io.swagger.TestUtils;
import io.swagger.client.*;
import io.swagger.client.CollectionFormats.*;
import io.swagger.client.api.*;
import io.swagger.client.model.*;
import retrofit.RetrofitError;
import retrofit.mime.TypedFile;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.*;
import static org.junit.Assert.*;
public class PetApiTest {
PetApi api = null;
@Before
public void setup() {
api = new ApiClient().createService(PetApi.class);
}
@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 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.AVAILABLE);
api.updatePet(pet);
List<Pet> pets = api.findPetsByStatus(new CSVParams("available"));
assertNotNull(pets);
boolean found = false;
for (Pet fetched : pets) {
if (fetched.getId().equals(pet.getId())) {
found = true;
break;
}
}
assertTrue(found);
}
@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(new CSVParams("friendly"));
assertNotNull(pets);
boolean found = false;
for (Pet fetched : pets) {
if (fetched.getId().equals(pet.getId())) {
found = true;
break;
}
}
assertTrue(found);
}
@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 (RetrofitError e) {
assertEquals(404, e.getResponse().getStatus());
}
}
@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 TypedFile("text/plain", file));
}
@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;
}
}

View File

@ -1,78 +0,0 @@
package io.swagger.petstore.test;
import io.swagger.TestUtils;
import io.swagger.client.ApiClient;
import io.swagger.client.api.*;
import io.swagger.client.model.*;
import retrofit.RetrofitError;
import java.lang.reflect.Field;
import java.util.Map;
import org.junit.*;
import static org.junit.Assert.*;
public class StoreApiTest {
StoreApi api = null;
@Before
public void setup() {
api = new ApiClient().createService(StoreApi.class);
}
@Test
public void testGetInventory() throws Exception {
Map<String, Integer> inventory = api.getInventory();
assertTrue(inventory.keySet().size() > 0);
}
@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 (RetrofitError 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,86 +0,0 @@
package io.swagger.petstore.test;
import io.swagger.TestUtils;
import io.swagger.client.ApiClient;
import io.swagger.client.api.*;
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 ApiClient().createService(UserApi.class);
}
@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;
}
}