Added tests to jersey2-java8 sample

These are the tests from the jersey2 sample - but adapted to use the
java8 time classes (rather than Joda time).
This commit is contained in:
ant3
2016-07-09 11:31:25 +01:00
parent 1ea80ab83a
commit bf8e1ade56
5 changed files with 416 additions and 401 deletions

View File

@@ -4,9 +4,9 @@ import io.swagger.client.model.Order;
import java.lang.Exception;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import org.junit.*;
import static org.junit.Assert.*;
@@ -23,23 +23,23 @@ public class JSONTest {
@Test
public void testDefaultDate() throws Exception {
final DateTimeFormatter dateFormat = ISODateTimeFormat.dateTime();
final DateTimeFormatter dateFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
final String dateStr = "2015-11-07T14:11:05.267Z";
order.setShipDate(dateFormat.parseDateTime(dateStr));
order.setShipDate(dateFormat.parse(dateStr, OffsetDateTime::from));
String str = json.getContext(null).writeValueAsString(order);
Order o = json.getContext(null).readValue(str, Order.class);
assertEquals(dateStr, dateFormat.print(o.getShipDate()));
assertEquals(dateStr, dateFormat.format(o.getShipDate()));
}
@Test
public void testCustomDate() throws Exception {
final DateTimeFormatter dateFormat = ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.forID("Etc/GMT+2"));
final DateTimeFormatter dateFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.of("Etc/GMT+2"));
final String dateStr = "2015-11-07T14:11:05-02:00";
order.setShipDate(dateFormat.parseDateTime(dateStr));
order.setShipDate(dateFormat.parse(dateStr, OffsetDateTime::from));
String str = json.getContext(null).writeValueAsString(order);
Order o = json.getContext(null).readValue(str, Order.class);
assertEquals(dateStr, dateFormat.print(o.getShipDate()));
assertEquals(dateStr, dateFormat.format(o.getShipDate()));
}
}

View File

@@ -1,180 +1,288 @@
/**
* 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.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 com.fasterxml.jackson.databind.ObjectMapper;
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.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 {
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());
Pet fetched = deserializeJson(new String(fetchedBytes), Pet.class, 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 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");
assertTrue(categoryIdObj instanceof Integer);
Integer categoryIdInt = (Integer) categoryIdObj;
assertEquals(category.getId(), Long.valueOf(categoryIdInt));
assertEquals(category.getName(), categoryMap.get("name"));
}
/**
* 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 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());
}
/**
* 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 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(Arrays.asList(new String[]{"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(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);
}
@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) {
ObjectMapper mapper = apiClient.getJSON().getContext(null);
try {
return mapper.writeValueAsString(o);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private <T> T deserializeJson(String json, Class<T> klass, ApiClient apiClient) {
ObjectMapper mapper = apiClient.getJSON().getContext(null);
try {
return mapper.readValue(json, klass);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

View File

@@ -1,108 +1,100 @@
/**
* 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.api;
import io.swagger.client.ApiException;
import io.swagger.client.model.Order;
import org.junit.Test;
import io.swagger.TestUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import io.swagger.client.*;
import io.swagger.client.auth.*;
import io.swagger.client.model.*;
import java.lang.reflect.Field;
import java.time.ZoneId;
import java.util.Map;
import java.text.SimpleDateFormat;
import java.time.OffsetDateTime;
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
api.getApiClient().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"));
}
/**
* 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);
assertTrue(firstEntry.getValue() instanceof Integer);
}
*/
@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().toInstant(), fetched.getShipDate().toInstant());
}
@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(OffsetDateTime.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,174 +1,88 @@
/**
* 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.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.api.*;
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;
}
}