Skip to content

Commit 46b08a0

Browse files
author
daniel.oliveira
committed
feat: Adicionado cobertura de código Jacoco e virtualLibraryAPI.
1 parent 00fc587 commit 46b08a0

18 files changed

+301
-50
lines changed

.github/workflows/maven.yml

+3-5
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,5 @@
11
name: virtualLibraryAPI
22

3-
env:
4-
MAVEN_OPT: -q
5-
63
on:
74
# Acione o fluxo de trabalho na solicitação push ou pull,
85
# mas apenas para a ramificação principal.
@@ -38,7 +35,8 @@ jobs:
3835
architecture: 'x64'
3936
- name: Test with Maven
4037
run: |
41-
mvn ${MAVEN_OPT} test -P test
38+
mvn -q -am clean test jacoco:report
39+
bash <(curl -s https://codecov.io/bash) -t ${{ secrets.CODECOV_TOKEN }}
4240
Build:
4341
needs: Test
4442
runs-on: ubuntu-latest
@@ -51,4 +49,4 @@ jobs:
5149
architecture: 'x64'
5250
- name: Build with Maven
5351
run: |
54-
mvn ${MAVEN_OPT} clean package install
52+
mvn -q clean package install

src/main/java/br/com/virtuallibrary/commons/controllers/BaseController.java

+5-2
Original file line numberDiff line numberDiff line change
@@ -99,8 +99,11 @@ public ResponseEntity<E> update(@RequestBody @Valid E object, @PathVariable ID i
9999
@ApiResponse(code = 404, message = "Registro não encontrado."),
100100
@ApiResponse(code = 500, message = "Erro interno do servidor") })
101101
public ResponseEntity<E> update(@RequestBody Map<String, String> updates, @PathVariable ID id) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
102-
return service.update(updates, id).map(entity -> ResponseEntity.ok().body(entity))
103-
.orElse(ResponseEntity.notFound().build());
102+
try {
103+
return service.update(updates, id).map(entity -> ResponseEntity.ok().body(entity)).get();
104+
} catch (Exception e) {
105+
return ResponseEntity.notFound().build();
106+
}
104107
}
105108

106109
}

src/main/java/br/com/virtuallibrary/commons/entities/BaseAudit.java

-2
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,13 @@
99
import lombok.Data;
1010
import lombok.EqualsAndHashCode;
1111
import lombok.NoArgsConstructor;
12-
import lombok.ToString;
1312
import lombok.experimental.SuperBuilder;
1413

1514
@Document
1615
@NoArgsConstructor
1716
@AllArgsConstructor
1817
@Data()
1918
@EqualsAndHashCode(callSuper = true)
20-
@ToString(callSuper = true)
2119
@SuperBuilder
2220
public abstract class BaseAudit extends BaseEntity {
2321

src/main/java/br/com/virtuallibrary/commons/entities/BaseEntity.java

-2
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,13 @@
1010
import lombok.Data;
1111
import lombok.EqualsAndHashCode;
1212
import lombok.NoArgsConstructor;
13-
import lombok.ToString;
1413
import lombok.experimental.SuperBuilder;
1514

1615
@Document
1716
@NoArgsConstructor
1817
@AllArgsConstructor
1918
@Data
2019
@EqualsAndHashCode(of = { "id" })
21-
@ToString(of = { "id" })
2220
@SuperBuilder
2321
public abstract class BaseEntity implements Serializable {
2422

src/main/java/br/com/virtuallibrary/commons/services/BaseService.java

-2
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,4 @@ public interface BaseService<E extends BaseEntity, ID extends Serializable, R ex
2828

2929
UserDetails getUser();
3030

31-
Optional<UserDetails> getPessoaLogada();
32-
3331
}

src/main/java/br/com/virtuallibrary/commons/services/BaseServiceImpl.java

+8-15
Original file line numberDiff line numberDiff line change
@@ -48,17 +48,6 @@ public UserDetails getUser() {
4848
}
4949
}
5050

51-
@Override
52-
public Optional<UserDetails> getPessoaLogada() {
53-
UserDetails userDetails = getUser();
54-
if (userDetails.getUsername().equals(ANONYMOUS)) {
55-
return Optional.empty();
56-
} else {
57-
// TODO: Obter o usuário logado.
58-
return Optional.empty();
59-
}
60-
}
61-
6251
public BaseServiceImpl(R repository) {
6352
this.repository = repository;
6453
this.entityClass = GenericsUtils.getGenericsInfo(this).getType(0);
@@ -118,7 +107,12 @@ public Optional<E> update(Map<String, String> updates, ID id)
118107
}
119108
boolean accessible = declaredField.canAccess(entity);
120109
declaredField.setAccessible(true);
121-
declaredField.set(entity, updates.get(fieldUpdate));
110+
// TODO: Refatorar.
111+
if (declaredField.getType().equals(int.class)) {
112+
declaredField.set(entity, Integer.valueOf(updates.get(fieldUpdate)));
113+
} else {
114+
declaredField.set(entity, updates.get(fieldUpdate));
115+
}
122116
declaredField.setAccessible(accessible);
123117
}
124118
checkAuditedEntity(entity);
@@ -168,16 +162,15 @@ private void checkAuditedEntity(E entity) {
168162
if (entity instanceof BaseAudit) {
169163
BaseAudit auditedEntity = (BaseAudit) entity;
170164

171-
// Garantir que não vieram informações do front-end.
172165
auditedEntity.setCreator(null);
173166
auditedEntity.setCreatedAt(null);
174167
auditedEntity.setUpdater(null);
175168
auditedEntity.setUpdatedAt(null);
176169

177170
Date date = new Date();
178171
String login = ANONYMOUS;
179-
if (getPessoaLogada().isPresent()) {
180-
// TODO: Adicionar o login do usuário.
172+
if (getUser() != null) {
173+
login = getUser().getUsername();
181174
}
182175

183176
if (auditedEntity.getId() == null) {

src/test/java/br/com/virtuallibrary/SuiteTest.java

+3-1
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,15 @@
66
import org.springframework.test.context.ActiveProfiles;
77

88
import br.com.virtuallibrary.suites.ControllersSuiteTest;
9+
import br.com.virtuallibrary.suites.OtherSuiteTest;
910
import br.com.virtuallibrary.suites.ServicesSuiteTest;
1011

1112
@SpringBootTest
1213
@RunWith(Suite.class)
1314
@Suite.SuiteClasses({
1415
ServicesSuiteTest.class,
15-
ControllersSuiteTest.class
16+
ControllersSuiteTest.class,
17+
OtherSuiteTest.class
1618
})
1719
@ActiveProfiles("test")
1820
public class SuiteTest {

src/test/java/br/com/virtuallibrary/controllers/BookControllerTest.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ public void testbyUpdateFields() throws Exception {
161161
Map<String, String> fields = new TreeMap<String, String>();
162162
fields.put("title", "newTitle");
163163
fields.put("author", "newAuthor");
164-
String json = putHttpServletResponse(String.format("%s/%s", API, ID), jsonEntityFields.write(fields).getJson(), status().isOk()).getContentAsString();
164+
String json = patchHttpServletResponse(String.format("%s/%s", API, ID), jsonEntityFields.write(fields).getJson(), status().isOk()).getContentAsString();
165165
ObjectMapper mapper = new ObjectMapper();
166166
Book obj = mapper.readValue(json, Book.class);
167167
assertEquals(obj, ENTITY_01);
@@ -173,7 +173,7 @@ public void testbyUpdateFieldNotFound() throws Exception {
173173
Map<String, String> fields = new TreeMap<String, String>();
174174
fields.put("asdas", "newTitle");
175175
fields.put("asdasd", "newAuthor");
176-
String json = putHttpServletResponse(String.format("%s/%s", API, ID), jsonEntityFields.write(fields).getJson(), status().isBadRequest()).getContentAsString();
176+
String json = patchHttpServletResponse(String.format("%s/%s", API, ID), jsonEntityFields.write(fields).getJson(), status().isNotFound()).getContentAsString();
177177
assertEquals(Constants.BLANK, json);
178178
}
179179

src/test/java/br/com/virtuallibrary/controllers/RatingControllerTest.java

+11-6
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ public class RatingControllerTest extends TestBaseController {
4040
private final String ID = "5dc4c9734e9b1214ed7a9e8a";
4141
private Rating ENTITY_01;
4242
private Rating ENTITY_02;
43+
private List<Rating> list;
4344

4445
@MockBean
4546
private RatingRepository repository;
@@ -60,13 +61,14 @@ public void setUp() {
6061
ENTITY_01 = Rating.builder().bookId("kjasdh6753hsf27634").stars(3).build();
6162
ENTITY_02 = Rating.builder().bookId("asgd5555423gsdjhkk").stars(4).build();
6263

63-
List<Rating> list = new ArrayList<>();
64+
list = new ArrayList<>();
6465
list.add(ENTITY_01);
6566
list.add(ENTITY_02);
6667

6768
when(repository.save(ArgumentMatchers.any())).thenReturn(ENTITY_01);
6869
when(repository.findById(anyString())).thenReturn(Optional.of(ENTITY_01));
6970
when(repository.findAll()).thenReturn(list);
71+
when(repository.findByBookId(ID)).thenReturn(list);
7072
}
7173

7274
@Test
@@ -78,12 +80,15 @@ public void testContexLoads() {
7880
@Test
7981
@WithMockUser(username=ADMIN,roles={USER_ROLE,ADMIN_ROLE})
8082
public void testGetAll() throws Exception {
81-
List<Rating> list = new ArrayList<>();
82-
list.add(ENTITY_01);
83-
list.add(ENTITY_02);
8483
assertEquals(getHttpServletResponse(API, status().isOk()).getContentAsString(), jsonList.write(list).getJson());
8584
}
8685

86+
@Test
87+
@WithMockUser(username=ADMIN,roles={USER_ROLE,ADMIN_ROLE})
88+
public void testGetAllBookId() throws Exception {
89+
assertEquals(getHttpServletResponse(String.format("%s?bookId=%s", API, ID), status().isOk()).getContentAsString(), jsonList.write(list).getJson());
90+
}
91+
8792
@Test
8893
@WithMockUser(username=ADMIN,roles={USER_ROLE,ADMIN_ROLE})
8994
public void testbyId() throws Exception {
@@ -161,7 +166,7 @@ public void testbyUpdateFields() throws Exception {
161166
Map<String, String> fields = new TreeMap<String, String>();
162167
fields.put("bookId", "kasdlkas63573sjd");
163168
fields.put("stars", "3");
164-
String json = putHttpServletResponse(String.format("%s/%s", API, ID), jsonEntityFields.write(fields).getJson(), status().isOk()).getContentAsString();
169+
String json = patchHttpServletResponse(String.format("%s/%s", API, ID), jsonEntityFields.write(fields).getJson(), status().isOk()).getContentAsString();
165170
ObjectMapper mapper = new ObjectMapper();
166171
Rating obj = mapper.readValue(json, Rating.class);
167172
assertEquals(obj, ENTITY_01);
@@ -173,7 +178,7 @@ public void testbyUpdateFieldNotFound() throws Exception {
173178
Map<String, String> fields = new TreeMap<String, String>();
174179
fields.put("asdas", "newEqwe");
175180
fields.put("asdasd", "newTWER");
176-
String json = putHttpServletResponse(String.format("%s/%s", API, ID), jsonEntityFields.write(fields).getJson(), status().isBadRequest()).getContentAsString();
181+
String json = patchHttpServletResponse(String.format("%s/%s", API, ID), jsonEntityFields.write(fields).getJson(), status().isNotFound()).getContentAsString();
177182
assertEquals(Constants.BLANK, json);
178183
}
179184

src/test/java/br/com/virtuallibrary/controllers/TestBaseController.java

+14-5
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
55
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
66
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
7+
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch;
78
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
89

910
import java.util.Map;
@@ -20,16 +21,16 @@
2021
import br.com.virtuallibrary.commons.Constants;
2122

2223
public abstract class TestBaseController {
23-
24+
2425
protected static final String ADMIN_ROLE = "ADMIN";
2526
protected static final String USER_ROLE = "USER";
2627
protected static final String ADMIN = "admin";
27-
28+
2829
protected JacksonTester<Map<String, String>> jsonEntityFields;
29-
30+
3031
@Autowired
3132
private MockMvc mockMvc;
32-
33+
3334
protected MockHttpServletResponse getHttpServletResponse(String url, ResultMatcher status) throws Exception {
3435
return httpServletResponse(HttpMethod.GET, url, null, status);
3536
}
@@ -48,7 +49,13 @@ protected MockHttpServletResponse postHttpServletResponse(String url, String jso
4849
return httpServletResponse(HttpMethod.POST, url, json, status);
4950
}
5051

51-
protected MockHttpServletResponse httpServletResponse(HttpMethod httpMethod, String url, String json, ResultMatcher status) throws Exception {
52+
protected MockHttpServletResponse patchHttpServletResponse(String url, String json, ResultMatcher status)
53+
throws Exception {
54+
return httpServletResponse(HttpMethod.PATCH, url, json, status);
55+
}
56+
57+
protected MockHttpServletResponse httpServletResponse(HttpMethod httpMethod, String url, String json,
58+
ResultMatcher status) throws Exception {
5259
MockHttpServletRequestBuilder requestBuilder = null;
5360

5461
if (HttpMethod.POST.equals(httpMethod)) {
@@ -59,6 +66,8 @@ protected MockHttpServletResponse httpServletResponse(HttpMethod httpMethod, Str
5966
requestBuilder = put(url).contentType(Constants.APPLICATION_JSON_UTF_8);
6067
} else if (HttpMethod.DELETE.equals(httpMethod)) {
6168
requestBuilder = delete(url).contentType(Constants.APPLICATION_JSON_UTF_8);
69+
} else if (HttpMethod.PATCH.equals(httpMethod)) {
70+
requestBuilder = patch(url).contentType(Constants.APPLICATION_JSON_UTF_8);
6271
}
6372

6473
if (json != null) {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package br.com.virtuallibrary.othertests;
2+
3+
import static org.junit.Assert.assertNotNull;
4+
import static org.junit.Assert.assertTrue;
5+
6+
import java.util.Date;
7+
8+
import org.junit.Before;
9+
import org.junit.Test;
10+
import org.junit.runner.RunWith;
11+
import org.springframework.test.context.junit4.SpringRunner;
12+
13+
import br.com.virtuallibrary.entity.Book;
14+
15+
@RunWith(SpringRunner.class)
16+
public class BookTest {
17+
18+
private Book entity;
19+
20+
@Before
21+
public void setUp() throws Exception {
22+
entity = Book.builder()
23+
.author("XST")
24+
.title("KJASD")
25+
.id("HSJD")
26+
.createdAt(new Date())
27+
.creator("user")
28+
.updatedAt(new Date())
29+
.updater("user")
30+
.build();
31+
}
32+
33+
@Test
34+
public void testHashCode() {
35+
assertNotNull(entity.hashCode());
36+
}
37+
38+
@Test
39+
public void testEqualsObjectNull() {
40+
assertTrue(!entity.equals(null));
41+
}
42+
43+
@Test
44+
public void testEqualsObjectNew() {
45+
assertTrue(!entity.equals(new Object()));
46+
}
47+
48+
@Test
49+
public void testEqualsObjectBook() {
50+
assertTrue(entity.equals(entity));
51+
}
52+
53+
@Test
54+
public void testEqualsNewBook() {
55+
assertTrue(!entity.equals(Book.builder().build()));
56+
}
57+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package br.com.virtuallibrary.othertests;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import org.junit.Before;
6+
import org.junit.Test;
7+
import org.junit.runner.RunWith;
8+
import org.springframework.beans.factory.annotation.Autowired;
9+
import org.springframework.boot.test.context.SpringBootTest;
10+
import org.springframework.test.context.junit4.SpringRunner;
11+
12+
import br.com.virtuallibrary.commons.utils.GenericsInfo;
13+
import br.com.virtuallibrary.commons.utils.GenericsUtils;
14+
import br.com.virtuallibrary.entity.Book;
15+
import br.com.virtuallibrary.repositories.BookRepository;
16+
import br.com.virtuallibrary.services.BookService;
17+
18+
@SpringBootTest
19+
@RunWith(SpringRunner.class)
20+
public class GenericsInfoTest {
21+
22+
@Autowired
23+
private BookService service;
24+
private GenericsInfo genericsInfo;
25+
26+
@Before
27+
public void setUp() throws Exception {
28+
genericsInfo = GenericsUtils.getGenericsInfo(service);
29+
}
30+
31+
@Test
32+
public void testGetTypeInt() {
33+
assertEquals(genericsInfo.getType(0), Book.class);
34+
}
35+
36+
@Test
37+
public void testGetType() {
38+
assertEquals(genericsInfo.getType(), Book.class);
39+
}
40+
41+
@Test
42+
public void testGetTypesBook() {
43+
assertEquals(genericsInfo.getTypes()[0], Book.class);
44+
}
45+
46+
@Test
47+
public void testGetTypesString() {
48+
assertEquals(genericsInfo.getTypes()[1], String.class);
49+
}
50+
51+
@Test
52+
public void testGetTypesBookRepository() {
53+
assertEquals(genericsInfo.getTypes()[2], BookRepository.class);
54+
}
55+
56+
}

0 commit comments

Comments
 (0)