diff --git a/application/model/src/main/java/org/fuseri/model/dto/common/Result.java b/application/model/src/main/java/org/fuseri/model/dto/common/Result.java deleted file mode 100644 index c75e421e91732dae34d803b7e715f7c395aea240..0000000000000000000000000000000000000000 --- a/application/model/src/main/java/org/fuseri/model/dto/common/Result.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.fuseri.model.dto.common; - -import lombok.Getter; -import lombok.Setter; - -import java.util.List; - -@Getter -@Setter -public class Result<T extends DomainObjectDto> { - - private long total; - private int page; - private int pageSize; - private List<T> items; -} diff --git a/application/model/src/main/java/org/fuseri/model/dto/course/CourseDto.java b/application/model/src/main/java/org/fuseri/model/dto/course/CourseDto.java index e0d571ff570d9845cfda18b31862473816d3b748..aac23cd106cfef126a5240a8280c84e9d213c743 100644 --- a/application/model/src/main/java/org/fuseri/model/dto/course/CourseDto.java +++ b/application/model/src/main/java/org/fuseri/model/dto/course/CourseDto.java @@ -41,8 +41,7 @@ public class CourseDto extends DomainObjectDto { @NotNull(message = "Student's list is required") @Valid - private List<Long> studentIds; - + private List<String> studentIds; public CourseDto(String name, Integer capacity, LanguageTypeDto languageTypeDto, ProficiencyLevelDto proficiencyLevelDto) { this.name = name; diff --git a/application/model/src/main/java/org/fuseri/model/dto/exercise/AnswerCreateDto.java b/application/model/src/main/java/org/fuseri/model/dto/exercise/AnswerCreateDto.java index f7a845f6c9bc9970e3e8bcc4d1e2d6e2929c712a..2418847a2d483585f0d0a57505f0cfd148aa2094 100644 --- a/application/model/src/main/java/org/fuseri/model/dto/exercise/AnswerCreateDto.java +++ b/application/model/src/main/java/org/fuseri/model/dto/exercise/AnswerCreateDto.java @@ -15,6 +15,6 @@ public class AnswerCreateDto { @NotNull private boolean correct; - @NotBlank - private String questionId; + @NotNull + private long questionId; } diff --git a/application/model/src/main/java/org/fuseri/model/dto/exercise/AnswerDto.java b/application/model/src/main/java/org/fuseri/model/dto/exercise/AnswerDto.java index 433244900c287f01549b3e43a4971f68a86a2cc7..2f87806e2c6869602b12473d464d35b96240aa03 100644 --- a/application/model/src/main/java/org/fuseri/model/dto/exercise/AnswerDto.java +++ b/application/model/src/main/java/org/fuseri/model/dto/exercise/AnswerDto.java @@ -3,13 +3,13 @@ package org.fuseri.model.dto.exercise; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; import lombok.Getter; import org.fuseri.model.dto.common.DomainObjectDto; -import java.util.Objects; - @AllArgsConstructor @Getter +@EqualsAndHashCode(callSuper = false) public class AnswerDto extends DomainObjectDto { @NotBlank @@ -17,22 +17,4 @@ public class AnswerDto extends DomainObjectDto { @NotNull private boolean correct; - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - AnswerDto answerDto = (AnswerDto) o; - - if (correct != answerDto.correct) return false; - return Objects.equals(text, answerDto.text); - } - - @Override - public int hashCode() { - int result = text != null ? text.hashCode() : 0; - result = 31 * result + (correct ? 1 : 0); - return result; - } } diff --git a/application/model/src/main/java/org/fuseri/model/dto/exercise/AnswersCreateDto.java b/application/model/src/main/java/org/fuseri/model/dto/exercise/AnswersCreateDto.java index 04996492928042452c248158a9d4cab9659a772a..f2c7da24058c59d4a600d9a7d7d0403652e46832 100644 --- a/application/model/src/main/java/org/fuseri/model/dto/exercise/AnswersCreateDto.java +++ b/application/model/src/main/java/org/fuseri/model/dto/exercise/AnswersCreateDto.java @@ -1,7 +1,7 @@ package org.fuseri.model.dto.exercise; import jakarta.validation.Valid; -import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; import lombok.AllArgsConstructor; import lombok.Getter; @@ -11,8 +11,8 @@ import java.util.List; @Getter public class AnswersCreateDto { - @NotBlank - private String questionId; + @NotNull + private long questionId; @Valid private List<AnswerInQuestionCreateDto> answers; diff --git a/application/model/src/main/java/org/fuseri/model/dto/exercise/ExerciseCreateDto.java b/application/model/src/main/java/org/fuseri/model/dto/exercise/ExerciseCreateDto.java index 332b343dce447081c05db0a98e2c57df8815602e..6d1cb1a7727b669e683f775e63aafc0e781816fe 100644 --- a/application/model/src/main/java/org/fuseri/model/dto/exercise/ExerciseCreateDto.java +++ b/application/model/src/main/java/org/fuseri/model/dto/exercise/ExerciseCreateDto.java @@ -9,7 +9,6 @@ import lombok.Getter; @AllArgsConstructor @Getter public class ExerciseCreateDto { - @NotBlank private String name; @@ -20,6 +19,6 @@ public class ExerciseCreateDto { @PositiveOrZero private int difficulty; - @NotBlank - private String courseId; + @NotNull + private long courseId; } diff --git a/application/model/src/main/java/org/fuseri/model/dto/exercise/ExerciseDto.java b/application/model/src/main/java/org/fuseri/model/dto/exercise/ExerciseDto.java index ff7abd444839ba89d15b50e72f31a3973b62ceef..537d0e63a1da348212904882e3f6d165d6cc9945 100644 --- a/application/model/src/main/java/org/fuseri/model/dto/exercise/ExerciseDto.java +++ b/application/model/src/main/java/org/fuseri/model/dto/exercise/ExerciseDto.java @@ -3,14 +3,14 @@ package org.fuseri.model.dto.exercise; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.PositiveOrZero; +import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import org.fuseri.model.dto.common.DomainObjectDto; -import java.util.Objects; - @Getter @Setter +@EqualsAndHashCode(callSuper = false) public class ExerciseDto extends DomainObjectDto { @NotBlank @@ -23,28 +23,6 @@ public class ExerciseDto extends DomainObjectDto { @PositiveOrZero private int difficulty; - @NotBlank - private String courseId; - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - ExerciseDto that = (ExerciseDto) o; - - if (difficulty != that.difficulty) return false; - if (!Objects.equals(name, that.name)) return false; - if (!Objects.equals(description, that.description)) return false; - return Objects.equals(courseId, that.courseId); - } - - @Override - public int hashCode() { - int result = name != null ? name.hashCode() : 0; - result = 31 * result + (description != null ? description.hashCode() : 0); - result = 31 * result + difficulty; - result = 31 * result + (courseId != null ? courseId.hashCode() : 0); - return result; - } + @NotNull + private long courseId; } diff --git a/application/model/src/main/java/org/fuseri/model/dto/exercise/QuestionCreateDto.java b/application/model/src/main/java/org/fuseri/model/dto/exercise/QuestionCreateDto.java index 738a9031739586351ba52b993c7522e0dbcb226d..cd215815305d8bb06de5b81e47f6b6e8380954d2 100644 --- a/application/model/src/main/java/org/fuseri/model/dto/exercise/QuestionCreateDto.java +++ b/application/model/src/main/java/org/fuseri/model/dto/exercise/QuestionCreateDto.java @@ -2,6 +2,7 @@ package org.fuseri.model.dto.exercise; import jakarta.validation.Valid; import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; import lombok.AllArgsConstructor; import lombok.Getter; @@ -14,8 +15,8 @@ public class QuestionCreateDto { @NotBlank private String text; - @NotBlank - private String exerciseId; + @NotNull + private long exerciseId; @Valid private List<AnswerInQuestionCreateDto> answers; diff --git a/application/model/src/main/java/org/fuseri/model/dto/exercise/QuestionDto.java b/application/model/src/main/java/org/fuseri/model/dto/exercise/QuestionDto.java index 5cca20b14b60c9361eaea0893ff874500b690c61..94ddd64f094b713cb14c216378f181b55844ea51 100644 --- a/application/model/src/main/java/org/fuseri/model/dto/exercise/QuestionDto.java +++ b/application/model/src/main/java/org/fuseri/model/dto/exercise/QuestionDto.java @@ -2,43 +2,29 @@ package org.fuseri.model.dto.exercise; import jakarta.validation.Valid; import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; import lombok.Getter; +import lombok.NoArgsConstructor; import lombok.Setter; import org.fuseri.model.dto.common.DomainObjectDto; import java.util.List; -import java.util.Objects; @Getter @Setter +@AllArgsConstructor +@NoArgsConstructor +@EqualsAndHashCode(callSuper = false) public class QuestionDto extends DomainObjectDto { @NotBlank private String text; - @NotBlank - private String exerciseId; + @NotNull + private long exerciseId; @Valid private List<AnswerDto> answers; - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - QuestionDto that = (QuestionDto) o; - - if (!Objects.equals(text, that.text)) return false; - if (!Objects.equals(exerciseId, that.exerciseId)) return false; - return Objects.equals(answers, that.answers); - } - - @Override - public int hashCode() { - int result = text != null ? text.hashCode() : 0; - result = 31 * result + (exerciseId != null ? exerciseId.hashCode() : 0); - result = 31 * result + (answers != null ? answers.hashCode() : 0); - return result; - } } diff --git a/application/model/src/main/java/org/fuseri/model/dto/exercise/QuestionUpdateDto.java b/application/model/src/main/java/org/fuseri/model/dto/exercise/QuestionUpdateDto.java index 2efa520493c718e108a180fabae12a4887913cab..59e0fda131a540c0c08da981fd36d156a49cb5ae 100644 --- a/application/model/src/main/java/org/fuseri/model/dto/exercise/QuestionUpdateDto.java +++ b/application/model/src/main/java/org/fuseri/model/dto/exercise/QuestionUpdateDto.java @@ -1,6 +1,7 @@ package org.fuseri.model.dto.exercise; import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; import lombok.Builder; import lombok.Getter; @@ -11,6 +12,6 @@ public class QuestionUpdateDto { @NotBlank private String text; - @NotBlank - private String exerciseId; + @NotNull + private long exerciseId; } diff --git a/application/model/src/main/java/org/fuseri/model/dto/user/UserDto.java b/application/model/src/main/java/org/fuseri/model/dto/user/UserDto.java index 4d6eba739bf848cf3933c63a8f9ca6607da95b59..633b3368c719832f910764609e778d24a26507ba 100644 --- a/application/model/src/main/java/org/fuseri/model/dto/user/UserDto.java +++ b/application/model/src/main/java/org/fuseri/model/dto/user/UserDto.java @@ -1,6 +1,8 @@ package org.fuseri.model.dto.user; import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import org.fuseri.model.dto.common.DomainObjectDto; import lombok.Getter; import lombok.Setter; import org.fuseri.model.dto.common.DomainObjectDto; diff --git a/application/module-certificate/src/test/java/org/fuseri/modulecertificate/CertificateControllerTests.java b/application/module-certificate/src/test/java/org/fuseri/modulecertificate/CertificateControllerTests.java index 1d06db7067cf1b9e89c0f0769b7a6111d3c238a7..3056468f4dc1f7d17dcb5d66de02b564a97e356e 100644 --- a/application/module-certificate/src/test/java/org/fuseri/modulecertificate/CertificateControllerTests.java +++ b/application/module-certificate/src/test/java/org/fuseri/modulecertificate/CertificateControllerTests.java @@ -10,19 +10,14 @@ import org.fuseri.model.dto.user.AddressDto; import org.fuseri.model.dto.user.UserDto; import org.fuseri.modulecertificate.service.CertificateFacade; import org.junit.jupiter.api.Test; -import org.mockito.ArgumentMatchers; -import org.mockito.Mockito; +import org.springdoc.core.converters.models.Pageable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; -import java.time.Instant; import java.util.List; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; @@ -110,16 +105,11 @@ class CertificateControllerTests { @Test void findCertificateIdForUserAndCourse() throws Exception { - Mockito.when(certificateFacade.findByUserIdAndCourseId(ArgumentMatchers.anyLong(), - ArgumentMatchers.anyLong())) - .thenReturn(List.of(certificateDto)); - mockMvc.perform(get("/certificates/findForUserAndCourse") .param("userId", "0") .param("courseId", "0")) .andExpect(status().isOk()) - .andExpect(jsonPath("$").isArray()) - .andExpect(jsonPath("$").isNotEmpty()); + .andExpect(content().string("[]")); } @Test @@ -161,12 +151,10 @@ class CertificateControllerTests { Mockito.when(certificateFacade.findAll(ArgumentMatchers.any(Pageable.class))) .thenReturn(Page.empty(PageRequest.of(0, 1))); - mockMvc.perform(get("/certificates") - .param("page", "0") - .param("size", "10")) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$.content").isEmpty()); + mockMvc.perform(get("/certificates/findAll") + .content("{ \"page\": 0, \"size\": 1, \"sort\": []}") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); } @Test diff --git a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/answer/Answer.java b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/answer/Answer.java index 12fac75aedf87d7c1f29fe7333a24762d19a9ad3..9686c42ea06b4286bfdb2b7c1324cef02121761f 100644 --- a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/answer/Answer.java +++ b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/answer/Answer.java @@ -1,7 +1,9 @@ package org.fuseri.moduleexercise.answer; +import jakarta.persistence.*; import lombok.*; import org.fuseri.moduleexercise.common.DomainObject; +import org.fuseri.moduleexercise.question.Question; /** * Represent Answer entity @@ -12,10 +14,16 @@ import org.fuseri.moduleexercise.common.DomainObject; @NoArgsConstructor @AllArgsConstructor @Builder +@Entity +@Table(name = "answer") public class Answer extends DomainObject { + private String text; + @Column(name = "is_correct") private boolean correct; - private String questionId; + @ManyToOne + @JoinColumn(name="question_id") + private Question question; } diff --git a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/answer/AnswerController.java b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/answer/AnswerController.java index 9f2f75a06870be2aa1bb7898a0caa471197f1681..b3829f98eff78333be094ae152fc0f6a5425d9d6 100644 --- a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/answer/AnswerController.java +++ b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/answer/AnswerController.java @@ -1,18 +1,25 @@ package org.fuseri.moduleexercise.answer; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; import jakarta.persistence.EntityNotFoundException; import jakarta.validation.Valid; -import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; import org.fuseri.model.dto.exercise.AnswerCreateDto; import org.fuseri.model.dto.exercise.AnswerDto; -import org.fuseri.model.dto.exercise.AnswersCreateDto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.*; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +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.RestController; import org.springframework.web.server.ResponseStatusException; -import java.util.List; - /** * Represent a REST API controller for answers * Handle HTTP requests related to answers @@ -28,30 +35,24 @@ public class AnswerController { this.facade = facade; } - /** - * Retrieve a list of AnswerDto objects which belong to question with questionId - * - * @param questionId the ID of the question for which to retrieve answers - * @return a List of AnswerDto objects - */ - @GetMapping("/{question-id}") - public List<AnswerDto> findAllByQuestionId(@NotBlank @PathVariable("question-id") String questionId) { - return facade.findAllByQuestionId(questionId); - } - /** * Create a new answer for the given question ID * * @param dto the AnswerCreateDto object containing information about the answer to create - * @return an AnswerDto object representing the newly created answer - * @throws ResponseStatusException if the question ID specified in the dto does not exist + * @return a ResponseEntity containing an AnswerDto object representing the newly created answer, or a 404 Not Found response + * if the question with the specified ID in dto was not found */ + @Operation(summary = "Create new answer for question", description = "Creates new answer for question.") + @ApiResponses(value = { + @ApiResponse(responseCode = "201", description = "Answers created successfully."), + @ApiResponse(responseCode = "400", description = "Invalid input.") + }) @PostMapping - public List<AnswerDto> createMultiple(@Valid @RequestBody AnswersCreateDto dto) { + public ResponseEntity<AnswerDto> create(@Valid @RequestBody AnswerCreateDto dto) { try { - return facade.createMultiple(dto); + return ResponseEntity.status(HttpStatus.CREATED).body(facade.create(dto)); } catch (EntityNotFoundException e) { - throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage()); + return ResponseEntity.notFound().build(); } } @@ -60,30 +61,42 @@ public class AnswerController { * * @param id of answer to update * @param dto dto with updated answer information - * @throws ResponseStatusException if the question id specified in the AnswerCreateDto dto does not exist + * @return A ResponseEntity with an AnswerDto object representing the updated answer on an HTTP status code of 200 if the update was successful. + * or a NOT_FOUND response if the answer ID is invalid */ + @Operation(summary = "Update an answer", description = "Updates an answer with the specified ID.") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Answer with the specified ID updated successfully."), + @ApiResponse(responseCode = "400", description = "Invalid input."), + @ApiResponse(responseCode = "404", description = "Answer with the specified ID was not found.") + }) @PutMapping("/{id}") - public AnswerDto update(@NotBlank @PathVariable String id, @Valid @RequestBody AnswerCreateDto dto) { + public ResponseEntity<AnswerDto> update(@NotNull @PathVariable long id, @Valid @RequestBody AnswerCreateDto dto) { try { - return facade.update(id, dto); + return ResponseEntity.ok(facade.update(id, dto)); } catch (EntityNotFoundException e) { - throw new ResponseStatusException(HttpStatus.NOT_FOUND, - e.getMessage()); + return ResponseEntity.notFound().build(); } } /** - * Delete answer with the given id + * Delete answer with the specified ID * * @param id of answer to delete * @throws ResponseStatusException if answer with specified id does not exist */ + @Operation(summary = "Delete an answer with specified ID", description = "Deletes an answer with the specified ID.") + @ApiResponses(value = { + @ApiResponse(responseCode = "204", description = "Answer with the specified ID deleted successfully."), + @ApiResponse(responseCode = "404", description = "Answer with the specified ID was not found.") + }) @DeleteMapping("/{id}") - public void delete(@NotBlank @PathVariable String id) { + public ResponseEntity<Void> delete(@NotNull @PathVariable long id) { try { facade.delete(id); + return ResponseEntity.noContent().build(); } catch (EntityNotFoundException e) { - throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage()); + return ResponseEntity.notFound().build(); } } } diff --git a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/answer/AnswerFacade.java b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/answer/AnswerFacade.java index 9ef573dca41c6d90e1396484a1c54e29b1730073..693c8322b6feddc366c372f6fdce6fd8505f37b7 100644 --- a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/answer/AnswerFacade.java +++ b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/answer/AnswerFacade.java @@ -1,95 +1,52 @@ package org.fuseri.moduleexercise.answer; +import jakarta.transaction.Transactional; import org.fuseri.model.dto.exercise.AnswerCreateDto; import org.fuseri.model.dto.exercise.AnswerDto; -import org.fuseri.model.dto.exercise.AnswersCreateDto; -import org.fuseri.moduleexercise.question.Question; -import org.fuseri.moduleexercise.question.QuestionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import org.springframework.web.bind.annotation.*; - -import java.util.ArrayList; -import java.util.List; +import org.springframework.web.bind.annotation.RequestBody; /** * Represent facade for managing answers * Provide simplified interface for manipulating with answers */ @Service +@Transactional public class AnswerFacade { private final AnswerService answerService; - private final QuestionService questionService; private final AnswerMapper mapper; - /** * Constructor for AnswerFacade * - * @param answerService the service responsible for handling answer-related logic - * @param questionService the service responsible for handling question-related logic - * @param mapper the mapper responsible for converting between DTOs and entities + * @param answerService the service responsible for handling answer-related logic + * @param mapper the mapper responsible for converting between DTOs and entities */ @Autowired - public AnswerFacade(AnswerService answerService, QuestionService questionService, AnswerMapper mapper) { + public AnswerFacade(AnswerService answerService, AnswerMapper mapper) { this.answerService = answerService; - this.questionService = questionService; this.mapper = mapper; } - /** - * Retrieve a list of AnswerDto objects which belong to question with questionId - * - * @param questionId the ID of the question for which to retrieve answers - * @return a List of AnswerDto objects - */ - public List<AnswerDto> findAllByQuestionId(String questionId) { - return mapper.toDtoList(answerService.findAllByQuestionId(questionId)); - } - /** * Create a new answer for the given question ID * * @param dto the AnswerCreateDto object containing information about the answer to create * @return an AnswerDto object representing the newly created answer */ - public List<AnswerDto> createMultiple(@RequestBody AnswersCreateDto dto) { - List<Answer> createdAnswers = new ArrayList<>(); - for (var answerDto : dto.getAnswers()) { - Question question; - question = questionService.find(dto.getQuestionId()); - - Answer answer = mapper.fromCreateDto(answerDto); - answer.setQuestionId(question.getId()); - var createdAnswer = answerService.create(answer); - question.getAnswers().add(answer); - createdAnswers.add(createdAnswer); - } - - return mapper.toDtoList(createdAnswers); + public AnswerDto create(@RequestBody AnswerCreateDto dto) { + return mapper.toDto(answerService.create(mapper.fromCreateDto(dto))); } /** - * Update an answer + * Update answer * * @param id of answer to update * @param dto dto with updated answer information */ - public AnswerDto update(String id, AnswerCreateDto dto) { - var updatedAnswer = mapper.fromCreateDto(dto); - updatedAnswer.setId(id); - answerService.update(updatedAnswer); - - Question question; - question = questionService.find(dto.getQuestionId()); - - var questionAnswers = question.getAnswers(); - questionAnswers.removeIf(a -> a.getId().equals(id)); - questionAnswers.add(updatedAnswer); - question.setAnswers(questionAnswers); - questionService.update(question); - - return mapper.toDto(updatedAnswer); + public AnswerDto update(long id, AnswerCreateDto dto) { + return mapper.toDto(answerService.update(id, mapper.fromCreateDto(dto))); } /** @@ -97,16 +54,7 @@ public class AnswerFacade { * * @param id of answer to delete */ - public void delete(String id) { - var answer = answerService.find(id); - - Question question; - question = questionService.find(answer.getQuestionId()); - - var questionAnswers = question.getAnswers(); - questionAnswers.removeIf(a -> a.getId().equals(answer.getId())); - question.setAnswers(questionAnswers); - + public void delete(long id) { answerService.delete(id); } } diff --git a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/answer/AnswerMapper.java b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/answer/AnswerMapper.java index 3dec5ca627e8808d54e7f27593c834a73a0f5fa5..44b8d1f80ec4e4983e82bd107d308f11ba89f9b6 100644 --- a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/answer/AnswerMapper.java +++ b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/answer/AnswerMapper.java @@ -4,13 +4,29 @@ import org.fuseri.model.dto.exercise.AnswerCreateDto; import org.fuseri.model.dto.exercise.AnswerDto; import org.fuseri.model.dto.exercise.AnswerInQuestionCreateDto; import org.fuseri.moduleexercise.common.DomainMapper; +import org.fuseri.moduleexercise.question.Question; +import org.fuseri.moduleexercise.question.QuestionService; import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.Named; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.List; +import java.util.Set; /** * Mapper between Answers and their corresponding DTOs */ -@Mapper -public interface AnswerMapper extends DomainMapper<Answer, AnswerDto> { +@Mapper(componentModel = "spring", uses = {QuestionService.class}) +public abstract class AnswerMapper implements DomainMapper<Answer, AnswerDto> { + + @Autowired + private QuestionService questionService; + + @Named("mapIdToQuestion") + public Question mapIdToQuestion(Long id) { + return questionService.find(id); + } /** * Convert DTO of type AnswerCreateDto to Answer @@ -18,12 +34,22 @@ public interface AnswerMapper extends DomainMapper<Answer, AnswerDto> { * @param dto DTO to be converted * @return corresponding Answer entity created from DTO */ - Answer fromCreateDto(AnswerCreateDto dto); + @Mapping(target = "question", source = "dto.questionId", qualifiedByName = "mapIdToQuestion") + public abstract Answer fromCreateDto(AnswerCreateDto dto); + + /** + * Convert Set of AnswerInQuestionCreateDto to List of corresponding Answers + * + * @param dtos to be converted + * @return corresponding list of Answers + */ + public abstract Set<Answer> fromCreateDtoList(List<AnswerInQuestionCreateDto> dtos); /** * Convert DTO of type AnswerInQuestionCreateDto to Answer + * * @param dto DTO to be converted * @return corresponding Answer entity created from DTO */ - Answer fromCreateDto(AnswerInQuestionCreateDto dto); + public abstract Answer fromCreateDto(AnswerInQuestionCreateDto dto); } diff --git a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/answer/AnswerRepository.java b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/answer/AnswerRepository.java index 7f1918988b192f6c0f0f5fe54f92544d4d72dcbf..8d0844a898915658d73220923586a5630ac351a7 100644 --- a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/answer/AnswerRepository.java +++ b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/answer/AnswerRepository.java @@ -1,14 +1,16 @@ package org.fuseri.moduleexercise.answer; -import org.fuseri.moduleexercise.common.DomainRepository; +import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; import java.util.List; /** * A repository interface for managing Answer entities */ -public interface AnswerRepository extends DomainRepository<Answer, String> { +@Repository +public interface AnswerRepository extends JpaRepository<Answer, Long> { /** * Find all answers to a question with the specified ID @@ -16,5 +18,5 @@ public interface AnswerRepository extends DomainRepository<Answer, String> { * @param questionId the ID of the question to find answers for * @return a list of all answers to the specified question */ - List<Answer> findByQuestionId(@Param("questionId") String questionId); + List<Answer> findByQuestionId(@Param("questionId") long questionId); } \ No newline at end of file diff --git a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/answer/AnswerRepositoryImpl.java b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/answer/AnswerRepositoryImpl.java deleted file mode 100644 index 7a75a834add8e358abb04aa628ad9885a80d5705..0000000000000000000000000000000000000000 --- a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/answer/AnswerRepositoryImpl.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.fuseri.moduleexercise.answer; - -import org.fuseri.moduleexercise.common.DomainRepositoryImpl; -import org.springframework.stereotype.Repository; - -import java.util.List; - -/** - * An implementation of the AnswerRepository interface - * Provides access to Answer entities stored in a data source - */ -@Repository -public class AnswerRepositoryImpl extends DomainRepositoryImpl<Answer> implements AnswerRepository { - - /** - * Find all answers to a question with the specified ID - * - * @param questionId the ID of the question to find answers for - * @return a list of all answers to the specified question - */ - @Override - public List<Answer> findByQuestionId(String questionId) { - return getItems() - .stream() - .filter(e -> e.getQuestionId().equals(questionId)) - .toList(); - } -} diff --git a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/answer/AnswerService.java b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/answer/AnswerService.java index 593656acfea40265f835d91d6b5f2572a8bdea31..f5346fc5993874b4de7ca7d49fe39ba8c17ee6ba 100644 --- a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/answer/AnswerService.java +++ b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/answer/AnswerService.java @@ -36,9 +36,13 @@ public class AnswerService extends DomainService<Answer> { * * @param questionId the ID of the question to retrieve answers for * @return a list of Answer entities with the specified question ID + * @throws EntityNotFoundException if question with questionId does not exist */ @Transactional(readOnly = true) - public List<Answer> findAllByQuestionId(String questionId) { + public List<Answer> findAllByQuestionId(long questionId) { + if (!getRepository().existsById(questionId)) { + throw new EntityNotFoundException("Question with id " + questionId + " not found."); + } return repository.findByQuestionId(questionId); } @@ -50,7 +54,7 @@ public class AnswerService extends DomainService<Answer> { * @throws EntityNotFoundException if no Answer entity exists with the specified id */ @Transactional(readOnly = true) - public Answer find(String id) { + public Answer find(long id) { return repository.findById(id) .orElseThrow(() -> new EntityNotFoundException("Answer '" + id + "' not found.")); } diff --git a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/common/DomainMapper.java b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/common/DomainMapper.java index 91151e34a7604b75d8ec6e7ef3a4767bbfff811a..39bf0015e1cacc60a34a78e804a77ce18ccc6875 100644 --- a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/common/DomainMapper.java +++ b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/common/DomainMapper.java @@ -1,10 +1,8 @@ package org.fuseri.moduleexercise.common; import org.fuseri.model.dto.common.DomainObjectDto; -import org.fuseri.model.dto.common.Result; -import org.mapstruct.Mapping; -import org.mapstruct.Mappings; import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; import java.util.List; @@ -42,18 +40,13 @@ public interface DomainMapper<T extends DomainObject, S extends DomainObjectDto> List<S> toDtoList(List<T> entities); /** - * Convert a {@link org.springframework.data.domain.Page} containing entities to a - * {@link Result} object containing a list of their corresponding DTO objects, along with - * pagination information + * Convert a {@link org.springframework.data.domain.Page} containing entities to a page containing DTOs * - * @param source the Page of entities to be converted - * @return a Result object containing a list of DTO objects and pagination information + * @param entities entities to be converted to DTOs + * @return a Page object containing a list of DTO objects and pagination information */ - @Mappings({ - @Mapping(target = "total", expression = "java(source.getTotalElements())"), - @Mapping(target = "page", expression = "java(source.getNumber())"), - @Mapping(target = "pageSize", expression = "java(source.getSize())"), - @Mapping(target = "items", expression = "java(toDtoList(source.getContent()))") - }) - Result<S> toResult(Page<T> source); + default Page<S> toDtoPage(Page<T> entities) { + return new PageImpl<>(toDtoList(entities.getContent()), entities.getPageable(), entities.getTotalPages()); + } + } diff --git a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/common/DomainObject.java b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/common/DomainObject.java index 077a8e5cdb521f4c233572accf0e6a8bb10ac4d3..aae4e7759835653b19afad27db311e8d23095515 100644 --- a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/common/DomainObject.java +++ b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/common/DomainObject.java @@ -1,12 +1,12 @@ package org.fuseri.moduleexercise.common; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.MappedSuperclass; import lombok.Getter; import lombok.Setter; -import java.util.UUID; - /** * Represent the base class for entities in the module. */ @@ -16,6 +16,7 @@ import java.util.UUID; public abstract class DomainObject { @Id - private String id = UUID.randomUUID().toString(); + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; } diff --git a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/common/DomainRepository.java b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/common/DomainRepository.java deleted file mode 100644 index fae42adfae3eabea93352b01a26b25d36418bee1..0000000000000000000000000000000000000000 --- a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/common/DomainRepository.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.fuseri.moduleexercise.common; - -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; - -import java.util.Optional; - -/** - * Dummy interface of repository. Later will be replaced by JpaRepository. - * - * @param <T> entity - * @param <ID> entity ID - */ -public interface DomainRepository<T, ID> { - - /** - * Save the specified entity - * - * @param entity entity to be saved - * @return created entity - */ - T save(T entity); - - /** - * Find entity by ID - * - * @param id ID of entity to be found - * @return {@code Optional} containing the found entity, - * or an empty {@code Optional} if no such entity exists - */ - Optional<T> findById(ID id); - - /** - * Retrieve a page of entities according to the specified pagination information - * - * @param pageRequest the pagination information for the query - * @return a page of entities that satisfy the pagination criteria - */ - Page<T> findAll(PageRequest pageRequest); - - /** - * Update entity - * - * @param entity entity to update - * @return updated entity - */ - T update(T entity); - - /** - * Delete the entity with the specified id - * Note that this does not do cascade deleting. - * We will have cascade deleting with usage of JpaRepository - * - * @param id the id of the entity to be deleted - */ - void deleteById(ID id); -} \ No newline at end of file diff --git a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/common/DomainRepositoryImpl.java b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/common/DomainRepositoryImpl.java deleted file mode 100644 index 5c6b588fa6f6396062c93acc959d2d823284c129..0000000000000000000000000000000000000000 --- a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/common/DomainRepositoryImpl.java +++ /dev/null @@ -1,106 +0,0 @@ -package org.fuseri.moduleexercise.common; - -import jakarta.persistence.EntityNotFoundException; -import lombok.Getter; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.PageRequest; - -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; - -/** - * Dummy implementation of repository. Later will be replaced by JpaRepository. - * - * @param <T> entity - */ -public abstract class DomainRepositoryImpl<T extends DomainObject> implements DomainRepository<T, String> { - - /** - * Dummy database - */ - @Getter - private final Set<T> items = new HashSet<>(); - - /** - * Save the specified entity - * - * @param entity entity to be saved - * @return created entity - */ - @Override - public T save(T entity) { - items.add(entity); - return entity; - } - - /** - * Find entity by ID - * - * @param id ID of entity to be found - * @return {@code Optional} containing the found entity, - * or an empty {@code Optional} if no such entity exists - */ - @Override - public Optional<T> findById(String id) { - return items.stream() - .filter(e -> e.getId().equals(id)) - .findFirst(); - } - - /** - * Retrieve a page of entities according to the specified pagination information - * - * @param pageRequest the pagination information for the query - * @return a page of entities that satisfy the pagination criteria - */ - @Override - public Page<T> findAll(PageRequest pageRequest) { - - int startIndex = pageRequest.getPageNumber() * pageRequest.getPageSize(); - - List<T> pageEntities = items.stream() - .skip(startIndex) - .limit(pageRequest.getPageSize()) - .toList(); - - return new PageImpl<>(pageEntities, pageRequest, pageEntities.size()); - } - - /** - * Update entity - * - * @param entity entity to update - * @return updated entity - */ - @Override - public T update(T entity) { - if (entity == null || entity.getId() == null) { - throw new IllegalArgumentException("Entity and its ID can not be null."); - } - - var optionalEntity = findById(entity.getId()); - if (optionalEntity.isEmpty()) { - throw new EntityNotFoundException("Entity not found with ID: " + entity.getId()); - } - - T oldEntity = optionalEntity.get(); - items.remove(oldEntity); - items.add(entity); - return entity; - } - - /** - * Delete the entity with the specified id - * Note that this does not do cascade deleting. - * We will have cascade deleting with usage of JpaRepository - * - * @param id the id of the entity to be deleted - */ - @Override - public void deleteById(String id) { - items.removeIf(e -> e.getId().equals(id)); - } -} \ No newline at end of file diff --git a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/common/DomainService.java b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/common/DomainService.java index badd21263def20ee0cf660c2be3f1f156a84aed4..e0824dae22c74ed937ed4a1cbda4dda48a16b912 100644 --- a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/common/DomainService.java +++ b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/common/DomainService.java @@ -1,5 +1,8 @@ package org.fuseri.moduleexercise.common; +import jakarta.persistence.EntityNotFoundException; +import org.springframework.data.jpa.repository.JpaRepository; + /** * Represent common service for managing entities * @@ -17,7 +20,7 @@ public abstract class DomainService<T extends DomainObject> { * * @return the repository used by this service */ - public abstract DomainRepository<T, String> getRepository(); + public abstract JpaRepository<T, Long> getRepository(); /** * Create an entity by saving it to the repository @@ -32,18 +35,24 @@ public abstract class DomainService<T extends DomainObject> { /** * Update an entity * + * @param id the entity ID * @param entity the entity to update * @return the updated entity */ - public T update(T entity) { - return getRepository().update(entity); + public T update(long id, T entity) { + if (!getRepository().existsById(id)) { + throw new EntityNotFoundException("Entity with id " + entity.getId() + " not found."); + } + entity.setId(id); + return getRepository().save(entity); } /** * Delete an entity with specified id * @param id id of the entity to delete */ - public void delete(String id) { + public void delete(long id) { getRepository().deleteById(id); } + } \ No newline at end of file diff --git a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/exercise/Exercise.java b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/exercise/Exercise.java index 65ff0e59f9a31773168eaf378000bac45f010fd0..6070b8a70b26a36f3e87b4f4661a43a64625cfe5 100644 --- a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/exercise/Exercise.java +++ b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/exercise/Exercise.java @@ -1,5 +1,6 @@ package org.fuseri.moduleexercise.exercise; +import jakarta.persistence.*; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; @@ -18,6 +19,8 @@ import java.util.Set; @Setter @NoArgsConstructor @Builder +@Entity +@Table(name = "exercise") public class Exercise extends DomainObject { private String name; @@ -26,8 +29,10 @@ public class Exercise extends DomainObject { private int difficulty; - private String courseId; + @Column(name = "lecture_id") + private long courseId; + @OneToMany(mappedBy="exercise", cascade = CascadeType.ALL) private Set<Question> questions = new HashSet<>(); /** @@ -39,7 +44,7 @@ public class Exercise extends DomainObject { * @param courseId id of lecture to which exercise belongs * @param questions question exercise contains */ - public Exercise(String name, String description, int difficulty, String courseId, Set<Question> questions) { + public Exercise(String name, String description, int difficulty, long courseId, Set<Question> questions) { this.name = name; this.description = description; this.difficulty = difficulty; diff --git a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/exercise/ExerciseController.java b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/exercise/ExerciseController.java index 1a53e6f9630c53ba29d16275f982202628181fbf..96f91fc77b92040b231cc51218ff393a26184530 100644 --- a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/exercise/ExerciseController.java +++ b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/exercise/ExerciseController.java @@ -1,17 +1,28 @@ package org.fuseri.moduleexercise.exercise; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; import jakarta.persistence.EntityNotFoundException; import jakarta.validation.Valid; -import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.PositiveOrZero; -import org.fuseri.model.dto.common.Result; import org.fuseri.model.dto.exercise.ExerciseCreateDto; import org.fuseri.model.dto.exercise.ExerciseDto; +import org.fuseri.model.dto.exercise.QuestionDto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.server.ResponseStatusException; +import org.springframework.http.ResponseEntity; +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; /** * Represent a REST API controller for exercises @@ -21,104 +32,153 @@ import org.springframework.web.server.ResponseStatusException; @RequestMapping("/exercises") public class ExerciseController { - private final ExerciseService service; - - private final ExerciseMapper mapper; + private final ExerciseFacade facade; /** - * Constructor for AnswerController + * Constructor for ExerciseController * - * @param service the service responsible for handling exercise-related logic - * @param mapper the mapper responsible for converting between DTOs and entities + * @param facade the facade responsible for handling exercise-related logic */ @Autowired - public ExerciseController(ExerciseService service, ExerciseMapper mapper) { - this.service = service; - this.mapper = mapper; + public ExerciseController(ExerciseFacade facade) { + this.facade = facade; } /** - * Create a new answer for the given question ID + * Create a new exercise * - * @param dto the ExerciseCreateDto object containing information about the exercise to create - * @return an ExerciseDto object representing the newly created exercise + * @param dto containing information about the exercise to create + * @return a ResponseEntity containing an ExerciseDto object representing the newly created exercise */ + @Operation(summary = "Create an exercise", description = "Creates a new exercise.") + @ApiResponses(value = { + @ApiResponse(responseCode = "201", description = "Exercise created successfully."), + @ApiResponse(responseCode = "400", description = "Invalid input.") + }) @PostMapping - public ExerciseDto create(@Valid @RequestBody ExerciseCreateDto dto) { - Exercise exercise = mapper.fromCreateDto(dto); - return mapper.toDto(service.create(exercise)); + public ResponseEntity<ExerciseDto> create(@Valid @RequestBody ExerciseCreateDto dto) { + ExerciseDto exerciseDto = facade.create(dto); + return ResponseEntity.status(HttpStatus.CREATED).body(exerciseDto); } /** * Find an exercise by ID * * @param id the ID of the exercise to find - * @return an ExerciseDto object representing the found exercise + * @return a ResponseEntity containing an ExerciseDto object representing the found exercise, or a 404 Not Found response + * if the exercise with the specified ID was not found */ + @Operation(summary = "Get an exercise by ID", description = "Returns an exercise with the specified ID.") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Exercise with the specified ID retrieved successfully."), + @ApiResponse(responseCode = "404", description = "Exercise with the specified ID was not found.") + }) @GetMapping("/{id}") - public ExerciseDto find(@NotBlank @PathVariable String id) { - return mapper.toDto(service.find(id)); + public ResponseEntity<ExerciseDto> find(@NotNull @PathVariable long id) { + try { + return ResponseEntity.ok(facade.find(id)); + } catch (EntityNotFoundException e) { + return ResponseEntity.notFound().build(); + } } /** - * Find exercises and return them in a paginated format + * Find exercises and return them in paginated format * * @param page the page number of the exercises to retrieve - * @return a Result object containing a list of ExerciseDto objects and pagination information + * @return A ResponseEntity containing paginated ExerciseDTOs. */ + @Operation(summary = "Get exercises in paginated format", description = "Returns exercises in paginated format.") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Successfully retrieved paginated exercises"), + @ApiResponse(responseCode = "400", description = "Invalid page number supplied"), + }) @GetMapping - public Result<ExerciseDto> findAll(@PositiveOrZero @RequestParam int page) { - Page<Exercise> exercise = service.findAll(page); - return mapper.toResult(exercise); + public ResponseEntity<Page<ExerciseDto>> findAll(@PositiveOrZero @RequestParam int page) { + return ResponseEntity.ok(facade.findAll(page)); } /** * Find exercises that mach filters and return them in paginated format * - * @param page the page number of the exercises to retrieve * @param courseId the id of the course to filter by * @param difficulty the difficulty level to filter by - * @return a Result object containing a list of filtered ExerciseDto objects woth pagination information + * @param page the page number of the exercises to retrieve + * @return A ResponseEntity containing filtered and paginated ExerciseDTOs */ + @Operation(summary = "Filter exercises per difficulty and per course", description = "Returns exercises which belong to specified course and have specified difficulty.") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Successfully retrieved filtered paginated exercises."), + }) @GetMapping("filter") - public Result<ExerciseDto> findPerDifficultyPerCourse( - @PositiveOrZero @RequestParam int page, @NotBlank @RequestParam String courseId, + public ResponseEntity<Page<ExerciseDto>> findPerDifficultyPerCourse( + @PositiveOrZero @RequestParam int page, @NotNull @RequestParam long courseId, @PositiveOrZero @RequestParam int difficulty) { - Page<Exercise> exercise = service.findPerDifficultyPerCourse(page, courseId, difficulty); - return mapper.toResult(exercise); + Page<ExerciseDto> exercises = facade.findByCourseIdAndDifficulty(courseId, difficulty, page); + return ResponseEntity.ok(exercises); + } + + /** + * Find questions by exercise ID and return them in a paginated format + * + * @param exerciseId the ID of the exercise to find questions for + * @param page the page number of the questions to retrieve + * @return a ResponseEntity containing paginated QuestionDTOs which belong to an exercise with exerciseId + * or a NOT_FOUND response if the exercise ID is invalid + */ + @Operation(summary = "Find questions belonging to exercise by exercise ID", + description = "Returns a paginated list of questions for the specified exercise ID.") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Questions found and returned successfully."), + @ApiResponse(responseCode = "404", description = "Exercise with the specified ID was not found.") + }) + @GetMapping("/{exercise-id}/questions") + public ResponseEntity<Page<QuestionDto>> findQuestions(@NotNull @PathVariable("exercise-id") long exerciseId, + @PositiveOrZero @RequestParam int page) { + try { + Page<QuestionDto> questions = facade.getQuestions(exerciseId, page); + return ResponseEntity.ok(questions); + } catch (EntityNotFoundException e) { + return ResponseEntity.notFound().build(); + } } /** - * Update an exercise with id + * Update an exercise with ID * * @param id the ID of the exercise to update * @param dto the ExerciseCreateDto object containing information about the exercise to update - * @return an ExerciseDto object representing the updated exercise - * @throws ResponseStatusException invalid exercise id + * @return A ResponseEntity with an ExerciseDto object representing the updated exercise an HTTP status code of 200 if the update was successful. + * or a NOT_FOUND response if the exercise ID is invalid */ - + @Operation(summary = "Update a exercise", description = "Updates a exercise with the specified ID.") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Exercise with the specified ID updated successfully."), + @ApiResponse(responseCode = "400", description = "Invalid input."), + @ApiResponse(responseCode = "404", description = "Exercise with the specified ID was not found.") + }) @PutMapping("/{id}") - public ExerciseDto update(@NotBlank @PathVariable String id, @Valid @RequestBody ExerciseCreateDto dto) { - Exercise exercise = mapper.fromCreateDto(dto); - exercise.setId(id); - + public ResponseEntity<ExerciseDto> update(@NotNull @PathVariable long id, @Valid @RequestBody ExerciseCreateDto dto) { try { - return mapper.toDto(service.update(exercise)); - } catch (IllegalArgumentException e) { - throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage()); + return ResponseEntity.ok(facade.update(id, dto)); } catch (EntityNotFoundException e) { - throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage()); + return ResponseEntity.notFound().build(); } } /** - * Delete an exercise with exerciseId + * Delete an exercise with ID * * @param id the ID of the exercise to delete */ + @Operation(summary = "Delete a exercise with specified ID", description = "Deletes a exercise with the specified ID.") + @ApiResponses(value = { + @ApiResponse(responseCode = "204", description = "Exercise with the specified ID deleted successfully."), + }) @DeleteMapping("/{id}") - public void delete(@NotBlank @PathVariable String id) { - service.delete(id); + public ResponseEntity<Void> delete(@NotNull @PathVariable long id) { + facade.delete(id); + return ResponseEntity.noContent().build(); } } diff --git a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/exercise/ExerciseFacade.java b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/exercise/ExerciseFacade.java new file mode 100644 index 0000000000000000000000000000000000000000..3134fadf5997e659f224d894f775c1df19e1ec90 --- /dev/null +++ b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/exercise/ExerciseFacade.java @@ -0,0 +1,121 @@ +package org.fuseri.moduleexercise.exercise; + +import jakarta.persistence.EntityNotFoundException; +import jakarta.transaction.Transactional; +import org.fuseri.model.dto.exercise.ExerciseCreateDto; +import org.fuseri.model.dto.exercise.ExerciseDto; +import org.fuseri.model.dto.exercise.QuestionDto; +import org.fuseri.moduleexercise.question.Question; +import org.fuseri.moduleexercise.question.QuestionMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.stereotype.Service; + +/** + * Represent facade for managing exercises + * Provide simplified interface for manipulating with exercises + */ +@Service +@Transactional +public class ExerciseFacade { + private final ExerciseService exerciseService; + private final ExerciseMapper exerciseMapper; + private final QuestionMapper questionMapper; + + /** + * Constructor for AnswerFacade + * + * @param exerciseService the service responsible for handling answer-related logic + * @param exerciseMapper the mapper responsible for converting between DTOs and entities + */ + @Autowired + public ExerciseFacade(ExerciseService exerciseService, ExerciseMapper exerciseMapper, QuestionMapper questionMapper) { + this.exerciseService = exerciseService; + this.exerciseMapper = exerciseMapper; + this.questionMapper = questionMapper; + } + + /** + * Create a new exercise + * + * @param exerciseDto dto with information from which exercise is created + * @return a created exercise dto + */ + public ExerciseDto create(ExerciseCreateDto exerciseDto) { + Exercise exerciseToCreate = exerciseMapper.fromCreateDto(exerciseDto); + Exercise createdExercise = exerciseService.create(exerciseToCreate); + return exerciseMapper.toDto(createdExercise); + } + + /** + * Retrieve the Exercise entity with the specified ID + * + * @param id the ID of the Exercise entity to retrieve + * @return the Exercise entity with the specified ID + * @throws EntityNotFoundException if no Exercise entity exists with the specified ID + */ + @org.springframework.transaction.annotation.Transactional(readOnly = true) + public ExerciseDto find(long id) { + return exerciseMapper.toDto(exerciseService.find(id)); + } + + /** + * Retrieve a page of Exercise entities + * + * @param page the page number to retrieve (0-indexed) + * @return paginated exerciseDTOs + */ + @org.springframework.transaction.annotation.Transactional(readOnly = true) + public Page<ExerciseDto> findAll(int page) { + return exerciseMapper.toDtoPage(exerciseService.findAll(page)); + } + + /** + * Retrieve a page of exercises filtered by the specified course id and difficulty level + * + * @param page the page number to retrieve + * @param courseId the id of the course to filter by + * @param difficulty the difficulty level to filter by + * @return paginated exerciseDTOs filtered by the specified course ID and difficulty level + */ + public Page<ExerciseDto> findByCourseIdAndDifficulty(long courseId, int difficulty, int page) { + Page<Exercise> exercises = exerciseService.findByCourseIdAndDifficulty(courseId, difficulty, page); + return exerciseMapper.toDtoPage(exercises); + } + + /** + * Retrieve a page of Question entities associated with the specified exercise ID + * + * @param exerciseId the ID of the exercise to retrieve questions for + * @param page the page number to retrieve (0-indexed) + * @return paginated questionDTOs associated with the specified exercise ID + */ + @org.springframework.transaction.annotation.Transactional(readOnly = true) + public Page<QuestionDto> getQuestions(long exerciseId, int page) { + Page<Question> questions = exerciseService.getQuestions(exerciseId, page); + return questionMapper.toDtoPage(questions); + } + + /** + * Update exercise + * + * @param id the ID of the exercise to update + * @param dto the ExerciseCreateDto object containing information about the exercise to update + * @return an ExerciseDto object representing the updated exercise + */ + public ExerciseDto update(long id, ExerciseCreateDto dto) { + Exercise exercise = exerciseMapper.fromCreateDto(dto); + Exercise updatedExercise = exerciseService.update(id, exercise); + return exerciseMapper.toDto(updatedExercise); + } + + /** + * Delete exercise + * + * @param id of exercise to delete + */ + public void delete(long id) { + exerciseService.delete(id); + } + +} diff --git a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/exercise/ExerciseMapper.java b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/exercise/ExerciseMapper.java index 3c211aaa5d034ecba3b54e738da0ebb4315b51bf..3b44db86873b1f10c1911149a9a018f25dfb423a 100644 --- a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/exercise/ExerciseMapper.java +++ b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/exercise/ExerciseMapper.java @@ -1,9 +1,14 @@ package org.fuseri.moduleexercise.exercise; +import org.fuseri.model.dto.course.CourseDto; import org.fuseri.model.dto.exercise.ExerciseCreateDto; import org.fuseri.model.dto.exercise.ExerciseDto; import org.fuseri.moduleexercise.common.DomainMapper; import org.mapstruct.Mapper; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; + +import java.util.List; /** * Mapper between Exercises and their corresponding DTOs @@ -18,4 +23,10 @@ public interface ExerciseMapper extends DomainMapper<Exercise, ExerciseDto> { * @return corresponding Exercise entity created from DTO */ Exercise fromCreateDto(ExerciseCreateDto dto); + + List<ExerciseDto> mapToList(List<Exercise> persons); + + default Page<ExerciseDto> mapToPageDto(Page<Exercise> courses) { + return new PageImpl<>(mapToList(courses.getContent()), courses.getPageable(), courses.getTotalPages()); + } } diff --git a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/exercise/ExerciseRepository.java b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/exercise/ExerciseRepository.java index 76ec2a3a1eaf05eb979ccd4cdd8d5267397addb3..a2ff556892065d2be6b365566bf3bac9a6e0a504 100644 --- a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/exercise/ExerciseRepository.java +++ b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/exercise/ExerciseRepository.java @@ -1,24 +1,34 @@ package org.fuseri.moduleexercise.exercise; -import org.fuseri.model.dto.common.Result; -import org.fuseri.moduleexercise.common.DomainRepository; +import org.fuseri.moduleexercise.question.Question; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; /** * A repository interface for managing Exercise entities */ -public interface ExerciseRepository extends DomainRepository<Exercise, String> { +@Repository +public interface ExerciseRepository extends JpaRepository<Exercise, Long> { /** * Filters the exercises by the specified difficulty level and course id, - * and returns a {@link Result} object containing these filtered exercises + * and returns an object containing these filtered exercises * along with pagination information * - * @param pageRequest the pagination settings for the result - * @param courseId the id of the course to filter by - * @param difficulty the difficulty level to filter by - * @return a {@link Result} object containing a list of paginated exercises that match the filter criteria + * @param courseId the id of the course to filter by + * @param difficulty the difficulty level to filter by + * @param pageable the pagination settings + * @return object containing a list of paginated exercises that match the filter criteria */ - Page<Exercise> filterPerDifficultyPerCourse(PageRequest pageRequest, String courseId, int difficulty); + @Query("SELECT e FROM Exercise e WHERE e.courseId = :courseId AND e.difficulty = :difficulty") + Page<Exercise> findByCourseIdAndDifficulty(long courseId, int difficulty, Pageable pageable); + + @Query("SELECT q FROM Exercise e JOIN e.questions q WHERE e.id = :exerciseId") + Page<Question> getQuestions(PageRequest pageRequest, @Param("exerciseId") Long exerciseId); + } diff --git a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/exercise/ExerciseRepositoryImpl.java b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/exercise/ExerciseRepositoryImpl.java deleted file mode 100644 index 3036f93b02043658d38c332c45d2cbc154f308c6..0000000000000000000000000000000000000000 --- a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/exercise/ExerciseRepositoryImpl.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.fuseri.moduleexercise.exercise; - -import org.fuseri.model.dto.common.Result; -import org.fuseri.moduleexercise.common.DomainRepositoryImpl; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.PageRequest; -import org.springframework.stereotype.Repository; - -import java.util.List; - -/** - * An implementation of the ExerciseRepository interface - * Provides access to Exercise entities stored in a data source - */ -@Repository -public class ExerciseRepositoryImpl extends DomainRepositoryImpl<Exercise> implements ExerciseRepository { - - /** - * Filters the exercises by the specified difficulty level and course id, - * and returns a {@link Result} object containing these filtered exercises - * along with pagination information - * - * @param pageRequest the pagination settings for the result - * @param courseId the id of the course to filter by - * @param difficulty the difficulty level to filter by - * @return a {@link Result} object containing a list of paginated exercises that match the filter criteria - */ - @Override - public Page<Exercise> filterPerDifficultyPerCourse(PageRequest pageRequest, String courseId, int difficulty) { - - int startIndex = pageRequest.getPageNumber() * pageRequest.getPageSize(); - - List<Exercise> pageEntities = getItems().stream() - .filter(e -> e.getCourseId().equals(courseId) && e.getDifficulty() == difficulty) - .skip(startIndex) - .limit(pageRequest.getPageSize()) - .toList(); - - return new PageImpl<>(pageEntities, pageRequest, pageEntities.size()); - } -} diff --git a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/exercise/ExerciseService.java b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/exercise/ExerciseService.java index 677c704a7892b13672c8534c0d731d3ba7a2abb6..41aa3c7e68a9c05b82fe0634d17c481525451d7c 100644 --- a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/exercise/ExerciseService.java +++ b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/exercise/ExerciseService.java @@ -3,6 +3,7 @@ package org.fuseri.moduleexercise.exercise; import jakarta.persistence.EntityNotFoundException; import lombok.Getter; import org.fuseri.moduleexercise.common.DomainService; +import org.fuseri.moduleexercise.question.Question; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; @@ -39,7 +40,7 @@ public class ExerciseService extends DomainService<Exercise> { * @throws EntityNotFoundException if no Exercise entity exists with the specified ID */ @Transactional(readOnly = true) - public Exercise find(String id) { + public Exercise find(long id) { return repository.findById(id) .orElseThrow(() -> new EntityNotFoundException("Exercise '" + id + "' not found.")); } @@ -58,13 +59,30 @@ public class ExerciseService extends DomainService<Exercise> { /** * Retrieve a page of exercises filtered by the specified course id and difficulty level * - * @param page the page number to retrieve * @param courseId the id of the course to filter by * @param difficulty the difficulty level to filter by - * @return a {@link Page} of {@link Exercise} objects filtered by the specified course id and difficulty level + * @param page the page number to retrieve + * @return paginated exercises filtered by the specified course ID and difficulty level */ - public Page<Exercise> findPerDifficultyPerCourse(int page, String courseId, int difficulty) { - return repository.filterPerDifficultyPerCourse( - PageRequest.of(page, DEFAULT_PAGE_SIZE), courseId, difficulty); + public Page<Exercise> findByCourseIdAndDifficulty(long courseId, int difficulty, int page) { + return repository.findByCourseIdAndDifficulty(courseId, difficulty, PageRequest.of(page, DEFAULT_PAGE_SIZE)); } + + /** + * Retrieve a page of Question entities associated with the specified exercise ID + * + * @param exerciseId the ID of the exercise to retrieve questions for + * @param page the page number to retrieve (0-indexed) + * @return a page of Question entities associated with the specified exercise ID + */ + @Transactional(readOnly = true) + public Page<Question> getQuestions(long exerciseId, int page) { + if (!repository.existsById(exerciseId)) { + throw new EntityNotFoundException("Exercise with ID " + exerciseId + "does not exist."); + } + return repository.getQuestions( + PageRequest.of(page, DomainService.DEFAULT_PAGE_SIZE), + exerciseId); + } + } diff --git a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/question/Question.java b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/question/Question.java index 042604af6ad1e339be34b38f5481806938dfbb38..03f62910b63062589484675c9f4d1ba436ec60c5 100644 --- a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/question/Question.java +++ b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/question/Question.java @@ -1,14 +1,21 @@ package org.fuseri.moduleexercise.question; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; +import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.fuseri.moduleexercise.answer.Answer; import org.fuseri.moduleexercise.common.DomainObject; +import org.fuseri.moduleexercise.exercise.Exercise; import java.util.HashSet; -import java.util.Objects; import java.util.Set; /** @@ -17,25 +24,27 @@ import java.util.Set; @Getter @Setter @NoArgsConstructor +@AllArgsConstructor @Builder +@Entity +@Table(name = "question") public class Question extends DomainObject { private String text; + @OneToMany(mappedBy = "question", cascade = CascadeType.ALL, orphanRemoval = true) private Set<Answer> answers = new HashSet<>(); - private String exerciseId; + @ManyToOne + @JoinColumn(name = "exercise_id", nullable = false) + private Exercise exercise; /** - * Constructor of question + * Add answers to question * - * @param text question text - * @param answers question answers - * @param exerciseId id of exercise the question belongs to + * @param answersToAdd to add */ - public Question(String text, Set<Answer> answers, String exerciseId) { - this.text = text; - this.answers = Objects.requireNonNullElseGet(answers, HashSet::new); - this.exerciseId = exerciseId; + public void addAnswers(Set<Answer> answersToAdd) { + answers.addAll(answersToAdd); } } diff --git a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/question/QuestionController.java b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/question/QuestionController.java index bd217cc1c00f36d02b1b074b6e9028c20e291220..9857e1c3d46120979b04339b2ddf0293c22c0ed8 100644 --- a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/question/QuestionController.java +++ b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/question/QuestionController.java @@ -1,17 +1,32 @@ package org.fuseri.moduleexercise.question; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; import jakarta.persistence.EntityNotFoundException; import jakarta.validation.Valid; -import jakarta.validation.constraints.NotBlank; -import jakarta.validation.constraints.PositiveOrZero; -import org.fuseri.model.dto.common.Result; +import jakarta.validation.constraints.NotNull; +import org.fuseri.model.dto.exercise.AnswerDto; +import org.fuseri.model.dto.exercise.AnswerInQuestionCreateDto; import org.fuseri.model.dto.exercise.QuestionCreateDto; import org.fuseri.model.dto.exercise.QuestionDto; import org.fuseri.model.dto.exercise.QuestionUpdateDto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.server.ResponseStatusException; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PatchMapping; +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.RestController; + +import java.util.List; /** * Represent a REST API controller for questions @@ -37,40 +52,64 @@ public class QuestionController { * Find a question by ID. * * @param id the ID of the question to find - * @return a QuestionDto object representing the found question + * @return a ResponseEntity containing a QuestionDto object representing the found question, or a 404 Not Found response + * if the question with the specified ID was not found */ + @Operation(summary = "Get a question by ID", description = "Returns a question with the specified ID.") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Question with the specified ID retrieved successfully.", + content = @Content(schema = @Schema(implementation = QuestionDto.class))), + @ApiResponse(responseCode = "404", description = "Question with the specified ID was not found.") + }) @GetMapping("/{id}") - public QuestionDto find(@NotBlank @PathVariable String id) { - return questionFacade.find(id); + public ResponseEntity<QuestionDto> find(@NotNull @PathVariable long id) { + try { + return ResponseEntity.ok(questionFacade.find(id)); + } catch (EntityNotFoundException e) { + return ResponseEntity.notFound().build(); + } } /** - * Find questions by exercise ID and return them in a paginated format + * Retrieve a list of AnswerDto objects which belong to the question with ID * - * @param exerciseId the ID of the exercise to find questions for - * @param page the page number of the questions to retrieve - * @return a Result object containing a list of QuestionDto objects and pagination information + * @param id the ID of the question for which to retrieve answers + * @return a ResponseEntity containing a List of AnswerDto objects, or a 404 Not Found response + * if the question with the specified ID was not found */ - @GetMapping("/exercise/{exercise-id}") - public Result<QuestionDto> findByExerciseId(@NotBlank @PathVariable("exercise-id") String exerciseId, - @PositiveOrZero @RequestParam int page) { - return questionFacade.findByExerciseId(exerciseId, page); + @Operation(summary = "Retrieve answers for a specific question") + @ApiResponse(responseCode = "200", description = "Successfully retrieved answers", + content = @Content(schema = @Schema(implementation = AnswerDto.class))) + @ApiResponse(responseCode = "404", description = "Question not found") + @GetMapping("/{id}/answers") + public ResponseEntity<List<AnswerDto>> getQuestionAnswers(@NotNull @PathVariable long id) { + try { + return ResponseEntity.ok(questionFacade.getQuestionAnswers(id)); + } catch (EntityNotFoundException e) { + return ResponseEntity.notFound().build(); + } } /** * Add a new question to an exercise * * @param dto a QuestionCreateDto object representing the new question to add - * @return a QuestionDto object representing the added question - * @throws ResponseStatusException if the exercise with exerciseId from QuestionCreateDto does not exist + * @return a ResponseEntity containing a QuestionDto object representing the posted question, or a 404 Not Found response + * if the exercise with the specified ID in dto was not found */ + @Operation(summary = "Add a new question with answers to an exercise", description = "Creates a new question with answers and associates it with the specified exercise.") + @ApiResponses(value = { + @ApiResponse(responseCode = "201", description = "Question with answers created and added to the exercise successfully.", + content = @Content(schema = @Schema(implementation = QuestionDto.class))), + @ApiResponse(responseCode = "404", description = "Exercise with the specified ID was not found.") + }) @PostMapping - public QuestionDto addQuestion(@Valid @RequestBody QuestionCreateDto dto) { + public ResponseEntity<QuestionDto> addQuestion(@Valid @RequestBody QuestionCreateDto dto) { try { - return questionFacade.create(dto); + QuestionDto createdQuestionDto = questionFacade.create(dto); + return ResponseEntity.status(HttpStatus.CREATED).body(createdQuestionDto); } catch (EntityNotFoundException e) { - throw new ResponseStatusException(HttpStatus.NOT_FOUND, - e.getMessage()); + return ResponseEntity.notFound().build(); } } @@ -78,27 +117,52 @@ public class QuestionController { * Update question * * @param dto a QuestionDto object representing the updated question with correct id - * @return a QuestionUpdateDto object representing the updated question - * @throws ResponseStatusException if the question with id doesn't exist or its exercise doesn't exist + * @return a ResponseEntity containing a QuestionUpdateDto object representing the updated question, + * or a 404 Not Found response if the question with the specified ID was not found */ + @Operation(summary = "Update a question by ID", description = "Updates a question with the specified ID.") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Question with the specified ID updated successfully."), + @ApiResponse(responseCode = "404", description = "Question with the specified ID was not found.") + }) @PutMapping("/{id}") - public QuestionDto updateQuestion(@NotBlank @PathVariable String id, @Valid @RequestBody QuestionUpdateDto dto) { + public ResponseEntity<QuestionDto> updateQuestion(@NotNull @PathVariable long id, @Valid @RequestBody QuestionUpdateDto dto) { try { - return questionFacade.update(id, dto); - } catch (IllegalArgumentException e) { - throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage()); + return ResponseEntity.ok(questionFacade.patchUpdate(id, dto)); } catch (EntityNotFoundException e) { - throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage()); + return ResponseEntity.notFound().build(); } } /** - * Add a new question to an exercise + * Delete question with ID from exercise * * @param id of question to delete */ + @Operation(summary = "Delete a question with specified ID", description = "Deletes a question with the specified ID.") + @ApiResponses(value = { + @ApiResponse(responseCode = "204", description = "Question with the specified ID deleted successfully."), + }) @DeleteMapping("/{id}") - public void deleteQuestion(@NotBlank @PathVariable String id) { + public ResponseEntity<Void> deleteQuestion(@NotNull @PathVariable long id) { questionFacade.delete(id); + return ResponseEntity.noContent().build(); + } + + /** + * Adds answers to the existing question resource + * + * @param id id of question to update + * @return the LectureDto representing the updated lecture + */ + @Operation(summary = "Add answers to the existing question.") + @PatchMapping("/{id}/answers") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "The question has been successfully updated"), + @ApiResponse(responseCode = "400", description = "The request body is invalid"), + @ApiResponse(responseCode = "404", description = "The question with the specified ID does not exist") + }) + public ResponseEntity<QuestionDto> addAnswers(@PathVariable Long id, @RequestBody List<AnswerInQuestionCreateDto> answerDtoList) { + return ResponseEntity.ok(questionFacade.addAnswers(id, answerDtoList)); } } \ No newline at end of file diff --git a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/question/QuestionFacade.java b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/question/QuestionFacade.java index 2f2cfc9f4219b69c9c475ecc70c6c4de428233a5..8fe1e2a19f4fd2663aa3a22e0e5f9848829f8800 100644 --- a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/question/QuestionFacade.java +++ b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/question/QuestionFacade.java @@ -1,40 +1,36 @@ package org.fuseri.moduleexercise.question; -import org.fuseri.model.dto.common.Result; +import jakarta.transaction.Transactional; +import org.fuseri.model.dto.exercise.AnswerDto; +import org.fuseri.model.dto.exercise.AnswerInQuestionCreateDto; import org.fuseri.model.dto.exercise.QuestionCreateDto; import org.fuseri.model.dto.exercise.QuestionDto; import org.fuseri.model.dto.exercise.QuestionUpdateDto; -import org.fuseri.moduleexercise.answer.Answer; import org.fuseri.moduleexercise.answer.AnswerMapper; import org.fuseri.moduleexercise.answer.AnswerService; -import org.fuseri.moduleexercise.exercise.Exercise; -import org.fuseri.moduleexercise.exercise.ExerciseService; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; import org.springframework.stereotype.Service; -import java.util.HashSet; import java.util.List; /** * Represent facade for managing questions * Provide simplified interface for manipulating with questions */ +@Transactional @Service public class QuestionFacade { private final QuestionService questionService; - private final ExerciseService exerciseService; private final AnswerService answerService; private final QuestionMapper questionMapper; private final AnswerMapper answerMapper; @Autowired public QuestionFacade( - QuestionService questionService, ExerciseService exerciseService, + QuestionService questionService, AnswerService answerService, QuestionMapper questionMapper, AnswerMapper answerMapper) { this.questionService = questionService; - this.exerciseService = exerciseService; this.answerService = answerService; this.questionMapper = questionMapper; this.answerMapper = answerMapper; @@ -46,21 +42,29 @@ public class QuestionFacade { * @param id the ID of the question to find * @return a QuestionDto object representing the found question */ - public QuestionDto find(String id) { - var a = questionService.find(id); - return questionMapper.toDto(a); + public QuestionDto find(long id) { + return questionMapper.toDto(questionService.find(id)); } /** - * Find questions by exercise ID and return them in a paginated format + * Retrieve a list of AnswerDto objects which belong to question with questionId * - * @param exerciseId the ID of the exercise to find questions for - * @param page the page number of the questions to retrieve - * @return a Result object containing a list of QuestionDto objects and pagination information + * @param questionId the ID of the question for which to retrieve answers + * @return a List of AnswerDto objects */ - public Result<QuestionDto> findByExerciseId(String exerciseId, int page) { - Page<Question> questions = questionService.findByExerciseId(exerciseId, page); - return questionMapper.toResult(questions); + public List<AnswerDto> getQuestionAnswers(long questionId) { + return answerMapper.toDtoList(answerService.findAllByQuestionId(questionId)); + } + + /** + * Add answers to question + * + * @param id question ID + * @param dto List with AnswerInQuestionCreateDto to add to question + * @return a QuestionDto object representing the updated question + */ + public QuestionDto addAnswers(Long id, List<AnswerInQuestionCreateDto> dto) { + return questionMapper.toDto(questionService.addAnswers(id, answerMapper.fromCreateDtoList(dto))); } /** @@ -70,30 +74,7 @@ public class QuestionFacade { * @return a QuestionDto object representing the added question */ public QuestionDto create(QuestionCreateDto dto) { - Question question = questionMapper.fromCreateDto(dto); - - Exercise exercise; - exercise = exerciseService.find(question.getExerciseId()); - - exercise.getQuestions().add(question); - question.setExerciseId(exercise.getId()); - - var answerDtos = dto.getAnswers(); - var answers = new HashSet<Answer>(); - for (var answerDto : answerDtos) { - Answer answer = answerMapper.fromCreateDto(answerDto); - answer = answerService.create(answer); - answers.add(answer); - } - - question.setAnswers(answers); - var createdQuestion = questionService.create(question); - - for (var answer : answers) { - answer.setQuestionId(createdQuestion.getId()); - } - - return questionMapper.toDto(createdQuestion); + return questionMapper.toDto(questionService.create(questionMapper.fromCreateDto(dto))); } /** @@ -102,12 +83,8 @@ public class QuestionFacade { * @param dto dto of updated question with correct id * @return dto of updated question */ - public QuestionDto update(String id, QuestionUpdateDto dto) { - Question question = questionMapper.fromUpdateDto(dto); - question.setId(id); - List<Answer> questionAnswers = answerService.findAllByQuestionId(id); - question.setAnswers(new HashSet<>(questionAnswers)); - Question updatedQuestion = questionService.update(question); + public QuestionDto patchUpdate(long id, QuestionUpdateDto dto) { + var updatedQuestion = questionService.patchUpdateWithoutAnswers(id, questionMapper.fromUpdateDto(dto)); return questionMapper.toDto(updatedQuestion); } @@ -116,11 +93,7 @@ public class QuestionFacade { * * @param id of qustion to delete */ - public void delete(String id) { - var question = questionService.find(id); - for (var answer : question.getAnswers()) { - answerService.delete(answer.getId()); - } + public void delete(long id) { questionService.delete(id); } } diff --git a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/question/QuestionMapper.java b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/question/QuestionMapper.java index 9c4e62a2a7845c32941b219a539030fcdbf98a16..b3cd97079670ef1e2c239e08076a8748643b7110 100644 --- a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/question/QuestionMapper.java +++ b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/question/QuestionMapper.java @@ -1,17 +1,53 @@ package org.fuseri.moduleexercise.question; +import org.fuseri.model.dto.exercise.AnswerInQuestionCreateDto; import org.fuseri.model.dto.exercise.QuestionCreateDto; import org.fuseri.model.dto.exercise.QuestionDto; import org.fuseri.model.dto.exercise.QuestionUpdateDto; +import org.fuseri.moduleexercise.answer.Answer; +import org.fuseri.moduleexercise.answer.AnswerMapper; import org.fuseri.moduleexercise.common.DomainMapper; +import org.fuseri.moduleexercise.exercise.Exercise; +import org.fuseri.moduleexercise.exercise.ExerciseService; import org.mapstruct.Mapper; import org.mapstruct.Mapping; +import org.mapstruct.Named; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.List; +import java.util.Set; /** * Mapper between Questions and their corresponding DTOs */ -@Mapper -public interface QuestionMapper extends DomainMapper<Question, QuestionDto> { +@Mapper(componentModel = "spring", uses = {AnswerMapper.class, ExerciseService.class}) +public abstract class QuestionMapper implements DomainMapper<Question, QuestionDto> { + + @Autowired + private ExerciseService exerciseService; + + @Autowired + private AnswerMapper answerMapper; + + @Named("mapIdToExercise") + public Exercise mapIdToExercise(Long id) { + return exerciseService.find(id); + } + + @Named("mapDtoAnswersToAnswers") + public Set<Answer> mapDtoAnswersToAnswers(List<AnswerInQuestionCreateDto> dtos) { + return answerMapper.fromCreateDtoList(dtos); + } + + /** + * Convert entity to its corresponding DTO + * + * @param question to be converted + * @return corresponding DTO created from question + */ + @Override + @Mapping(target = "exerciseId", source = "question.exercise.id") + public abstract QuestionDto toDto(Question question); /** * Convert DTO of type QuestionCreateDto to Question @@ -19,8 +55,10 @@ public interface QuestionMapper extends DomainMapper<Question, QuestionDto> { * @param dto DTO to be converted * @return corresponding Question entity created from DTO */ - @Mapping(target = "answers", ignore = true) - Question fromCreateDto(QuestionCreateDto dto); + @Mapping(target = "exercise", source = "dto.exerciseId", qualifiedByName = "mapIdToExercise") + @Mapping(target = "answers", source = "dto.answers", qualifiedByName = "mapDtoAnswersToAnswers") + public abstract Question fromCreateDto(QuestionCreateDto dto); - Question fromUpdateDto(QuestionUpdateDto dto); + @Mapping(target = "exercise", source = "dto.exerciseId", qualifiedByName = "mapIdToExercise") + public abstract Question fromUpdateDto(QuestionUpdateDto dto); } diff --git a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/question/QuestionRepository.java b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/question/QuestionRepository.java index 0f924cd5794fbfb300a826813de050a1dc7b4222..b5b2adc4d3208451e1d1789654def49121feb14f 100644 --- a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/question/QuestionRepository.java +++ b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/question/QuestionRepository.java @@ -1,20 +1,11 @@ package org.fuseri.moduleexercise.question; -import org.fuseri.moduleexercise.common.DomainRepository; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; /** * A repository interface for managing Question entities */ -public interface QuestionRepository extends DomainRepository<Question, String> { - - /** - * Find a page of questions associated with the exercise with the specified ID - * - * @param exerciseId the ID of the exercise to find questions for - * @param pageRequest the page request specifying the page number and page size - * @return a page of questions associated with the specified exercise - */ - Page<Question> findByExerciseId(String exerciseId, PageRequest pageRequest); +@Repository +public interface QuestionRepository extends JpaRepository<Question, Long> { } \ No newline at end of file diff --git a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/question/QuestionRepositoryImpl.java b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/question/QuestionRepositoryImpl.java deleted file mode 100644 index 703b89dcd133afb330a3468fb0e24cc60d0e41d4..0000000000000000000000000000000000000000 --- a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/question/QuestionRepositoryImpl.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.fuseri.moduleexercise.question; - -import org.fuseri.moduleexercise.common.DomainRepositoryImpl; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.PageRequest; -import org.springframework.stereotype.Repository; - -import java.util.List; - -/** - * An implementation of the QuestionRepository interface - * Provides access to Question entities stored in a data source - */ -@Repository -public class QuestionRepositoryImpl extends DomainRepositoryImpl<Question> implements QuestionRepository { - - /** - * Find a page of questions associated with the exercise with the specified ID - * - * @param exerciseId the ID of the exercise to find questions for - * @param pageRequest the page request specifying the page number and page size - * @return a page of questions associated with the specified exercise - */ - @Override - public Page<Question> findByExerciseId(String exerciseId, PageRequest pageRequest) { - List<Question> filteredQuestions = getItems() - .stream() - .filter(e -> e.getExerciseId().equals(exerciseId)) - .skip(pageRequest.getOffset()) - .limit(pageRequest.getPageSize()) - .toList(); - - return new PageImpl<>(filteredQuestions, pageRequest, filteredQuestions.size()); - } -} diff --git a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/question/QuestionService.java b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/question/QuestionService.java index f30867aa5da680b2f61004a645c8fe1b21534161..f0676eee28256d926e768b0fee5df3cf52275fac 100644 --- a/application/module-exercise/src/main/java/org/fuseri/moduleexercise/question/QuestionService.java +++ b/application/module-exercise/src/main/java/org/fuseri/moduleexercise/question/QuestionService.java @@ -2,13 +2,15 @@ package org.fuseri.moduleexercise.question; import jakarta.persistence.EntityNotFoundException; import lombok.Getter; +import org.fuseri.moduleexercise.answer.Answer; import org.fuseri.moduleexercise.common.DomainService; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.util.Optional; +import java.util.Set; + /** * Represent a service for managing Question entities */ @@ -39,23 +41,48 @@ public class QuestionService extends DomainService<Question> { * @throws EntityNotFoundException if no Question entity exists with the specified ID */ @Transactional(readOnly = true) - public Question find(String id) { + public Question find(long id) { return repository.findById(id) .orElseThrow(() -> new EntityNotFoundException("Question '" + id + "' not found.")); } /** - * Retrieve a page of Question entities associated with the specified exercise ID + * Patch update a question. Don't update question answers. * - * @param exerciseId the ID of the exercise to retrieve questions for - * @param page the page number to retrieve (0-indexed) - * @return a page of Question entities associated with the specified exercise ID + * @param id the question ID + * @param updatedQuestion the question to update + * @return the updated question */ - @Transactional(readOnly = true) - public Page<Question> findByExerciseId(String exerciseId, int page) { - return repository.findByExerciseId( - exerciseId, - PageRequest.of(page, DomainService.DEFAULT_PAGE_SIZE)); + @Transactional + public Question patchUpdateWithoutAnswers(Long id, Question updatedQuestion) { + Optional<Question> optionalQuestion = repository.findById(id); + if (optionalQuestion.isPresent()) { + Question question = optionalQuestion.get(); + question.setText(updatedQuestion.getText()); + question.setExercise(updatedQuestion.getExercise()); + return repository.save(question); + } else { + throw new EntityNotFoundException("Question with id: " + id + " was not found."); + } } + /** + * Add answers to question with question ID. + * + * @param id of question + * @param answers to add to question + * @return updated question + */ + public Question addAnswers(Long id, Set<Answer> answers) { + Optional<Question> optionalQuestion = repository.findById(id); + if (optionalQuestion.isPresent()) { + Question question = optionalQuestion.get(); + question.addAnswers(answers); + return repository.save(question); + } else { + throw new EntityNotFoundException( + "Question with id: " + id + " was not found."); + } + + } } diff --git a/application/module-exercise/src/main/resources/application.properties b/application/module-exercise/src/main/resources/application.properties index ec3c390e0877b6c499b7aade0abc0111d719d865..22a97362c389b6439b4b17bb0c4e7d144ce4f1a5 100644 --- a/application/module-exercise/src/main/resources/application.properties +++ b/application/module-exercise/src/main/resources/application.properties @@ -1 +1,3 @@ -server.port=5002 \ No newline at end of file +server.port=5002 +spring.h2.console.enabled=true +spring.datasource.url=jdbc:h2:mem:exercices \ No newline at end of file diff --git a/application/module-exercise/src/test/java/org/fuseri/moduleexercise/answer/AnswerControllerTest.java b/application/module-exercise/src/test/java/org/fuseri/moduleexercise/answer/AnswerControllerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..66eaea5afcd6ba64f557df3e63151398ea0bf233 --- /dev/null +++ b/application/module-exercise/src/test/java/org/fuseri/moduleexercise/answer/AnswerControllerTest.java @@ -0,0 +1,180 @@ +package org.fuseri.moduleexercise.answer; + +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.persistence.EntityNotFoundException; +import org.fuseri.model.dto.exercise.AnswerCreateDto; +import org.fuseri.model.dto.exercise.AnswerDto; +import org.fuseri.model.dto.exercise.AnswerInQuestionCreateDto; +import org.fuseri.model.dto.exercise.AnswersCreateDto; +import org.fuseri.model.dto.exercise.ExerciseCreateDto; +import org.fuseri.model.dto.exercise.QuestionCreateDto; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentMatchers; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; + +import java.util.List; + +import static org.hamcrest.Matchers.is; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest +@AutoConfigureMockMvc +public class AnswerControllerTest { + + @Autowired + ObjectMapper objectMapper; + + @Autowired + private MockMvc mockMvc; + + @MockBean + private AnswerFacade answerFacade; + long exerciseId = 1L; + ExerciseCreateDto exercise; + QuestionCreateDto question1; + QuestionCreateDto question2; + + public static String asJsonString(final Object obj) { + try { + return new ObjectMapper().writeValueAsString(obj); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @BeforeEach + void init() { + exercise = new ExerciseCreateDto("idioms", "exercise on basic idioms", 2, 0); + question1 = new QuestionCreateDto("this statement is false", exerciseId, + List.of(new AnswerInQuestionCreateDto("dis a logical paradox", true))); + question2 = new QuestionCreateDto("What month of the year has 28 days?", exerciseId, + List.of(new AnswerInQuestionCreateDto("February", false), + new AnswerInQuestionCreateDto("All of them", true))); + } + + @Test + void testCreateAnswer() throws Exception { + var answerCreateDto = new AnswerCreateDto("BA", true, 1); + var answerDto = new AnswerDto("BA", true); + when(answerFacade.create(ArgumentMatchers.isA(AnswerCreateDto.class))).thenReturn(answerDto); + + mockMvc.perform(post("/answers") + .content(asJsonString(answerCreateDto)) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.text", is("BA"))) + .andExpect(jsonPath("$.correct", is(true))); + } + + @Test + void testCreateAnswerEmptyText() throws Exception { + var incorrect1 = new AnswerInQuestionCreateDto("", false); + var createAnswer = new AnswersCreateDto(1, List.of(incorrect1)); + + mockMvc.perform(post("/answers") + .content(asJsonString(createAnswer)) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().is4xxClientError()); + } + + @Test + void testCreateAnswerMissingText() throws Exception { + var prompt = """ + { + "questionId": 1, + "answers": [ + { + "text": "something", + "correct": false + } + ] + } + """; + + mockMvc.perform(post("/answers") + .content(prompt) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().is4xxClientError()); + } + + @Test + void testCreateAnswerMissingCorrect() throws Exception { + + var prompt = """ + { + "questionId": 1, + "answers": [ + { + "text": "something" + } + ] + } + """; + + mockMvc.perform(post("/answers") + .content(prompt) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().is4xxClientError()); + } + + @Test + void testUpdate() throws Exception { + long id = 1L; + var updated = new AnswerDto("dis true", false); + when(answerFacade.update(ArgumentMatchers.eq(id), ArgumentMatchers.isA(AnswerCreateDto.class))).thenReturn(updated); + + mockMvc.perform(put("/answers/{id}", id) + .content(asJsonString(updated)) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.text", is("dis true"))) + .andExpect(jsonPath("$.correct", is(false))); + } + + @Test + void testUpdateNotFoundAnswer() throws Exception { + long id = 1L; + var toUpdate = new AnswerCreateDto("dis true", false, 1); + when(answerFacade.update(ArgumentMatchers.eq(id), ArgumentMatchers.isA(AnswerCreateDto.class))).thenThrow(new EntityNotFoundException()); + mockMvc.perform(put("/answers/{id}", id) + .content(asJsonString(toUpdate)).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isNotFound()); + } + + @Test + void testUpdateEmptyText() throws Exception { + var updated = new AnswerCreateDto("", false, 1); + mockMvc.perform(put("/answers/1") + .content(asJsonString(updated)).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().is4xxClientError()); + } + + @Test + void testUpdateMissingField() throws Exception { + var updated = """ + { + "correct": false, + "questionId": 1 + } + """; + + mockMvc.perform(put("/answers/1") + .content(updated).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().is4xxClientError()); + } + + @Test + void testDelete() throws Exception { + mockMvc.perform(delete("/answers/1")) + .andExpect(status().is2xxSuccessful()); + } +} diff --git a/application/module-exercise/src/test/java/org/fuseri/moduleexercise/answer/AnswerFacadeTest.java b/application/module-exercise/src/test/java/org/fuseri/moduleexercise/answer/AnswerFacadeTest.java new file mode 100644 index 0000000000000000000000000000000000000000..f0faeebafdfaa1d1ec4986277f83495f879ef7b0 --- /dev/null +++ b/application/module-exercise/src/test/java/org/fuseri/moduleexercise/answer/AnswerFacadeTest.java @@ -0,0 +1,53 @@ +package org.fuseri.moduleexercise.answer; + +import org.fuseri.model.dto.exercise.AnswerCreateDto; +import org.fuseri.model.dto.exercise.AnswerDto; +import org.fuseri.moduleexercise.exercise.Exercise; +import org.fuseri.moduleexercise.question.Question; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; + +import java.util.HashSet; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@SpringBootTest +class AnswerFacadeTest { + + @Autowired + private AnswerFacade answerFacade; + + @MockBean + private AnswerService answerService; + + @MockBean + private AnswerMapper answerMapper; + + private final AnswerDto answerDto = new AnswerDto("name", true); + private final AnswerCreateDto answerCreateDto = new AnswerCreateDto("name", true, 1L); + private final Question question = new Question("text", new HashSet<>(), new Exercise()); + private final Answer answer = new Answer("name", true, question); + + @Test + void update() { + long id = 1L; + when(answerMapper.fromCreateDto(answerCreateDto)).thenReturn(answer); + when(answerService.update(id, answer)).thenReturn(answer); + when(answerMapper.toDto(answer)).thenReturn(answerDto); + + AnswerDto actualDto = answerFacade.update(id, answerCreateDto); + assertEquals(answerDto, actualDto); + } + + @Test + void delete() { + long id = 1L; + answerFacade.delete(id); + verify(answerService).delete(id); + } + +} diff --git a/application/module-exercise/src/test/java/org/fuseri/moduleexercise/answer/AnswerRepositoryTest.java b/application/module-exercise/src/test/java/org/fuseri/moduleexercise/answer/AnswerRepositoryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..0f567b69064c57addccf48a92a66c5c5c72f3896 --- /dev/null +++ b/application/module-exercise/src/test/java/org/fuseri/moduleexercise/answer/AnswerRepositoryTest.java @@ -0,0 +1,91 @@ +package org.fuseri.moduleexercise.answer; + +import org.fuseri.moduleexercise.exercise.Exercise; +import org.fuseri.moduleexercise.question.Question; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; + +@DataJpaTest +class AnswerRepositoryTest { + + @Autowired + AnswerRepository answerRepository; + + @Autowired + TestEntityManager entityManager; + + Exercise exercise = new Exercise("name", "desc", 2, 1L, new HashSet<>()); + + Question question = new Question("text", new HashSet<>(), exercise); + + Answer answer = new Answer("text", false, question); + Answer answer2 = new Answer("text2", true, question); + + @BeforeEach + void init() { + entityManager.persist(exercise); + entityManager.persist(question); + } + + @Test + void saveAnswer() { + Answer createdAnswer = answerRepository.save(answer); + + Assertions.assertNotNull(createdAnswer); + Assertions.assertEquals(answer, createdAnswer); + } + + @Test + void findByQuestionId() { + entityManager.persist(answer); + entityManager.flush(); + + Answer foundAnswer = answerRepository.findById(answer.getId()).orElse(null); + + Assertions.assertNotNull(foundAnswer); + Assertions.assertEquals(foundAnswer, answer); + } + + @Test + void testFindAllQuestions() { + entityManager.persist(exercise); + entityManager.persist(question); + entityManager.persist(answer); + entityManager.persist(answer2); + entityManager.flush(); + + Page<Answer> coursePage = answerRepository.findAll(PageRequest.of(0, 42)); + + Assertions.assertEquals(2, coursePage.getTotalElements()); + Assertions.assertEquals(coursePage.getContent(), Arrays.asList(answer, answer2)); + } + + @Test + void testFindAllQuestionsEmpty() { + Page<Answer> coursePage = answerRepository.findAll(PageRequest.of(0, 42)); + + Assertions.assertEquals(0, coursePage.getTotalElements()); + Assertions.assertEquals(coursePage.getContent(), new ArrayList<>()); + } + + @Test + void testDeleteAnswer() { + Long id = entityManager.persist(answer).getId(); + entityManager.flush(); + + answerRepository.deleteById(id); + + Assertions.assertTrue(answerRepository.findById(id).isEmpty()); + } + +} diff --git a/application/module-exercise/src/test/java/org/fuseri/moduleexercise/answer/AnswerServiceTest.java b/application/module-exercise/src/test/java/org/fuseri/moduleexercise/answer/AnswerServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..ee53178ff5e7f13e73f3ed97da52421e3c6e3dcb --- /dev/null +++ b/application/module-exercise/src/test/java/org/fuseri/moduleexercise/answer/AnswerServiceTest.java @@ -0,0 +1,78 @@ +package org.fuseri.moduleexercise.answer; + +import jakarta.persistence.EntityNotFoundException; +import org.fuseri.moduleexercise.exercise.Exercise; +import org.fuseri.moduleexercise.question.Question; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; + +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@SpringBootTest +class AnswerServiceTest { + + @Autowired + AnswerService service; + + @MockBean + AnswerRepository answerRepository; + + Answer answer; + Question question; + Exercise exercise; + + @BeforeEach + void setup() { + exercise = new Exercise("idioms", "exercise on basic idioms", 2, 1L, new HashSet<>()); + question = new Question("text", new HashSet<>(), exercise); + answer = new Answer("text", false, question); + } + + + @Test + void create() { + when(answerRepository.save(answer)).thenReturn(answer); + Answer result = service.create(answer); + Assertions.assertEquals(answer, result); + verify(answerRepository).save(answer); + } + + @Test + void notFound() { + when(answerRepository.findById(anyLong())).thenReturn(Optional.empty()); + Assertions.assertThrows(EntityNotFoundException.class, () -> service.find(anyLong())); + } + + @Test + void find() { + when(answerRepository.findById(anyLong())).thenReturn(Optional.of(answer)); + + Answer result = service.find(anyLong()); + + Assertions.assertEquals(answer, result); + verify(answerRepository).findById(anyLong()); + } + + @Test + void findAllByQuestionId() { + long id = 1; + List<Answer> list = Collections.emptyList(); + + when(answerRepository.existsById(id)).thenReturn(true); + when(answerRepository.findByQuestionId(id)).thenReturn(list); + List<Answer> result = service.findAllByQuestionId(1L); + + Assertions.assertEquals(list, result); + verify(answerRepository).findByQuestionId(id); + } +} diff --git a/application/module-exercise/src/test/java/org/fuseri/moduleexercise/answer/AnswerTest.java b/application/module-exercise/src/test/java/org/fuseri/moduleexercise/answer/AnswerTest.java deleted file mode 100644 index da00608e87053cae0b248e864e0a5797d816f9bc..0000000000000000000000000000000000000000 --- a/application/module-exercise/src/test/java/org/fuseri/moduleexercise/answer/AnswerTest.java +++ /dev/null @@ -1,173 +0,0 @@ -package org.fuseri.moduleexercise.answer; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.fuseri.model.dto.exercise.AnswerDto; -import org.fuseri.model.dto.exercise.AnswerInQuestionCreateDto; -import org.fuseri.model.dto.exercise.AnswersCreateDto; -import org.fuseri.model.dto.exercise.ExerciseCreateDto; -import org.fuseri.model.dto.exercise.ExerciseDto; -import org.fuseri.model.dto.exercise.QuestionCreateDto; -import org.fuseri.model.dto.exercise.QuestionDto; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.http.MediaType; -import org.springframework.test.web.servlet.MockMvc; -import java.util.List; -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; - -@SpringBootTest -@AutoConfigureMockMvc -public class AnswerTest { - - @Autowired - ObjectMapper objectMapper; - @Autowired - private MockMvc mockMvc; - - public static String asJsonString(final Object obj) { - try { - return new ObjectMapper().writeValueAsString(obj); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private QuestionDto createQuestion(String id) throws Exception { - var question = new QuestionCreateDto("this statement is false", id, - List.of(new AnswerInQuestionCreateDto("dis a logical paradox", true))); - - - var posted = mockMvc.perform(post("/questions") - .content(asJsonString(question)) - .contentType(MediaType.APPLICATION_JSON)); - - var cont = posted.andReturn().getResponse().getContentAsString(); - var res = objectMapper.readValue(cont, QuestionDto.class); - return res; - } - - - private String createExercise() { - var postExercise = new ExerciseCreateDto("idioms", "exercise on basic idioms", 2, "0"); - - String id = ""; - - try { - var dis = mockMvc.perform(post("/exercises") - .content(asJsonString(postExercise)) - .contentType(MediaType.APPLICATION_JSON)); - var ok = dis.andReturn().getResponse().getContentAsString(); - - var ll = objectMapper.readValue(ok, ExerciseDto.class); - - id = ll.getId(); - } catch (Exception e) { - assert (false); - } - return id; - } - - - @Test - void testCreateAnswer() throws Exception { - - List<AnswerDto> res = createAnswer(); - - var expected1 = new AnswerDto("True", false); - var expected2 = new AnswerDto("False", false); - - assert (res.get(0).equals(expected1)); - assert (res.get(1).equals(expected2)); - - } - - private List<AnswerDto> createAnswer() throws Exception { - var exerciseId = createExercise(); - var question = createQuestion(exerciseId); - - var incorrect1 = new AnswerInQuestionCreateDto("True", false); - var incorrect2 = new AnswerInQuestionCreateDto("False", false); - - var createAnswer = new AnswersCreateDto(question.getId(), List.of(incorrect1, incorrect2)); - - var posted = mockMvc.perform(post("/answers") - .content(asJsonString(createAnswer)) - .contentType(MediaType.APPLICATION_JSON)); - - var asStr = posted.andReturn().getResponse().getContentAsString(); - - var res = objectMapper.readValue(asStr, new TypeReference<List<AnswerDto>>() { - }); - return res; - } - - - @Test - void getAnswer() throws Exception { - var exerciseId = createExercise(); - var question = createQuestion(exerciseId); - - var gets = mockMvc.perform(get(String.format("/answers/%s", question.getId()))); - - var content2 = gets.andReturn().getResponse().getContentAsString(); - - var res = objectMapper.readValue(content2, new TypeReference<List<AnswerDto>>() { - }); - - assert (res.equals(question.getAnswers())); - - } - - @Test - void testUpdate() throws Exception { - - var exerciseId = createExercise(); - var question = createQuestion(exerciseId); - - var incorrect1 = new AnswerInQuestionCreateDto("True", false); - var incorrect2 = new AnswerInQuestionCreateDto("False", false); - - - var createAnswer = new AnswersCreateDto(question.getId(), List.of(incorrect1, incorrect2)); - - - var posted = mockMvc.perform(post("/answers") - .content(asJsonString(createAnswer)) - .contentType(MediaType.APPLICATION_JSON)); - - var asStr = posted.andReturn().getResponse().getContentAsString(); - - var res = objectMapper.readValue(asStr, new TypeReference<List<AnswerDto>>() { - }); - - - var updated = """ - { - "text": "dis true", - "correct": false, - "questionId": "%s" - } - """; - - - updated = String.format(updated, question.getId()); - - var puts = mockMvc.perform(put(String.format("/answers/%s", res.get(0).getId())) - .content(updated).contentType(MediaType.APPLICATION_JSON)); - - var content = puts.andReturn().getResponse().getContentAsString(); - - var res2 = objectMapper.readValue(content, AnswerDto.class); - - var expected = new AnswerDto("dis true", false); - - assert res2.equals(expected); - - } - -} diff --git a/application/module-exercise/src/test/java/org/fuseri/moduleexercise/exercise/ExerciseControllerTest.java b/application/module-exercise/src/test/java/org/fuseri/moduleexercise/exercise/ExerciseControllerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..dce5d42843d4279b7813b5a9aa65038c41d245ff --- /dev/null +++ b/application/module-exercise/src/test/java/org/fuseri/moduleexercise/exercise/ExerciseControllerTest.java @@ -0,0 +1,261 @@ +package org.fuseri.moduleexercise.exercise; + +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.persistence.EntityNotFoundException; +import org.fuseri.model.dto.exercise.ExerciseCreateDto; +import org.fuseri.model.dto.exercise.ExerciseDto; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentMatchers; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.data.domain.PageImpl; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; + +import java.util.ArrayList; + +import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + + +@SpringBootTest +@AutoConfigureMockMvc +public class ExerciseControllerTest { + + @Autowired + ObjectMapper objectMapper; + + @Autowired + private MockMvc mockMvc; + + @MockBean + ExerciseFacade facade; + + public static String asJsonString(final Object obj) { + try { + return new ObjectMapper().writeValueAsString(obj); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private ExerciseDto exerciseDto; + private ExerciseDto exerciseDto1; + private ExerciseDto exerciseDto2; + private ExerciseCreateDto exerciseCreateDto; + private ExerciseCreateDto exerciseCreateDto1; + private ExerciseCreateDto exerciseCreateDto2; + + + @BeforeEach + void init() { + exerciseDto = new ExerciseDto(); + exerciseDto.setName("idioms"); + exerciseDto.setDescription("exercise on basic idioms"); + exerciseDto.setDifficulty(2); + exerciseDto.setCourseId(0); + + exerciseDto1 = new ExerciseDto(); + exerciseDto1.setName("idioms1"); + exerciseDto1.setDescription("exercise on basic idioms"); + exerciseDto1.setDifficulty(2); + exerciseDto1.setCourseId(0); + + exerciseDto2 = new ExerciseDto(); + exerciseDto2.setName("idioms2"); + exerciseDto2.setDescription("exercise on basic idioms"); + exerciseDto2.setDifficulty(1); + exerciseDto2.setCourseId(0); + + exerciseCreateDto = new ExerciseCreateDto("idioms", "exercise on basic idioms", 2, 0); + exerciseCreateDto1 = new ExerciseCreateDto("idioms1", "exercise on intermediate idioms", 2, 0); + exerciseCreateDto2 = new ExerciseCreateDto("idioms2", "exercise on basic idioms", 1, 0L); + } + + @Test + void getExercise() throws Exception { + long id = 1L; + when(facade.find(id)).thenReturn(exerciseDto); + mockMvc.perform(get("/exercises/{id}", id)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.name", is(exerciseCreateDto.getName()))) + .andExpect(jsonPath("$.description", is(exerciseCreateDto.getDescription()))) + .andExpect(jsonPath("$.courseId", is((int) exerciseCreateDto.getCourseId()))) + .andExpect(jsonPath("$.difficulty", is(exerciseCreateDto.getDifficulty()))); + } + + @Test + void testDelete() throws Exception { + mockMvc.perform(delete("/exercises/1")) + .andExpect(status().is2xxSuccessful()); + } + + @Test + void getExercise_notFound() throws Exception { + long id = 1L; + when(facade.find(id)).thenThrow(new EntityNotFoundException("")); + mockMvc.perform(get("/exercises/{id}", id)) + .andExpect(status().isNotFound()); + } + + @Test + void FindAll() { + when(facade.findAll(0)).thenReturn(new PageImpl<>(new ArrayList<>())); + try { + var response = mockMvc.perform(get("/exercises").param("page", "0")); + + var dis = response.andExpect(status().isOk()) + .andExpect(status().is2xxSuccessful()).andReturn().getResponse().getContentAsString(); + assertTrue(dis.contains("\"content\":[]")); + } catch (Exception e) { + throw new RuntimeException(e); + } + + + } + + @Test + void getFiltered() { + when(facade.findByCourseIdAndDifficulty(0, 2, 0)).thenReturn(new PageImpl<>(new ArrayList<>())); + try { + var filtered = mockMvc.perform(get("/exercises/filter").param("page", "0").param("courseId", "0").param("difficulty", "2")); + var content = filtered.andReturn().getResponse().getContentAsString(); + + assertTrue(content.contains("\"content\":[]")); + } catch (Exception e) { + assert (false); + } + } + + @Test + void testCreateExercise() throws Exception { + when(facade.create(ArgumentMatchers.isA(ExerciseCreateDto.class))).thenReturn(exerciseDto); + mockMvc.perform(post("/exercises").content(asJsonString(exerciseCreateDto)).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.name").value("idioms")) + .andExpect(jsonPath("$.description").value("exercise on basic idioms")) + .andExpect(jsonPath("$.difficulty").value(2)) + .andExpect(jsonPath("$.courseId").value("0")).andReturn().getResponse().getContentAsString(); + } + + @Test + void testCreateExerciseEmptyBody() throws Exception { + var postExercise = ""; + mockMvc.perform(post("/exercises").content((postExercise)).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().is4xxClientError()).andReturn().getResponse().getContentAsString(); + } + + + @Test + void testCreateExerciseMissingDesc() throws Exception { + var postExercise = """ + { + "name": "idioms", + "difficulty": 2, + "courseId": 0, + } + """; + + mockMvc.perform(post("/exercises").content((postExercise)).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().is4xxClientError()).andReturn().getResponse().getContentAsString(); + } + + @Test + void testCreateExerciseMissingName() throws Exception { + var postExercise = """ + { + "description: "exercise on basic idioms", + "difficulty": 2, + "courseId": 0, + } + """; + + mockMvc.perform(post("/exercises").content((postExercise)).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().is4xxClientError()).andReturn().getResponse().getContentAsString(); + } + + @Test + void testCreateExerciseMissingDifficulty() throws Exception { + var postExercise = """ + { + "name": "idioms" + "description: "exercise on basic idioms", + "courseId": 0 + } + """; + + mockMvc.perform(post("/exercises").content((postExercise)).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().is4xxClientError()).andReturn().getResponse().getContentAsString(); + } + + @Test + void testCreateExerciseMissingCourseId() throws Exception { + var postExercise = """ + { + "name": "idioms" + "description: "exercise on basic idioms", + "difficulty": 0 + } + """; + + mockMvc.perform(post("/exercises").content((postExercise)).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().is4xxClientError()).andReturn().getResponse().getContentAsString(); + } + + + @Test + void testUpdate() throws Exception { + long id = 1L; + when(facade.update(ArgumentMatchers.eq(id), ArgumentMatchers.isA(ExerciseCreateDto.class))).thenReturn(exerciseDto); + + var theId = String.format("/exercises/%d", id); + var dis = mockMvc.perform(put(theId).content(asJsonString(exerciseCreateDto)).contentType(MediaType.APPLICATION_JSON)); + + dis.andExpect(status().isOk()).andExpect(jsonPath("$.name", is(exerciseDto.getName()))) + .andExpect(jsonPath("$.difficulty", is(exerciseDto.getDifficulty()))) + .andExpect(jsonPath("$.description", is(exerciseDto.getDescription()))); + } + + @Test + void testUpdateNotFound() { + long id = 9999L; + when(facade.update(ArgumentMatchers.eq(id), ArgumentMatchers.isA(ExerciseCreateDto.class))).thenThrow(new EntityNotFoundException()); + + try { + var theId = String.format("/exercises/%d", id); + mockMvc.perform(put(theId).content(asJsonString(exerciseCreateDto)).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isNotFound()); + + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Test + void testUpdateIncorrectBody() { + long id = 1L; + var content = """ + { + "description": "exercise on basic idioms", + "difficulty": 2, + "courseId": 0 + } + """; + try { + var theId = String.format("/exercises/%d", id); + mockMvc.perform(put(theId).content(content).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().is4xxClientError()); + + } catch (Exception e) { + throw new RuntimeException(e); + } + } + +} diff --git a/application/module-exercise/src/test/java/org/fuseri/moduleexercise/exercise/ExerciseFacadeTest.java b/application/module-exercise/src/test/java/org/fuseri/moduleexercise/exercise/ExerciseFacadeTest.java new file mode 100644 index 0000000000000000000000000000000000000000..0be6f3770b15f6963a2a3200e888efd8115cd4c3 --- /dev/null +++ b/application/module-exercise/src/test/java/org/fuseri/moduleexercise/exercise/ExerciseFacadeTest.java @@ -0,0 +1,99 @@ +package org.fuseri.moduleexercise.exercise; + +import org.fuseri.model.dto.exercise.ExerciseCreateDto; +import org.fuseri.model.dto.exercise.ExerciseDto; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@SpringBootTest +@AutoConfigureMockMvc +class ExerciseFacadeTest { + + @Autowired + ExerciseFacade exerciseFacade; + + @MockBean + ExerciseService exerciseService; + + @MockBean + ExerciseMapper exerciseMapper; + + private final ExerciseDto exerciseDto = new ExerciseDto(); + + private final ExerciseCreateDto exerciseCreateDto = new ExerciseCreateDto("name", "desc", 2, 1); + + private final Exercise exercise = new Exercise(); + + @Test + void create() { + when(exerciseMapper.fromCreateDto(exerciseCreateDto)).thenReturn(exercise); + when(exerciseService.create(exercise)).thenReturn(exercise); + when(exerciseMapper.toDto(exercise)).thenReturn(exerciseDto); + + ExerciseDto actualDto = exerciseFacade.create(exerciseCreateDto); + + assertEquals(exerciseDto, actualDto); + } + + @Test + void testFindById() { + long id = 1L; + + when(exerciseService.find(id)).thenReturn(exercise); + when(exerciseMapper.toDto(exercise)).thenReturn(exerciseDto); + + ExerciseDto actualDto = exerciseFacade.find(id); + + assertNotNull(actualDto); + assertEquals(exerciseDto, actualDto); + } + + @Test + void testFindAll() { + int page = 0; + Pageable pageable = PageRequest.of(0, 10); + Page<Exercise> exercisePage = new PageImpl<>(List.of(exercise), pageable, 0); + Page<ExerciseDto> expectedPageDto = new PageImpl<>(List.of(exerciseDto)); + + when(exerciseService.findAll(page)).thenReturn(exercisePage); + when(exerciseMapper.toDtoPage(exercisePage)).thenReturn(expectedPageDto); + + Page<ExerciseDto> actualPageDto = exerciseFacade.findAll(page); + + assertEquals(expectedPageDto, actualPageDto); + } + + @Test + void update() { + long id = 1L; + when(exerciseMapper.fromCreateDto(exerciseCreateDto)).thenReturn(exercise); + when(exerciseService.update(id, exercise)).thenReturn(exercise); + when(exerciseMapper.toDto(exercise)).thenReturn(exerciseDto); + + ExerciseDto actualDto = exerciseFacade.update(id, exerciseCreateDto); + + assertEquals(exerciseDto, actualDto); + } + + @Test + void testDelete() { + long id = 1L; + exerciseFacade.delete(id); + verify(exerciseService).delete(id); + } + +} diff --git a/application/module-exercise/src/test/java/org/fuseri/moduleexercise/exercise/ExerciseRepositoryTest.java b/application/module-exercise/src/test/java/org/fuseri/moduleexercise/exercise/ExerciseRepositoryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..1d8eec54a05e1384cfed5cb5aa136f5c680410ce --- /dev/null +++ b/application/module-exercise/src/test/java/org/fuseri/moduleexercise/exercise/ExerciseRepositoryTest.java @@ -0,0 +1,80 @@ +package org.fuseri.moduleexercise.exercise; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; + +import java.util.Arrays; +import java.util.HashSet; + +@DataJpaTest +class ExerciseRepositoryTest { + + @Autowired + ExerciseRepository exerciseRepository; + + @Autowired + TestEntityManager entityManager; + + Exercise exercise = new Exercise("name", "desc", 2, 1L, new HashSet<>()); + + @Test + void saveExercise() { + Exercise saved = exerciseRepository.save(exercise); + + Assertions.assertNotNull(saved); + Assertions.assertEquals(exercise, saved); + } + + @Test + void findById() { + entityManager.persist(exercise); + entityManager.flush(); + + Exercise found = exerciseRepository.findById(exercise.getId()).orElse(null); + + Assertions.assertNotNull(found); + Assertions.assertEquals(found, exercise); + } + + + @Test + void findByCourseIdAndDifficulty() { + entityManager.persist(exercise); + entityManager.flush(); + + Page<Exercise> found = exerciseRepository.findByCourseIdAndDifficulty(1L, 2, PageRequest.of(0, 10)); + + Assertions.assertEquals(1, found.getTotalElements()); + Assertions.assertEquals(found.getContent().get(0), exercise); + } + + @Test + void testFindAllExercises() { + Exercise exercise1 = new Exercise(); + + entityManager.persist(exercise); + entityManager.persist(exercise1); + entityManager.flush(); + + Page<Exercise> coursePage = exerciseRepository.findAll(PageRequest.of(0, 42)); + + Assertions.assertEquals(2, coursePage.getTotalElements()); + Assertions.assertEquals(coursePage.getContent(), Arrays.asList(exercise, exercise1)); + } + + @Test + void testDeleteExercise() { + Long id = entityManager.persist(exercise).getId(); + entityManager.flush(); + + exerciseRepository.deleteById(id); + + Assertions.assertTrue(exerciseRepository.findById(id).isEmpty()); + } + +} diff --git a/application/module-exercise/src/test/java/org/fuseri/moduleexercise/exercise/ExerciseServiceTest.java b/application/module-exercise/src/test/java/org/fuseri/moduleexercise/exercise/ExerciseServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..7d54a6cc2869ee3e00af9abb67933de0ca71a9c6 --- /dev/null +++ b/application/module-exercise/src/test/java/org/fuseri/moduleexercise/exercise/ExerciseServiceTest.java @@ -0,0 +1,111 @@ +package org.fuseri.moduleexercise.exercise; + +import jakarta.persistence.EntityNotFoundException; +import org.fuseri.model.dto.exercise.ExerciseCreateDto; +import org.fuseri.moduleexercise.question.Question; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Optional; + +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + + +@SpringBootTest +class ExerciseServiceTest { + + @MockBean + ExerciseRepository exerciseRepository; + + @Autowired + ExerciseService exerciseService; + + Exercise exercise; + ExerciseCreateDto exercise2; + ExerciseCreateDto exercise3; + + @BeforeEach + void setup() { + exercise = new Exercise("idioms", "exercise on basic idioms", 2, 1L, new HashSet<>()); + exercise2 = new ExerciseCreateDto("idioms1", "exercise on intermediate idioms", 2, 0); + exercise3 = new ExerciseCreateDto("idioms2", "exercise on basic idioms", 1, 0L); + } + + @Test + void create() { + when(exerciseRepository.save(exercise)).thenReturn(exercise); + Exercise result = exerciseService.create(exercise); + Assertions.assertEquals(exercise, result); + verify(exerciseRepository).save(exercise); + } + + @Test + void notFound() { + when(exerciseRepository.findById(anyLong())).thenReturn(Optional.empty()); + + Assertions.assertThrows(EntityNotFoundException.class, () -> exerciseService.find(anyLong())); + } + + @Test + void find() { + when(exerciseRepository.findById(anyLong())).thenReturn(Optional.of(exercise)); + + Exercise result = exerciseService.find(anyLong()); + + Assertions.assertEquals(exercise, result); + verify(exerciseRepository).findById(anyLong()); + } + + @Test + void findAll() { + Pageable pageable = PageRequest.of(0, 10); + Page<Exercise> page = new PageImpl<>(Collections.emptyList(), pageable, 0); + + when(exerciseRepository.findAll(pageable)).thenReturn(page); + Page<Exercise> result = exerciseService.findAll(0); + + Assertions.assertEquals(page, result); + verify(exerciseRepository).findAll(pageable); + } + + @Test + void findByCourseIdAndDifficulty() { + PageRequest pageable = PageRequest.of(0, 10); + Page<Exercise> page = new PageImpl<>(Collections.emptyList(), pageable, 0); + + when(exerciseRepository.findByCourseIdAndDifficulty(1L, 2, pageable)).thenReturn(page); + + Page<Exercise> result = exerciseService.findByCourseIdAndDifficulty(1L, 2, 0); + + Assertions.assertEquals(page, result); + verify(exerciseRepository).findByCourseIdAndDifficulty(1L, 2, pageable); + } + + + @Test + void getQuestions() { + PageRequest pageable = PageRequest.of(0, 10); + Page<Question> page = new PageImpl<>(Collections.emptyList(), pageable, 0); + + when(exerciseRepository.getQuestions(pageable, 1L)).thenReturn(page); + when(exerciseRepository.existsById(1L)).thenReturn(true); + + + Page<Question> result = exerciseService.getQuestions(1L, 0); + + Assertions.assertEquals(page, result); + verify(exerciseRepository).getQuestions(pageable, 1L); + } +} diff --git a/application/module-exercise/src/test/java/org/fuseri/moduleexercise/exercise/ExerciseTest.java b/application/module-exercise/src/test/java/org/fuseri/moduleexercise/exercise/ExerciseTest.java deleted file mode 100644 index a634b41941ff09a1d6fa1a82125c2015c3206bf1..0000000000000000000000000000000000000000 --- a/application/module-exercise/src/test/java/org/fuseri/moduleexercise/exercise/ExerciseTest.java +++ /dev/null @@ -1,161 +0,0 @@ -package org.fuseri.moduleexercise.exercise; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.fuseri.model.dto.common.Result; -import org.fuseri.model.dto.exercise.ExerciseCreateDto; -import org.fuseri.model.dto.exercise.ExerciseDto; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.http.MediaType; -import org.springframework.test.web.servlet.MockMvc; - -import java.util.Map; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; - - -@SpringBootTest -@AutoConfigureMockMvc -public class ExerciseTest { - @Autowired - ObjectMapper objectMapper; - @Autowired - private MockMvc mockMvc; - - public static String asJsonString(final Object obj) { - try { - return new ObjectMapper().writeValueAsString(obj); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - - @Test - void getExercise() { - var postExercise = new ExerciseCreateDto("idioms", "exercise on basic idioms", 2, "0"); - - String id = ""; - - try { - var dis = mockMvc.perform(post("/exercises").content(asJsonString(postExercise)).contentType(MediaType.APPLICATION_JSON)); - var ok = dis.andReturn().getResponse().getContentAsString(); - - var ll = objectMapper.readValue(ok, ExerciseDto.class); - - id = ll.getId(); - } catch (Exception e) { - assert (false); - } - - - try { - var theId = String.format("/exercises/%s", id); - var smth = mockMvc.perform(get(theId)); - - } catch (Exception e) { - //do absolutely nothing - } - } - - @Test - void getFiltered() { - - - var postExercise = new ExerciseCreateDto("idioms", "exercise on basic idioms", 0, "0"); - var postExercise1 = new ExerciseCreateDto("idioms1", "exercise on basic idioms", 0, "0"); - var postExercise2 = new ExerciseCreateDto("idioms2", "exercise on basic idioms", 1, "0"); - - try { - var exercise1 = mockMvc.perform(post("/exercises").content(asJsonString(postExercise)).contentType(MediaType.APPLICATION_JSON)); - - var exercise2 = mockMvc.perform(post("/exercises").content(asJsonString(postExercise1)).contentType(MediaType.APPLICATION_JSON)); - var exercise3 = mockMvc.perform(post("/exercises").content(asJsonString(postExercise2)).contentType(MediaType.APPLICATION_JSON)); - } catch (Exception e) { - //do absolutly nothing - } - - - Map<String, String> params; - - try { - var filtered = mockMvc.perform(get("/exercises/filter").param("page", "0").param("courseId", "0").param("difficulty", "0")); - - var content = filtered.andReturn().getResponse().getContentAsString(); - - var res = objectMapper.readValue(content, new TypeReference<Result<ExerciseDto>>() { - }); - - assert (res.getTotal() == 2); - } catch (Exception e) { - assert (false); - } - } - - @Test - void testCreateExercise() throws Exception { - var expectedResponse = new ExerciseDto(); - var postExercise = new ExerciseCreateDto("idioms", "exercise on basic idioms", 2, "0"); - - mockMvc.perform(post("/exercises").content(asJsonString(postExercise)).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(jsonPath("$.name").value("idioms")).andExpect(jsonPath("$.description").value("exercise on basic idioms")).andExpect(jsonPath("$.difficulty").value(2)).andExpect(jsonPath("$.courseId").value("0")).andReturn().getResponse().getContentAsString(); - } - - @Test - void testUpdate() { - var postExercise = new ExerciseCreateDto("idioms", "exercise on basic idioms", 2, "0"); - - String id = ""; - - try { - var dis = mockMvc.perform(post("/exercises").content(asJsonString(postExercise)).contentType(MediaType.APPLICATION_JSON)); - var ok = dis.andReturn().getResponse().getContentAsString(); - - var ll = objectMapper.readValue(ok, ExerciseDto.class); - - id = ll.getId(); - } catch (Exception e) { - assert (false); - } - - var expectedExercise = new ExerciseDto(); - expectedExercise.setId(id); - expectedExercise.setName("idioms"); - expectedExercise.setDifficulty(2); - expectedExercise.setCourseId("idioms"); - expectedExercise.setDescription("exercise on basic idioms"); - - var content = """ - { - "name": "idioms", - "description": "exercise on basic idioms", - "difficulty": 2, - "courseId": "idioms" - } - """; - - - try { - var theId = String.format("/exercises/%s", id); - var dis = mockMvc.perform(put(theId).content(content).contentType(MediaType.APPLICATION_JSON)); - - var str = dis.andReturn().getResponse().getContentAsString(); - - var res = objectMapper.readValue(str, ExerciseDto.class); - - assert res.equals(expectedExercise); - - } catch (Exception e) { - throw new RuntimeException(e); - } - - } - -} diff --git a/application/module-exercise/src/test/java/org/fuseri/moduleexercise/question/QuestionFacadeTest.java b/application/module-exercise/src/test/java/org/fuseri/moduleexercise/question/QuestionFacadeTest.java new file mode 100644 index 0000000000000000000000000000000000000000..33e1ca0a8f8b9ff86d3ec16f12a5df86738c5d29 --- /dev/null +++ b/application/module-exercise/src/test/java/org/fuseri/moduleexercise/question/QuestionFacadeTest.java @@ -0,0 +1,125 @@ +package org.fuseri.moduleexercise.question; + + +import org.fuseri.model.dto.exercise.AnswerDto; +import org.fuseri.model.dto.exercise.AnswerInQuestionCreateDto; +import org.fuseri.model.dto.exercise.QuestionCreateDto; +import org.fuseri.model.dto.exercise.QuestionDto; +import org.fuseri.model.dto.exercise.QuestionUpdateDto; +import org.fuseri.moduleexercise.answer.Answer; +import org.fuseri.moduleexercise.answer.AnswerMapper; +import org.fuseri.moduleexercise.answer.AnswerService; +import org.fuseri.moduleexercise.exercise.Exercise; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@SpringBootTest +class QuestionFacadeTest { + + @Autowired + QuestionFacade questionFacade; + + @MockBean + QuestionService questionService; + + @MockBean + AnswerService answerService; + + @MockBean + QuestionMapper questionMapper; + + @MockBean + AnswerMapper answerMapper; + + private final QuestionDto questionDto = new QuestionDto(); + + private final QuestionCreateDto questionCreateDto = new QuestionCreateDto("name", 1L, new ArrayList<>()); + + private final QuestionUpdateDto questionUpdateDto = QuestionUpdateDto.builder().build(); + + private final Exercise exercise = new Exercise(); + + private final Question question = new Question("text", new HashSet<>(), exercise); + Set<Answer> answers = new HashSet<>(List.of(new Answer("BA", true, question))); + + @Test + void create() { + when(questionMapper.fromCreateDto(questionCreateDto)).thenReturn(question); + when(questionService.create(question)).thenReturn(question); + when(questionMapper.toDto(question)).thenReturn(questionDto); + + QuestionDto actualDto = questionFacade.create(questionCreateDto); + + assertEquals(questionDto, actualDto); + } + + @Test + void find() { + long id = 1L; + + when(questionService.find(id)).thenReturn(question); + when(questionMapper.toDto(question)).thenReturn(questionDto); + + QuestionDto actualDto = questionFacade.find(id); + + assertNotNull(actualDto); + assertEquals(questionDto, actualDto); + } + + @Test + void patchUpdate() { + long id = 1L; + when(questionMapper.fromUpdateDto(questionUpdateDto)).thenReturn(question); + when(questionService.patchUpdateWithoutAnswers(id, question)).thenReturn(question); + when(questionMapper.toDto(question)).thenReturn(questionDto); + QuestionDto actualDto = questionFacade.patchUpdate(id, questionUpdateDto); + + assertEquals(questionDto, actualDto); + } + + @Test + void testDelete() { + long id = 1L; + when(questionService.find(id)).thenReturn(question); + + questionFacade.delete(id); + verify(questionService).delete(id); + } + + @Test + void getQuestionAnswers() { + long id = 1L; + List<Answer> answers = List.of(new Answer("BA", true, question)); + List<AnswerDto> answerDtos = List.of(new AnswerDto("BA", true)); + when(answerMapper.toDtoList(answers)).thenReturn(answerDtos); + when(answerService.findAllByQuestionId(id)).thenReturn(answers); + var actualAnswers = questionFacade.getQuestionAnswers(id); + assertEquals(answerDtos, actualAnswers); + } + + @Test + void addAnswers() { + long id = 1L; + question.setAnswers(answers); + List<AnswerInQuestionCreateDto> answerDtos = List.of(new AnswerInQuestionCreateDto("BA", true)); + QuestionDto questionDtoAnswers = new QuestionDto(question.getText(), question.getExercise().getId(), List.of(new AnswerDto("BA", true))); + + when(answerMapper.fromCreateDtoList(answerDtos)).thenReturn(answers); + when(questionService.addAnswers(id, answers)).thenReturn(question); + when(questionMapper.toDto(question)).thenReturn(questionDtoAnswers); + QuestionDto actualQuestionDto = questionFacade.addAnswers(id, answerDtos); + assertEquals(questionDtoAnswers, actualQuestionDto); + } +} diff --git a/application/module-exercise/src/test/java/org/fuseri/moduleexercise/question/QuestionRepositoryTest.java b/application/module-exercise/src/test/java/org/fuseri/moduleexercise/question/QuestionRepositoryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..3c0eb33e9b5b83677709c5d43c1f8c47d94db32d --- /dev/null +++ b/application/module-exercise/src/test/java/org/fuseri/moduleexercise/question/QuestionRepositoryTest.java @@ -0,0 +1,88 @@ +package org.fuseri.moduleexercise.question; + +import org.fuseri.moduleexercise.exercise.Exercise; +import org.fuseri.moduleexercise.exercise.ExerciseRepository; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; + +@DataJpaTest +public class QuestionRepositoryTest { + + @Autowired + QuestionRepository repository; + + @Autowired + ExerciseRepository exerciseRepository; + + @Autowired + TestEntityManager entityManager; + + + Exercise exercise = new Exercise("name","desc",2,1L,new HashSet<>()); + + Question question = new Question("text",new HashSet<>(),exercise); + Question question2 = new Question("text2",new HashSet<>(),exercise); + + @BeforeEach + void init() { + exerciseRepository.save(exercise); + } + + @Test + void saveQuestion() { + Question saved = repository.save(question); + + Assertions.assertNotNull(saved); + Assertions.assertEquals(question, saved); + } + + @Test + void findById() { + entityManager.persist(question); + entityManager.flush(); + + Question found = repository.findById(question.getId()).orElse(null); + + Assertions.assertNotNull(found); + Assertions.assertEquals(found, question); + } + + + @Test + void testFindAllQuestions() { + entityManager.persist(question); + entityManager.persist(question2); + + Page<Question> coursePage = repository.findAll(PageRequest.of(0, 42)); + + Assertions.assertEquals(2, coursePage.getTotalElements()); + Assertions.assertEquals(coursePage.getContent(), Arrays.asList(question, question2)); + } + @Test + void testFindAllQuestionsEmpty() { + Page<Question> coursePage = repository.findAll(PageRequest.of(0, 42)); + + Assertions.assertEquals(0, coursePage.getTotalElements()); + Assertions.assertEquals(coursePage.getContent(), new ArrayList<>()); + } + + @Test + void testDeleteQuestion() { + Long id = entityManager.persist(question).getId(); + entityManager.flush(); + + repository.deleteById(id); + + Assertions.assertTrue(repository.findById(id).isEmpty()); + } +} diff --git a/application/module-exercise/src/test/java/org/fuseri/moduleexercise/question/QuestionServiceTest.java b/application/module-exercise/src/test/java/org/fuseri/moduleexercise/question/QuestionServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..298510e1ea93958b62dc321e70031f2c8d0c2ab3 --- /dev/null +++ b/application/module-exercise/src/test/java/org/fuseri/moduleexercise/question/QuestionServiceTest.java @@ -0,0 +1,83 @@ +package org.fuseri.moduleexercise.question; + +import jakarta.persistence.EntityNotFoundException; +import org.fuseri.moduleexercise.answer.Answer; +import org.fuseri.moduleexercise.exercise.Exercise; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; + +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@SpringBootTest +class QuestionServiceTest { + + @MockBean + QuestionRepository questionRepository; + + @Autowired + QuestionService questionService; + + Exercise exercise; + Question question; + Question question1; + + @BeforeEach + void setup() { + exercise = new Exercise("idioms", "exercise on basic idioms",2,1L,new HashSet<>()); + question = new Question("text",new HashSet<>(),exercise); + question1 = new Question("text2",new HashSet<>(),exercise); + } + + + @Test + void create() { + when(questionRepository.save(question)).thenReturn(question); + Question result = questionService.create(question); + Assertions.assertEquals(question, result); + verify(questionRepository).save(question); + } + + @Test + void notFound() { + when(questionRepository.findById(anyLong())).thenReturn(Optional.empty()); + + Assertions.assertThrows(EntityNotFoundException.class, () -> questionService.find(anyLong())); + } + + @Test + void find() { + when(questionRepository.findById(anyLong())).thenReturn(Optional.of(question)); + + Question result = questionService.find(anyLong()); + + Assertions.assertEquals(question, result); + verify(questionRepository).findById(anyLong()); + } + + @Test + void patchUpdateWithoutAnswers() { + when(questionRepository.findById(anyLong())).thenReturn(Optional.of(question)); + when(questionRepository.save(question)).thenReturn(question); + Question result = questionService.patchUpdateWithoutAnswers(anyLong(), question); + Assertions.assertEquals(question, result); + } + + @Test + void addAnswers() { + Set<Answer> answers = Set.of(new Answer("BA", true, question)); + question.setAnswers(answers); + when(questionRepository.findById(anyLong())).thenReturn(Optional.of(question)); + when(questionRepository.save(question)).thenReturn(question); + Question result = questionService.patchUpdateWithoutAnswers(anyLong(), question); + Assertions.assertEquals(question, result); + } +} diff --git a/application/module-exercise/src/test/java/org/fuseri/moduleexercise/question/QuestionTest.java b/application/module-exercise/src/test/java/org/fuseri/moduleexercise/question/QuestionTest.java index a099ff7c8cf058e033931222d5c76469ac40003e..8383971d23f186ac9740263ebb47ed4ab303be1f 100644 --- a/application/module-exercise/src/test/java/org/fuseri/moduleexercise/question/QuestionTest.java +++ b/application/module-exercise/src/test/java/org/fuseri/moduleexercise/question/QuestionTest.java @@ -1,27 +1,41 @@ package org.fuseri.moduleexercise.question; -import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; -import org.fuseri.model.dto.common.Result; +import jakarta.persistence.EntityNotFoundException; import org.fuseri.model.dto.exercise.AnswerDto; import org.fuseri.model.dto.exercise.AnswerInQuestionCreateDto; import org.fuseri.model.dto.exercise.ExerciseCreateDto; -import org.fuseri.model.dto.exercise.ExerciseDto; import org.fuseri.model.dto.exercise.QuestionCreateDto; import org.fuseri.model.dto.exercise.QuestionDto; +import org.fuseri.model.dto.exercise.QuestionUpdateDto; +import org.fuseri.moduleexercise.exercise.Exercise; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentMatcher; +import org.mockito.ArgumentMatchers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; +import static org.hamcrest.Matchers.is; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.util.ArrayList; import java.util.List; -import java.util.Map; +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; @SpringBootTest @@ -33,6 +47,11 @@ public class QuestionTest { @Autowired private MockMvc mockMvc; + @MockBean + QuestionFacade facade; + + private QuestionDto qston; + public static String asJsonString(final Object obj) { try { return new ObjectMapper().writeValueAsString(obj); @@ -41,113 +60,146 @@ public class QuestionTest { } } - @Test - void testCreateQuestion() throws Exception { - String id = createExercise(); - var answr = new AnswerDto("dis a logical paradox", true); - QuestionDto res = createQuestion(id); - var expected = new QuestionDto(); - expected.setAnswers(List.of(answr)); - expected.setExerciseId(id); - expected.setId(res.getId()); - expected.setText("this statement is false"); - - assert expected.equals(res); + private void createExercise() { + var postExercise = new ExerciseCreateDto("idioms", "exercise on basic idioms", 2, 0L); + var postExercise2 = new ExerciseCreateDto("riddles", "simple english riddles", 2, 0L); + try { + mockMvc.perform(post("/exercises").content(asJsonString(postExercise)).contentType(MediaType.APPLICATION_JSON)); + mockMvc.perform(post("/exercises").content(asJsonString(postExercise2)).contentType(MediaType.APPLICATION_JSON)); + + } catch (Exception e) { + assert (false); + } } - private QuestionDto createQuestion(String id) throws Exception { + @BeforeEach + void init() { +// createExercise(); + + qston = new QuestionDto("\"what is the meaning of: costs an arm and leg\"",1,new ArrayList<>()); + long id = 2; + var question = new QuestionCreateDto("this statement is false", id, List.of(new AnswerInQuestionCreateDto("dis a logical paradox", true))); + var question2 = new QuestionCreateDto("What month of the year has 28 days?", id, List.of(new AnswerInQuestionCreateDto("February", false), new AnswerInQuestionCreateDto("All of them", true))); + ResultActions posted = null; + } + @Test + void testCreateQuestion() throws Exception { + var exerciseId = 1L; + var question = new QuestionCreateDto("what is the meaning of: costs an arm and leg", exerciseId, List.of(new AnswerInQuestionCreateDto("dis very expencive", true), new AnswerInQuestionCreateDto("FMA refference", false))); + when(facade.create(ArgumentMatchers.isA(QuestionCreateDto.class))).thenReturn(qston); var posted = mockMvc.perform(post("/questions").content(asJsonString(question)).contentType(MediaType.APPLICATION_JSON)); + posted.andExpect(status().isCreated()) + .andExpect(jsonPath("$.text", is(qston.getText()))) + .andExpect(jsonPath("$.exerciseId", is((int)qston.getExerciseId()))); - var cont = posted.andReturn().getResponse().getContentAsString(); - var res = objectMapper.readValue(cont, QuestionDto.class); - return res; } - private String createExercise() { - var postExercise = new ExerciseCreateDto("idioms", "exercise on basic idioms", 2, "0"); - - String id = ""; - - try { - var dis = mockMvc.perform(post("/exercises").content(asJsonString(postExercise)).contentType(MediaType.APPLICATION_JSON)); - var ok = dis.andReturn().getResponse().getContentAsString(); + @Test + void testCreateQuestionEmptyQuestions() throws Exception { + var prompt = """ + { + "text": "this is a question without exercise Id", + "exerciseId": 1, + "answers": [] + } + """; - var ll = objectMapper.readValue(ok, ExerciseDto.class); + var posted = mockMvc.perform(post("/questions").content(prompt).contentType(MediaType.APPLICATION_JSON)); - id = ll.getId(); - } catch (Exception e) { - assert (false); - } - return id; + posted.andExpect(status().isCreated()); } @Test - void getQuestion() throws Exception { - + void testCreateQuestionEmptyField() throws Exception { + var exerciseId = 1L; + var question = new QuestionCreateDto("", exerciseId, List.of(new AnswerInQuestionCreateDto("dis very expencive", true), new AnswerInQuestionCreateDto("FMA refference", false))); + var posted = mockMvc.perform(post("/questions").content(asJsonString(question)).contentType(MediaType.APPLICATION_JSON)); - String exerciseId = createExercise(); - var question = createQuestion(exerciseId); + posted.andExpect(status().is4xxClientError()); + } - var theId = String.format("/questions/%s", question.getId()); + @Test + void testCreateQuestionMissingField() throws Exception { + var prompt = """ + { + "text": "this is a question without exercise Id, + "answers" : [] + } + """; + var posted = mockMvc.perform(post("/questions").content(prompt).contentType(MediaType.APPLICATION_JSON)); - var gets = mockMvc.perform(get(theId)); + posted.andExpect(status().is4xxClientError()); + } - var content = gets.andReturn().getResponse().getContentAsString(); - var res = objectMapper.readValue(content, QuestionDto.class); + private QuestionDto createQuestion(long id) throws Exception { + var question = new QuestionCreateDto("this statement is false", id, List.of(new AnswerInQuestionCreateDto("dis a logical paradox", true))); + var posted = mockMvc.perform(post("/questions").content(asJsonString(question)).contentType(MediaType.APPLICATION_JSON)); + var cont = posted.andReturn().getResponse().getContentAsString(); + var res = objectMapper.readValue(cont, QuestionDto.class); + return res; + } - assert res.equals(question); + @Test + void getQuestion() throws Exception { + var question = new QuestionDto("this statement is false",1L,new ArrayList<>()); + when(facade.find(1)).thenReturn(question); + var gets = mockMvc.perform(get("/questions/1")); + gets.andExpect(status().isOk()).andExpect(jsonPath("$.text", is("this statement is false"))); } @Test - void getByExercise() throws Exception { - - var exerciseId = createExercise(); - var question = createQuestion(exerciseId); + void getQuestionNotFound() throws Exception { + when(facade.find(9999)).thenThrow(new EntityNotFoundException()); + var gets = mockMvc.perform(get("/questions/9999")); + gets.andExpect(status().isNotFound()); + } - var theId = String.format("/questions/exercise/%s", exerciseId); - var smth = mockMvc.perform(get(theId).param("page", "0")); + @Test + void getAnswer() throws Exception { - var content = smth.andReturn().getResponse().getContentAsString(); - var res = objectMapper.readValue(content, new TypeReference<Result<QuestionDto>>() { - }); + var sss = List.of(new AnswerDto("February", false), new AnswerDto("All of them", true)); + when(facade.getQuestionAnswers(2)).thenReturn(sss); + var gets = mockMvc.perform(get("/questions/2/answers")); + gets.andExpect(status().isOk()) + .andExpect(jsonPath("$[0].text", is("February"))) + .andExpect(jsonPath("$[1].text", is("All of them"))); - Map<String, String> params; - assert (res.getItems().get(0).equals(question)); } @Test void TestUpdate() throws Exception { - String id = createExercise(); - var question = createQuestion(id); - var updated = """ { "text": "wat a paradox?", - "exerciseId": "%s" + "exerciseId": "1" } """; - updated = String.format(updated, id); - - var smth = mockMvc.perform(put(String.format("/questions/%s", question.getId())).content(updated).contentType(MediaType.APPLICATION_JSON)); - - var content = smth.andReturn().getResponse().getContentAsString(); - - var res = objectMapper.readValue(content, QuestionDto.class); + var question = new QuestionDto("wat a paradox?",1,new ArrayList<>()); - question.setText("wat a paradox?"); + when(facade.patchUpdate(ArgumentMatchers.eq(1), ArgumentMatchers.isA(QuestionUpdateDto.class))).thenReturn(question); + var gets = mockMvc.perform(put("/questions/1").content(updated).contentType(MediaType.APPLICATION_JSON)); - assert (question.equals(res)); + gets.andExpect(status().isOk()); + } +@Test + void deleteExisting() { + try { + mockMvc.perform(delete("/questions/1")).andExpect(status().isNoContent()); + } catch (Exception e) { + throw new RuntimeException(e); } } + +} diff --git a/application/module-language-school/src/test/java/org/fuseri/modulelanguageschool/course/CourseControllerTest.java b/application/module-language-school/src/test/java/org/fuseri/modulelanguageschool/course/CourseControllerTest.java index 21ed4e68ecce1e1025dc0f14f1525345589a0e36..b75d751ab035fcb4c53014a3fac3ecf41b990508 100644 --- a/application/module-language-school/src/test/java/org/fuseri/modulelanguageschool/course/CourseControllerTest.java +++ b/application/module-language-school/src/test/java/org/fuseri/modulelanguageschool/course/CourseControllerTest.java @@ -218,9 +218,10 @@ public class CourseControllerTest { .andExpect(status().isOk()) .andExpect(jsonPath("$.name").value("english b2 course")) .andExpect(jsonPath("$.capacity").value(10)) - .andExpect(jsonPath("$.language").value("ENGLISH")) - .andExpect(jsonPath("$.proficiency").value("B2")) - .andExpect(jsonPath("$.studentIds").exists()); + .andExpect(jsonPath("$.languageTypeDto").value("ENGLISH")) + .andExpect(jsonPath("$.proficiencyLevelDto").value("B2")) + .andExpect(jsonPath("$.studentIds").value(student.getId())) + .andReturn().getResponse().getContentAsString(); } @Test diff --git a/application/module-language-school/src/test/java/org/fuseri/modulelanguageschool/user/UserControllerTest.java b/application/module-language-school/src/test/java/org/fuseri/modulelanguageschool/user/UserControllerTest.java index 59f5032bf8a1fe520fa1160415230843c3d2850f..112bbb53472fd0e906ad0068f6ee335e0b0cc17e 100644 --- a/application/module-language-school/src/test/java/org/fuseri/modulelanguageschool/user/UserControllerTest.java +++ b/application/module-language-school/src/test/java/org/fuseri/modulelanguageschool/user/UserControllerTest.java @@ -121,7 +121,7 @@ class UserControllerTest { .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); - Long id = objectMapper.readValue(response, UserDto.class).getId(); + String id = objectMapper.readValue(response, UserDto.class).getId(); mockMvc.perform(get("/users/{id}", id)) .andExpect(status().isOk()) @@ -142,7 +142,7 @@ class UserControllerTest { .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); - Long id = objectMapper.readValue(response, UserDto.class).getId(); + String id = objectMapper.readValue(response, UserDto.class).getId(); mockMvc.perform(delete("/users/{id}", id) .contentType(MediaType.APPLICATION_JSON)) @@ -156,7 +156,7 @@ class UserControllerTest { .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); - Long id = objectMapper.readValue(response, UserDto.class).getId(); + String id = objectMapper.readValue(response, UserDto.class).getId(); var updatedUsername = "novak"; var userToUpdate = new UserCreateDto( @@ -195,7 +195,7 @@ class UserControllerTest { .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); - Long id = objectMapper.readValue(response, UserDto.class).getId(); + String id = objectMapper.readValue(response, UserDto.class).getId(); mockMvc.perform(post("/users/logout/{id}", id)) .andExpect(status().isOk());