Skip to content

Commit f43d1c0

Browse files
committed
integration tests de Book
1 parent 1a0ca42 commit f43d1c0

File tree

7 files changed

+351
-15
lines changed

7 files changed

+351
-15
lines changed
Lines changed: 253 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,253 @@
1+
package com.library.app.book.resource;
2+
3+
import com.google.gson.JsonArray;
4+
import com.google.gson.JsonObject;
5+
import com.google.gson.JsonPrimitive;
6+
import com.library.app.author.model.Author;
7+
import com.library.app.book.model.Book;
8+
import com.library.app.category.model.Category;
9+
import com.library.app.common.json.JsonReader;
10+
import com.library.app.common.json.JsonWriter;
11+
import com.library.app.common.model.HttpCode;
12+
import com.library.app.commontests.utils.*;
13+
import org.jboss.arquillian.container.test.api.Deployment;
14+
import org.jboss.arquillian.container.test.api.RunAsClient;
15+
import org.jboss.arquillian.junit.Arquillian;
16+
import org.jboss.arquillian.test.api.ArquillianResource;
17+
import org.jboss.shrinkwrap.api.spec.WebArchive;
18+
import org.junit.Before;
19+
import org.junit.Test;
20+
import org.junit.runner.RunWith;
21+
22+
import javax.ws.rs.core.Response;
23+
import java.net.URL;
24+
25+
import static com.library.app.commontests.book.BookForTestsRepository.*;
26+
import static com.library.app.commontests.user.UserForTestsRepository.admin;
27+
import static com.library.app.commontests.user.UserForTestsRepository.johnDoe;
28+
import static com.library.app.commontests.utils.FileTestNameUtils.getPathFileResponse;
29+
import static com.library.app.commontests.utils.JsonTestUtils.assertJsonMatchesFileContent;
30+
import static org.hamcrest.CoreMatchers.*;
31+
import static org.junit.Assert.assertThat;
32+
33+
/**
34+
* @author gabriel.freitas
35+
*/
36+
@RunWith(Arquillian.class)
37+
public class BookResourceIntTest {
38+
39+
private static final String PATH_RESOURCE = ResourceDefinitions.BOOK.getResourceName();
40+
@ArquillianResource
41+
private URL deploymentUrl;
42+
private ResourceClient resourceClient;
43+
44+
@Deployment
45+
public static WebArchive createDeployment() {
46+
return ArquillianTestUtils.createDeploymentArchive();
47+
}
48+
49+
@Before
50+
public void initTestCase() {
51+
resourceClient = new ResourceClient(deploymentUrl);
52+
53+
resourceClient.resourcePath("DB/").delete();
54+
55+
resourceClient.resourcePath("DB/" + ResourceDefinitions.USER.getResourceName()).postWithContent("");
56+
resourceClient.resourcePath("DB/" + ResourceDefinitions.CATEGORY.getResourceName()).postWithContent("");
57+
resourceClient.resourcePath("DB/" + ResourceDefinitions.AUTHOR.getResourceName()).postWithContent("");
58+
59+
resourceClient.user(admin());
60+
}
61+
62+
@Test
63+
@RunAsClient
64+
public void addValidBookAndFindIt() {
65+
final Long bookId = addBookAndGetId(normalizeDependenciesWithRest(designPatterns()));
66+
findBookAndAssertResponseWithBook(bookId, designPatterns());
67+
}
68+
69+
@Test
70+
@RunAsClient
71+
public void addBookWithNullTitle() {
72+
final Book book = normalizeDependenciesWithRest(cleanCode());
73+
book.setTitle(null);
74+
addBookWithValidationError(book, "bookErrorNullTitle.json");
75+
}
76+
77+
@Test
78+
@RunAsClient
79+
public void addBookWithInexistentCategory() {
80+
final Book book = normalizeDependenciesWithRest(cleanCode());
81+
book.getCategory().setId(999L);
82+
addBookWithValidationError(book, "bookErrorInexistentCategory.json");
83+
}
84+
85+
@Test
86+
@RunAsClient
87+
public void addBookWithInexistentAuthor() {
88+
final Book book = normalizeDependenciesWithRest(cleanCode());
89+
book.getAuthors().get(0).setId(999L);
90+
addBookWithValidationError(book, "bookErrorInexistentAuthor.json");
91+
}
92+
93+
@Test
94+
@RunAsClient
95+
public void updateValidBook() {
96+
final Long bookId = addBookAndGetId(normalizeDependenciesWithRest(designPatterns()));
97+
findBookAndAssertResponseWithBook(bookId, designPatterns());
98+
99+
final Book book = normalizeDependenciesWithRest(designPatterns());
100+
book.setPrice(10D);
101+
book.getAuthors().remove(0);
102+
103+
final Response response = resourceClient.resourcePath(PATH_RESOURCE + "/" + bookId).putWithContent(
104+
getJsonForBook(book));
105+
assertThat(response.getStatus(), is(equalTo(HttpCode.OK.getCode())));
106+
107+
findBookAndAssertResponseWithBook(bookId, book);
108+
}
109+
110+
@Test
111+
@RunAsClient
112+
public void updateBookNotFound() {
113+
final Book book = normalizeDependenciesWithRest(cleanCode());
114+
final Response response = resourceClient.resourcePath(PATH_RESOURCE + "/" + 999).putWithContent(
115+
getJsonForBook(book));
116+
assertThat(response.getStatus(), is(equalTo(HttpCode.NOT_FOUND.getCode())));
117+
}
118+
119+
@Test
120+
@RunAsClient
121+
public void findBookNotFound() {
122+
final Response response = resourceClient.resourcePath(PATH_RESOURCE + "/" + 999).get();
123+
assertThat(response.getStatus(), is(equalTo(HttpCode.NOT_FOUND.getCode())));
124+
}
125+
126+
@Test
127+
@RunAsClient
128+
public void findByFilterPaginatingAndOrderingDescendingByTitle() {
129+
resourceClient.resourcePath("DB/" + PATH_RESOURCE).postWithContent("");
130+
131+
// first page
132+
Response response = resourceClient.resourcePath(PATH_RESOURCE + "?page=0&per_page=3&sort=-title").get();
133+
assertThat(response.getStatus(), is(equalTo(HttpCode.OK.getCode())));
134+
assertResponseContainsTheBooks(response, 5, refactoring(), peaa(), effectiveJava());
135+
136+
// second page
137+
response = resourceClient.resourcePath(PATH_RESOURCE + "?page=1&per_page=3&sort=-title").get();
138+
assertThat(response.getStatus(), is(equalTo(HttpCode.OK.getCode())));
139+
assertResponseContainsTheBooks(response, 5, designPatterns(), cleanCode());
140+
}
141+
142+
@Test
143+
@RunAsClient
144+
public void findByFilterWithNoUser() {
145+
final Response response = resourceClient.user(null).resourcePath(PATH_RESOURCE).get();
146+
assertThat(response.getStatus(), is(equalTo(HttpCode.UNAUTHORIZED.getCode())));
147+
}
148+
149+
@Test
150+
@RunAsClient
151+
public void findByFilterWithUserCustomer() {
152+
final Response response = resourceClient.user(johnDoe()).resourcePath(PATH_RESOURCE).get();
153+
assertThat(response.getStatus(), is(equalTo(HttpCode.OK.getCode())));
154+
}
155+
156+
@Test
157+
@RunAsClient
158+
public void findByIdIdWithUserCustomer() {
159+
final Response response = resourceClient.user(johnDoe()).resourcePath(PATH_RESOURCE + "/999").get();
160+
assertThat(response.getStatus(), is(equalTo(HttpCode.FORBIDDEN.getCode())));
161+
}
162+
163+
private void addBookWithValidationError(final Book bookToAdd, final String responseFileName) {
164+
final Response response = resourceClient.resourcePath(PATH_RESOURCE).postWithContent(getJsonForBook(bookToAdd));
165+
assertThat(response.getStatus(), is(equalTo(HttpCode.VALIDATION_ERROR.getCode())));
166+
assertJsonResponseWithFile(response, responseFileName);
167+
}
168+
169+
private void assertJsonResponseWithFile(final Response response, final String fileName) {
170+
assertJsonMatchesFileContent(response.readEntity(String.class), getPathFileResponse(PATH_RESOURCE, fileName));
171+
}
172+
173+
private void assertResponseContainsTheBooks(final Response response, final int expectedTotalRecords,
174+
final Book... expectedBooks) {
175+
176+
final JsonArray booksList = IntTestUtils.assertJsonHasTheNumberOfElementsAndReturnTheEntries(response,
177+
expectedTotalRecords, expectedBooks.length);
178+
179+
for (int i = 0; i < expectedBooks.length; i++) {
180+
final Book expectedBook = expectedBooks[i];
181+
assertThat(booksList.get(i).getAsJsonObject().get("title").getAsString(),
182+
is(equalTo(expectedBook.getTitle())));
183+
}
184+
}
185+
186+
private Long addBookAndGetId(final Book book) {
187+
return IntTestUtils.addElementWithContentAndGetId(resourceClient, PATH_RESOURCE, getJsonForBook(book));
188+
}
189+
190+
private String getJsonForBook(final Book book) {
191+
final JsonObject bookJson = new JsonObject();
192+
bookJson.addProperty("title", book.getTitle());
193+
bookJson.addProperty("description", book.getDescription());
194+
bookJson.addProperty("categoryId", book.getCategory().getId());
195+
196+
final JsonArray authorsIds = new JsonArray();
197+
for (final Author author : book.getAuthors()) {
198+
authorsIds.add(new JsonPrimitive(author.getId()));
199+
}
200+
bookJson.add("authorsIds", authorsIds);
201+
bookJson.addProperty("price", book.getPrice());
202+
return JsonWriter.writeToString(bookJson);
203+
}
204+
205+
private Book normalizeDependenciesWithRest(final Book book) {
206+
book.getCategory().setId(loadCategoryFromRest(book.getCategory()).getId());
207+
for (final Author author : book.getAuthors()) {
208+
author.setId(loadAuthorFromRest(author).getId());
209+
}
210+
return book;
211+
}
212+
213+
private Category loadCategoryFromRest(final Category category) {
214+
final Response response = resourceClient.resourcePath(
215+
"DB/" + ResourceDefinitions.CATEGORY.getResourceName() + "/" + category.getName()).get();
216+
assertThat(response.getStatus(), is(equalTo(HttpCode.OK.getCode())));
217+
218+
final String bodyResponse = response.readEntity(String.class);
219+
return new Category(JsonTestUtils.getIdFromJson(bodyResponse));
220+
}
221+
222+
private Author loadAuthorFromRest(final Author author) {
223+
final Response response = resourceClient.resourcePath(
224+
"DB/" + ResourceDefinitions.AUTHOR.getResourceName() + "/" + author.getName()).get();
225+
assertThat(response.getStatus(), is(equalTo(HttpCode.OK.getCode())));
226+
227+
final String bodyResponse = response.readEntity(String.class);
228+
return new Author(JsonTestUtils.getIdFromJson(bodyResponse));
229+
}
230+
231+
private void findBookAndAssertResponseWithBook(final Long bookIdToBeFound, final Book expectedBook) {
232+
final String bodyResponse = IntTestUtils.findById(resourceClient, PATH_RESOURCE, bookIdToBeFound);
233+
234+
final JsonObject bookJson = JsonReader.readAsJsonObject(bodyResponse);
235+
assertThat(bookJson.get("id").getAsLong(), is(notNullValue()));
236+
assertThat(bookJson.get("title").getAsString(), is(equalTo(expectedBook.getTitle())));
237+
assertThat(bookJson.get("description").getAsString(), is(equalTo(expectedBook.getDescription())));
238+
assertThat(bookJson.getAsJsonObject("category").get("name").getAsString(), is(equalTo(expectedBook
239+
.getCategory().getName())));
240+
241+
final JsonArray authors = bookJson.getAsJsonArray("authors");
242+
assertThat(authors.size(), is(equalTo(expectedBook.getAuthors().size())));
243+
for (int i = 0; i < authors.size(); i++) {
244+
final String actualAuthorName = authors.get(i).getAsJsonObject().get("name").getAsString();
245+
final String expectedAuthorName = expectedBook.getAuthors().get(i).getName();
246+
assertThat(actualAuthorName, is(equalTo(expectedAuthorName)));
247+
}
248+
249+
assertThat(bookJson.get("price").getAsDouble(), is(equalTo(expectedBook.getPrice())));
250+
}
251+
252+
}
253+

library-int-tests/src/test/java/com/library/app/commontests/author/AuthorResourceDB.java

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,17 @@
11
package com.library.app.commontests.author;
22

3+
import com.library.app.author.model.Author;
4+
import com.library.app.author.model.filter.AuthorFilter;
5+
import com.library.app.author.resource.AuthorJsonConverter;
36
import com.library.app.author.services.AuthorServices;
7+
import com.library.app.common.json.JsonWriter;
8+
import com.library.app.common.model.HttpCode;
9+
import com.library.app.common.model.PaginatedData;
410

511
import javax.inject.Inject;
6-
import javax.ws.rs.POST;
7-
import javax.ws.rs.Path;
8-
import javax.ws.rs.Produces;
12+
import javax.ws.rs.*;
913
import javax.ws.rs.core.MediaType;
14+
import javax.ws.rs.core.Response;
1015

1116
import static com.library.app.commontests.author.AuthorForTestsRepository.allAuthors;
1217

@@ -20,8 +25,26 @@ public class AuthorResourceDB {
2025
@Inject
2126
private AuthorServices authorServices;
2227

28+
@Inject
29+
private AuthorJsonConverter authorJsonConverter;
30+
2331
@POST
2432
public void addAll() {
2533
allAuthors().forEach(authorServices::add);
2634
}
35+
36+
@GET
37+
@Path("/{name}")
38+
public Response findByName(@PathParam("name") final String name) {
39+
final AuthorFilter authorFilter = new AuthorFilter();
40+
authorFilter.setName(name);
41+
42+
final PaginatedData<Author> authors = authorServices.findByFilter(authorFilter);
43+
if (authors.getNumberOfRows() > 0) {
44+
final Author author = authors.getRow(0);
45+
final String authorAsJson = JsonWriter.writeToString(authorJsonConverter.convertToJsonElement(author));
46+
return Response.status(HttpCode.OK.getCode()).entity(authorAsJson).build();
47+
}
48+
return Response.status(HttpCode.NOT_FOUND.getCode()).build();
49+
}
2750
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.library.app.commontests.book;
2+
3+
import static com.library.app.commontests.book.BookForTestsRepository.*;
4+
5+
import javax.inject.Inject;
6+
import javax.persistence.EntityManager;
7+
import javax.persistence.PersistenceContext;
8+
import javax.ws.rs.POST;
9+
import javax.ws.rs.Path;
10+
import javax.ws.rs.Produces;
11+
import javax.ws.rs.core.MediaType;
12+
13+
import com.library.app.book.services.BookServices;
14+
15+
/**
16+
* @author gabriel.freitas
17+
*/
18+
@Path("/DB/books")
19+
@Produces(MediaType.APPLICATION_JSON)
20+
public class BookResourceDB {
21+
22+
@PersistenceContext
23+
private EntityManager em;
24+
25+
@Inject
26+
private BookServices bookServices;
27+
28+
@POST
29+
public void addAll() {
30+
allBooks().forEach((book) -> bookServices.add(normalizeDependencies(book, em)));
31+
}
32+
33+
}

library-int-tests/src/test/java/com/library/app/commontests/category/CategoryResourceDB.java

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,17 @@
11
package com.library.app.commontests.category;
22

3+
import com.library.app.category.model.Category;
4+
import com.library.app.category.resource.CategoryJsonConverter;
35
import com.library.app.category.services.CategoryServices;
6+
import com.library.app.common.json.JsonWriter;
7+
import com.library.app.common.model.HttpCode;
48

59
import javax.inject.Inject;
6-
import javax.ws.rs.POST;
7-
import javax.ws.rs.Path;
8-
import javax.ws.rs.Produces;
10+
import javax.ws.rs.*;
911
import javax.ws.rs.core.MediaType;
12+
import javax.ws.rs.core.Response;
13+
import java.util.List;
14+
import java.util.Optional;
1015

1116
import static com.library.app.commontests.category.CategoryForTestsRepository.allCategories;
1217

@@ -20,9 +25,26 @@ public class CategoryResourceDB {
2025
@Inject
2126
private CategoryServices categoryServices;
2227

28+
@Inject
29+
private CategoryJsonConverter categoryJsonConverter;
30+
2331
@POST
2432
public void addAll() {
2533
allCategories().forEach(categoryServices::add);
2634
}
2735

36+
@GET
37+
@Path("/{name}")
38+
public Response findByName(@PathParam("name") final String name) {
39+
final List<Category> categories = categoryServices.findAll();
40+
final Optional<Category> category = categories.stream().filter(c -> c.getName().equals(name)).findFirst();
41+
if (category.isPresent()) {
42+
final String categoryAsJson = JsonWriter
43+
.writeToString(categoryJsonConverter.convertToJsonElement(category.get()));
44+
return Response.status(HttpCode.OK.getCode()).entity(categoryAsJson).build();
45+
} else {
46+
return Response.status(HttpCode.NOT_FOUND.getCode()).build();
47+
}
48+
}
49+
2850
}

0 commit comments

Comments
 (0)