From 71773a6471279e978d069be81bb784fe099b2ccb Mon Sep 17 00:00:00 2001 From: Raja Kolli Date: Wed, 22 Nov 2023 17:11:45 +0000 Subject: [PATCH] clean unused endpoints --- .../learning/awslambda/entities/Actor.java | 2 +- .../exception/ActorNotFoundException.java | 4 +- .../awslambda/mapper/ActorMapper.java | 13 +- .../model/query/FindActorsQuery.java | 3 - .../awslambda/model/request/ActorRequest.java | 2 +- .../model/response/ActorResponse.java | 2 +- .../awslambda/model/response/PagedResult.java | 27 --- .../repositories/ActorRepository.java | 5 +- .../awslambda/services/ActorService.java | 60 +------ .../web/controllers/ActorController.java | 63 +------ .../migration/02-create_actors_table.xml | 2 +- .../awslambda/SchemaValidationTest.java | 2 +- .../awslambda/SqsListenerIntegrationTest.java | 60 ------- .../awslambda/common/ContainersConfig.java | 4 +- .../awslambda/services/ActorServiceTest.java | 67 ------- .../web/controllers/ActorControllerIT.java | 89 +-------- .../web/controllers/ActorControllerTest.java | 169 +----------------- 17 files changed, 30 insertions(+), 544 deletions(-) delete mode 100644 aws-lambda-project/src/main/java/com/learning/awslambda/model/query/FindActorsQuery.java delete mode 100644 aws-lambda-project/src/main/java/com/learning/awslambda/model/response/PagedResult.java delete mode 100644 aws-lambda-project/src/test/java/com/learning/awslambda/SqsListenerIntegrationTest.java delete mode 100644 aws-lambda-project/src/test/java/com/learning/awslambda/services/ActorServiceTest.java diff --git a/aws-lambda-project/src/main/java/com/learning/awslambda/entities/Actor.java b/aws-lambda-project/src/main/java/com/learning/awslambda/entities/Actor.java index 49075036..8618d99d 100644 --- a/aws-lambda-project/src/main/java/com/learning/awslambda/entities/Actor.java +++ b/aws-lambda-project/src/main/java/com/learning/awslambda/entities/Actor.java @@ -26,7 +26,7 @@ public class Actor { private Long id; @Column(nullable = false) - private String text; + private String name; @Override public boolean equals(Object o) { diff --git a/aws-lambda-project/src/main/java/com/learning/awslambda/exception/ActorNotFoundException.java b/aws-lambda-project/src/main/java/com/learning/awslambda/exception/ActorNotFoundException.java index 7ae33a9c..405762d4 100644 --- a/aws-lambda-project/src/main/java/com/learning/awslambda/exception/ActorNotFoundException.java +++ b/aws-lambda-project/src/main/java/com/learning/awslambda/exception/ActorNotFoundException.java @@ -2,7 +2,7 @@ public class ActorNotFoundException extends ResourceNotFoundException { - public ActorNotFoundException(Long id) { - super("Actor with Id '%d' not found".formatted(id)); + public ActorNotFoundException(String name) { + super("Actor with Name '%s' not found".formatted(name)); } } diff --git a/aws-lambda-project/src/main/java/com/learning/awslambda/mapper/ActorMapper.java b/aws-lambda-project/src/main/java/com/learning/awslambda/mapper/ActorMapper.java index 56387f42..d2cc3a50 100644 --- a/aws-lambda-project/src/main/java/com/learning/awslambda/mapper/ActorMapper.java +++ b/aws-lambda-project/src/main/java/com/learning/awslambda/mapper/ActorMapper.java @@ -3,7 +3,6 @@ import com.learning.awslambda.entities.Actor; import com.learning.awslambda.model.request.ActorRequest; import com.learning.awslambda.model.response.ActorResponse; -import java.util.List; import org.springframework.stereotype.Service; @Service @@ -11,19 +10,11 @@ public class ActorMapper { public Actor toEntity(ActorRequest actorRequest) { Actor actor = new Actor(); - actor.setText(actorRequest.text()); + actor.setName(actorRequest.name()); return actor; } - public void mapActorWithRequest(Actor actor, ActorRequest actorRequest) { - actor.setText(actorRequest.text()); - } - public ActorResponse toResponse(Actor actor) { - return new ActorResponse(actor.getId(), actor.getText()); - } - - public List toResponseList(List actorList) { - return actorList.stream().map(this::toResponse).toList(); + return new ActorResponse(actor.getId(), actor.getName()); } } diff --git a/aws-lambda-project/src/main/java/com/learning/awslambda/model/query/FindActorsQuery.java b/aws-lambda-project/src/main/java/com/learning/awslambda/model/query/FindActorsQuery.java deleted file mode 100644 index dd8df797..00000000 --- a/aws-lambda-project/src/main/java/com/learning/awslambda/model/query/FindActorsQuery.java +++ /dev/null @@ -1,3 +0,0 @@ -package com.learning.awslambda.model.query; - -public record FindActorsQuery(int pageNo, int pageSize, String sortBy, String sortDir) {} diff --git a/aws-lambda-project/src/main/java/com/learning/awslambda/model/request/ActorRequest.java b/aws-lambda-project/src/main/java/com/learning/awslambda/model/request/ActorRequest.java index 1910afc0..c2e2857f 100644 --- a/aws-lambda-project/src/main/java/com/learning/awslambda/model/request/ActorRequest.java +++ b/aws-lambda-project/src/main/java/com/learning/awslambda/model/request/ActorRequest.java @@ -2,4 +2,4 @@ import jakarta.validation.constraints.NotEmpty; -public record ActorRequest(@NotEmpty(message = "Text cannot be empty") String text) {} +public record ActorRequest(@NotEmpty(message = "Name cannot be empty") String name) {} diff --git a/aws-lambda-project/src/main/java/com/learning/awslambda/model/response/ActorResponse.java b/aws-lambda-project/src/main/java/com/learning/awslambda/model/response/ActorResponse.java index 31771b8e..2a19330c 100644 --- a/aws-lambda-project/src/main/java/com/learning/awslambda/model/response/ActorResponse.java +++ b/aws-lambda-project/src/main/java/com/learning/awslambda/model/response/ActorResponse.java @@ -1,3 +1,3 @@ package com.learning.awslambda.model.response; -public record ActorResponse(Long id, String text) {} +public record ActorResponse(Long id, String name) {} diff --git a/aws-lambda-project/src/main/java/com/learning/awslambda/model/response/PagedResult.java b/aws-lambda-project/src/main/java/com/learning/awslambda/model/response/PagedResult.java deleted file mode 100644 index 37f5c942..00000000 --- a/aws-lambda-project/src/main/java/com/learning/awslambda/model/response/PagedResult.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.learning.awslambda.model.response; - -import com.fasterxml.jackson.annotation.JsonProperty; -import java.util.List; -import org.springframework.data.domain.Page; - -public record PagedResult( - List data, - long totalElements, - int pageNumber, - int totalPages, - @JsonProperty("isFirst") boolean isFirst, - @JsonProperty("isLast") boolean isLast, - @JsonProperty("hasNext") boolean hasNext, - @JsonProperty("hasPrevious") boolean hasPrevious) { - public PagedResult(Page page, List data) { - this( - data, - page.getTotalElements(), - page.getNumber() + 1, - page.getTotalPages(), - page.isFirst(), - page.isLast(), - page.hasNext(), - page.hasPrevious()); - } -} diff --git a/aws-lambda-project/src/main/java/com/learning/awslambda/repositories/ActorRepository.java b/aws-lambda-project/src/main/java/com/learning/awslambda/repositories/ActorRepository.java index 578714a3..0504943f 100644 --- a/aws-lambda-project/src/main/java/com/learning/awslambda/repositories/ActorRepository.java +++ b/aws-lambda-project/src/main/java/com/learning/awslambda/repositories/ActorRepository.java @@ -1,6 +1,9 @@ package com.learning.awslambda.repositories; import com.learning.awslambda.entities.Actor; +import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; -public interface ActorRepository extends JpaRepository {} +public interface ActorRepository extends JpaRepository { + Optional findByNameLike(String name); +} diff --git a/aws-lambda-project/src/main/java/com/learning/awslambda/services/ActorService.java b/aws-lambda-project/src/main/java/com/learning/awslambda/services/ActorService.java index 577ec9f2..72faab0c 100644 --- a/aws-lambda-project/src/main/java/com/learning/awslambda/services/ActorService.java +++ b/aws-lambda-project/src/main/java/com/learning/awslambda/services/ActorService.java @@ -1,20 +1,10 @@ package com.learning.awslambda.services; -import com.learning.awslambda.entities.Actor; -import com.learning.awslambda.exception.ActorNotFoundException; import com.learning.awslambda.mapper.ActorMapper; -import com.learning.awslambda.model.query.FindActorsQuery; -import com.learning.awslambda.model.request.ActorRequest; import com.learning.awslambda.model.response.ActorResponse; -import com.learning.awslambda.model.response.PagedResult; import com.learning.awslambda.repositories.ActorRepository; -import java.util.List; import java.util.Optional; import lombok.RequiredArgsConstructor; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -26,53 +16,7 @@ public class ActorService { private final ActorRepository actorRepository; private final ActorMapper actorMapper; - public PagedResult findAllActors(FindActorsQuery findActorsQuery) { - - // create Pageable instance - Pageable pageable = createPageable(findActorsQuery); - - Page actorsPage = actorRepository.findAll(pageable); - - List actorResponseList = actorMapper.toResponseList(actorsPage.getContent()); - - return new PagedResult<>(actorsPage, actorResponseList); - } - - private Pageable createPageable(FindActorsQuery findActorsQuery) { - int pageNo = Math.max(findActorsQuery.pageNo() - 1, 0); - Sort sort = Sort.by( - findActorsQuery.sortDir().equalsIgnoreCase(Sort.Direction.ASC.name()) - ? Sort.Order.asc(findActorsQuery.sortBy()) - : Sort.Order.desc(findActorsQuery.sortBy())); - return PageRequest.of(pageNo, findActorsQuery.pageSize(), sort); - } - - public Optional findActorById(Long id) { - return actorRepository.findById(id).map(actorMapper::toResponse); - } - - @Transactional - public ActorResponse saveActor(ActorRequest actorRequest) { - Actor actor = actorMapper.toEntity(actorRequest); - Actor savedActor = actorRepository.save(actor); - return actorMapper.toResponse(savedActor); - } - - @Transactional - public ActorResponse updateActor(Long id, ActorRequest actorRequest) { - Actor actor = actorRepository.findById(id).orElseThrow(() -> new ActorNotFoundException(id)); - - // Update the actor object with data from actorRequest - actorMapper.mapActorWithRequest(actor, actorRequest); - - // Save the updated actor object - Actor updatedActor = actorRepository.save(actor); - - return actorMapper.toResponse(updatedActor); - } - - @Transactional - public void deleteActorById(Long id) { - actorRepository.deleteById(id); + public Optional findActorByName(String name) { + return actorRepository.findByNameLike(name).map(actorMapper::toResponse); } } diff --git a/aws-lambda-project/src/main/java/com/learning/awslambda/web/controllers/ActorController.java b/aws-lambda-project/src/main/java/com/learning/awslambda/web/controllers/ActorController.java index 0123671d..aa200c85 100644 --- a/aws-lambda-project/src/main/java/com/learning/awslambda/web/controllers/ActorController.java +++ b/aws-lambda-project/src/main/java/com/learning/awslambda/web/controllers/ActorController.java @@ -1,80 +1,27 @@ package com.learning.awslambda.web.controllers; import com.learning.awslambda.exception.ActorNotFoundException; -import com.learning.awslambda.model.query.FindActorsQuery; -import com.learning.awslambda.model.request.ActorRequest; import com.learning.awslambda.model.response.ActorResponse; -import com.learning.awslambda.model.response.PagedResult; import com.learning.awslambda.services.ActorService; -import com.learning.awslambda.utils.AppConstants; -import jakarta.validation.Valid; -import java.net.URI; import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; import org.springframework.http.ResponseEntity; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.servlet.support.ServletUriComponentsBuilder; @RestController @RequestMapping("/api/actors") -@Slf4j @RequiredArgsConstructor public class ActorController { private final ActorService actorService; - @GetMapping - public PagedResult getAllActors( - @RequestParam(value = "pageNo", defaultValue = AppConstants.DEFAULT_PAGE_NUMBER, required = false) - int pageNo, - @RequestParam(value = "pageSize", defaultValue = AppConstants.DEFAULT_PAGE_SIZE, required = false) - int pageSize, - @RequestParam(value = "sortBy", defaultValue = AppConstants.DEFAULT_SORT_BY, required = false) - String sortBy, - @RequestParam(value = "sortDir", defaultValue = AppConstants.DEFAULT_SORT_DIRECTION, required = false) - String sortDir) { - FindActorsQuery findActorsQuery = new FindActorsQuery(pageNo, pageSize, sortBy, sortDir); - return actorService.findAllActors(findActorsQuery); - } - - @GetMapping("/{id}") - public ResponseEntity getActorById(@PathVariable Long id) { - return actorService.findActorById(id).map(ResponseEntity::ok).orElseThrow(() -> new ActorNotFoundException(id)); - } - - @PostMapping - public ResponseEntity createActor(@RequestBody @Validated ActorRequest actorRequest) { - ActorResponse response = actorService.saveActor(actorRequest); - URI location = ServletUriComponentsBuilder.fromCurrentRequest() - .path("/api/actors/{id}") - .buildAndExpand(response.id()) - .toUri(); - return ResponseEntity.created(location).body(response); - } - - @PutMapping("/{id}") - public ResponseEntity updateActor( - @PathVariable Long id, @RequestBody @Valid ActorRequest actorRequest) { - return ResponseEntity.ok(actorService.updateActor(id, actorRequest)); - } - - @DeleteMapping("/{id}") - public ResponseEntity deleteActor(@PathVariable Long id) { + @GetMapping("/{name}") + public ResponseEntity getActorByName(@PathVariable String name) { return actorService - .findActorById(id) - .map(actor -> { - actorService.deleteActorById(id); - return ResponseEntity.ok(actor); - }) - .orElseThrow(() -> new ActorNotFoundException(id)); + .findActorByName(name) + .map(ResponseEntity::ok) + .orElseThrow(() -> new ActorNotFoundException(name)); } } diff --git a/aws-lambda-project/src/main/resources/db/changelog/migration/02-create_actors_table.xml b/aws-lambda-project/src/main/resources/db/changelog/migration/02-create_actors_table.xml index 565644f9..a6629d36 100644 --- a/aws-lambda-project/src/main/resources/db/changelog/migration/02-create_actors_table.xml +++ b/aws-lambda-project/src/main/resources/db/changelog/migration/02-create_actors_table.xml @@ -19,7 +19,7 @@ - + diff --git a/aws-lambda-project/src/test/java/com/learning/awslambda/SchemaValidationTest.java b/aws-lambda-project/src/test/java/com/learning/awslambda/SchemaValidationTest.java index 762f5098..6e56cc2e 100644 --- a/aws-lambda-project/src/test/java/com/learning/awslambda/SchemaValidationTest.java +++ b/aws-lambda-project/src/test/java/com/learning/awslambda/SchemaValidationTest.java @@ -7,7 +7,7 @@ properties = { "spring.jpa.hibernate.ddl-auto=validate", "spring.test.database.replace=none", - "spring.datasource.url=jdbc:tc:postgresql:16.0-alpine:///db" + "spring.datasource.url=jdbc:tc:postgresql:16.1-alpine:///db" }) class SchemaValidationTest { diff --git a/aws-lambda-project/src/test/java/com/learning/awslambda/SqsListenerIntegrationTest.java b/aws-lambda-project/src/test/java/com/learning/awslambda/SqsListenerIntegrationTest.java deleted file mode 100644 index 096f5065..00000000 --- a/aws-lambda-project/src/test/java/com/learning/awslambda/SqsListenerIntegrationTest.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.learning.awslambda; - -import static org.assertj.core.api.Assertions.assertThat; - -import com.learning.awslambda.common.AbstractIntegrationTest; -import java.time.Duration; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import lombok.extern.slf4j.Slf4j; -import org.awaitility.Awaitility; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import software.amazon.awssdk.services.sqs.SqsAsyncClient; -import software.amazon.awssdk.services.sqs.model.CreateQueueRequest; -import software.amazon.awssdk.services.sqs.model.CreateQueueResponse; -import software.amazon.awssdk.services.sqs.model.Message; -import software.amazon.awssdk.services.sqs.model.QueueAttributeName; -import software.amazon.awssdk.services.sqs.model.ReceiveMessageResponse; - -@Slf4j -class SqsListenerIntegrationTest extends AbstractIntegrationTest { - - @Autowired - private SqsAsyncClient sqsAsyncClient; - - @Test - void shouldSendAndReceiveSqsMessage() throws ExecutionException, InterruptedException { - String queueName = "test_queue"; - String queueURL = this.createQueue(queueName) - .thenApply(CreateQueueResponse::queueUrl) - .get(); - - this.sqsAsyncClient - .sendMessage(request -> request.messageBody("test message").queueUrl(queueURL)) - .thenRun(() -> log.info("Message sent successfully to the Amazon sqs.")); - - Awaitility.given() - .atMost(Duration.ofSeconds(30)) - .pollInterval(Duration.ofSeconds(3)) - .await() - .untilAsserted(() -> { - List messages = sqsAsyncClient - .receiveMessage(builder -> builder.queueUrl(queueURL)) - .thenApply(ReceiveMessageResponse::messages) - .get(); - assertThat(messages).isNotEmpty(); - }); - } - - private CompletableFuture createQueue(String queueName) { - CreateQueueRequest createQueueRequest = CreateQueueRequest.builder() - .queueName(queueName) - .attributes(Map.of(QueueAttributeName.MESSAGE_RETENTION_PERIOD, "86400")) - .build(); - - return sqsAsyncClient.createQueue(createQueueRequest); - } -} diff --git a/aws-lambda-project/src/test/java/com/learning/awslambda/common/ContainersConfig.java b/aws-lambda-project/src/test/java/com/learning/awslambda/common/ContainersConfig.java index 71f8ffc6..c5131611 100644 --- a/aws-lambda-project/src/test/java/com/learning/awslambda/common/ContainersConfig.java +++ b/aws-lambda-project/src/test/java/com/learning/awslambda/common/ContainersConfig.java @@ -14,13 +14,13 @@ public class ContainersConfig { @Bean @ServiceConnection PostgreSQLContainer postgreSQLContainer() { - return new PostgreSQLContainer<>(DockerImageName.parse("postgres:16.0-alpine")); + return new PostgreSQLContainer<>(DockerImageName.parse("postgres:16.1-alpine")); } @Bean LocalStackContainer localstackContainer(DynamicPropertyRegistry registry) { LocalStackContainer localStackContainer = - new LocalStackContainer(DockerImageName.parse("localstack/localstack:2.3.2")); + new LocalStackContainer(DockerImageName.parse("localstack/localstack:3.0.0")); registry.add("spring.cloud.aws.credentials.access-key", localStackContainer::getAccessKey); registry.add("spring.cloud.aws.credentials.secret-key", localStackContainer::getSecretKey); registry.add("spring.cloud.aws.region.static", localStackContainer::getRegion); diff --git a/aws-lambda-project/src/test/java/com/learning/awslambda/services/ActorServiceTest.java b/aws-lambda-project/src/test/java/com/learning/awslambda/services/ActorServiceTest.java deleted file mode 100644 index 7375c572..00000000 --- a/aws-lambda-project/src/test/java/com/learning/awslambda/services/ActorServiceTest.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.learning.awslambda.services; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.times; -import static org.mockito.BDDMockito.verify; -import static org.mockito.BDDMockito.willDoNothing; - -import com.learning.awslambda.entities.Actor; -import com.learning.awslambda.mapper.ActorMapper; -import com.learning.awslambda.model.response.ActorResponse; -import com.learning.awslambda.repositories.ActorRepository; -import java.util.Optional; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; - -@ExtendWith(MockitoExtension.class) -class ActorServiceTest { - - @Mock - private ActorRepository actorRepository; - - @Mock - private ActorMapper actorMapper; - - @InjectMocks - private ActorService actorService; - - @Test - void findActorById() { - // given - given(actorRepository.findById(1L)).willReturn(Optional.of(getActor())); - given(actorMapper.toResponse(any(Actor.class))).willReturn(getActorResponse()); - // when - Optional optionalActor = actorService.findActorById(1L); - // then - assertThat(optionalActor).isPresent(); - ActorResponse actor = optionalActor.get(); - assertThat(actor.id()).isEqualTo(1L); - assertThat(actor.text()).isEqualTo("junitTest"); - } - - @Test - void deleteActorById() { - // given - willDoNothing().given(actorRepository).deleteById(1L); - // when - actorService.deleteActorById(1L); - // then - verify(actorRepository, times(1)).deleteById(1L); - } - - private Actor getActor() { - Actor actor = new Actor(); - actor.setId(1L); - actor.setText("junitTest"); - return actor; - } - - private ActorResponse getActorResponse() { - return new ActorResponse(1L, "junitTest"); - } -} diff --git a/aws-lambda-project/src/test/java/com/learning/awslambda/web/controllers/ActorControllerIT.java b/aws-lambda-project/src/test/java/com/learning/awslambda/web/controllers/ActorControllerIT.java index 10cde700..fb9d2d1c 100644 --- a/aws-lambda-project/src/test/java/com/learning/awslambda/web/controllers/ActorControllerIT.java +++ b/aws-lambda-project/src/test/java/com/learning/awslambda/web/controllers/ActorControllerIT.java @@ -1,27 +1,18 @@ package com.learning.awslambda.web.controllers; import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.Matchers.hasSize; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import com.learning.awslambda.common.AbstractIntegrationTest; import com.learning.awslambda.entities.Actor; -import com.learning.awslambda.model.request.ActorRequest; import com.learning.awslambda.repositories.ActorRepository; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; class ActorControllerIT extends AbstractIntegrationTest { @@ -41,89 +32,15 @@ void setUp() { actorList = actorRepository.saveAll(actorList); } - @Test - void shouldFetchAllActors() throws Exception { - this.mockMvc - .perform(get("/api/actors")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.data.size()", is(actorList.size()))) - .andExpect(jsonPath("$.totalElements", is(3))) - .andExpect(jsonPath("$.pageNumber", is(1))) - .andExpect(jsonPath("$.totalPages", is(1))) - .andExpect(jsonPath("$.isFirst", is(true))) - .andExpect(jsonPath("$.isLast", is(true))) - .andExpect(jsonPath("$.hasNext", is(false))) - .andExpect(jsonPath("$.hasPrevious", is(false))); - } - @Test void shouldFindActorById() throws Exception { Actor actor = actorList.get(0); - Long actorId = actor.getId(); - - this.mockMvc - .perform(get("/api/actors/{id}", actorId)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.id", is(actor.getId()), Long.class)) - .andExpect(jsonPath("$.text", is(actor.getText()))); - } - - @Test - void shouldCreateNewActor() throws Exception { - ActorRequest actorRequest = new ActorRequest("New Actor"); - this.mockMvc - .perform(post("/api/actors") - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(actorRequest))) - .andExpect(status().isCreated()) - .andExpect(header().exists(HttpHeaders.LOCATION)) - .andExpect(jsonPath("$.id", notNullValue())) - .andExpect(jsonPath("$.text", is(actorRequest.text()))); - } - - @Test - void shouldReturn400WhenCreateNewActorWithoutText() throws Exception { - ActorRequest actorRequest = new ActorRequest(null); - - this.mockMvc - .perform(post("/api/actors") - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(actorRequest))) - .andExpect(status().isBadRequest()) - .andExpect(header().string("Content-Type", is("application/problem+json"))) - .andExpect(jsonPath("$.type", is("about:blank"))) - .andExpect(jsonPath("$.title", is("Constraint Violation"))) - .andExpect(jsonPath("$.status", is(400))) - .andExpect(jsonPath("$.detail", is("Invalid request content."))) - .andExpect(jsonPath("$.instance", is("/api/actors"))) - .andExpect(jsonPath("$.violations", hasSize(1))) - .andExpect(jsonPath("$.violations[0].field", is("text"))) - .andExpect(jsonPath("$.violations[0].message", is("Text cannot be empty"))) - .andReturn(); - } - - @Test - void shouldUpdateActor() throws Exception { - Long actorId = actorList.get(0).getId(); - ActorRequest actorRequest = new ActorRequest("Updated Actor"); - - this.mockMvc - .perform(put("/api/actors/{id}", actorId) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(actorRequest))) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.id", is(actorId), Long.class)) - .andExpect(jsonPath("$.text", is(actorRequest.text()))); - } - - @Test - void shouldDeleteActor() throws Exception { - Actor actor = actorList.get(0); + String actorName = actor.getName(); this.mockMvc - .perform(delete("/api/actors/{id}", actor.getId())) + .perform(get("/api/actors/{name}", actorName)) .andExpect(status().isOk()) .andExpect(jsonPath("$.id", is(actor.getId()), Long.class)) - .andExpect(jsonPath("$.text", is(actor.getText()))); + .andExpect(jsonPath("$.name", is(actor.getName()))); } } diff --git a/aws-lambda-project/src/test/java/com/learning/awslambda/web/controllers/ActorControllerTest.java b/aws-lambda-project/src/test/java/com/learning/awslambda/web/controllers/ActorControllerTest.java index a9401a58..1f60524b 100644 --- a/aws-lambda-project/src/test/java/com/learning/awslambda/web/controllers/ActorControllerTest.java +++ b/aws-lambda-project/src/test/java/com/learning/awslambda/web/controllers/ActorControllerTest.java @@ -2,27 +2,14 @@ import static com.learning.awslambda.utils.AppConstants.PROFILE_TEST; import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.Matchers.hasSize; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.doNothing; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import com.fasterxml.jackson.databind.ObjectMapper; import com.learning.awslambda.entities.Actor; -import com.learning.awslambda.exception.ActorNotFoundException; -import com.learning.awslambda.model.query.FindActorsQuery; -import com.learning.awslambda.model.request.ActorRequest; import com.learning.awslambda.model.response.ActorResponse; -import com.learning.awslambda.model.response.PagedResult; import com.learning.awslambda.services.ActorService; import java.util.ArrayList; import java.util.List; @@ -32,10 +19,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; @@ -62,157 +45,15 @@ void setUp() { this.actorList.add(new Actor(3L, "text 3")); } - @Test - void shouldFetchAllActors() throws Exception { - - Page page = new PageImpl<>(actorList); - PagedResult actorPagedResult = new PagedResult<>(page, getActorResponseList()); - FindActorsQuery findActorsQuery = new FindActorsQuery(0, 10, "id", "asc"); - given(actorService.findAllActors(findActorsQuery)).willReturn(actorPagedResult); - - this.mockMvc - .perform(get("/api/actors")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.data.size()", is(actorList.size()))) - .andExpect(jsonPath("$.totalElements", is(3))) - .andExpect(jsonPath("$.pageNumber", is(1))) - .andExpect(jsonPath("$.totalPages", is(1))) - .andExpect(jsonPath("$.isFirst", is(true))) - .andExpect(jsonPath("$.isLast", is(true))) - .andExpect(jsonPath("$.hasNext", is(false))) - .andExpect(jsonPath("$.hasPrevious", is(false))); - } - @Test void shouldFindActorById() throws Exception { - Long actorId = 1L; - ActorResponse actor = new ActorResponse(actorId, "text 1"); - given(actorService.findActorById(actorId)).willReturn(Optional.of(actor)); + String actorId = "text"; + ActorResponse actor = new ActorResponse(1L, "text 1"); + given(actorService.findActorByName(actorId)).willReturn(Optional.of(actor)); this.mockMvc - .perform(get("/api/actors/{id}", actorId)) + .perform(get("/api/actors/{name}", actorId)) .andExpect(status().isOk()) - .andExpect(jsonPath("$.text", is(actor.text()))); - } - - @Test - void shouldReturn404WhenFetchingNonExistingActor() throws Exception { - Long actorId = 1L; - given(actorService.findActorById(actorId)).willReturn(Optional.empty()); - - this.mockMvc - .perform(get("/api/actors/{id}", actorId)) - .andExpect(status().isNotFound()) - .andExpect(header().string("Content-Type", is(MediaType.APPLICATION_PROBLEM_JSON_VALUE))) - .andExpect(jsonPath("$.type", is("http://api.aws-lambda-project.com/errors/not-found"))) - .andExpect(jsonPath("$.title", is("Not Found"))) - .andExpect(jsonPath("$.status", is(404))) - .andExpect(jsonPath("$.detail").value("Actor with Id '%d' not found".formatted(actorId))); - } - - @Test - void shouldCreateNewActor() throws Exception { - - ActorResponse actor = new ActorResponse(1L, "some text"); - ActorRequest actorRequest = new ActorRequest("some text"); - given(actorService.saveActor(any(ActorRequest.class))).willReturn(actor); - - this.mockMvc - .perform(post("/api/actors") - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(actorRequest))) - .andExpect(status().isCreated()) - .andExpect(header().exists(HttpHeaders.LOCATION)) - .andExpect(jsonPath("$.id", notNullValue())) - .andExpect(jsonPath("$.text", is(actor.text()))); - } - - @Test - void shouldReturn400WhenCreateNewActorWithoutText() throws Exception { - ActorRequest actorRequest = new ActorRequest(null); - - this.mockMvc - .perform(post("/api/actors") - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(actorRequest))) - .andExpect(status().isBadRequest()) - .andExpect(header().string("Content-Type", is("application/problem+json"))) - .andExpect(jsonPath("$.type", is("about:blank"))) - .andExpect(jsonPath("$.title", is("Constraint Violation"))) - .andExpect(jsonPath("$.status", is(400))) - .andExpect(jsonPath("$.detail", is("Invalid request content."))) - .andExpect(jsonPath("$.instance", is("/api/actors"))) - .andExpect(jsonPath("$.violations", hasSize(1))) - .andExpect(jsonPath("$.violations[0].field", is("text"))) - .andExpect(jsonPath("$.violations[0].message", is("Text cannot be empty"))) - .andReturn(); - } - - @Test - void shouldUpdateActor() throws Exception { - Long actorId = 1L; - ActorResponse actor = new ActorResponse(actorId, "Updated text"); - ActorRequest actorRequest = new ActorRequest("Updated text"); - given(actorService.updateActor(eq(actorId), any(ActorRequest.class))).willReturn(actor); - - this.mockMvc - .perform(put("/api/actors/{id}", actorId) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(actorRequest))) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.id", is(actorId), Long.class)) - .andExpect(jsonPath("$.text", is(actor.text()))); - } - - @Test - void shouldReturn404WhenUpdatingNonExistingActor() throws Exception { - Long actorId = 1L; - ActorRequest actorRequest = new ActorRequest("Updated text"); - given(actorService.updateActor(eq(actorId), any(ActorRequest.class))) - .willThrow(new ActorNotFoundException(actorId)); - - this.mockMvc - .perform(put("/api/actors/{id}", actorId) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(actorRequest))) - .andExpect(status().isNotFound()) - .andExpect(header().string("Content-Type", is(MediaType.APPLICATION_PROBLEM_JSON_VALUE))) - .andExpect(jsonPath("$.type", is("http://api.aws-lambda-project.com/errors/not-found"))) - .andExpect(jsonPath("$.title", is("Not Found"))) - .andExpect(jsonPath("$.status", is(404))) - .andExpect(jsonPath("$.detail").value("Actor with Id '%d' not found".formatted(actorId))); - } - - @Test - void shouldDeleteActor() throws Exception { - Long actorId = 1L; - ActorResponse actor = new ActorResponse(actorId, "Some text"); - given(actorService.findActorById(actorId)).willReturn(Optional.of(actor)); - doNothing().when(actorService).deleteActorById(actorId); - - this.mockMvc - .perform(delete("/api/actors/{id}", actorId)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.text", is(actor.text()))); - } - - @Test - void shouldReturn404WhenDeletingNonExistingActor() throws Exception { - Long actorId = 1L; - given(actorService.findActorById(actorId)).willReturn(Optional.empty()); - - this.mockMvc - .perform(delete("/api/actors/{id}", actorId)) - .andExpect(header().string("Content-Type", is(MediaType.APPLICATION_PROBLEM_JSON_VALUE))) - .andExpect(jsonPath("$.type", is("http://api.aws-lambda-project.com/errors/not-found"))) - .andExpect(jsonPath("$.title", is("Not Found"))) - .andExpect(jsonPath("$.status", is(404))) - .andExpect(jsonPath("$.detail").value("Actor with Id '%d' not found".formatted(actorId))); - } - - List getActorResponseList() { - return actorList.stream() - .map(actor -> new ActorResponse(actor.getId(), actor.getText())) - .toList(); + .andExpect(jsonPath("$.name", is(actor.name()))); } }