diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5096962 --- /dev/null +++ b/.gitignore @@ -0,0 +1,89 @@ +log/ +.settings/ +.classpath +.project + +#Maven +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties +.mvn/wrapper/maven-wrapper.jar + +#Intellij +out/ + # User-specific stuff + .idea/**/workspace.xml + .idea/**/tasks.xml + .idea/**/usage.statistics.xml + .idea/**/dictionaries + .idea/**/shelf + # Generated files + .idea/**/contentModel.xml + # Sensitive or high-churn files + .idea/**/dataSources/ + .idea/**/dataSources.ids + .idea/**/dataSources.local.xml + .idea/**/sqlDataSources.xml + .idea/**/dynamic.xml + .idea/**/uiDesigner.xml + .idea/**/dbnavigator.xml + # Gradle + .idea/**/gradle.xml + .idea/**/libraries + # CMake + cmake-build-*/ + # Mongo Explorer plugin + .idea/**/mongoSettings.xml + # File-based project format + *.iws + # mpeltonen/sbt-idea plugin + .idea_modules/ + # JIRA plugin + atlassian-ide-plugin.xml + # Cursive Clojure plugin + .idea/replstate.xml + # Crashlytics plugin (for Android Studio and IntelliJ) + com_crashlytics_export_strings.xml + crashlytics.properties + crashlytics-build.properties + fabric.properties + # Editor-based Rest Client + .idea/httpRequests + # Android studio 3.1+ serialized cache file + .idea/caches/build_file_checksums.ser + +#Eclipse +.metadata +bin/ +tmp/ +*.tmp +*.bak +*.swp +*~.nib +local.properties +.settings/ +.loadpath +.recommenders +.externalToolBuilders/ +*.launch +*.pydevproject +.cproject +.autotools +.factorypath +.buildpath +.target +.tern-project +.texlipse +.springBeans +.recommenders/ +.apt_generated/ +.apt_generated_test/ +.cache-main +.scala_dependencies +.worksheet \ No newline at end of file diff --git a/CODEOWNERS b/CODEOWNERS new file mode 100644 index 0000000..a7799fd --- /dev/null +++ b/CODEOWNERS @@ -0,0 +1 @@ +* @apokochito diff --git a/README.md b/README.md index 2b63717..a90013c 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,51 @@ -# StoriesAPI -StoriesAPI by Team Kingsman +# StoriesAPI + +README file for StoriesAPI + +## Getting Started + +Created on 4/30/2020 + +StoriesAPI is an API to manage the stories for the ResourceSC project created for 4thSource to have control in the future Internships programs. This API has an MVC structure created with Spring Boot Framework. + +GitHub - [https://github.com/Internship4thSource/StoriesAPI](https://github.com/Internship4thSource/StoriesAPI) + +AWS EB (QA Enviroment) - [http://stories-qa.us-east-2.elasticbeanstalk.com/stories/](http://stories-qa.us-east-2.elasticbeanstalk.com/stories/) + +## Tools + +| Technology| Usage| +| --- | --- | +| Eclipse | IDE | +| Java 8 | Programming Lenguague | +| Spring | Framework | +| Maven | Dependencies/Release Handler | +| Swagger | Documentation | +| Postman| Testing | +| Log4j2 | Log Managment | +| Junit 4 | Unit Testing | +| Mockito | Testing Framework| +| MongoDB | NoSQL Database | +| MongoCompass | Mongo GUI | +| AWS Elastic BeanStalk | Deploying Web App | + +## Contributor Team + +| Developer| Email | +| --- | --- | +| Dana Elena Pinto Apolinar | diana.pinto@agilethought.com | +| Jose Armando Sanchez Barajas | jose.sanchez@agilethought.com | +| Alejandro Gutierrez Aguilar | alejandro.gutierrez@agilethought.com | +| Juan Zepeda Hernandez | juan.zepeda@agilethought.com | + + +## Copyright / License + +#### 4thSource an AgileTought Company + +## Documentation + +Swagger - [http://stories-qa.us-east-2.elasticbeanstalk.com/swagger-ui.html#/Microservices_STORY/](http://stories-qa.us-east-2.elasticbeanstalk.com/swagger-ui.html#/Microservices_STORY) + +## Status +Actuator - [http://stories-qa.us-east-2.elasticbeanstalk.com/actuator/health](http://stories-qa.us-east-2.elasticbeanstalk.com/actuator/health) diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..53cf016 --- /dev/null +++ b/pom.xml @@ -0,0 +1,248 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.4.RELEASE + + + + com.stories + stories + 1.0.1 + stories + Stories application + + + 8 + UTF-8 + 1.8 + + + + + org.projectlombok + lombok + 1.18.12 + provided + + + + org.springframework.boot + spring-boot-starter-actuator + + + + org.springframework.boot + spring-boot-starter-data-mongodb + + + + ma.glasnost.orika + orika-core + 1.5.4 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.apache.logging.log4j + log4j-core + 2.8.2 + + + + org.apache.logging.log4j + log4j-api + 2.8.2 + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + com.fasterxml.jackson.core + jackson-core + + + + com.fasterxml.jackson.core + jackson-databind + + + + com.fasterxml.jackson.core + jackson-annotations + + + + junit + junit + test + + + + com.github.kongchen + swagger-maven-plugin + 3.1.2 + + + + io.springfox + springfox-swagger2 + 2.9.2 + + + + io.springfox + springfox-swagger-ui + 2.9.2 + + + + org.testng + testng + 7.1.0 + test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.jacoco + jacoco-maven-plugin + 0.8.3 + + + **/domain/**/* + **/exception/**/* + **/model/**/* + **/config/**/* + **/mapper/**/* + **/repository/**/* + **/constants/**/* + **/com/stories/StoriesApplication.class + **/com/stories/controller/GlobalExceptionHandler.class + + + + + prepare-agent + + prepare-agent + + + + report + + report + + test + + target/jacoco-report + + + + + + + com.github.kongchen + swagger-maven-plugin + 3.1.7 + + + compile + + generate + + + + + + + true + com.stories + + + Stories API + + Official documentation for Stories AP + + + 0.0.1 + + + http://stories-qa.us-east-2.elasticbeanstalk.com + + + ${project.basedir}/src/main/resources + swagger + json,yaml + true + + + + + + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + + com.github.kongchen + + + swagger-maven-plugin + + + [3.1.7,) + + + generate + + + + + + + + + + + + + + + diff --git a/src/main/java/com/stories/StoriesApplication.java b/src/main/java/com/stories/StoriesApplication.java new file mode 100644 index 0000000..d6ad0c4 --- /dev/null +++ b/src/main/java/com/stories/StoriesApplication.java @@ -0,0 +1,11 @@ +package com.stories; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class StoriesApplication { + public static void main(String[] args) { + SpringApplication.run(StoriesApplication.class, args); + } +} \ No newline at end of file diff --git a/src/main/java/com/stories/config/OrikaMapper.java b/src/main/java/com/stories/config/OrikaMapper.java new file mode 100644 index 0000000..67f416b --- /dev/null +++ b/src/main/java/com/stories/config/OrikaMapper.java @@ -0,0 +1,19 @@ +package com.stories.config; + +import org.springframework.context.annotation.Configuration; + +import com.stories.domain.StoryDomain; +import com.stories.model.StoryModel; + +import ma.glasnost.orika.MapperFactory; +import ma.glasnost.orika.impl.ConfigurableMapper; + +@Configuration +public class OrikaMapper extends ConfigurableMapper { + + public MapperFactory mapper(MapperFactory factory) { + factory.classMap(StoryModel.class, StoryDomain.class).byDefault().register(); + return factory; + } + +} \ No newline at end of file diff --git a/src/main/java/com/stories/config/SwaggerConfig.java b/src/main/java/com/stories/config/SwaggerConfig.java new file mode 100644 index 0000000..a0f3553 --- /dev/null +++ b/src/main/java/com/stories/config/SwaggerConfig.java @@ -0,0 +1,46 @@ +package com.stories.config; + + +import org.springframework.context.annotation.Bean; +import org.springframework.stereotype.Component; + +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@EnableSwagger2 +@Component +public class SwaggerConfig { + + @Bean + public Docket SwaggerApi() { + return new Docket(DocumentationType.SWAGGER_2) + .select() + .apis(RequestHandlerSelectors.basePackage("com.stories")) + .paths(PathSelectors.any()) + .build() + .apiInfo(apiDetails()); + } + + private ApiInfo apiDetails() { + + @SuppressWarnings("deprecation") + ApiInfo apiInfo = new ApiInfo( + "Stories API", + "Official documentation for Stories AP", + "1.0", + "Terms of service", + "apache license", + "http://stories-qa.us-east-2.elasticbeanstalk.com", + "API" + ); + + return apiInfo; + } + + + +} diff --git a/src/main/java/com/stories/constants/StoriesApiConstants.java b/src/main/java/com/stories/constants/StoriesApiConstants.java new file mode 100644 index 0000000..963ce86 --- /dev/null +++ b/src/main/java/com/stories/constants/StoriesApiConstants.java @@ -0,0 +1,66 @@ +package com.stories.constants; + +public class StoriesApiConstants { + public static final String[] statusArray = { "Refining", "Ready to Work", "Working", "Testing", "Ready to Accept", "Accepted" }; + public static final String[] storyDomainValidationArray = { "Story_id", "Sprint_id", "Status", "Assignee_id" }; + public static final String[] taskDomainValidationArray = { "Story_id", "Task_id", "Status", "assignee" }; + public static final int[] pointsArray = { 0, 1, 2, 3, 5 }; + public static final String[] specialCharactersArray = {"?","!","(",")","$","&","/","@","^",">","<","|","#",";",":","[","]","{","}","+","*","¨","¿","-","=","%",",","'",".","_","°","~"}; + public static final String[] validationPathArray = { "/Sprints/", "/StoryDomain/", "/Users/", "/stories/" }; + + public static final String httpStatusBadRequest = "BAD_REQUEST"; + public static final String httpStatusConflict = "CONFLICT"; + public static final String httpCodeStatusBadRequest = "400"; + + public static final String pathStories = "/stories/"; + public static final String pathTasks = "/tasks/"; + + public static final String storyFieldStatusInvalidException = "The Status field should be one of the following options: 'Refining', 'Ready to Work', 'Working', 'Testing', 'Ready to Accept' or 'Accepted'; but none found"; + public static final String storyFieldsNameAndStatusRequiredException = "The JSON format provided is invalid, please provide the required fields 'Name','Status'"; + public static final String storyFieldNameRequiredException = "The JSON format provided is invalid, please provide the required field 'Name'"; + public static final String storyFieldStatusRequiredException = "The JSON format provided is invalid, please provide the required field 'Status'"; + public static final String storyFieldNameExistException = "There is a story with this name already"; + public static final String storyFieldTasksEmptyException = "There are not tasks for this user story yet"; + public static final String storiesNotFoundException = "Stories not found"; + public static final String storyFieldIdNotFoundException = "Story not found"; + public static final String storyFieldSprintIdDoesntExistException = "The id entered in the sprint_id field does not exist"; + public static final String storyFieldUserIdDoesntExistException = "The id entered in the sprint_id field does not exist"; + public static final String storyFieldAssigneDoesntExistException = "User assignee_id does not exist"; + public static final String storyFieldStoryIdSpecialCharacter = "Story not found"; + public static final String storyFieldSprintIdSpecialCharacter = "The id entered in the sprint_id field does not exist"; + public static final String storyFieldAssigneSpecialCharacter = "User assignee_id does not exist"; + public static final String storyFieldProgressNegativeException = "The number entered in the progress field is a negative number"; + public static final String storyFieldProgressExceedsException = "The number entered in the progress field exceeds 100%"; + public static final String storyFieldPointsNegativeException = "The number entered in the points field is a negative number"; + public static final String storyFieldPointsInvalidException = "The number entered in the points field does not match a valid story point"; + + public static final String taskFieldAssigneeNotFoundException = "User assignee_id does not exist"; + public static final String taskFieldIdNotFoundException = "Task not found"; + public static final String taskFieldNameRequiredException = "The JSON format provided is invalid, please provide the required field 'Name'"; + public static final String storyFieldTaskIdSpecialCharacter = "Task not found"; + + public static final String[] ValidationStorySpecialCharacterMessage = {storyFieldStoryIdSpecialCharacter, storyFieldSprintIdSpecialCharacter, storyFieldStatusInvalidException, storyFieldAssigneSpecialCharacter}; + public static final String[] ValidationTaskSpecialCharacterMessage = {storyFieldStoryIdSpecialCharacter, storyFieldTaskIdSpecialCharacter, storyFieldStatusInvalidException, storyFieldAssigneSpecialCharacter}; + + public static final String notesInGetStories = " This method will return a list of users stories. "; + public static final String notesInGetStory = " This method will return a of story. "; + public static final String notesInPostStory = " This method will create a new user story.
" + + "
" + + "
  1. Name
  2. " + + "
  3. Status
  4. " + + "

" + +"Please don't use an ID field in your request body to create a new Story."; + public static final String notesInDeleteStory = " This method will delete a user story. "; + public static final String notesInPutStory = " This method will update a user story.
" + +"Please don't use an ID field in your request body to edit a Story."; + public static final String notesInDeleteTask = " This method will delete a task. "; + public static final String notesInPutTask = " This method will update a task from a story.
" + +"Please don't use an ID field in your request body to edit a Task.";; + public static final String notesInGetTasks = " This method will return a list of the tasks of a story. "; + public static final String notesInGetTask = " This method will return a task from a story. "; + public static final String notesInPostTask = " This method will create a new task.
" + + "
" + + "
  1. Name

" + + "Please don't use an ID field in your request body to create a new Task."; +} + diff --git a/src/main/java/com/stories/controller/GlobalExceptionHandler.java b/src/main/java/com/stories/controller/GlobalExceptionHandler.java new file mode 100644 index 0000000..baae371 --- /dev/null +++ b/src/main/java/com/stories/controller/GlobalExceptionHandler.java @@ -0,0 +1,72 @@ +package com.stories.controller; + +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.servlet.NoHandlerFoundException; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; + +import com.stories.exception.ApiError; +import com.stories.exception.EntityNotFoundException; + +@Order(Ordered.HIGHEST_PRECEDENCE) +@ControllerAdvice +public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { + + @Override + public ResponseEntity handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, + HttpStatus status, WebRequest request) { + + String[] statusArray = { "points", "progress", "start_date", "due_date", "history", "tasks"}; + String mss = ""; + for (int i = 0; i < statusArray.length; i++) { + if (ex.toString().indexOf(statusArray[i]) == -1) { + + } else { + if (statusArray[i].equals(ex.toString().substring(ex.toString().indexOf(statusArray[i]), + ex.toString().indexOf(statusArray[i]) + statusArray[i].length()))) { + mss = ""; + mss = ex.toString().substring(ex.toString().indexOf(statusArray[i]), + ex.toString().indexOf(statusArray[i]) + statusArray[i].length()); + if (mss.equals("start_date") || mss.equals("due_date")) { + mss = "Malformed JSON request, format date should be: ex. 'YYYY-MM-DD'; at " + mss; + } + else if(mss.equals("points")) { + mss = "Malformed JSON request, the format of the '"+ mss +"' field is not valid, Non-numeric content"; + } + else if(mss.equals("progress")) { + mss = "Malformed JSON request, the format of the '"+ mss +"' field is not valid, Non-numeric content"; + } + else if(mss.equals("tasks")) { + mss = "Malformed JSON request, the format of the '"+ mss +"' field is not a valid"; + } + else if(mss.equals("history")) { + mss = "Malformed JSON request, the format of the '"+ mss +"' field is not a valid"; + } + else { + mss = "Malformed JSON request " + mss; + } + return buildResponseEntity(new ApiError(HttpStatus.BAD_REQUEST, 400, mss, "/stories/")); + } + } + } + String error = "Malformed JSON request"; + return buildResponseEntity(new ApiError(HttpStatus.BAD_REQUEST, error, ex)); + } + + private ResponseEntity buildResponseEntity(ApiError apiError) { + return new ResponseEntity<>(apiError, HttpStatus.valueOf(apiError.getStatus())); + } + + @ExceptionHandler({ EntityNotFoundException.class }) + public ResponseEntity handleEntityNotFoundException(EntityNotFoundException ex) { + return buildResponseEntity( + new ApiError(ex.getError(), ex.getStatus(), ex.getMessage(), ex.getPath().toString())); + } +} \ No newline at end of file diff --git a/src/main/java/com/stories/controller/StoriesController.java b/src/main/java/com/stories/controller/StoriesController.java new file mode 100644 index 0000000..f644c63 --- /dev/null +++ b/src/main/java/com/stories/controller/StoriesController.java @@ -0,0 +1,143 @@ +package com.stories.controller; + +import java.util.List; + +import javax.validation.Valid; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +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.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +import com.stories.constants.StoriesApiConstants; +import com.stories.domain.StoryDomain; +import com.stories.domain.StoryDomainId; +import com.stories.domain.TasksDomain; +import com.stories.exception.EntityNotFoundException; +import com.stories.service.StoriesServiceImpl; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; + +@RestController +@Api(value = "Microservices STORY", tags = "Microservices STORY") +@RequestMapping(value = "/stories") +public class StoriesController { + + @Autowired + StoriesServiceImpl storyService; + + @ApiOperation(value = " GET Stories ", notes = StoriesApiConstants.notesInGetStories) + @ApiResponses({ @ApiResponse(code = 200, message = " Success operation ") }) + @ResponseStatus(value = HttpStatus.OK) + @GetMapping(value = "/", produces = "application/json") + @ResponseBody + public List getAllStories() throws Exception { + return storyService.getAllStories(); + } + + @ApiOperation(value = " GET Story ", notes = StoriesApiConstants.notesInGetStory) + @ApiResponses({ @ApiResponse(code = 200, message = " Success operation "), + @ApiResponse(code = 404, message = " Story not found ") }) + @ResponseStatus(value = HttpStatus.OK) + @GetMapping(value = "/{id}", produces = "application/json") + @ResponseBody + public StoryDomain getStoryById(@Valid @PathVariable String id) throws Exception { + return storyService.getStoryById(id); + } + + @ApiOperation(value = " POST Story ", notes = StoriesApiConstants.notesInPostStory) + @ApiResponses({ @ApiResponse(code = 201, message = " Success operation "), + @ApiResponse(code = 400, message = " Story has an invalid status Json "), + @ApiResponse(code= 409, message ="There is a story with this name already.
The user provided does not exist.
User assignee_id does not exist")}) + @ResponseStatus(value = HttpStatus.CREATED) + @PostMapping(value = "/", consumes = "application/json", produces = "application/json") + @ResponseBody + public ResponseEntity createStory(@Valid @RequestBody StoryDomain request) throws Exception { + StoryDomainId storyDomainId = new StoryDomainId(); + storyDomainId.setId(storyService.createStory(request)); + return new ResponseEntity<>(storyDomainId, HttpStatus.CREATED); + } + + @ApiOperation(value = " DELETE Story ", notes = StoriesApiConstants.notesInDeleteStory) + @ApiResponses({ @ApiResponse(code = 204, message = " Success operation "), + @ApiResponse(code = 404, message = " Story not found ") }) + @ResponseStatus(HttpStatus.NO_CONTENT) + @DeleteMapping(value = "/{id}") + public void deleteStory(@Valid @PathVariable String id) throws Exception { + storyService.deleteStory(id); + } + + @ApiOperation(value = " DELETE Task ", notes = StoriesApiConstants.notesInDeleteTask) + @ApiResponses({ @ApiResponse(code = 204, message = " Success operation "), + @ApiResponse(code = 404, message = " Story not found ") }) + @ResponseStatus(HttpStatus.NO_CONTENT) + @DeleteMapping(value = "/{id}/tasks/{taskId}") + public void deleteTask(@Valid @PathVariable String id, @PathVariable String taskId) throws Exception { + storyService.deleteTask(id, taskId); + } + + @ApiOperation(value = " PUT Story ", notes = StoriesApiConstants.notesInPutStory) + @ApiResponses({ @ApiResponse(code = 200, message = " Success operation "), + @ApiResponse(code = 404, message = " Story not found "), + @ApiResponse(code = 400, message = " Malformed JSON request ") }) + @ResponseStatus(value = HttpStatus.OK) + @PutMapping(value = "/{id}", consumes = "application/json", produces = "application/json") + public StoryDomain updateStory(@Valid @RequestBody StoryDomain request, @PathVariable String id) throws Exception { + return storyService.updateStory(request, id); + } + + @ApiOperation(value = " PUT Task ", notes = StoriesApiConstants.notesInPutTask) + @ApiResponses({ @ApiResponse(code = 200, message = " Success operation "), + @ApiResponse(code = 404, message = " Task not found ") }) + @ResponseStatus(value = HttpStatus.OK) + @PutMapping(value = "/{storyId}/tasks/{taskId}", produces = "application/json") + @ResponseBody + public TasksDomain updateTaskById(@Valid @RequestBody TasksDomain task, @PathVariable("storyId") String id, + @PathVariable("taskId") String _id) throws Exception { + return storyService.updateTaskById(task, id, _id); + } + + @ApiOperation(value = " GET Tasks ", notes = StoriesApiConstants.notesInGetTasks) + @ApiResponses({ @ApiResponse(code = 200, message = " Success operation ") }) + @ResponseStatus(value = HttpStatus.OK) + @GetMapping(value = "/{id}/tasks", produces = "application/json") + @ResponseBody + public List getTasksByStory(@Valid @PathVariable String id) throws EntityNotFoundException { + return storyService.getTasksByStory(id); + } + + @ApiOperation(value = " GET Task ", notes = StoriesApiConstants.notesInGetTask) + @ApiResponses({ @ApiResponse(code = 200, message = " Success operation "), + @ApiResponse(code = 404, message = " Task not found ") }) + @ResponseStatus(value = HttpStatus.OK) + @GetMapping(value = "/{storyId}/tasks/{taskId}", produces = "application/json") + @ResponseBody + public TasksDomain getTaskById(@Valid @PathVariable("storyId") String storyId, + @PathVariable("taskId") String taskId) throws Exception { + return storyService.getTaskById(storyId, taskId); + } + + @ApiOperation(value = " POST Task ", notes = StoriesApiConstants.notesInPostTask) + @ApiResponses({ @ApiResponse(code = 201, message = " Success operation "), + @ApiResponse(code = 400, message = " Task has an invalid status Json ")}) + @ResponseStatus(value = HttpStatus.CREATED) + @PostMapping(value = "/{id}/tasks", consumes = "application/json", produces = "application/json") + public ResponseEntity createTask(@Valid @RequestBody TasksDomain taskDomain, @PathVariable String id) throws Exception { + StoryDomainId storyDomainId = new StoryDomainId(); + storyDomainId.setId(storyService.createTask(taskDomain, id)); + return new ResponseEntity<>(storyDomainId, HttpStatus.CREATED); + } + +} \ No newline at end of file diff --git a/src/main/java/com/stories/domain/SprintDomain.java b/src/main/java/com/stories/domain/SprintDomain.java new file mode 100644 index 0000000..eec736b --- /dev/null +++ b/src/main/java/com/stories/domain/SprintDomain.java @@ -0,0 +1,18 @@ +package com.stories.domain; + +import java.time.LocalDate; + +import lombok.Data; + +@Data +public class SprintDomain { + + private String id; + private String name; + private String technology; + private boolean active; + private boolean is_backlog; + private LocalDate start_date; + private LocalDate end_date; + +} diff --git a/src/main/java/com/stories/domain/StoryDomain.java b/src/main/java/com/stories/domain/StoryDomain.java new file mode 100644 index 0000000..f6cb9d9 --- /dev/null +++ b/src/main/java/com/stories/domain/StoryDomain.java @@ -0,0 +1,71 @@ +package com.stories.domain; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; + +import org.springframework.data.mongodb.core.index.Indexed; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +@Data +public class StoryDomain { + + @ApiModelProperty(example="5e827f2f48b0866f87e1cbc2", value="Identifier of the story") + private String _id; + + @ApiModelProperty(example="5ea1cabbcafedd13f03bf05c", value="Identifier of the sprint") + private String sprint_id; + + @ApiModelProperty(example="Java", value="Technology used") + private String technology; + + @ApiModelProperty(example="Create new story", value="Name of the story") + @Indexed(unique = true) + private String name; + + @ApiModelProperty(example="Make new Stories", value="Story description") + private String description; + + @ApiModelProperty(example="As a website user, I want to able to submit feedback.", value= "Acceptance criteria of the story") + private String acceptance_criteria; + + @ApiModelProperty(example="1", value="Points of the story") + private int points; + + @ApiModelProperty(example="10", value="Progress of the story") + private int progress; + + @ApiModelProperty(example="Working", value="Status of the story") + private String status; + + @ApiModelProperty(example="The first steps", value="Notes of the story") + private String notes; + + @ApiModelProperty(example="Research information in sure websites", value="Comments of the story") + private String comments; + + @ApiModelProperty(example="2020-08-25", value="Start date of the story") + private LocalDate start_date; + + @ApiModelProperty(example="2020-08-25", value="Due date of the story") + private LocalDate due_date; + + @ApiModelProperty(example="High", value="Priority of the story") + private String priority; + + @ApiModelProperty(example="5ea7125ce6cd3109e8bc71c6", value="Identifier of the user") + private String assignee_id; + + @ApiModelProperty(example="[]", value="The history of the story") + private List history; + + @ApiModelProperty(example="[]", value="The tasks of the story") + private List tasks; + + public StoryDomain() { + this.history = new ArrayList<>(); + this.tasks = new ArrayList<>(); + } +} diff --git a/src/main/java/com/stories/domain/StoryDomainId.java b/src/main/java/com/stories/domain/StoryDomainId.java new file mode 100644 index 0000000..8cbd55f --- /dev/null +++ b/src/main/java/com/stories/domain/StoryDomainId.java @@ -0,0 +1,10 @@ +package com.stories.domain; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class StoryDomainId { + private String Id; +} diff --git a/src/main/java/com/stories/domain/TasksDomain.java b/src/main/java/com/stories/domain/TasksDomain.java new file mode 100644 index 0000000..4be8c72 --- /dev/null +++ b/src/main/java/com/stories/domain/TasksDomain.java @@ -0,0 +1,27 @@ +package com.stories.domain; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +@Data +public class TasksDomain { + + @ApiModelProperty(example="5e827f2f48b0866f87e1cbc2", value="Identifier of the task") + private String _id; + + @ApiModelProperty(example="Make PR", value="name of the task") + private String name; + + @ApiModelProperty(example="Create Pull Request to master", value="description of the task") + private String description; + + @ApiModelProperty(example="Working", value="status of the task") + private String status; + + @ApiModelProperty(example="Waiting for review", value="comments about the task") + private String comments; + + @ApiModelProperty(example="5ea7125ce6cd3109e8bc71c6", value="Identifier of the user") + private String assignee; + +} \ No newline at end of file diff --git a/src/main/java/com/stories/domain/UserDomain.java b/src/main/java/com/stories/domain/UserDomain.java new file mode 100644 index 0000000..b22dfd4 --- /dev/null +++ b/src/main/java/com/stories/domain/UserDomain.java @@ -0,0 +1,19 @@ +package com.stories.domain; + +import lombok.Data; + +@Data +public class UserDomain { + + private String userId; + private String firstName; + private String lastName; + private String email; + private String phone; + private String startDate; + private String endDate; + private String activeTechnology; + private String status; + private String role; + +} diff --git a/src/main/java/com/stories/exception/ApiError.java b/src/main/java/com/stories/exception/ApiError.java new file mode 100644 index 0000000..751a5e8 --- /dev/null +++ b/src/main/java/com/stories/exception/ApiError.java @@ -0,0 +1,64 @@ +package com.stories.exception; + +import java.time.LocalDateTime; + +import org.springframework.http.HttpStatus; + +import com.fasterxml.jackson.annotation.JsonFormat; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class ApiError { + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss") + private LocalDateTime timestamp; + private String error; + private int status; + private String message; + private String path; + + public ApiError() { + this.timestamp = LocalDateTime.now(); + } + + public ApiError(HttpStatus error) { + this(); + this.error = error.getReasonPhrase(); + } + + public ApiError(HttpStatus error, Throwable ex) { + this(); + this.error = error.getReasonPhrase(); + this.message = "Unexpected error"; + } + + public ApiError(HttpStatus error, String message) { + this(); + this.error = error.getReasonPhrase(); + this.message = message; + } + + public ApiError(HttpStatus error, String message, Throwable ex) { + this(); + this.error = error.getReasonPhrase(); + this.message = message; + } + + public ApiError(HttpStatus error, int status, String message, String path) { + this(); + this.error = error.getReasonPhrase(); + this.status = error.value(); + this.message = message; + this.path = path; + } + + public ApiError(HttpStatus error, String message, Throwable ex, String path) { + this(); + this.error = error.getReasonPhrase(); + this.message = message; + this.path = path; + } +} \ No newline at end of file diff --git a/src/main/java/com/stories/exception/EntityNotFoundException.java b/src/main/java/com/stories/exception/EntityNotFoundException.java new file mode 100644 index 0000000..3915147 --- /dev/null +++ b/src/main/java/com/stories/exception/EntityNotFoundException.java @@ -0,0 +1,49 @@ +package com.stories.exception; + +import org.springframework.http.HttpStatus; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class EntityNotFoundException extends Exception { + + private static final long serialVersionUID = 1002819552332825026L; + private HttpStatus error; + private Class entityType; + private String message; + private Throwable cause; + private int status; + private String path; + + public EntityNotFoundException(String message) { + this.error = HttpStatus.NOT_FOUND; + this.message = message; + } + + public EntityNotFoundException(String message, HttpStatus status, String path) { + this.error = HttpStatus.CONFLICT; + this.message = message; + this.path = path; + } + + public EntityNotFoundException(String message, String path) { + this(message); + this.path = path; + } + + public EntityNotFoundException(String message, int status, Class entityType, String path) { + this.message = message; + this.status = status; + this.entityType = entityType; + this.path = path; + } + + public EntityNotFoundException(String message, String error, String path) { + this.error = HttpStatus.BAD_REQUEST; + this.status = HttpStatus.BAD_REQUEST.value(); + this.message = message; + this.path = path; + } +} \ No newline at end of file diff --git a/src/main/java/com/stories/heathchecks/sprintsHealthcheck.java b/src/main/java/com/stories/heathchecks/sprintsHealthcheck.java new file mode 100644 index 0000000..7d2249a --- /dev/null +++ b/src/main/java/com/stories/heathchecks/sprintsHealthcheck.java @@ -0,0 +1,47 @@ +package com.stories.heathchecks; + +import java.util.List; + +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.HealthIndicator; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; + +import com.stories.domain.SprintDomain; + +@Component +public class sprintsHealthcheck implements HealthIndicator { + + private final String message_key = "Sprints API "; + RestTemplate restTemplate = new RestTemplate(); + + @Override + public Health health() { + if (!isRunningUsersAPI()) { + return Health.down().withDetail(message_key, "Not Available").build(); + } + return Health.up().withDetail(message_key, "Available").build(); + } + + public Boolean isRunningUsersAPI() { + String uri = "http://sprints-qa.us-east-2.elasticbeanstalk.com/sprints/"; + Boolean isRunning = false; + try { + ResponseEntity> sprintsResponse = restTemplate.exchange(uri, HttpMethod.GET, null, + new ParameterizedTypeReference>() { + }); + if (sprintsResponse != null & sprintsResponse.hasBody()) { + isRunning = true; + } + } catch (RestClientException e) { + return isRunning; + } catch (Exception e) { + return isRunning; + } + return isRunning; + } +} diff --git a/src/main/java/com/stories/heathchecks/usersHealthcheck.java b/src/main/java/com/stories/heathchecks/usersHealthcheck.java new file mode 100644 index 0000000..ea608e1 --- /dev/null +++ b/src/main/java/com/stories/heathchecks/usersHealthcheck.java @@ -0,0 +1,46 @@ +package com.stories.heathchecks; + +import java.util.List; + +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.HealthIndicator; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; + +import com.stories.domain.UserDomain; + +@Component +public class usersHealthcheck implements HealthIndicator { + private final String message_key = "Users API"; + RestTemplate restTemplate = new RestTemplate(); + + @Override + public Health health() { + if (!isRunningUsersAPI()) { + return Health.down().withDetail(message_key, "Not Available").build(); + } + return Health.up().withDetail(message_key, "Available").build(); + } + + public Boolean isRunningUsersAPI() { + String uri = "http://sourcescusersapi-test.us-west-1.elasticbeanstalk.com/api/users/"; + Boolean isRunning = false; + try { + ResponseEntity> usersResponse = restTemplate.exchange(uri, HttpMethod.GET, null, + new ParameterizedTypeReference>() { + }); + if (usersResponse != null & usersResponse.hasBody()) { + isRunning = true; + } + } catch (RestClientException e) { + return isRunning; + } catch (Exception e) { + return isRunning; + } + return isRunning; + } +} diff --git a/src/main/java/com/stories/model/StoryModel.java b/src/main/java/com/stories/model/StoryModel.java new file mode 100644 index 0000000..f8c2ae4 --- /dev/null +++ b/src/main/java/com/stories/model/StoryModel.java @@ -0,0 +1,36 @@ +package com.stories.model; + +import java.time.LocalDate; +import java.util.List; + +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.index.Indexed; +import org.springframework.data.mongodb.core.mapping.Document; + +import lombok.Data; + +@Data +@Document(collection = "stories") +public class StoryModel { + + @Id + private String _id; + private String sprint_id; + private String technology; + @Indexed(unique = true) + private String name; + private String description; + private String acceptance_criteria; + private int points; + private int progress; + private String status; + private String notes; + private String comments; + private LocalDate start_date; + private LocalDate due_date; + private String priority; + private String assignee_id; + private List history; + private List tasks; + +} diff --git a/src/main/java/com/stories/model/TaskModel.java b/src/main/java/com/stories/model/TaskModel.java new file mode 100644 index 0000000..7f8b0db --- /dev/null +++ b/src/main/java/com/stories/model/TaskModel.java @@ -0,0 +1,20 @@ +package com.stories.model; + +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +import lombok.Data; + +@Data +@Document(collection = "stories") +public class TaskModel { + + @Id + private String _id; + private String name; + private String description; + private String status; + private String comments; + private String assignee; + +} \ No newline at end of file diff --git a/src/main/java/com/stories/model/UserModel.java b/src/main/java/com/stories/model/UserModel.java new file mode 100644 index 0000000..83d894a --- /dev/null +++ b/src/main/java/com/stories/model/UserModel.java @@ -0,0 +1,18 @@ +package com.stories.model; + +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import lombok.Data; + +@Data +@JsonIgnoreProperties(ignoreUnknown = true) +@Document(collection = "users") +public class UserModel { + + @Id + private String _id; + +} diff --git a/src/main/java/com/stories/repository/StoriesCustomRepository.java b/src/main/java/com/stories/repository/StoriesCustomRepository.java new file mode 100644 index 0000000..9463dad --- /dev/null +++ b/src/main/java/com/stories/repository/StoriesCustomRepository.java @@ -0,0 +1,14 @@ +package com.stories.repository; + +import org.springframework.data.mongodb.core.aggregation.AggregationResults; + +import com.stories.domain.TasksDomain; +import com.stories.exception.EntityNotFoundException; +import com.stories.model.TaskModel; + +public interface StoriesCustomRepository { + + AggregationResults getTasksByStory(String id); + + AggregationResults getTaskById(String storyId, String _id) throws EntityNotFoundException; +} diff --git a/src/main/java/com/stories/repository/StoriesCustomRepositoryImpl.java b/src/main/java/com/stories/repository/StoriesCustomRepositoryImpl.java new file mode 100644 index 0000000..915ce3c --- /dev/null +++ b/src/main/java/com/stories/repository/StoriesCustomRepositoryImpl.java @@ -0,0 +1,57 @@ +package com.stories.repository; + +import javax.ws.rs.InternalServerErrorException; + + +import org.bson.types.ObjectId; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.aggregation.Aggregation; +import org.springframework.data.mongodb.core.aggregation.AggregationResults; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.stereotype.Repository; + +import com.stories.domain.TasksDomain; +import com.stories.exception.EntityNotFoundException; +import com.stories.model.TaskModel; + +@Repository +public class StoriesCustomRepositoryImpl implements StoriesCustomRepository { + +private MongoTemplate mongoTemplate; + + public StoriesCustomRepositoryImpl(MongoTemplate mongoTemplate) { + this.mongoTemplate = mongoTemplate; + } + + @Override + public AggregationResults getTasksByStory(String id) { + Aggregation aggregation = Aggregation.newAggregation( + Aggregation.unwind("tasks"), + Aggregation.match(Criteria.where("_id").is(id)), + Aggregation.project("tasks._id", "tasks.name", "tasks.description", "tasks.status", "tasks.comments", "tasks.assignee") + ); + AggregationResults results = mongoTemplate.aggregate(aggregation,"stories", TasksDomain.class); + + return results; + + } + + @Override + public AggregationResults getTaskById(String id ,String _id) throws EntityNotFoundException{ + try { + Aggregation aggregation = Aggregation.newAggregation( + Aggregation.unwind("tasks"), + Aggregation.match(Criteria.where("tasks._id").is(new ObjectId(_id))), + Aggregation.project("tasks._id", "tasks.name", "tasks.description", + "tasks.status", "tasks.comments", "tasks.assignee") + ); + AggregationResults results = mongoTemplate.aggregate(aggregation, "stories", TaskModel.class); + return results; + + }catch(Exception e) { + throw new EntityNotFoundException("Task not found", "/stories/" + id + "/tasks/" + _id); + } + + } + +} \ No newline at end of file diff --git a/src/main/java/com/stories/repository/StoriesRepository.java b/src/main/java/com/stories/repository/StoriesRepository.java new file mode 100644 index 0000000..04dbde3 --- /dev/null +++ b/src/main/java/com/stories/repository/StoriesRepository.java @@ -0,0 +1,12 @@ +package com.stories.repository; + +import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.stereotype.Repository; + +import com.stories.model.StoryModel; +import com.stories.model.TaskModel; + +@Repository +public interface StoriesRepository extends MongoRepository { + public TaskModel findByTasks__id(String id); +} \ No newline at end of file diff --git a/src/main/java/com/stories/repository/UsersRepository.java b/src/main/java/com/stories/repository/UsersRepository.java new file mode 100644 index 0000000..6a85377 --- /dev/null +++ b/src/main/java/com/stories/repository/UsersRepository.java @@ -0,0 +1,11 @@ +package com.stories.repository; + +import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.stereotype.Repository; + +import com.stories.model.UserModel; + +@Repository +public interface UsersRepository extends MongoRepository { + +} diff --git a/src/main/java/com/stories/service/StoriesService.java b/src/main/java/com/stories/service/StoriesService.java new file mode 100644 index 0000000..fb7d841 --- /dev/null +++ b/src/main/java/com/stories/service/StoriesService.java @@ -0,0 +1,30 @@ +package com.stories.service; + +import java.util.List; + +import com.stories.domain.StoryDomain; +import com.stories.domain.TasksDomain; +import com.stories.exception.EntityNotFoundException; + +public interface StoriesService { + + StoryDomain getStoryById(String id) throws Exception; + + List getAllStories() throws Exception; + + public String createStory(StoryDomain request) throws Exception; + + void deleteStory(String id) throws Exception; + + StoryDomain updateStory(StoryDomain request, String id) throws Exception; + + List getTasksByStory(String id) throws EntityNotFoundException; + + TasksDomain getTaskById(String id, String _id) throws Exception; + + void deleteTask(String id, String taskId) throws Exception; + + public String createTask(TasksDomain taskDomain, String id) throws Exception; + + public TasksDomain updateTaskById(TasksDomain task, String id, String _id) throws Exception; +} \ No newline at end of file diff --git a/src/main/java/com/stories/service/StoriesServiceImpl.java b/src/main/java/com/stories/service/StoriesServiceImpl.java new file mode 100644 index 0000000..1d15836 --- /dev/null +++ b/src/main/java/com/stories/service/StoriesServiceImpl.java @@ -0,0 +1,540 @@ +package com.stories.service; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.regex.Pattern; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.bson.types.ObjectId; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; + +import com.stories.constants.StoriesApiConstants; +import com.stories.domain.StoryDomain; +import com.stories.domain.TasksDomain; +import com.stories.exception.EntityNotFoundException; +import com.stories.model.StoryModel; +import com.stories.model.TaskModel; +import com.stories.repository.StoriesCustomRepository; +import com.stories.repository.StoriesRepository; +import com.stories.repository.UsersRepository; +import com.stories.sprintsclient.SprintsClient; +import com.stories.usersclient.UsersClient; + +import io.micrometer.core.instrument.util.StringUtils; +import ma.glasnost.orika.MapperFacade; + +@Service +public class StoriesServiceImpl implements StoriesService { + + @Autowired + StoriesRepository storiesRepository; + + @Autowired + UsersRepository usersRepository; + + @Autowired + StoriesCustomRepository storiesCustomRepository; + + private static Logger logger = LogManager.getLogger(); + + @Autowired + private MapperFacade mapperFacade; + + StoryModel storyModel = new StoryModel(); + List storiesModel = new ArrayList(); + StoryDomain storyDomain = new StoryDomain(); + List storiesDomain = new ArrayList<>(); + + + @Autowired + SprintsClient sprintClient; + + @Autowired + UsersClient userClient; + + @Override + public String createStory(StoryDomain storyDomain) throws Exception { + storyDomain.setStart_date(dateValidation(storyDomain.getStart_date())); + String[] mensaggeDinamicValidation = dynamicValidation(storyDomain, ""); + + if (StringUtils.isEmpty(mensaggeDinamicValidation[0])) { + storyModel = mapperFacade.map(storyDomain, StoryModel.class); + logger.debug("Creating story with the json : {}", storyModel); + String id = nameValidation(storyModel).get_id(); + return id; + } else { + if(mensaggeDinamicValidation[2] == StoriesApiConstants.httpStatusBadRequest) { + throw new EntityNotFoundException(mensaggeDinamicValidation[0],"", mensaggeDinamicValidation[1]); + } + else if(mensaggeDinamicValidation[2] == StoriesApiConstants.httpStatusConflict) { + throw new EntityNotFoundException(mensaggeDinamicValidation[0], HttpStatus.CONFLICT, mensaggeDinamicValidation[1]); + } + else { + throw new EntityNotFoundException(mensaggeDinamicValidation[0], mensaggeDinamicValidation[1]); + } + } + } + + @Override + public String createTask(TasksDomain taskDomain, String id) throws Exception { + TaskModel taskModel = new TaskModel(); + String mensaggeDinamicValidation = TaskSpecialCharacterValidation(taskDomain, id, ""); + + if(!StringUtils.isEmpty(mensaggeDinamicValidation)) { + throw new EntityNotFoundException(mensaggeDinamicValidation, "", StoriesApiConstants.pathStories); + } + if(storiesRepository.existsById(id)) { + if(!StringUtils.isEmpty(taskDomain.getName())) { + if (userNullTaskValidation(taskDomain.getAssignee())) { + if (statusTaskValidation(StoriesApiConstants.statusArray, taskDomain.getStatus())) { + storyModel = storiesRepository.findById(id).get(); + List tasks = storyModel.getTasks(); + taskModel = mapperFacade.map(taskDomain, TaskModel.class); + taskModel.set_id(new ObjectId().toString()); + tasks.add(taskModel); + storyModel.setTasks(tasks); + logger.debug("Creating task for the US: "+ storyModel.get_id() +" with the json: "+ taskModel); + storiesRepository.save(storyModel); + return taskModel.get_id(); + }else { + throw new EntityNotFoundException( + StoriesApiConstants.storyFieldStatusInvalidException, + StoriesApiConstants.httpCodeStatusBadRequest, + StoriesApiConstants.pathStories); + } + }else { + throw new EntityNotFoundException(StoriesApiConstants.taskFieldAssigneeNotFoundException, StoriesApiConstants.pathStories); + } + }else { + throw new EntityNotFoundException(StoriesApiConstants.taskFieldNameRequiredException, + StoriesApiConstants.httpCodeStatusBadRequest, + StoriesApiConstants.pathStories); + } + }else { + throw new EntityNotFoundException(StoriesApiConstants.storyFieldIdNotFoundException, StoriesApiConstants.pathStories + id + StoriesApiConstants.pathTasks); + } + } + + @Override + public void deleteStory(String id) throws Exception { + if (!storiesRepository.existsById(id)) { + throw new EntityNotFoundException(StoriesApiConstants.storyFieldIdNotFoundException,StoriesApiConstants.pathStories + id); + } else + logger.debug("Deleting story with the id: " + id); + storiesRepository.deleteById(id); + } + + @Override + public void deleteTask(String id, String taskId) throws Exception { + if (!storiesRepository.existsById(id)) { + throw new EntityNotFoundException(StoriesApiConstants.storyFieldIdNotFoundException, StoriesApiConstants.pathStories + id); + } else { + storyModel = storiesRepository.findById(id).get(); + List tasks = storyModel.getTasks(); + if (!tasks.isEmpty()) { + for (int i = 0; i < tasks.size(); i++) { + if (tasks.get(i).get_id().toString().equals(taskId)) { + tasks.remove(i); + logger.debug("Deleting task: "+ taskId +" of the US: "+ storyModel.get_id()); + storyModel.setTasks(tasks); + storiesRepository.save(storyModel); + } else if (i == (tasks.size() - 1)) { + throw new EntityNotFoundException(StoriesApiConstants.taskFieldIdNotFoundException, + StoriesApiConstants.pathStories + id + StoriesApiConstants.pathTasks + taskId); + } + } + } else { + throw new EntityNotFoundException(StoriesApiConstants.storyFieldTasksEmptyException, StoriesApiConstants.pathTasks); + } + } + } + + @Override + public StoryDomain updateStory(StoryDomain storyDomain, String id) throws Exception { + storyDomain.setStart_date(dateValidation(storyDomain.getStart_date())); + String[] mensaggeDinamicValidation = dynamicValidation(storyDomain, id); + + if (StringUtils.isEmpty(mensaggeDinamicValidation[0])) { + if (storiesRepository.existsById(id)) { + List tasksModel = storiesRepository.findById(id).get().getTasks(); + storyModel = mapperFacade.map(storyDomain, StoryModel.class); + storyModel.set_id(id); + storyModel.setTasks(tasksModel); + nameValidation(storyModel); + storyDomain = mapperFacade.map(storyModel, StoryDomain.class); + logger.debug("Updating story with the id: " + id + " - JSON : {}", storyDomain); + return storyDomain; + } else { + throw new EntityNotFoundException(StoriesApiConstants.storyFieldIdNotFoundException, StoriesApiConstants.pathStories + id); + } + } else { + if(mensaggeDinamicValidation[2] == StoriesApiConstants.httpStatusBadRequest) { + throw new EntityNotFoundException(mensaggeDinamicValidation[0],"", mensaggeDinamicValidation[1]); + } + else if(mensaggeDinamicValidation[2] == StoriesApiConstants.httpStatusConflict) { + throw new EntityNotFoundException(mensaggeDinamicValidation[0], HttpStatus.CONFLICT, mensaggeDinamicValidation[1]); + } + else { + throw new EntityNotFoundException(mensaggeDinamicValidation[0], mensaggeDinamicValidation[1]); + } + } + } + + @Override + public TasksDomain updateTaskById(TasksDomain task, String id, String _id) throws Exception { + String mensaggeDinamicValidation = TaskSpecialCharacterValidation(task, id, _id); + + if(!StringUtils.isEmpty(mensaggeDinamicValidation)) { + throw new EntityNotFoundException(mensaggeDinamicValidation, "", StoriesApiConstants.pathStories); + } + if (storiesRepository.existsById(id)) { + task.set_id(_id); + if (!statusTaskValidation(StoriesApiConstants.statusArray, task.getStatus())) { + throw new EntityNotFoundException( + StoriesApiConstants.storyFieldStatusInvalidException, + StoriesApiConstants.httpCodeStatusBadRequest, + StoriesApiConstants.pathStories); + } + if (!StringUtils.isEmpty(task.getAssignee())) { + if (!userClient.existUserById(task.getAssignee())) { + throw new EntityNotFoundException(StoriesApiConstants.taskFieldAssigneeNotFoundException, HttpStatus.CONFLICT, + StoriesApiConstants.pathStories + id + StoriesApiConstants.pathTasks + _id); + } + } + if (StringUtils.isEmpty(task.getName())) { + throw new EntityNotFoundException(StoriesApiConstants.taskFieldNameRequiredException, + StoriesApiConstants.httpCodeStatusBadRequest, + StoriesApiConstants.pathStories + id + StoriesApiConstants.pathTasks + _id); + } + storyModel = storiesRepository.findById(id).get(); + List updatedTasks = new ArrayList<>(); + boolean taskFoundFlag = false; + for (TaskModel tasks : storyModel.getTasks()) { + if (task.get_id().equals(tasks.get_id())) { + tasks.set_id(task.get_id()); + tasks.setName(task.getName()); + tasks.setDescription(task.getDescription()); + tasks.setStatus(task.getStatus()); + tasks.setComments(task.getComments()); + tasks.setAssignee(task.getAssignee()); + taskFoundFlag = true; + } + updatedTasks.add(tasks); + } + if (!taskFoundFlag) { + throw new EntityNotFoundException(StoriesApiConstants.taskFieldIdNotFoundException, StoriesApiConstants.pathStories + id + StoriesApiConstants.pathTasks + _id); + } + storyModel.setTasks(updatedTasks); + storiesRepository.save(storyModel); + logger.debug("Updating task: " + id + " of the US: "+ storyModel.get_id() +" with the JSON: "+ task); + return task; + } else { + throw new EntityNotFoundException(StoriesApiConstants.storyFieldIdNotFoundException, StoriesApiConstants.pathStories + id); + } + } + + @Override + public StoryDomain getStoryById(String id) throws Exception { + if (!storiesRepository.existsById(id)) + throw new EntityNotFoundException(StoriesApiConstants.storyFieldIdNotFoundException, StoriesApiConstants.pathStories + id); + storyModel = storiesRepository.findById(id).get(); + storyDomain = mapperFacade.map(storyModel, StoryDomain.class); + logger.debug("Getting story with the id: " + id + " - JSON : {}", storyDomain); + return storyDomain; + } + + @Override + public List getAllStories() throws Exception { + List allStoriesModel = new ArrayList<>(); + List allStoriesDomain = new ArrayList<>(); + allStoriesModel = storiesRepository.findAll(); + if (allStoriesModel == null) + throw new EntityNotFoundException(StoriesApiConstants.storiesNotFoundException, StoriesApiConstants.pathStories); + for (int i = 0; i < allStoriesModel.size(); i++) { + allStoriesDomain.add(mapperFacade.map(allStoriesModel.get(i), StoryDomain.class)); + } + logger.debug("Getting all stories - JSON : {}", allStoriesDomain); + return allStoriesDomain; + } + + @Override + public TasksDomain getTaskById(String id, String _id) throws Exception { + if (storiesRepository.existsById(id)) { + TaskModel taskModel = storiesCustomRepository.getTaskById(id, _id).getUniqueMappedResult(); + if (taskModel.get_id() == null) { + throw new EntityNotFoundException(StoriesApiConstants.taskFieldIdNotFoundException, StoriesApiConstants.pathStories + id + StoriesApiConstants.pathTasks + _id); + } + TaskModel storyWithId = storiesRepository.findByTasks__id(_id); + if(storyWithId.get_id().equals(id)) { + TasksDomain taskDomain = mapperFacade.map(taskModel, TasksDomain.class); + logger.debug("Getting task: " + _id + " of the US: " + id + ", task JSON : {}", taskDomain); + return taskDomain; + } + throw new EntityNotFoundException(StoriesApiConstants.taskFieldIdNotFoundException, StoriesApiConstants.pathStories + id); + } + throw new EntityNotFoundException(StoriesApiConstants.storyFieldIdNotFoundException, StoriesApiConstants.pathStories + id); + } + + public List getTasksByStory(String id) throws EntityNotFoundException { + if (storiesRepository.existsById(id)) { + List results = storiesCustomRepository.getTasksByStory(id).getMappedResults(); + logger.debug("Getting all tasks of the US: " + id + " - JSON : {}", results); + return results; + } + throw new EntityNotFoundException(StoriesApiConstants.storyFieldIdNotFoundException, StoriesApiConstants.pathStories + id + StoriesApiConstants.pathTasks); + } + + private String statusValidation(String[] statusArray, String storyStatus) { + String validationStatus = ""; + if (!(Arrays.asList(statusArray).contains(storyStatus))) { + validationStatus = StoriesApiConstants.storyFieldStatusInvalidException; + } + if (StringUtils.isEmpty(validationStatus)) { + return validationStatus; + } else { + return validationStatus + " AND "; + } + } + + private StoryModel nameValidation(StoryModel storyModel) throws EntityNotFoundException { + try { + storiesRepository.save(storyModel); + return storyModel; + } catch (Exception e) { + throw new EntityNotFoundException(StoriesApiConstants.storyFieldNameExistException, HttpStatus.CONFLICT, StoriesApiConstants.pathStories); + } + } + + private String userNullValidation(String assigneeId) { + String validation = ""; + if (StringUtils.isEmpty(assigneeId)) { + + } else { + if (!userClient.existUserById(assigneeId)) { + validation = StoriesApiConstants.storyFieldAssigneDoesntExistException; + return validation + " AND "; + } + } + return validation; + } + + private String sprintNullValidation(String sprintId) { + String validation = ""; + if (StringUtils.isEmpty(sprintId)) { + + } else { + if (!sprintClient.existsSprintById(sprintId)) + validation = StoriesApiConstants.storyFieldSprintIdDoesntExistException; + } + if (StringUtils.isEmpty(validation)) { + return validation; + } else { + return validation + " AND "; + } + } + + private String nameStatusNullValidation(String name, String status) { + String validationNameStatus = ""; + + if (StringUtils.isEmpty(name) && StringUtils.isEmpty(status)) { + validationNameStatus = StoriesApiConstants.storyFieldsNameAndStatusRequiredException; + } else if (StringUtils.isEmpty(name)) { + validationNameStatus = StoriesApiConstants.storyFieldNameRequiredException; + } else if (StringUtils.isEmpty(status)) { + validationNameStatus = StoriesApiConstants.storyFieldStatusRequiredException; + } + + if (!StringUtils.isEmpty(validationNameStatus)) { + return validationNameStatus; + } else { + return validationNameStatus; + } + } + + private LocalDate dateValidation(LocalDate date) { + if ((!(date == null || (StringUtils.isEmpty(date.toString()))))) { + return date; + } else { + return LocalDate.now(); + } + } + + private String proggressValidation(int progress) { + String progressValidation = ""; + if (progress < 0) { + progressValidation = StoriesApiConstants.storyFieldProgressNegativeException; + } + if (progress > 100) { + progressValidation = StoriesApiConstants.storyFieldProgressExceedsException; + } + if (StringUtils.isEmpty(progressValidation)) { + return progressValidation; + } else { + return progressValidation + " AND "; + } + } + + private String pointsValidation(int points, int[] pointsArray) { + String pointsValidation = ""; + if (points < 0) { + pointsValidation = StoriesApiConstants.storyFieldPointsNegativeException; + } else { + for (int i = 0; i < pointsArray.length; i++) { + if (points == pointsArray[i]) { + break; + } else if (i == pointsArray.length - 1) { + pointsValidation = StoriesApiConstants.storyFieldPointsInvalidException; + } + } + } + if (StringUtils.isEmpty(pointsValidation)) { + return pointsValidation; + } else { + return pointsValidation + " AND "; + } + } + + private String[] dynamicValidation(StoryDomain storyDomain, String storyId) { + String[] mensaggeDinamicValidation = { "", "" , ""}; + String validationRespons = ""; + int countValidationPositive = 0; + + List validateSpecialCharacterField = new ArrayList<>(); + validateSpecialCharacterField.add(storyId); + validateSpecialCharacterField.add(storyDomain.getSprint_id()); + validateSpecialCharacterField.add(storyDomain.getStatus()); + validateSpecialCharacterField.add(storyDomain.getAssignee_id()); + + validationRespons = nameStatusNullValidation(storyDomain.getName(), storyDomain.getStatus()); + if (!StringUtils.isEmpty(validationRespons)) { + mensaggeDinamicValidation[0] = mensaggeDinamicValidation[0] + validationRespons; + mensaggeDinamicValidation[1] = mensaggeDinamicValidation[1] + StoriesApiConstants.pathStories + storyId; + mensaggeDinamicValidation[2] = StoriesApiConstants.httpStatusBadRequest; + return mensaggeDinamicValidation; + } + + validationRespons = ""; + for(int i= 0; i < validateSpecialCharacterField.size(); i++) { + if(validateSpecialCharacterField.get(i) != null) { + boolean err = Pattern.compile("[a-zA-Z0-9\\s]*").matcher(validateSpecialCharacterField.get(i)).matches(); + if (!err) { + countValidationPositive++; + if (StringUtils.isEmpty(validationRespons)) { + validationRespons = StoriesApiConstants.ValidationStorySpecialCharacterMessage[i]; + } else { + validationRespons = validationRespons + " AND " + StoriesApiConstants.ValidationStorySpecialCharacterMessage[i]; + } + } + } + } + if(countValidationPositive >= 1) { + mensaggeDinamicValidation[0] = validationRespons; + } + + if(!StringUtils.isEmpty(mensaggeDinamicValidation[0])) { + mensaggeDinamicValidation[1] = StoriesApiConstants.pathStories + storyId; + mensaggeDinamicValidation[2] = StoriesApiConstants.httpStatusBadRequest; + return mensaggeDinamicValidation; + } + + if((!StringUtils.isEmpty(storyDomain.getSprint_id())) || (!StringUtils.isEmpty(storyDomain.getAssignee_id()))) { + validationRespons = sprintNullValidation(storyDomain.getSprint_id()); + if (!StringUtils.isEmpty(validationRespons)) { + mensaggeDinamicValidation[0] = mensaggeDinamicValidation[0] + validationRespons; + } + + validationRespons = userNullValidation(storyDomain.getAssignee_id()); + if (!StringUtils.isEmpty(validationRespons)) { + mensaggeDinamicValidation[0] = mensaggeDinamicValidation[0] + validationRespons; + } + + mensaggeDinamicValidation[1] = mensaggeDinamicValidation[1] + StoriesApiConstants.pathStories + storyId; + mensaggeDinamicValidation[2] = StoriesApiConstants.httpStatusConflict; + if(!StringUtils.isEmpty(mensaggeDinamicValidation[0])) { + mensaggeDinamicValidation[0] = endCheckValidation(mensaggeDinamicValidation[0]); + return mensaggeDinamicValidation; + } + } + + if((!StringUtils.isEmpty(storyDomain.getStatus())) || !(StringUtils.isEmpty(storyDomain.getProgress()+"")) || !(StringUtils.isEmpty(storyDomain.getPoints()+""))) { + validationRespons = pointsValidation(storyDomain.getPoints(), StoriesApiConstants.pointsArray); + if (!StringUtils.isEmpty(validationRespons)) { + mensaggeDinamicValidation[0] = mensaggeDinamicValidation[0] + validationRespons; + } + + validationRespons = proggressValidation(storyDomain.getProgress()); + if (!StringUtils.isEmpty(validationRespons)) { + mensaggeDinamicValidation[0] = mensaggeDinamicValidation[0] + validationRespons; + } + + validationRespons = statusValidation(StoriesApiConstants.statusArray, storyDomain.getStatus()); + if (!StringUtils.isEmpty(validationRespons)) { + mensaggeDinamicValidation[0] = mensaggeDinamicValidation[0] + validationRespons; + } + + mensaggeDinamicValidation[1] = mensaggeDinamicValidation[1] + StoriesApiConstants.pathStories + storyId; + mensaggeDinamicValidation[2] = StoriesApiConstants.httpStatusBadRequest; + if(!StringUtils.isEmpty(mensaggeDinamicValidation[0])) { + mensaggeDinamicValidation[0] = endCheckValidation(mensaggeDinamicValidation[0]); + return mensaggeDinamicValidation; + } + } + mensaggeDinamicValidation[1] = validationRespons; + return mensaggeDinamicValidation; + } + + private String endCheckValidation(String validation) { + validation = validation.subSequence(0, validation.length()-4).toString(); + return validation; + } + + private boolean userNullTaskValidation(String assigneeId) throws EntityNotFoundException { + if (StringUtils.isEmpty(assigneeId)) { + return true; + } else { + if (!userClient.existUserById(assigneeId)) + throw new EntityNotFoundException(StoriesApiConstants.taskFieldAssigneeNotFoundException,HttpStatus.CONFLICT,StoriesApiConstants.pathStories); + return true; + } + } + + private boolean statusTaskValidation(String[] statusArray, String status) { + if(StringUtils.isEmpty(status)) { + return true; + }else { + return Arrays.asList(statusArray).contains(status); + } + } + + private String TaskSpecialCharacterValidation(TasksDomain task, String storyId, String taskId) { + int countValidationPositive = 0; + String validationRespons = ""; + + List validateSpecialCharacterField = new ArrayList<>(); + validateSpecialCharacterField.add(storyId); + validateSpecialCharacterField.add(taskId); + validateSpecialCharacterField.add(task.getStatus()); + validateSpecialCharacterField.add(task.getAssignee()); + + for(int i= 0; i < validateSpecialCharacterField.size(); i++) { + if(validateSpecialCharacterField.get(i) != null) { + boolean err = Pattern.compile("[a-zA-Z0-9\\s]*").matcher(validateSpecialCharacterField.get(i)).matches(); + if (!err) { + countValidationPositive++; + if (StringUtils.isEmpty(validationRespons)) { + validationRespons = StoriesApiConstants.ValidationTaskSpecialCharacterMessage[i]; + } else { + validationRespons = validationRespons + " AND " + StoriesApiConstants.ValidationTaskSpecialCharacterMessage[i]; + } + } + } + } + + return validationRespons; + } +} \ No newline at end of file diff --git a/src/main/java/com/stories/sprintsclient/SprintsClient.java b/src/main/java/com/stories/sprintsclient/SprintsClient.java new file mode 100644 index 0000000..777beaa --- /dev/null +++ b/src/main/java/com/stories/sprintsclient/SprintsClient.java @@ -0,0 +1,47 @@ +package com.stories.sprintsclient; + +import java.util.List; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; + +import com.stories.domain.SprintDomain; + +@Component +public class SprintsClient { + + private static Logger logger = LogManager.getLogger(); + + RestTemplate restTemplate = new RestTemplate(); + + public boolean existsSprintById(String id) throws RestClientException { + String uri = "http://sprints-qa.us-east-2.elasticbeanstalk.com/sprints/"; + boolean exists = false; + try { + ResponseEntity> sprintsResponse = restTemplate.exchange(uri, HttpMethod.GET, null, + new ParameterizedTypeReference>() { + }); + + if (sprintsResponse != null && sprintsResponse.hasBody()) { + List sprints = sprintsResponse.getBody(); + logger.debug("Getting all sprints: " + sprints); + for (int i = 0; i < sprints.size(); i++) { + if (id.equals(sprints.get(i).getId())) { + exists = true; + logger.debug("Getting sprint if exist: " + sprints.get(i)); + break; + } + } + } + } catch (RestClientException e) { + throw new RestClientException("Spritns API has no entities"); + } + return exists; + } +} \ No newline at end of file diff --git a/src/main/java/com/stories/usersclient/UsersClient.java b/src/main/java/com/stories/usersclient/UsersClient.java new file mode 100644 index 0000000..553041e --- /dev/null +++ b/src/main/java/com/stories/usersclient/UsersClient.java @@ -0,0 +1,46 @@ +package com.stories.usersclient; + +import java.util.List; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; + +import com.stories.domain.UserDomain; + +@Component +public class UsersClient { + + private static Logger logger = LogManager.getLogger(); + + RestTemplate restTemplate = new RestTemplate(); + + public boolean existUserById(String id) throws RestClientException { + String uri = "http://sourcescusersapi-test.us-west-1.elasticbeanstalk.com/api/users/"; + boolean exists = false; + try { + ResponseEntity> usersResponse = restTemplate.exchange(uri, HttpMethod.GET, null, + new ParameterizedTypeReference>() { + }); + if (usersResponse != null && usersResponse.hasBody()) { + List users = usersResponse.getBody(); + logger.debug("Getting all users: " + users); + for (int i = 0; i < users.size(); i++) { + if (id.equals(users.get(i).getUserId())) { + exists = true; + logger.debug("Getting user if exist: " + users.get(i)); + break; + } + } + } + } catch (RestClientException e) { + throw new RestClientException("Users API has no entities"); + } + return exists; + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..dd4adb2 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,12 @@ +server.port=5000 +spring.data.mongodb.uri=mongodb+srv://:@cluster0-nomfh.mongodb.net +spring.data.mongodb.database= +management.endpoints.web.exposure.include=* +# HEALTH ENDPOINT +management.endpoint.health.show-details=always +# INFO ENDPOINT CONFIGURATION +info.app.name=@project.name@ +info.app.description=@project.description@ +info.app.version=@project.version@ +info.app.encoding=@project.build.sourceEncoding@ +info.app.java.version=@java.version@ \ No newline at end of file diff --git a/src/main/resources/log4j2.properties b/src/main/resources/log4j2.properties new file mode 100644 index 0000000..c719f10 --- /dev/null +++ b/src/main/resources/log4j2.properties @@ -0,0 +1,26 @@ +name = PropertiesConfig +property.filename = log +appenders = console, file + +appender.console.type = Console +appender.console.name = STDOUT +appender.console.layout.type = PatternLayout +appender.console.layout.compact= true +appender.console.layout.eventEol= true +appender.console.layout.pattern = %d{dd MMM yyyy HH:mm:ss} - %m%n + +appender.file.type = File +appender.file.name = LOGFILE +appender.file.fileName=${filename}/properties.log +appender.console.layout.type = PatternLayout +appender.console.layout.pattern = %d{dd MMM yyyy HH:mm:ss} - %m%n + +loggers=file +logger.file.name= com.stories.service.StoriesServiceImpl +logger.file.level = debug +logger.file.appenderRefs = file +logger.file.appenderRef.file.ref = LOGFILE + +rootLogger.level = debug +rootLogger.appenderRefs = stdout +rootLogger.appenderRef.stdout.ref = STDOUT \ No newline at end of file diff --git a/src/test/java/com/stories/constants/StoriesApiTestsConstants.java b/src/test/java/com/stories/constants/StoriesApiTestsConstants.java new file mode 100644 index 0000000..f216317 --- /dev/null +++ b/src/test/java/com/stories/constants/StoriesApiTestsConstants.java @@ -0,0 +1,46 @@ +package com.stories.constants; + + +public class StoriesApiTestsConstants { + + public static final String uriStories = "/stories/"; + public static final String uriGetByIdInvalid = "/stories/5e6a8441bf#ERFSasda"; + public static final String uriStory = "/stories/5e7134c9099a9a0ab248c90b"; + public static final String uriTask = "/stories/5e7133b6430bf4151ec1e85f/tasks/5e7133b6430bf4151ec1e85f"; + public static final String uriTaskInvalid = "/stories/5e7133b6430bf4151ec1e85f/tasks/5e6a8441bf#ERFSasda"; + public static final String uriTasks = "/stories/5e7133b6430bf4151ec1e85f/tasks/"; + + public static final String idValid = "5e7134c9099a9a0ab248c90b"; + public static final String ValidPutTaskId = "5e8cf37b7a605837de2865ad"; + + public static final String InvalidId = "wrong123"; + + public static final Boolean booleanTrue = true; + public static final Boolean booleanFalse = false; + + public static final String messageTask = "Task with the given id was not found."; + public static final String messageIdTask = "Task with the given id was not found."; + public static final String messageMalformedJSON = "Task with the given id was not found."; + public static final String messageStoryJson = "Story has an invalid status Json"; + public static final String messageStory = "Story not found"; + public static final String messageStories = "Stories not found"; + public static final String messageName = "The JSON format provided is invalid, please provide the required field ('Name')."; + public static final String messageSprintId = "The sprint_id does not exists"; + public static final String messageStatusInvalid = "The Status field should be one of the following options: 'Refining' ,'Ready to Work', 'Working', 'Testing', 'Ready to Accept' or 'Accepted'."; + public static final String numbreError = "400"; + public static final String path = "/stories/"; + public static final String pathTask = "/tasks/"; + public static final String plusError = "fdsfd"; + public static final String varEmpty = ""; + + public static final String uriSprintClient = "http://sprints-qa.us-east-2.elasticbeanstalk.com/sprints/"; + public static final String uriUserClient = "http://sourcescusersapi-test.us-west-1.elasticbeanstalk.com/api/users/"; + public static final String sprintIdValid = "5e827f2f48b0866f87e1cbc2"; + public static final String sprintIdInvalid = "5e78f5e792675632e42d1a96"; + public static final String userIdValid = "5ea7125ce6cd3109e8bc71c6"; + public static final String userIdInvalid = "5ea7125ce6cd3109e8bc71cf"; + public static final String messageSprints = "sprints API has no entities"; + public static final String messageUsers = "users API has no entities"; + + public static final String specificId = "5e8dc1ba4ce33c0efc555845"; +} diff --git a/src/test/java/com/stories/controller/ControllerTests.java b/src/test/java/com/stories/controller/ControllerTests.java new file mode 100644 index 0000000..3fb69f3 --- /dev/null +++ b/src/test/java/com/stories/controller/ControllerTests.java @@ -0,0 +1,219 @@ +package com.stories.controller; + +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.ResultHandler; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.http.HttpStatus; + +import com.stories.constants.StoriesApiTestsConstants; +import com.stories.exception.EntityNotFoundException; +import com.stories.service.StoriesServiceImpl; +import com.stories.utils.TestUtils; + +@RunWith(SpringRunner.class) +@WebMvcTest(controllers = StoriesController.class) +public class ControllerTests { + + @MockBean + private StoriesServiceImpl storiesServiceImpl; + + @Autowired + private MockMvc mockMvc; + + private TestUtils testUtils = new TestUtils(); + + @Test + public void getAllValid() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get(StoriesApiTestsConstants.uriStories)).andExpect(status().isOk()); + } + + @Test + public void getByIdValid() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get(StoriesApiTestsConstants.uriStory).contentType(StoriesApiTestsConstants.idValid)) + .andExpect(status().isOk()); + } + + @Test(expected = EntityNotFoundException.class) + public void getByIdInvalid() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get(StoriesApiTestsConstants.uriGetByIdInvalid)).andDo(new ResultHandler() { + @Override + public void handle(MvcResult mvcResult) throws Exception { + throw new EntityNotFoundException(StoriesApiTestsConstants.messageStory, StoriesApiTestsConstants.path); + } + }).andExpect(status().isNotFound()); + } + + @Test + public void putTestTrue() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.put(StoriesApiTestsConstants.uriStory).contentType(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON).characterEncoding("UTF-8") + .content(testUtils.setStoryInJsonFormat(StoriesApiTestsConstants.idValid))).andExpect(status().isOk()); + } + + @Test(expected = EntityNotFoundException.class) + public void putTestInvelidId() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.put(StoriesApiTestsConstants.uriGetByIdInvalid).contentType(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON).characterEncoding("UTF-8") + .content(testUtils.setStoryInJsonFormat(StoriesApiTestsConstants.idValid))).andDo(new ResultHandler() { + @Override + public void handle(MvcResult mvcResult) throws Exception { + throw new EntityNotFoundException(StoriesApiTestsConstants.messageStory, StoriesApiTestsConstants.path); + } + }).andExpect(status().isNotFound()); + } + + @Test + public void putTestInvalidJson() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.put(StoriesApiTestsConstants.uriStory).contentType(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON).characterEncoding("UTF-8") + .content(testUtils.setStoryInJsonBadFormat(StoriesApiTestsConstants.idValid))) + .andExpect(status().isBadRequest()); + } + + @Test + public void deleteTestTrue() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.delete(StoriesApiTestsConstants.uriStory).contentType(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON).characterEncoding("UTF-8") + .content(testUtils.setStoryInJsonFormat(StoriesApiTestsConstants.idValid))).andExpect(status().isNoContent()); + } + + @Test + public void deleteTaskTrue() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.delete(StoriesApiTestsConstants.uriTask).contentType(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON).characterEncoding("UTF-8") + .content(testUtils.setStoryInJsonFormat(StoriesApiTestsConstants.idValid))).andExpect(status().isNoContent()); + } + + @Test(expected = EntityNotFoundException.class) + public void deleteTaskInvalidId() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.delete(StoriesApiTestsConstants.uriTask).contentType(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON).characterEncoding("UTF-8") + .content(testUtils.setStoryInJsonFormat(StoriesApiTestsConstants.idValid))).andDo(new ResultHandler() { + @Override + public void handle(MvcResult mvcResult) throws Exception { + throw new EntityNotFoundException(StoriesApiTestsConstants.messageTask, HttpStatus.CONFLICT,StoriesApiTestsConstants.path); + }}).andExpect(status().isConflict()); + } + + @Test(expected = EntityNotFoundException.class) + public void deleteTestInvalidId() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.delete(StoriesApiTestsConstants.uriStory).contentType(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON).characterEncoding("UTF-8") + .content(testUtils.setStoryInJsonFormat(StoriesApiTestsConstants.idValid))).andDo(new ResultHandler() { + @Override + public void handle(MvcResult mvcResult) throws Exception { + throw new EntityNotFoundException( + StoriesApiTestsConstants.messageStatusInvalid, + StoriesApiTestsConstants.varEmpty, + StoriesApiTestsConstants.path); + } + }).andExpect(status().isNotFound()); + } + + @Test + public void postTestValidJson() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.post(StoriesApiTestsConstants.uriStories).contentType(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON).characterEncoding("UTF-8") + .content(testUtils.postStoryValidJson(StoriesApiTestsConstants.idValid))).andDo(print()) + .andExpect(status().isCreated()); + } + + @Test(expected = EntityNotFoundException.class) + public void postTestInvalidStatusJson() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.post(StoriesApiTestsConstants.uriStories).contentType(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON).characterEncoding("UTF-8") + .content(testUtils.postStoryInvalidStatusJson())).andDo(new ResultHandler() { + @Override + public void handle(MvcResult mvcResult) throws Exception { + throw new EntityNotFoundException(StoriesApiTestsConstants.messageStoryJson, StoriesApiTestsConstants.path); + } + }).andExpect(status().isBadRequest()); + } + + @Test(expected = EntityNotFoundException.class) + public void postTestInvalidJson() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.post(StoriesApiTestsConstants.uriStories).contentType(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON).characterEncoding("UTF-8") + .content(testUtils.postStoryBadJsonFormat())).andDo(new ResultHandler() { + @Override + public void handle(MvcResult mvcResult) throws Exception { + throw new EntityNotFoundException(StoriesApiTestsConstants.messageMalformedJSON, StoriesApiTestsConstants.path); + } + }).andExpect(status().isBadRequest()); + } + + @Test() + public void getTaskByStoryTest() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get(StoriesApiTestsConstants.uriTask).contentType("6e413de9099a9a0ab248c90c")) + .andExpect(status().isOk()); + } + + @Test + public void getTasksByStoryTest() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get(StoriesApiTestsConstants.uriTasks)).andExpect(status().isOk()); + } + + @Test(expected = EntityNotFoundException.class) + public void getTaskByIdInvalid() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get(StoriesApiTestsConstants.uriTaskInvalid)).andDo(new ResultHandler() { + @Override + public void handle(MvcResult mvcResult) throws Exception { + throw new EntityNotFoundException(StoriesApiTestsConstants.messageIdTask, StoriesApiTestsConstants.pathTask); + + } + }).andExpect(status().isNotFound()); + } + + @Test + public void postTestTaskValidJson() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.post(StoriesApiTestsConstants.uriTasks).contentType(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON).characterEncoding("UTF-8") + .content(testUtils.postStoryValidJson(StoriesApiTestsConstants.idValid))).andDo(print()) + .andExpect(status().isCreated()); + } + + @Test(expected = EntityNotFoundException.class) + public void postTaskTestInvalidStatusJson() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.post(StoriesApiTestsConstants.uriTasks).contentType(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON).characterEncoding("UTF-8") + .content(testUtils.postStoryInvalidStatusJson())).andDo(new ResultHandler() { + @Override + public void handle(MvcResult mvcResult) throws Exception { + throw new EntityNotFoundException(StoriesApiTestsConstants.messageStoryJson, StoriesApiTestsConstants.path); + } + }).andExpect(status().isBadRequest()); + } + + @Test + public void putTaskByIdTest() throws Exception{ + mockMvc.perform(MockMvcRequestBuilders.put(StoriesApiTestsConstants.uriTask).contentType(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON).characterEncoding("UTF-8") + .content(testUtils.setStoryInJsonFormat(StoriesApiTestsConstants.idValid))) + .andExpect(status().isOk()); + } + + + @Test(expected = EntityNotFoundException.class) + public void putTasktNotFound() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.put(StoriesApiTestsConstants.uriTaskInvalid).contentType(MediaType.APPLICATION_JSON_VALUE) + .contentType(MediaType.APPLICATION_JSON).characterEncoding("UTF-8") + .content(testUtils.setStoryInJsonFormat(StoriesApiTestsConstants.idValid))).andDo(new ResultHandler() { + @Override + public void handle(MvcResult mvcResult) throws Exception { + throw new EntityNotFoundException(StoriesApiTestsConstants.messageStory, StoriesApiTestsConstants.path); + } + }).andExpect(status().isNotFound()); + } + +} diff --git a/src/test/java/com/stories/healthcheckstests/sprintsHealthcheckTest.java b/src/test/java/com/stories/healthcheckstests/sprintsHealthcheckTest.java new file mode 100644 index 0000000..37618b2 --- /dev/null +++ b/src/test/java/com/stories/healthcheckstests/sprintsHealthcheckTest.java @@ -0,0 +1,54 @@ +package com.stories.healthcheckstests; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.client.RestTemplate; + +import com.stories.constants.StoriesApiTestsConstants; +import com.stories.domain.SprintDomain; +import com.stories.heathchecks.sprintsHealthcheck; +import com.stories.utils.TestUtils; + +@RunWith(SpringRunner.class) +public class sprintsHealthcheckTest { + private TestUtils testUtils; + + @Mock + private RestTemplate restTemplate; + + @InjectMocks + private sprintsHealthcheck sprintsHealthcheck; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + testUtils = new TestUtils(); + } + + @Test + public void healt() { + sprintsHealthcheck.health(); + ResponseEntity> sprintEntity = new ResponseEntity>( + testUtils.getSprintDomaintList(), HttpStatus.OK); + Mockito.when(restTemplate.exchange(StoriesApiTestsConstants.uriSprintClient, HttpMethod.GET, null, + new ParameterizedTypeReference>() { + })).thenReturn(sprintEntity); + assertEquals(StoriesApiTestsConstants.booleanTrue, + sprintsHealthcheck.isRunningUsersAPI()); + sprintsHealthcheck.health(); + } +} diff --git a/src/test/java/com/stories/healthcheckstests/usersHealthcheckTest.java b/src/test/java/com/stories/healthcheckstests/usersHealthcheckTest.java new file mode 100644 index 0000000..fe2ed4b --- /dev/null +++ b/src/test/java/com/stories/healthcheckstests/usersHealthcheckTest.java @@ -0,0 +1,55 @@ +package com.stories.healthcheckstests; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.client.RestTemplate; + +import com.stories.constants.StoriesApiTestsConstants; +import com.stories.domain.SprintDomain; +import com.stories.domain.UserDomain; +import com.stories.heathchecks.usersHealthcheck; +import com.stories.utils.TestUtils; + +@RunWith(SpringRunner.class) +public class usersHealthcheckTest { + private TestUtils testUtils; + + @Mock + private RestTemplate restTemplate; + + @InjectMocks + private usersHealthcheck usersHealthcheck; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + testUtils = new TestUtils(); + } + + @Test + public void healt() throws Exception { + usersHealthcheck.health(); + ResponseEntity> userEntity = new ResponseEntity>( + testUtils.getUserDomainList(), HttpStatus.OK); + Mockito.when(restTemplate.exchange(StoriesApiTestsConstants.uriUserClient, HttpMethod.GET, null, + new ParameterizedTypeReference>() { + })).thenReturn(userEntity); + assertEquals(StoriesApiTestsConstants.booleanTrue, + usersHealthcheck.isRunningUsersAPI()); + usersHealthcheck.health(); + } +} diff --git a/src/test/java/com/stories/service/ServiceTests.java b/src/test/java/com/stories/service/ServiceTests.java new file mode 100644 index 0000000..21a8671 --- /dev/null +++ b/src/test/java/com/stories/service/ServiceTests.java @@ -0,0 +1,586 @@ +package com.stories.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.when; + +import java.util.Optional; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration; +import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.aggregation.Aggregation; +import org.springframework.data.mongodb.core.aggregation.AggregationResults; +import org.springframework.http.HttpStatus; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.stories.constants.StoriesApiTestsConstants; +import com.stories.domain.StoryDomain; +import com.stories.domain.TasksDomain; +import com.stories.exception.EntityNotFoundException; +import com.stories.model.StoryModel; +import com.stories.model.TaskModel; +import com.stories.repository.StoriesCustomRepository; +import com.stories.repository.StoriesRepository; +import com.stories.repository.UsersRepository; +import com.stories.sprintsclient.SprintsClient; +import com.stories.usersclient.UsersClient; +import com.stories.utils.TestUtils; +import com.stories.utils.UnitTestProperties; + +import ma.glasnost.orika.MapperFacade; + +@SpringBootTest +@RunWith(SpringJUnit4ClassRunner.class) +@EnableAutoConfiguration(exclude = { MongoAutoConfiguration.class, MongoDataAutoConfiguration.class }) +public class ServiceTests { + + @MockBean + StoriesRepository storiesRepository; + + @MockBean + UsersRepository usersRepository; + + @MockBean + StoriesCustomRepository storiesCustomRepository; + + @MockBean + private MapperFacade mapperFacade; + + @Autowired + UnitTestProperties unitTestProperties; + + @MockBean + SprintsClient sprintsClient; + + @MockBean + UsersClient usersClient; + + @InjectMocks + StoriesServiceImpl storiesServiceImpl; + + private TestUtils testUtils; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + testUtils = new TestUtils(); + } + + MongoTemplate mongoTemplate = Mockito.mock(MongoTemplate.class); + + @Test + public void getById() throws Exception { + when(storiesRepository.existsById(unitTestProperties.getUrlId())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(storiesRepository.findById(unitTestProperties.getUrlId())) + .thenReturn(Optional.of(TestUtils.getDummyStoryModel())); + when(mapperFacade.map(testUtils.getStoryModel(), StoryDomain.class)) + .thenReturn(testUtils.getDummyStoryDomain()); + when(storiesServiceImpl.getStoryById(unitTestProperties.getUrlId())) + .thenReturn(testUtils.getDummyStoryDomain()); + assertEquals(testUtils.getDummyStoryDomain(), storiesServiceImpl.getStoryById(unitTestProperties.getUrlId())); + } + + @Test(expected = EntityNotFoundException.class) + public void getByIdException() throws Exception { + when(storiesRepository.existsById(unitTestProperties.getUrlId())) + .thenReturn(StoriesApiTestsConstants.booleanFalse); + when(storiesServiceImpl.getStoryById(unitTestProperties.getUrlId())).thenThrow( + new EntityNotFoundException(StoriesApiTestsConstants.messageStory, StoriesApiTestsConstants.path)); + } + + @Test + public void getAllStories() throws Exception { + when(storiesRepository.findAll()).thenReturn(storiesServiceImpl.storiesModel); + assertEquals(storiesServiceImpl.storiesDomain, storiesServiceImpl.getAllStories()); + } + + @Test(expected = EntityNotFoundException.class) + public void getAllStoriesException() throws Exception { + when(storiesRepository.findAll()).thenReturn(TestUtils.listStoriesModelNull()); + when(storiesServiceImpl.getAllStories()).thenThrow( + new EntityNotFoundException(StoriesApiTestsConstants.messageStories, StoriesApiTestsConstants.path)); + } + + @Test + public void updateStory() throws Exception { + when(usersClient.existUserById(unitTestProperties.getModelAssigneeId())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(storiesRepository.findById(unitTestProperties.getModelId())) + .thenReturn(Optional.of(TestUtils.getStoryModel())); + when(sprintsClient.existsSprintById(unitTestProperties.getSprintClientId())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(storiesRepository.existsById(unitTestProperties.getModelId())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(mapperFacade.map(testUtils.getStoryDomain(), StoryModel.class)).thenReturn(testUtils.getStoryModel()); + storiesServiceImpl.updateStory(testUtils.getStoryDomain(), unitTestProperties.getModelId()); + } + + @Test(expected = EntityNotFoundException.class) + public void updateUserException() throws Exception { + when(usersClient.existUserById(unitTestProperties.getModelAssigneeId())) + .thenReturn(StoriesApiTestsConstants.booleanFalse); + storiesServiceImpl.updateStory(testUtils.getStoryDomain(), unitTestProperties.getUrlId()); + } + + @Test(expected = EntityNotFoundException.class) + public void updateStorykSpecialChar() throws Exception { + when(storiesServiceImpl.updateStory(testUtils.getStoryDomainSpecialChar(), unitTestProperties.getDomainId())) + .thenThrow( + new EntityNotFoundException("The next field have special characters: Status", "", "/stories/")); + storiesServiceImpl.updateStory(testUtils.getStoryDomainSpecialChar(), unitTestProperties.getDomainId()); + } + + @Test(expected = EntityNotFoundException.class) + public void updateStorySpecialsChars() throws Exception { + when(storiesServiceImpl.updateStory(testUtils.getStoryDomainSpecialsChars(), unitTestProperties.getDomainId())) + .thenThrow(new EntityNotFoundException("The next field have special characters: Status, assignee", "", + "/stories/")); + storiesServiceImpl.updateStory(testUtils.getStoryDomainSpecialsChars(), unitTestProperties.getDomainId()); + } + + @Test(expected = EntityNotFoundException.class) + public void updateStorySprintException() throws Exception { + when(usersClient.existUserById(unitTestProperties.getModelAssigneeId())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(sprintsClient.existsSprintById(unitTestProperties.getSprintClientId())) + .thenReturn(StoriesApiTestsConstants.booleanFalse); + storiesServiceImpl.updateStory(testUtils.getStoryDomain(), unitTestProperties.getUrlId()); + } + + @Test(expected = EntityNotFoundException.class) + public void updateStoryIdException() throws Exception { + when(usersClient.existUserById(unitTestProperties.getModelAssigneeId())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(sprintsClient.existsSprintById(unitTestProperties.getSprintClientId())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(storiesRepository.existsById(unitTestProperties.getModelId())) + .thenReturn(StoriesApiTestsConstants.booleanFalse); + storiesServiceImpl.updateStory(testUtils.getStoryDomain(), unitTestProperties.getUrlId()); + } + + @Test(expected = EntityNotFoundException.class) + public void updateStoryStatusException() throws Exception { + when(usersClient.existUserById(testUtils.getStoryDomainStatusInvalid().getAssignee_id())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(sprintsClient.existsSprintById(testUtils.getStoryDomainStatusInvalid().getSprint_id())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(storiesRepository.existsById(unitTestProperties.getModelId())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(mapperFacade.map(testUtils.getStoryDomainStatusInvalid(), StoryModel.class)) + .thenReturn(testUtils.getStoryModel()); + when(storiesServiceImpl.updateStory(testUtils.getStoryDomainStatusInvalid(), + testUtils.getStoryModel().get_id())) + .thenThrow(new EntityNotFoundException(StoriesApiTestsConstants.messageStatusInvalid, + StoriesApiTestsConstants.varEmpty, StoriesApiTestsConstants.path)); + storiesServiceImpl.createStory(testUtils.getStoryDomainStatusInvalid()); + } + + @Test(expected = EntityNotFoundException.class) + public void updateException() throws Exception { + when(storiesServiceImpl.updateStory(storiesServiceImpl.storyDomain, testUtils.getStoryModel().get_id())) + .thenThrow(new EntityNotFoundException(StoriesApiTestsConstants.messageStory, + StoriesApiTestsConstants.path)); + } + + @Test + public void deleteStory() throws Exception { + when(storiesRepository.existsById(unitTestProperties.getUrlId())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + Mockito.doNothing().when(storiesRepository).deleteById(unitTestProperties.getUrlId()); + storiesServiceImpl.deleteStory(unitTestProperties.getUrlId()); + } + + @Test(expected = EntityNotFoundException.class) + public void deleteStoryException() throws Exception { + when(storiesRepository.existsById(unitTestProperties.getUrlId())) + .thenReturn(StoriesApiTestsConstants.booleanFalse); + storiesServiceImpl.deleteStory(unitTestProperties.getUrlId()); + } + + @Test + public void deleteTask() throws Exception { + when(storiesRepository.existsById(unitTestProperties.getModelId())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(storiesRepository.findById(unitTestProperties.getModelId())) + .thenReturn(Optional.of(testUtils.getStoryTaskModel())); + storiesServiceImpl.deleteTask(testUtils.getStoryTaskModel().get_id(), + testUtils.getStoryTaskModel().getTasks().get(0).get_id()); + } + + @Test(expected = EntityNotFoundException.class) + public void deleteTaskNotFoundException() throws Exception { + when(storiesRepository.existsById(unitTestProperties.getModelId())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(storiesRepository.findById(unitTestProperties.getModelId())) + .thenReturn(Optional.of(testUtils.getStoryTaskModel())); + storiesServiceImpl.deleteTask(testUtils.getStoryTaskModel().get_id(), + testUtils.getStoryTaskModel().getTasks().get(0).get_id() + StoriesApiTestsConstants.plusError); + } + + @Test(expected = EntityNotFoundException.class) + public void deleteTaskException() throws Exception { + when(storiesRepository.existsById(unitTestProperties.getUrlId())) + .thenReturn(StoriesApiTestsConstants.booleanFalse); + storiesServiceImpl.deleteTask(unitTestProperties.getUrlId(), storiesServiceImpl.storyModel.get_id()); + } + + @Test(expected = EntityNotFoundException.class) + public void deleteTaskNullException() throws Exception { + when(storiesRepository.existsById(testUtils.getStoryTaskNullModel().get_id())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(storiesRepository.findById(testUtils.getStoryTaskNullModel().get_id())) + .thenReturn(Optional.of(testUtils.getStoryTaskNullModel())); + storiesServiceImpl.deleteTask(unitTestProperties.getModelId(), unitTestProperties.getTasksModelId()); + } + + @Test + public void createTask() throws Exception { + when(storiesRepository.existsById(unitTestProperties.getModelId())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(usersClient.existUserById(testUtils.getTasksDomain().getAssignee())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(storiesRepository.findById(unitTestProperties.getModelId())) + .thenReturn(Optional.of(TestUtils.getStoryModel())); + when(mapperFacade.map(testUtils.getTasksDomain(), TaskModel.class)).thenReturn(TestUtils.getTasksModel()); + when(storiesRepository.save(TestUtils.getStoryModel())).thenReturn(TestUtils.getStoryModel()); + storiesServiceImpl.createTask(testUtils.getTasksDomain(), unitTestProperties.getModelId()); + } + + @Test(expected = EntityNotFoundException.class) + public void createTaskSpecialChar() throws Exception { + when(storiesServiceImpl.createTask(testUtils.getTaskDomainSpecialChar(), unitTestProperties.getModelId())) + .thenThrow( + new EntityNotFoundException("The next field have special characters: Status", "", "/stories/")); + storiesServiceImpl.createTask(testUtils.getTaskDomainSpecialChar(), unitTestProperties.getModelId()); + } + + @Test(expected = EntityNotFoundException.class) + public void createTaskSpecialsChars() throws Exception { + when(storiesServiceImpl.createTask(testUtils.getTaskDomainSpecialsChars(), unitTestProperties.getModelId())) + .thenThrow(new EntityNotFoundException("The next field have special characters: Status, assignee", "", + "/stories/")); + storiesServiceImpl.createTask(testUtils.getTaskDomainSpecialsChars(), unitTestProperties.getModelId()); + } + + @Test(expected = EntityNotFoundException.class) + public void createTaskStoryExistException() throws Exception { + when(storiesRepository.existsById(unitTestProperties.getModelId())) + .thenReturn(StoriesApiTestsConstants.booleanFalse); + when(storiesServiceImpl.createTask(TestUtils.getTasksDomain(), unitTestProperties.getModelId())) + .thenThrow(new EntityNotFoundException(StoriesApiTestsConstants.messageStory, HttpStatus.CONFLICT, + StoriesApiTestsConstants.path)); + } + + @Test(expected = EntityNotFoundException.class) + public void createTaskNameException() throws Exception { + when(storiesRepository.existsById(unitTestProperties.getModelId())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(storiesServiceImpl.createTask(testUtils.getTasksNameNullDomain(), unitTestProperties.getModelId())) + .thenThrow(new EntityNotFoundException(StoriesApiTestsConstants.messageName, + StoriesApiTestsConstants.numbreError, StoriesApiTestsConstants.path)); + } + + @Test(expected = EntityNotFoundException.class) + public void createTaskUserExistException() throws Exception { + when(storiesRepository.existsById(unitTestProperties.getModelId())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(usersClient.existUserById(TestUtils.getDummyTasksDomain().getAssignee())) + .thenReturn(StoriesApiTestsConstants.booleanFalse); + when(storiesServiceImpl.createTask(testUtils.getTasksDomain(), unitTestProperties.getModelId())) + .thenThrow(new EntityNotFoundException(StoriesApiTestsConstants.messageStory, HttpStatus.CONFLICT, + StoriesApiTestsConstants.path)); + } + + @Test(expected = EntityNotFoundException.class) + public void createTaskStatusException() throws Exception { + when(storiesRepository.existsById(unitTestProperties.getModelId())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(usersClient.existUserById(testUtils.getTasksDomainStatusValid().getAssignee())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(storiesServiceImpl.createTask(testUtils.getTasksDomainStatusValid(), unitTestProperties.getModelId())) + .thenThrow(new EntityNotFoundException(StoriesApiTestsConstants.messageStatusInvalid, + StoriesApiTestsConstants.numbreError, StoriesApiTestsConstants.path)); + } + + @Test + public void createTaskStatusNullException() throws Exception { + when(storiesRepository.existsById(unitTestProperties.getModelId())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(usersClient.existUserById(testUtils.getTasksStatusNullDomain().getAssignee())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(storiesRepository.findById(unitTestProperties.getModelId())) + .thenReturn(Optional.of(TestUtils.getStoryModel())); + when(mapperFacade.map(testUtils.getTasksStatusNullDomain(), TaskModel.class)) + .thenReturn(TestUtils.getTasksModel()); + when(storiesRepository.save(TestUtils.getStoryModel())).thenReturn(TestUtils.getStoryModel()); + storiesServiceImpl.createTask(testUtils.getTasksStatusNullDomain(), unitTestProperties.getModelId()); + } + + @Test + public void createStory() throws Exception { + when(mapperFacade.map(TestUtils.getStoryDomain(), StoryModel.class)).thenReturn(testUtils.getStoryModel()); + when(usersClient.existUserById(unitTestProperties.getModelAssigneeId())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(sprintsClient.existsSprintById(unitTestProperties.getSprintClientId())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(storiesRepository.save(TestUtils.getStoryModel())).thenReturn(testUtils.getStoryModel()); + assertEquals(unitTestProperties.getUrlId(), storiesServiceImpl.createStory(TestUtils.getStoryDomain())); + } + + @Test(expected = EntityNotFoundException.class) + public void createStoryStatusException() throws Exception { + when(usersClient.existUserById(testUtils.getStoryDomainStatusInvalid().getAssignee_id())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(sprintsClient.existsSprintById(testUtils.getStoryDomainStatusInvalid().getSprint_id())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(mapperFacade.map(testUtils.getStoryDomainStatusInvalid(), StoryModel.class)) + .thenReturn(testUtils.getStoryModelStatusInvalid()); + when(storiesServiceImpl.createStory(testUtils.getStoryDomainStatusInvalid())) + .thenThrow(new EntityNotFoundException(StoriesApiTestsConstants.messageStatusInvalid, + StoriesApiTestsConstants.varEmpty, StoriesApiTestsConstants.path)); + storiesServiceImpl.createStory(testUtils.getStoryDomainStatusInvalid()); + } + + @Test(expected = EntityNotFoundException.class) + public void createStorySprintIdException() throws Exception { + when(usersClient.existUserById(testUtils.getStoryDomainAssigneInvalid().getAssignee_id())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(mapperFacade.map(testUtils.getStoryDomainAssigneInvalid(), StoryModel.class)) + .thenReturn(testUtils.getStoryModelAssigneInvalid()); + when(storiesServiceImpl.createStory(testUtils.getStoryDomainAssigneInvalid())).thenThrow( + new EntityNotFoundException(StoriesApiTestsConstants.messageSprintId, StoriesApiTestsConstants.path)); + storiesServiceImpl.createStory(testUtils.getStoryDomainAssigneInvalid()); + } + + @Test(expected = EntityNotFoundException.class) + public void createStoryNameInvalid() throws Exception { + when(usersClient.existUserById(testUtils.getStoryDomainNameInvalid().getAssignee_id())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(mapperFacade.map(testUtils.getStoryDomainNameInvalid(), StoryModel.class)) + .thenReturn(testUtils.getStoryModelNameInvalid()); + when(storiesServiceImpl.createStory(testUtils.getStoryDomainNameInvalid())) + .thenThrow(new EntityNotFoundException(StoriesApiTestsConstants.messageName, + StoriesApiTestsConstants.varEmpty, StoriesApiTestsConstants.path)); + } + + @Test(expected = EntityNotFoundException.class) + public void createStoryStatusInvalid() throws Exception { + when(usersClient.existUserById(testUtils.getStoryDomainStatusNull().getAssignee_id())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(mapperFacade.map(testUtils.getStoryDomainStatusNull(), StoryModel.class)) + .thenReturn(testUtils.getStoryModelStatusNull()); + when(storiesServiceImpl.createStory(testUtils.getStoryDomainStatusNull())) + .thenThrow(new EntityNotFoundException(StoriesApiTestsConstants.messageName, + StoriesApiTestsConstants.varEmpty, StoriesApiTestsConstants.path)); + } + + @Test(expected = EntityNotFoundException.class) + public void createStartDateNull() throws Exception { + when(usersClient.existUserById(testUtils.getStoryDomainStarDateNull().getAssignee_id())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(mapperFacade.map(testUtils.getStoryDomainStarDateNull(), StoryModel.class)) + .thenReturn(testUtils.getStoryModelStarDateNull()); + when(storiesServiceImpl.createStory(testUtils.getStoryDomainStarDateNull())) + .thenThrow(new EntityNotFoundException(StoriesApiTestsConstants.messageName, + StoriesApiTestsConstants.varEmpty, StoriesApiTestsConstants.path)); + } + + @Test(expected = EntityNotFoundException.class) + public void createPointsProggresNegative() throws Exception { + when(usersClient.existUserById(testUtils.getStoryDomainPointsProggresNegative().getAssignee_id())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(sprintsClient.existsSprintById(testUtils.getStoryDomainPointsProggresNegative().getSprint_id())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(mapperFacade.map(testUtils.getStoryDomainPointsProggresNegative(), StoryModel.class)) + .thenReturn(testUtils.getStoryModelPointsProggresNegative()); + when(storiesServiceImpl.createStory(testUtils.getStoryDomainPointsProggresNegative())) + .thenThrow(new EntityNotFoundException(StoriesApiTestsConstants.messageName, + StoriesApiTestsConstants.varEmpty, StoriesApiTestsConstants.path)); + } + + @Test(expected = EntityNotFoundException.class) + public void createPointsProgressInvalid() throws Exception { + when(usersClient.existUserById(testUtils.getStoryDomainPointsProgressInvalid().getAssignee_id())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(sprintsClient.existsSprintById(testUtils.getStoryDomainPointsProgressInvalid().getSprint_id())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(mapperFacade.map(testUtils.getStoryDomainPointsProgressInvalid(), StoryModel.class)) + .thenReturn(testUtils.getStoryModelPointsProgressInvalid()); + when(storiesServiceImpl.createStory(testUtils.getStoryDomainPointsProgressInvalid())) + .thenThrow(new EntityNotFoundException(StoriesApiTestsConstants.messageName, + StoriesApiTestsConstants.varEmpty, StoriesApiTestsConstants.path)); + } + + @Test + public void getTasksByStory() throws Exception { + AggregationResults aggregationResultsMock = Mockito.mock(AggregationResults.class); + Aggregation aggregateMock = Mockito.mock(Aggregation.class); + + when(storiesRepository.existsById(unitTestProperties.getUrlId())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + Mockito.doReturn(aggregationResultsMock).when(mongoTemplate).aggregate(Mockito.any(Aggregation.class), + Mockito.eq("stories"), Mockito.eq(TasksDomain.class)); + Mockito.doReturn(testUtils.getTasksDomainList()).when(aggregationResultsMock).getMappedResults(); + when(storiesCustomRepository.getTasksByStory(unitTestProperties.getUrlId())).thenReturn(aggregationResultsMock); + when(storiesServiceImpl.getTasksByStory(unitTestProperties.getUrlId())) + .thenReturn(testUtils.getTasksDomainList()); + + assertEquals(testUtils.getTasksDomainList(), storiesServiceImpl.getTasksByStory(unitTestProperties.getUrlId())); + } + + @Test(expected = EntityNotFoundException.class) + public void getTasksByStoryFail() throws Exception { + when(storiesRepository.existsById(unitTestProperties.getUrlId())) + .thenReturn(StoriesApiTestsConstants.booleanFalse); + when(storiesServiceImpl.getTasksByStory(unitTestProperties.getUrlId())).thenThrow(new EntityNotFoundException( + StoriesApiTestsConstants.messageStory, StoriesApiTestsConstants.path + unitTestProperties.getUrlId())); + + } + + @Test + public void getTaskById() throws Exception { + AggregationResults aggregationResultsMock = Mockito.mock(AggregationResults.class); + when(storiesRepository.existsById(unitTestProperties.getUrlId())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + Mockito.doReturn(aggregationResultsMock).when(mongoTemplate).aggregate(Mockito.any(Aggregation.class), + Mockito.eq("stories"), Mockito.eq(TaskModel.class)); + Mockito.doReturn(testUtils.getTaskModelId()).when(aggregationResultsMock).getUniqueMappedResult(); + when(storiesCustomRepository.getTaskById(unitTestProperties.getUrlId(), unitTestProperties.getUrlId())) + .thenReturn(aggregationResultsMock); + when(mapperFacade.map(testUtils.getTaskModelId(), TasksDomain.class)) + .thenReturn(testUtils.getDummyTasksDomain()); + when(storiesRepository.findByTasks__id(unitTestProperties.getUrlId())).thenReturn(testUtils.getTaskModelId()); + assertEquals(testUtils.getDummyTasksDomain(), + storiesServiceImpl.getTaskById(unitTestProperties.getUrlId(), unitTestProperties.getUrlId())); + } + + @Test(expected = EntityNotFoundException.class) + public void getTaskByIdNoStory() throws Exception { + when(storiesRepository.existsById(unitTestProperties.getUrlId())) + .thenReturn(StoriesApiTestsConstants.booleanFalse); + when(storiesServiceImpl.getTaskById(unitTestProperties.getUrlId(), unitTestProperties.getUrlId())) + .thenThrow(new EntityNotFoundException(StoriesApiTestsConstants.messageStory, + StoriesApiTestsConstants.path + unitTestProperties.getUrlId())); + } + + @Test(expected = EntityNotFoundException.class) + public void getTaskByIdNoEquals() throws Exception { + AggregationResults aggregationResultsMock = Mockito.mock(AggregationResults.class); + when(storiesRepository.existsById(unitTestProperties.getUrlId())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + Mockito.doReturn(aggregationResultsMock).when(mongoTemplate).aggregate(Mockito.any(Aggregation.class), + Mockito.eq("stories"), Mockito.eq(TaskModel.class)); + Mockito.doReturn(testUtils.getTaskModelId()).when(aggregationResultsMock).getUniqueMappedResult(); + when(storiesCustomRepository.getTaskById(unitTestProperties.getUrlId(), unitTestProperties.getUrlId())) + .thenReturn(aggregationResultsMock); + when(mapperFacade.map(testUtils.getDummyTaskModel(), TasksDomain.class)) + .thenReturn(testUtils.getDummyTasksDomain()); + when(storiesRepository.findByTasks__id(unitTestProperties.getUrlId())) + .thenReturn(testUtils.getDummyTaskModel()); + assertEquals(StoriesApiTestsConstants.specificId, testUtils.getDummyTaskModel().get_id()); + assertEquals(testUtils.getDummyTasksDomain(), + storiesServiceImpl.getTaskById(unitTestProperties.getUrlId(), unitTestProperties.getUrlId())); + } + + @Test(expected = EntityNotFoundException.class) + public void getTaskByIdTry() throws Exception { + AggregationResults aggregationResultsMock = Mockito.mock(AggregationResults.class); + when(storiesRepository.existsById(unitTestProperties.getUrlId())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + Mockito.doReturn(aggregationResultsMock).when(mongoTemplate).aggregate(Mockito.any(Aggregation.class), + Mockito.eq("stories"), Mockito.eq(TaskModel.class)); + Mockito.doReturn(testUtils.getTaskModelNull()).when(aggregationResultsMock).getUniqueMappedResult(); + when(storiesCustomRepository.getTaskById(unitTestProperties.getUrlId(), unitTestProperties.getUrlId())) + .thenReturn(aggregationResultsMock); + when(mapperFacade.map(testUtils.getDummyTaskModel(), TasksDomain.class)) + .thenReturn(testUtils.getDummyTasksDomain()); + assertEquals(testUtils.getDummyTasksDomain(), + storiesServiceImpl.getTaskById(unitTestProperties.getUrlId(), unitTestProperties.getUrlId())); + } + + @Test + public void updateTaskbyIdHappyPath() throws Exception { + when(storiesRepository.existsById(unitTestProperties.getModelId())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(storiesRepository.findById(unitTestProperties.getModelId())) + .thenReturn(java.util.Optional.of(testUtils.getStoryTaskModel())); + storiesServiceImpl.updateTaskById(testUtils.getUpdateTaskDomain(), unitTestProperties.getModelId(), + StoriesApiTestsConstants.ValidPutTaskId); + } + + @Test(expected = EntityNotFoundException.class) + public void updateStorySpecialChar() throws Exception { + when(storiesServiceImpl.updateTaskById(testUtils.getTaskDomainSpecialChar(), unitTestProperties.getModelId(), + testUtils.getTaskModelId().get_id())).thenThrow( + new EntityNotFoundException("The next field have special characters: Status", "", "/stories/")); + storiesServiceImpl.updateTaskById(testUtils.getTaskDomainSpecialChar(), unitTestProperties.getModelId(), + testUtils.getTaskModelId().get_id()); + } + + @Test(expected = EntityNotFoundException.class) + public void updateTaskSpecialsChars() throws Exception { + when(storiesServiceImpl.updateTaskById(testUtils.getTaskDomainSpecialsChars(), unitTestProperties.getModelId(), + testUtils.getTaskModelId().get_id())).thenThrow( + new EntityNotFoundException("The next field have special characters: Status, assignee", "", + "/stories/")); + storiesServiceImpl.updateTaskById(testUtils.getTaskDomainSpecialsChars(), unitTestProperties.getModelId(), + testUtils.getTaskModelId().get_id()); + } + + @Test(expected = EntityNotFoundException.class) + public void updateTaskByIdStoryNotFound() throws Exception { + when(storiesRepository.existsById(unitTestProperties.getModelId())) + .thenReturn(StoriesApiTestsConstants.booleanFalse); + storiesServiceImpl.updateTaskById(testUtils.getDummyTasksDomain(), unitTestProperties.getModelId(), + StoriesApiTestsConstants.ValidPutTaskId); + } + + @Test(expected = EntityNotFoundException.class) + public void updateTaskByIdStatusValidation() throws Exception { + when(storiesRepository.existsById(unitTestProperties.getModelId())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + storiesServiceImpl.updateTaskById(testUtils.getUpdateTaskDomainWrongstatus(), unitTestProperties.getModelId(), + StoriesApiTestsConstants.ValidPutTaskId); + } + + @Test(expected = EntityNotFoundException.class) + public void updateTaskbyIdInvalidAsignee() throws Exception { + when(storiesRepository.existsById(unitTestProperties.getModelId())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(usersClient.existUserById(testUtils.getUpdateTaskDomainAssignee().getAssignee())) + .thenReturn(StoriesApiTestsConstants.booleanFalse); + storiesServiceImpl.updateTaskById(testUtils.getUpdateTaskDomainAssignee(), unitTestProperties.getModelId(), + StoriesApiTestsConstants.ValidPutTaskId); + } + + @Test(expected = EntityNotFoundException.class) + public void updateTaskbyIdNameEmpty() throws Exception { + when(storiesRepository.existsById(unitTestProperties.getModelId())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(usersClient.existUserById(testUtils.getUpdateTaskDomainNameEmpty().getAssignee())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + storiesServiceImpl.updateTaskById(testUtils.getUpdateTaskDomainNameEmpty(), unitTestProperties.getModelId(), + StoriesApiTestsConstants.ValidPutTaskId); + } + + @Test(expected = EntityNotFoundException.class) + public void updateTaskbyIdInvalidTask() throws Exception { + when(storiesRepository.existsById(unitTestProperties.getModelId())) + .thenReturn(StoriesApiTestsConstants.booleanTrue); + when(storiesRepository.findById(unitTestProperties.getModelId())) + .thenReturn(java.util.Optional.of(testUtils.getStoryTaskModel())); + storiesServiceImpl.updateTaskById(testUtils.getUpdateTaskDomain(), unitTestProperties.getModelId(), + StoriesApiTestsConstants.InvalidId); + } +} \ No newline at end of file diff --git a/src/test/java/com/stories/sprintsClient/SprintsClientTest.java b/src/test/java/com/stories/sprintsClient/SprintsClientTest.java new file mode 100644 index 0000000..19c8f22 --- /dev/null +++ b/src/test/java/com/stories/sprintsClient/SprintsClientTest.java @@ -0,0 +1,78 @@ +package com.stories.sprintsClient; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; + +import com.stories.constants.StoriesApiTestsConstants; +import com.stories.domain.SprintDomain; +import com.stories.sprintsclient.SprintsClient; +import com.stories.utils.TestUtils; +import com.stories.utils.UnitTestProperties; + +@RunWith(SpringRunner.class) +public class SprintsClientTest { + + UnitTestProperties unitTestProperties; + + private TestUtils testUtils; + + @Mock + private RestTemplate restTemplate; + + @InjectMocks + private SprintsClient sprintsClient; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + testUtils = new TestUtils(); + } + + @Test + public void existsSprintById() throws Exception { + ResponseEntity> sprintEntity = new ResponseEntity>( + testUtils.getSprintDomaintList(), HttpStatus.OK); + Mockito.when(restTemplate.exchange(StoriesApiTestsConstants.uriSprintClient, HttpMethod.GET, null, + new ParameterizedTypeReference>() { + })).thenReturn(sprintEntity); + assertEquals(StoriesApiTestsConstants.booleanTrue, + sprintsClient.existsSprintById(StoriesApiTestsConstants.sprintIdValid)); + } + + @Test + public void noExistsSprintById() throws Exception { + ResponseEntity> sprintEntity = new ResponseEntity>( + testUtils.getSprintDomaintList(), HttpStatus.OK); + Mockito.when(restTemplate.exchange(StoriesApiTestsConstants.uriSprintClient, HttpMethod.GET, null, + new ParameterizedTypeReference>() { + })).thenReturn(sprintEntity); + assertEquals(StoriesApiTestsConstants.booleanFalse, + sprintsClient.existsSprintById(StoriesApiTestsConstants.sprintIdInvalid)); + } + + @Test(expected = RestClientException.class) + public void existsSprintByIdException() throws Exception { + ResponseEntity> sprintEntity = new ResponseEntity>( + testUtils.getNullSprintDomaintList(), HttpStatus.NOT_FOUND); + Mockito.when(restTemplate.exchange(StoriesApiTestsConstants.uriSprintClient, HttpMethod.GET, null, + new ParameterizedTypeReference>() { + })).thenThrow(new RestClientException(StoriesApiTestsConstants.messageSprints)); + sprintsClient.existsSprintById("5e78f5e792675632e42d1a96"); + } +} \ No newline at end of file diff --git a/src/test/java/com/stories/usersClient/UsersClientTest.java b/src/test/java/com/stories/usersClient/UsersClientTest.java new file mode 100644 index 0000000..ca969ed --- /dev/null +++ b/src/test/java/com/stories/usersClient/UsersClientTest.java @@ -0,0 +1,78 @@ +package com.stories.usersClient; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; + +import com.stories.constants.StoriesApiTestsConstants; +import com.stories.domain.UserDomain; +import com.stories.usersclient.UsersClient; +import com.stories.utils.TestUtils; +import com.stories.utils.UnitTestProperties; + +@RunWith(SpringRunner.class) +public class UsersClientTest { + + UnitTestProperties unitTestProperties; + + private TestUtils testUtils; + + @Mock + private RestTemplate restTemplate; + + @InjectMocks + private UsersClient usersClient; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + testUtils = new TestUtils(); + } + + @Test + public void existsUserById() throws Exception { + ResponseEntity> userEntity = new ResponseEntity>( + testUtils.getUserDomainList(), HttpStatus.OK); + Mockito.when(restTemplate.exchange(StoriesApiTestsConstants.uriUserClient, HttpMethod.GET, null, + new ParameterizedTypeReference>() { + })).thenReturn(userEntity); + assertEquals(StoriesApiTestsConstants.booleanTrue, + usersClient.existUserById(StoriesApiTestsConstants.userIdValid)); + } + + @Test + public void noExistsUsertById() throws Exception { + ResponseEntity> userEntity = new ResponseEntity>( + testUtils.getUserDomainList(), HttpStatus.OK); + Mockito.when(restTemplate.exchange(StoriesApiTestsConstants.uriUserClient, HttpMethod.GET, null, + new ParameterizedTypeReference>() { + })).thenReturn(userEntity); + assertEquals(StoriesApiTestsConstants.booleanFalse, + usersClient.existUserById(StoriesApiTestsConstants.userIdInvalid)); + } + + @Test(expected = RestClientException.class) + public void existsUserByIdException() throws Exception { + ResponseEntity> userEntity = new ResponseEntity>( + testUtils.getNullUserDomaintList(), HttpStatus.NOT_FOUND); + Mockito.when(restTemplate.exchange(StoriesApiTestsConstants.uriUserClient, HttpMethod.GET, null, + new ParameterizedTypeReference>() { + })).thenThrow(new RestClientException(StoriesApiTestsConstants.messageUsers)); + usersClient.existUserById("5ea7125ce6cd3109e8bc71cf"); + } +} \ No newline at end of file diff --git a/src/test/java/com/stories/utils/TestUtils.java b/src/test/java/com/stories/utils/TestUtils.java new file mode 100644 index 0000000..908706d --- /dev/null +++ b/src/test/java/com/stories/utils/TestUtils.java @@ -0,0 +1,894 @@ +package com.stories.utils; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; + +import com.stories.domain.SprintDomain; +import com.stories.domain.StoryDomain; +import com.stories.domain.TasksDomain; +import com.stories.domain.UserDomain; +import com.stories.model.StoryModel; +import com.stories.model.TaskModel; + +@Component +public class TestUtils { + + private static UnitTestProperties unitTestProperties; + + @Autowired + private TestUtils(UnitTestProperties unitTestProperties) { + TestUtils.unitTestProperties = unitTestProperties; + } + + public TestUtils() { + } + + public RestTemplate getrestTemplate() { + RestTemplate restTemplate = new RestTemplate(); + return restTemplate; + } + + public StoryModel getEmtyStoryMdodel() { + StoryModel storyModel = new StoryModel(); + return storyModel; + } + + public StoryDomain getEmtyStoryDomain() { + StoryDomain storyDomain = new StoryDomain(); + return storyDomain; + } + + public List getEmtyStoryModelList() { + List storiesModelList = new ArrayList(); + return storiesModelList; + } + + public List getEmtySprintsDomain() { + List storyDomain = new ArrayList(); + return storyDomain; + } + + public TasksDomain getEmptyTasksDomain() { + TasksDomain tasksDomain = new TasksDomain(); + return tasksDomain; + } + + public TaskModel getEmptyTasksModel() { + TaskModel taskModel = new TaskModel(); + return taskModel; + } + + public String setStoryInJsonFormat(String id) { + return "{\"id\":\"" + id + + "\", \"sprint_id\":\"UUID\", \"technology\":\"Java\",\"name\":\"Create Stories POST endpoint\", \"description\":\"\",\"acceptance_criteria\":\"\",\"points\":2,\"progress\":885, \"status\":\"Working\",\"notes\":\"\",\"comments\":\"Test\", \"start_date\":\"2020-08-25\",\"due_date\":\"2020-08-25\",\"priority\":\"High\", \"assignee_id\":\"UUID\",\"history\":[\"\",\"\"]}"; + } + + public String postStoryValidJson(String id) { + return "{\"id\":\"" + id + + "\", \"sprint_id\":\"UUID\", \"technology\":\"Java\",\"name\":\"Create Stories POST endpoint\", \"description\":\"\",\"acceptance_criteria\":\"\",\"points\":2,\"progress\":885, \"status\":\"Working\",\"notes\":\"\",\"comments\":\"Test\", \"start_date\":\"2020-08-25\",\"due_date\":\"2020-08-25\",\"priority\":\"High\", \"assignee_id\":\"UUID\",\"history\":[\"\",\"\"]}"; + } + + public String postStoryInvalidStatusJson() { + return "{\"sprint_id\":\"UUID\", \"technology\":\"Javas\",\"name\":\"Create Stories POST endpoint\", \"description\":\"\",\"acceptance_criteria\":\"\",\"points\":2,\"progress\":885, \"status\":\"working\",\"notes\":\"\",\"comments\":\"Test\", \"start_date\":\"2020-08-25\",\"due_date\":\"2020-08-25\",\"priority\":\"High\", \"assignee_id\":\"UUID\",\"history\":[\"\",\"\"]}"; + } + + public String setStoryInJsonBadFormat(String id) { + return "{\"id\":\"" + id + + "\", \"sprint_id\":\"UUID\", \"technology\":\"Java\",\"name\":\"Create Stories POST endpoint\", \"description\":\"\",\"acceptance_criteria\":\"\",\"points\":\"2#\",\"progress\":885, \"status\":\"Working\",\"notes\":\"\",\"comments\":\"Test\", \"start_date\":\"2020-08-25\",\"due_date\":\"2020-08-25\",\"priority\":\"High\", \"assignee_id\":\"UUID\",\"history\":[\"\",\"\"]}"; + } + + public String postStoryBadJsonFormat() { + return "{\"sprint_id\":\"UUID\", \"technology\":\"Javas\",\"name\":\"Create Stories POST endpoint\", \"description\":\"\",\"acceptance_criteria\":\"\",\"points\":\"213\",\"progress\":885, \"status\":\"working\",\"notes\":\"\",\"comments\":\"Test\", \"start_date\":\"2020-08-25\",\"due_date\":\"2020-08-25\",\"priority\":\"High\", \"assignee_id\":\"UUID\",\"history\":[\"\",\"\"]}"; + } + + public String getByid() { + return "{\"sprint_id\":\"hola\", \"technology\":\"Java\",\"name\":\"Probando la impresion en consola y json file\", \"description\":\"\",\"acceptance_criteria\":\"\",\"points\":1,\"progress\":1, \"status\":\"Working\",\"notes\":\"!\",\"comments\":\"$\", \"start_date\":\"2020-08-25\",\"due_date\":\"2020-08-25\",\"priority\":\"%\", \"assignee_id\":\"Prueba\",\"history\":[\"1\",\"2\"]}"; + } + + public static StoryDomain getDummyStoryDomain() { + LocalDate date = LocalDate.now(); + ArrayList historyList = new ArrayList<>(); + historyList.add("1"); + historyList.add("2"); + StoryDomain storyDomain = new StoryDomain(); + storyDomain.setSprint_id("Hello"); + storyDomain.setTechnology("Java"); + storyDomain.setName("Try Test"); + storyDomain.setDescription(""); + storyDomain.setAcceptance_criteria(""); + storyDomain.setPoints(1); + storyDomain.setProgress(1); + storyDomain.setStatus("Working"); + storyDomain.setNotes("!"); + storyDomain.setComments("$"); + storyDomain.setStart_date(date); + storyDomain.setDue_date(date); + storyDomain.setPriority("%"); + storyDomain.setAssignee_id("Try Test"); + storyDomain.setHistory(historyList); + return storyDomain; + } + + public static StoryModel getDummyStoryModel() { + ArrayList historyList = new ArrayList<>(); + historyList.add(unitTestProperties.modelHistory1); + historyList.add(unitTestProperties.modelHistory2); + StoryModel storyModel = new StoryModel(); + storyModel.set_id(unitTestProperties.modelId); + storyModel.setSprint_id(unitTestProperties.modelSprintid); + storyModel.setTechnology(unitTestProperties.modelTechnology); + storyModel.setName(unitTestProperties.modelName); + storyModel.setDescription(unitTestProperties.modelDescription); + storyModel.setAcceptance_criteria(unitTestProperties.modelAcceptanceCriteria); + storyModel.setPoints(unitTestProperties.modelPoints); + storyModel.setProgress(unitTestProperties.modelProgress); + storyModel.setStatus(unitTestProperties.modelStatus); + storyModel.setNotes(unitTestProperties.modelNotes); + storyModel.setComments(unitTestProperties.modelComments); + storyModel.setStart_date(unitTestProperties.modelStartDate); + storyModel.setDue_date(unitTestProperties.modelDueDate); + storyModel.setPriority(unitTestProperties.modelPriority); + storyModel.setAssignee_id(unitTestProperties.modelAssigneeId); + storyModel.setHistory(historyList); + return storyModel; + } + + public static List listStoriesModelNull() { + List storiesModel = new ArrayList(); + storiesModel = null; + return storiesModel; + } + + public static StoryDomain getStoryDomain() { + StoryDomain storyDomain = new StoryDomain(); + List historyList = new ArrayList<>(); + historyList.add(unitTestProperties.domainHistory1); + historyList.add(unitTestProperties.domainHistory2); + storyDomain.setSprint_id(unitTestProperties.domainSprintId); + storyDomain.setTechnology(unitTestProperties.domainTechnology); + storyDomain.setName(unitTestProperties.domainName); + storyDomain.setDescription(unitTestProperties.domainDescription); + storyDomain.setAcceptance_criteria(unitTestProperties.domainAcceptanceCriteria); + storyDomain.setPoints(unitTestProperties.domainPoints); + storyDomain.setProgress(unitTestProperties.domainProgress); + storyDomain.setStatus(unitTestProperties.domainStatus); + storyDomain.setNotes(unitTestProperties.domainNotes); + storyDomain.setComments(unitTestProperties.domainComment); + storyDomain.setStart_date(unitTestProperties.domainStartDate); + storyDomain.setDue_date(unitTestProperties.domainDueDate); + storyDomain.setPriority(unitTestProperties.domainPriority); + storyDomain.setAssignee_id(unitTestProperties.domainAssigneeId); + storyDomain.setHistory(historyList); + + return storyDomain; + } + + public static TasksDomain getTasksDomain() { + TasksDomain tasksDomain = new TasksDomain(); + tasksDomain.set_id(unitTestProperties.TasksdomainId); + tasksDomain.setName(unitTestProperties.TasksdomainName); + tasksDomain.setDescription(unitTestProperties.TasksdomainDescription); + tasksDomain.setStatus(unitTestProperties.TasksdomainStatus); + tasksDomain.setComments(unitTestProperties.TasksdomainComments); + tasksDomain.setAssignee(unitTestProperties.TasksdomainAssignee); + return tasksDomain; + } + + public static List getTasksDomainList() { + List tasksDomainList = new ArrayList(); + TasksDomain tasksDomain = new TasksDomain(); + tasksDomain.set_id(unitTestProperties.domainId); + tasksDomain.setName(unitTestProperties.domainName); + tasksDomain.setDescription(unitTestProperties.domainDescription); + tasksDomain.setStatus(unitTestProperties.domainStatus); + tasksDomain.setComments(unitTestProperties.domainComment); + tasksDomain.setAssignee(unitTestProperties.domainAssigneeId); + tasksDomainList.add(tasksDomain); + return tasksDomainList; + } + + public static TaskModel getTasksModel() { + TaskModel tasksModel = new TaskModel(); + tasksModel.set_id(unitTestProperties.TasksModelId); + tasksModel.setName(unitTestProperties.TasksdomainName); + tasksModel.setDescription(unitTestProperties.TasksdomainDescription); + tasksModel.setStatus(unitTestProperties.TasksdomainStatus); + tasksModel.setComments(unitTestProperties.TasksdomainComments); + tasksModel.setAssignee(unitTestProperties.TasksdomainAssignee); + return tasksModel; + } + + public static StoryModel getStoryModel() { + StoryModel storyModel = new StoryModel(); + ArrayList historyList = new ArrayList<>(); + historyList.add(unitTestProperties.modelHistory1); + historyList.add(unitTestProperties.modelHistory2); + storyModel.set_id(unitTestProperties.modelId); + storyModel.setSprint_id(unitTestProperties.modelSprintid); + storyModel.setTechnology(unitTestProperties.modelTechnology); + storyModel.setName(unitTestProperties.modelName); + storyModel.setDescription(unitTestProperties.modelDescription); + storyModel.setAcceptance_criteria(unitTestProperties.modelAcceptanceCriteria); + storyModel.setPoints(unitTestProperties.modelPoints); + storyModel.setProgress(unitTestProperties.modelProgress); + storyModel.setStatus(unitTestProperties.modelStatus); + storyModel.setNotes(unitTestProperties.modelNotes); + storyModel.setComments(unitTestProperties.modelComments); + storyModel.setStart_date(unitTestProperties.modelStartDate); + storyModel.setDue_date(unitTestProperties.modelDueDate); + storyModel.setPriority(unitTestProperties.modelPriority); + storyModel.setAssignee_id(unitTestProperties.modelAssigneeId); + storyModel.setHistory(historyList); + storyModel.setTasks(getTaskModelList()); + + return storyModel; + } + + public static List getTaskModelList() { + List tasks = new ArrayList(); + TaskModel tasksModel = new TaskModel(); + tasksModel.set_id(unitTestProperties.TasksModelId); + tasksModel.setName(unitTestProperties.TasksdomainName); + tasksModel.setDescription(unitTestProperties.TasksdomainDescription); + tasksModel.setStatus(unitTestProperties.TasksdomainStatus); + tasksModel.setComments(unitTestProperties.TasksdomainComments); + tasksModel.setAssignee(unitTestProperties.TasksdomainAssignee); + tasks.add(tasksModel); + return tasks; + } + + public static StoryModel getStoryTaskModel() { + StoryModel storyModel = new StoryModel(); + ArrayList historyList = new ArrayList<>(); + ArrayList taskList = new ArrayList<>(); + TaskModel taskModel = new TaskModel(); + taskModel.set_id("5e8cf37b7a605837de2865ad"); + taskModel.setName("New Tasks Armando"); + taskModel.setStatus("Working"); + taskModel.setAssignee("5e6bbc854244ac0cbc8df65d"); + taskList.add(taskModel); + historyList.add(unitTestProperties.modelHistory1); + historyList.add(unitTestProperties.modelHistory2); + storyModel.set_id(unitTestProperties.modelId); + storyModel.setSprint_id(unitTestProperties.modelSprintid); + storyModel.setTechnology(unitTestProperties.modelTechnology); + storyModel.setName(unitTestProperties.modelName); + storyModel.setDescription(unitTestProperties.modelDescription); + storyModel.setAcceptance_criteria(unitTestProperties.modelAcceptanceCriteria); + storyModel.setPoints(unitTestProperties.modelPoints); + storyModel.setProgress(unitTestProperties.modelProgress); + storyModel.setStatus(unitTestProperties.modelStatus); + storyModel.setNotes(unitTestProperties.modelNotes); + storyModel.setComments(unitTestProperties.modelComments); + storyModel.setStart_date(unitTestProperties.modelStartDate); + storyModel.setDue_date(unitTestProperties.modelDueDate); + storyModel.setPriority(unitTestProperties.modelPriority); + storyModel.setAssignee_id(unitTestProperties.modelAssigneeId); + storyModel.setHistory(historyList); + storyModel.setTasks(taskList); + + return storyModel; + } + + public static List getStoryModelList() { + List storyModelList = new ArrayList(); + StoryModel storyModel = new StoryModel(); + ArrayList historyList = new ArrayList<>(); + historyList.add(unitTestProperties.modelHistory1); + historyList.add(unitTestProperties.modelHistory2); + storyModel.set_id(unitTestProperties.modelId); + storyModel.setSprint_id(unitTestProperties.modelSprintid); + storyModel.setTechnology(unitTestProperties.modelTechnology); + storyModel.setName(unitTestProperties.modelName); + storyModel.setDescription(unitTestProperties.modelDescription); + storyModel.setAcceptance_criteria(unitTestProperties.modelAcceptanceCriteria); + storyModel.setPoints(unitTestProperties.modelPoints); + storyModel.setProgress(unitTestProperties.modelProgress); + storyModel.setStatus(unitTestProperties.modelStatus); + storyModel.setNotes(unitTestProperties.modelNotes); + storyModel.setComments(unitTestProperties.modelComments); + storyModel.setStart_date(unitTestProperties.modelStartDate); + storyModel.setDue_date(unitTestProperties.modelDueDate); + storyModel.setPriority(unitTestProperties.modelPriority); + storyModel.setAssignee_id(unitTestProperties.modelAssigneeId); + storyModel.setHistory(historyList); + storyModelList.add(storyModel); + return storyModelList; + } + + public static List getSprintDomaintList() { + List sprintDomainList = new ArrayList(); + SprintDomain sprintDomain = new SprintDomain(); + sprintDomain.setId("5e827f2f48b0866f87e1cbc2"); + sprintDomain.setName("asd"); + sprintDomain.setTechnology("asd"); + sprintDomain.setActive(true); + sprintDomain.set_backlog(false); + sprintDomain.setStart_date(LocalDate.now()); + sprintDomain.setEnd_date(LocalDate.now()); + sprintDomainList.add(sprintDomain); + return sprintDomainList; + } + + public static List getNullSprintDomaintList() { + List sprintDomainList = new ArrayList(); + sprintDomainList.add(null); + return sprintDomainList; + } + + public static List getUserDomainList() { + List userDomainList = new ArrayList(); + UserDomain userDomain = new UserDomain(); + userDomain.setUserId("5ea7125ce6cd3109e8bc71c6"); + userDomain.setFirstName("Armando"); + userDomain.setLastName("Sanchez"); + userDomain.setEmail("armandosz@outlook.com"); + userDomain.setPhone("3123231"); + userDomain.setStartDate("2020-04-29T23:49:44.215Z"); + userDomain.setEndDate("2020-04-29T23:49:44.215Z"); + userDomain.setActiveTechnology("Java"); + userDomain.setStatus("active"); + userDomain.setRole("Intern"); + userDomainList.add(userDomain); + return userDomainList; + } + + public static List getNullUserDomaintList() { + List userDomainList = new ArrayList(); + userDomainList.add(null); + return userDomainList; + } + + public static TasksDomain getDummyTasksDomain() { + TasksDomain tasksDomain = new TasksDomain(); + tasksDomain.set_id("5e8dc1ba4ce33c0efc555845"); + tasksDomain.setName("TaskDomainTest"); + tasksDomain.setDescription("TasksDomainDescriptionTest"); + tasksDomain.setStatus("TaskDomainStatusTest"); + tasksDomain.setComments("TasksDomainCommentsTest"); + tasksDomain.setAssignee("TasksDomainAssigneeTest"); + return tasksDomain; + } + + public static TaskModel getDummyTaskModel() { + TaskModel taskModel = new TaskModel(); + taskModel.set_id("5e8dc1ba4ce33c0efc555845"); + taskModel.setName("TaskModelTest"); + taskModel.setDescription("TasksModelDescriptionTest"); + taskModel.setStatus("TaskModelStatusTest"); + taskModel.setComments("TasksModelCommentsTest"); + taskModel.setAssignee("TasksModelAssigneeTest"); + return taskModel; + } + + public static TasksDomain getUpdateTaskDomain() { + TasksDomain tasksDomain = new TasksDomain(); + tasksDomain.setName("test"); + tasksDomain.setDescription(""); + tasksDomain.setStatus("Working"); + tasksDomain.setComments("comments"); + tasksDomain.setAssignee(""); + return tasksDomain; + } + + public static TasksDomain getUpdateTaskDomainWrongstatus() { + TasksDomain tasksDomain = new TasksDomain(); + tasksDomain.setName("test"); + tasksDomain.setDescription(""); + tasksDomain.setStatus("Wrong"); + tasksDomain.setComments("comments"); + tasksDomain.setAssignee(""); + return tasksDomain; + } + + public static TasksDomain getUpdateTaskDomainAssignee() { + TasksDomain tasksDomain = new TasksDomain(); + tasksDomain.setName("test"); + tasksDomain.setDescription(""); + tasksDomain.setStatus("Working"); + tasksDomain.setComments("comments"); + tasksDomain.setAssignee("5e6bbc854244ac0cbc8df65d"); + return tasksDomain; + } + + public static TasksDomain getUpdateTaskDomainNameEmpty() { + TasksDomain tasksDomain = new TasksDomain(); + tasksDomain.setName(null); + tasksDomain.setDescription(""); + tasksDomain.setStatus("Working"); + tasksDomain.setComments("comments"); + tasksDomain.setAssignee("5e6bbc854244ac0cbc8df65d"); + return tasksDomain; + } + + public static TaskModel getTaskModelId() { + TaskModel taskModel = new TaskModel(); + taskModel.set_id("5e7668cfacfc726352dc5abc"); + return taskModel; + } + + public static TaskModel getTaskModelNull() { + TaskModel taskModel = new TaskModel(); + taskModel.set_id(null); + taskModel.setName("TaskModelTest"); + taskModel.setDescription("TasksModelDescriptionTest"); + taskModel.setStatus("TaskModelStatusTest"); + taskModel.setComments("TasksModelCommentsTest"); + taskModel.setAssignee("TasksModelAssigneeTest"); + return taskModel; + } + + public static TasksDomain getTaskDomainSpecialChar() { + TasksDomain taskDomain = new TasksDomain(); + taskDomain.set_id("5e8dc1ba4ce33c0efc555845"); + taskDomain.setName("TaskModelTest"); + taskDomain.setDescription("TasksModelDescriptionTest"); + taskDomain.setStatus("TaskModelStatusTest_"); + taskDomain.setComments("TasksModelCommentsTest"); + taskDomain.setAssignee("TasksModelAssigneeTest"); + return taskDomain; + } + + public static TasksDomain getTaskDomainSpecialsChars() { + TasksDomain taskDomain = new TasksDomain(); + taskDomain.set_id("5e8dc1ba4ce33c0efc555845"); + taskDomain.setName("TaskModelTest"); + taskDomain.setDescription("TasksModelDescriptionTest"); + taskDomain.setStatus("TaskModelStatusTest_"); + taskDomain.setComments("TasksModelCommentsTest"); + taskDomain.setAssignee("TasksModelAssigneeTest_"); + return taskDomain; + } + + public static StoryDomain getStoryDomainSpecialsChars() { + StoryDomain storyDomain = new StoryDomain(); + List historyList = new ArrayList<>(); + historyList.add(unitTestProperties.domainHistory1); + historyList.add(unitTestProperties.domainHistory2); + storyDomain.set_id(unitTestProperties.domainId); + storyDomain.setSprint_id(unitTestProperties.domainSprintId); + storyDomain.setTechnology(unitTestProperties.domainTechnology); + storyDomain.setName(unitTestProperties.domainName); + storyDomain.setDescription(unitTestProperties.domainDescription); + storyDomain.setAcceptance_criteria(unitTestProperties.domainAcceptanceCriteria); + storyDomain.setPoints(unitTestProperties.domainPoints); + storyDomain.setProgress(unitTestProperties.domainProgress); + storyDomain.setStatus(unitTestProperties.domainStatus + "_"); + storyDomain.setNotes(unitTestProperties.domainNotes); + storyDomain.setComments(unitTestProperties.domainComment); + storyDomain.setStart_date(unitTestProperties.domainStartDate); + storyDomain.setDue_date(unitTestProperties.domainDueDate); + storyDomain.setPriority(unitTestProperties.domainPriority); + storyDomain.setAssignee_id(unitTestProperties.domainAssigneeId + "_"); + storyDomain.setHistory(historyList); + + return storyDomain; + } + + public static StoryDomain getStoryDomainSpecialChar() { + StoryDomain storyDomain = new StoryDomain(); + List historyList = new ArrayList<>(); + historyList.add(unitTestProperties.domainHistory1); + historyList.add(unitTestProperties.domainHistory2); + storyDomain.set_id(unitTestProperties.domainId); + storyDomain.setSprint_id(unitTestProperties.domainSprintId); + storyDomain.setTechnology(unitTestProperties.domainTechnology); + storyDomain.setName(unitTestProperties.domainName); + storyDomain.setDescription(unitTestProperties.domainDescription); + storyDomain.setAcceptance_criteria(unitTestProperties.domainAcceptanceCriteria); + storyDomain.setPoints(unitTestProperties.domainPoints); + storyDomain.setProgress(unitTestProperties.domainProgress); + storyDomain.setStatus(unitTestProperties.domainStatus + "_"); + storyDomain.setNotes(unitTestProperties.domainNotes); + storyDomain.setComments(unitTestProperties.domainComment); + storyDomain.setStart_date(unitTestProperties.domainStartDate); + storyDomain.setDue_date(unitTestProperties.domainDueDate); + storyDomain.setPriority(unitTestProperties.domainPriority); + storyDomain.setAssignee_id(unitTestProperties.domainAssigneeId); + storyDomain.setHistory(historyList); + + return storyDomain; + } + + public static StoryDomain getStoryDomainAssigneInvalid() { + StoryDomain storyDomain = new StoryDomain(); + List historyList = new ArrayList<>(); + historyList.add(unitTestProperties.domainHistory1); + historyList.add(unitTestProperties.domainHistory2); + storyDomain.set_id(unitTestProperties.domainId); + storyDomain.setSprint_id(unitTestProperties.domainSprintId); + storyDomain.setTechnology(unitTestProperties.domainTechnology); + storyDomain.setName(unitTestProperties.domainName); + storyDomain.setDescription(unitTestProperties.domainDescription); + storyDomain.setAcceptance_criteria(unitTestProperties.domainAcceptanceCriteria); + storyDomain.setPoints(unitTestProperties.domainPoints); + storyDomain.setProgress(unitTestProperties.domainProgress); + storyDomain.setStatus(unitTestProperties.domainStatus); + storyDomain.setNotes(unitTestProperties.domainNotes); + storyDomain.setComments(unitTestProperties.domainComment); + storyDomain.setStart_date(unitTestProperties.domainStartDate); + storyDomain.setDue_date(unitTestProperties.domainDueDate); + storyDomain.setPriority(unitTestProperties.domainPriority); + storyDomain.setAssignee_id(unitTestProperties.domainAssigneeId); + storyDomain.setHistory(historyList); + return storyDomain; + } + + public static StoryModel getStoryModelAssigneInvalid() { + StoryModel storyModel = new StoryModel(); + List historyList = new ArrayList<>(); + historyList.add(unitTestProperties.domainHistory1); + historyList.add(unitTestProperties.domainHistory2); + storyModel.set_id(unitTestProperties.domainId); + storyModel.setSprint_id(unitTestProperties.domainSprintId); + storyModel.setTechnology(unitTestProperties.domainTechnology); + storyModel.setName(unitTestProperties.domainName); + storyModel.setDescription(unitTestProperties.domainDescription); + storyModel.setAcceptance_criteria(unitTestProperties.domainAcceptanceCriteria); + storyModel.setPoints(unitTestProperties.domainPoints); + storyModel.setProgress(unitTestProperties.domainProgress); + storyModel.setStatus(unitTestProperties.domainStatus); + storyModel.setNotes(unitTestProperties.domainNotes); + storyModel.setComments(unitTestProperties.domainComment); + storyModel.setStart_date(unitTestProperties.domainStartDate); + storyModel.setDue_date(unitTestProperties.domainDueDate); + storyModel.setPriority(unitTestProperties.domainPriority); + storyModel.setAssignee_id(unitTestProperties.domainAssigneeId); + storyModel.setHistory(historyList); + return storyModel; + } + + public static StoryDomain getStoryDomainNameInvalid() { + StoryDomain storyDomain = new StoryDomain(); + List historyList = new ArrayList<>(); + historyList.add(unitTestProperties.domainHistory1); + historyList.add(unitTestProperties.domainHistory2); + storyDomain.set_id(unitTestProperties.domainId); + storyDomain.setSprint_id(unitTestProperties.domainSprintId); + storyDomain.setTechnology(unitTestProperties.domainTechnology); + storyDomain.setName(""); + storyDomain.setDescription(unitTestProperties.domainDescription); + storyDomain.setAcceptance_criteria(unitTestProperties.domainAcceptanceCriteria); + storyDomain.setPoints(unitTestProperties.domainPoints); + storyDomain.setProgress(unitTestProperties.domainProgress); + storyDomain.setStatus(unitTestProperties.domainStatus); + storyDomain.setNotes(unitTestProperties.domainNotes); + storyDomain.setComments(unitTestProperties.domainComment); + storyDomain.setStart_date(unitTestProperties.domainStartDate); + storyDomain.setDue_date(unitTestProperties.domainDueDate); + storyDomain.setPriority(unitTestProperties.domainPriority); + storyDomain.setAssignee_id(unitTestProperties.domainAssigneeId); + storyDomain.setHistory(historyList); + return storyDomain; + } + + public static StoryModel getStoryModelNameInvalid() { + StoryModel storyModel = new StoryModel(); + List historyList = new ArrayList<>(); + historyList.add(unitTestProperties.domainHistory1); + historyList.add(unitTestProperties.domainHistory2); + storyModel.set_id(unitTestProperties.domainId); + storyModel.setSprint_id(unitTestProperties.domainSprintId); + storyModel.setTechnology(unitTestProperties.domainTechnology); + storyModel.setName(""); + storyModel.setDescription(unitTestProperties.domainDescription); + storyModel.setAcceptance_criteria(unitTestProperties.domainAcceptanceCriteria); + storyModel.setPoints(unitTestProperties.domainPoints); + storyModel.setProgress(unitTestProperties.domainProgress); + storyModel.setStatus(unitTestProperties.domainStatus); + storyModel.setNotes(unitTestProperties.domainNotes); + storyModel.setComments(unitTestProperties.domainComment); + storyModel.setStart_date(unitTestProperties.domainStartDate); + storyModel.setDue_date(unitTestProperties.domainDueDate); + storyModel.setPriority(unitTestProperties.domainPriority); + storyModel.setAssignee_id(unitTestProperties.domainAssigneeId); + storyModel.setHistory(historyList); + return storyModel; + } + + public static StoryDomain getStoryDomainStatusInvalid() { + StoryDomain storyDomain = new StoryDomain(); + List historyList = new ArrayList<>(); + historyList.add(unitTestProperties.domainHistory1); + historyList.add(unitTestProperties.domainHistory2); + storyDomain.set_id(unitTestProperties.domainId); + storyDomain.setSprint_id(unitTestProperties.domainSprintId); + storyDomain.setTechnology(unitTestProperties.domainTechnology); + storyDomain.setName(unitTestProperties.domainName); + storyDomain.setDescription(unitTestProperties.domainDescription); + storyDomain.setAcceptance_criteria(unitTestProperties.domainAcceptanceCriteria); + storyDomain.setPoints(unitTestProperties.domainPoints); + storyDomain.setProgress(unitTestProperties.domainProgress); + storyDomain.setStatus(unitTestProperties.domainStatus + "a"); + storyDomain.setNotes(unitTestProperties.domainNotes); + storyDomain.setComments(unitTestProperties.domainComment); + storyDomain.setStart_date(unitTestProperties.domainStartDate); + storyDomain.setDue_date(unitTestProperties.domainDueDate); + storyDomain.setPriority(unitTestProperties.domainPriority); + storyDomain.setAssignee_id(unitTestProperties.domainAssigneeId); + storyDomain.setHistory(historyList); + return storyDomain; + } + + public static StoryModel getStoryModelStatusInvalid() { + StoryModel storyModel = new StoryModel(); + List historyList = new ArrayList<>(); + historyList.add(unitTestProperties.domainHistory1); + historyList.add(unitTestProperties.domainHistory2); + storyModel.set_id(unitTestProperties.domainId); + storyModel.setSprint_id(unitTestProperties.domainSprintId); + storyModel.setTechnology(unitTestProperties.domainTechnology); + storyModel.setName(unitTestProperties.domainName); + storyModel.setDescription(unitTestProperties.domainDescription); + storyModel.setAcceptance_criteria(unitTestProperties.domainAcceptanceCriteria); + storyModel.setPoints(unitTestProperties.domainPoints); + storyModel.setProgress(unitTestProperties.domainProgress); + storyModel.setStatus(unitTestProperties.domainStatus + "a"); + storyModel.setNotes(unitTestProperties.domainNotes); + storyModel.setComments(unitTestProperties.domainComment); + storyModel.setStart_date(unitTestProperties.domainStartDate); + storyModel.setDue_date(unitTestProperties.domainDueDate); + storyModel.setPriority(unitTestProperties.domainPriority); + storyModel.setAssignee_id(unitTestProperties.domainAssigneeId); + storyModel.setHistory(historyList); + return storyModel; + } + + public static StoryDomain getStoryDomainStatusNull() { + StoryDomain storyDomain = new StoryDomain(); + List historyList = new ArrayList<>(); + historyList.add(unitTestProperties.domainHistory1); + historyList.add(unitTestProperties.domainHistory2); + storyDomain.set_id(unitTestProperties.domainId); + storyDomain.setSprint_id(unitTestProperties.domainSprintId); + storyDomain.setTechnology(unitTestProperties.domainTechnology); + storyDomain.setName(unitTestProperties.domainName); + storyDomain.setDescription(unitTestProperties.domainDescription); + storyDomain.setAcceptance_criteria(unitTestProperties.domainAcceptanceCriteria); + storyDomain.setPoints(unitTestProperties.domainPoints); + storyDomain.setProgress(unitTestProperties.domainProgress); + storyDomain.setStatus(""); + storyDomain.setNotes(unitTestProperties.domainNotes); + storyDomain.setComments(unitTestProperties.domainComment); + storyDomain.setStart_date(unitTestProperties.domainStartDate); + storyDomain.setDue_date(unitTestProperties.domainDueDate); + storyDomain.setPriority(unitTestProperties.domainPriority); + storyDomain.setAssignee_id(unitTestProperties.domainAssigneeId); + storyDomain.setHistory(historyList); + return storyDomain; + } + + public static StoryModel getStoryModelStatusNull() { + StoryModel storyModel = new StoryModel(); + List historyList = new ArrayList<>(); + historyList.add(unitTestProperties.domainHistory1); + historyList.add(unitTestProperties.domainHistory2); + storyModel.set_id(unitTestProperties.domainId); + storyModel.setSprint_id(unitTestProperties.domainSprintId); + storyModel.setTechnology(unitTestProperties.domainTechnology); + storyModel.setName(unitTestProperties.domainName); + storyModel.setDescription(unitTestProperties.domainDescription); + storyModel.setAcceptance_criteria(unitTestProperties.domainAcceptanceCriteria); + storyModel.setPoints(unitTestProperties.domainPoints); + storyModel.setProgress(unitTestProperties.domainProgress); + storyModel.setStatus(""); + storyModel.setNotes(unitTestProperties.domainNotes); + storyModel.setComments(unitTestProperties.domainComment); + storyModel.setStart_date(unitTestProperties.domainStartDate); + storyModel.setDue_date(unitTestProperties.domainDueDate); + storyModel.setPriority(unitTestProperties.domainPriority); + storyModel.setAssignee_id(unitTestProperties.domainAssigneeId); + storyModel.setHistory(historyList); + return storyModel; + } + + public static StoryDomain getStoryDomainStarDateNull() { + StoryDomain storyDomain = new StoryDomain(); + List historyList = new ArrayList<>(); + historyList.add(unitTestProperties.domainHistory1); + historyList.add(unitTestProperties.domainHistory2); + storyDomain.set_id(unitTestProperties.domainId); + storyDomain.setSprint_id(unitTestProperties.domainSprintId); + storyDomain.setTechnology(unitTestProperties.domainTechnology); + storyDomain.setName(unitTestProperties.domainName); + storyDomain.setDescription(unitTestProperties.domainDescription); + storyDomain.setAcceptance_criteria(unitTestProperties.domainAcceptanceCriteria); + storyDomain.setPoints(unitTestProperties.domainPoints); + storyDomain.setProgress(unitTestProperties.domainProgress); + storyDomain.setStatus(unitTestProperties.domainStatus); + storyDomain.setNotes(unitTestProperties.domainNotes); + storyDomain.setComments(unitTestProperties.domainComment); + storyDomain.setStart_date(null); + storyDomain.setDue_date(unitTestProperties.domainDueDate); + storyDomain.setPriority(unitTestProperties.domainPriority); + storyDomain.setAssignee_id(unitTestProperties.domainAssigneeId); + storyDomain.setHistory(historyList); + return storyDomain; + } + + public static StoryModel getStoryModelStarDateNull() { + StoryModel storyModel = new StoryModel(); + List historyList = new ArrayList<>(); + historyList.add(unitTestProperties.domainHistory1); + historyList.add(unitTestProperties.domainHistory2); + storyModel.set_id(unitTestProperties.domainId); + storyModel.setSprint_id(unitTestProperties.domainSprintId); + storyModel.setTechnology(unitTestProperties.domainTechnology); + storyModel.setName(unitTestProperties.domainName); + storyModel.setDescription(unitTestProperties.domainDescription); + storyModel.setAcceptance_criteria(unitTestProperties.domainAcceptanceCriteria); + storyModel.setPoints(unitTestProperties.modelPoints); + storyModel.setProgress(unitTestProperties.modelProgress); + storyModel.setStatus(unitTestProperties.modelStatus); + storyModel.setNotes(unitTestProperties.domainNotes); + storyModel.setComments(unitTestProperties.domainComment); + storyModel.setStart_date(null); + storyModel.setDue_date(unitTestProperties.domainDueDate); + storyModel.setPriority(unitTestProperties.domainPriority); + storyModel.setAssignee_id(unitTestProperties.domainAssigneeId); + storyModel.setHistory(historyList); + return storyModel; + } + + public static StoryDomain getStoryDomainPointsProggresNegative() { + StoryDomain storyDomain = new StoryDomain(); + List historyList = new ArrayList<>(); + historyList.add(unitTestProperties.domainHistory1); + historyList.add(unitTestProperties.domainHistory2); + storyDomain.set_id(unitTestProperties.domainId); + storyDomain.setSprint_id(unitTestProperties.domainSprintId); + storyDomain.setTechnology(unitTestProperties.domainTechnology); + storyDomain.setName(unitTestProperties.domainName); + storyDomain.setDescription(unitTestProperties.domainDescription); + storyDomain.setAcceptance_criteria(unitTestProperties.domainAcceptanceCriteria); + storyDomain.setPoints(-1); + storyDomain.setProgress(-1); + storyDomain.setStatus(unitTestProperties.domainStatus); + storyDomain.setNotes(unitTestProperties.domainNotes); + storyDomain.setComments(unitTestProperties.domainComment); + storyDomain.setStart_date(unitTestProperties.domainStartDate); + storyDomain.setDue_date(unitTestProperties.domainDueDate); + storyDomain.setPriority(unitTestProperties.domainPriority); + storyDomain.setAssignee_id(unitTestProperties.domainAssigneeId); + storyDomain.setHistory(historyList); + return storyDomain; + } + + public static StoryModel getStoryModelPointsProggresNegative() { + StoryModel storyModel = new StoryModel(); + List historyList = new ArrayList<>(); + historyList.add(unitTestProperties.domainHistory1); + historyList.add(unitTestProperties.domainHistory2); + storyModel.set_id(unitTestProperties.domainId); + storyModel.setSprint_id(unitTestProperties.domainSprintId); + storyModel.setTechnology(unitTestProperties.domainTechnology); + storyModel.setName(unitTestProperties.domainName); + storyModel.setDescription(unitTestProperties.domainDescription); + storyModel.setAcceptance_criteria(unitTestProperties.domainAcceptanceCriteria); + storyModel.setPoints(-1); + storyModel.setProgress(-1); + storyModel.setStatus(unitTestProperties.modelStatus); + storyModel.setNotes(unitTestProperties.domainNotes); + storyModel.setComments(unitTestProperties.domainComment); + storyModel.setStart_date(unitTestProperties.modelStartDate); + storyModel.setDue_date(unitTestProperties.domainDueDate); + storyModel.setPriority(unitTestProperties.domainPriority); + storyModel.setAssignee_id(unitTestProperties.domainAssigneeId); + storyModel.setHistory(historyList); + return storyModel; + } + + public static StoryDomain getStoryDomainPointsProgressInvalid() { + StoryDomain storyDomain = new StoryDomain(); + List historyList = new ArrayList<>(); + historyList.add(unitTestProperties.domainHistory1); + historyList.add(unitTestProperties.domainHistory2); + storyDomain.set_id(unitTestProperties.domainId); + storyDomain.setSprint_id(unitTestProperties.domainSprintId); + storyDomain.setTechnology(unitTestProperties.domainTechnology); + storyDomain.setName(unitTestProperties.domainName); + storyDomain.setDescription(unitTestProperties.domainDescription); + storyDomain.setAcceptance_criteria(unitTestProperties.domainAcceptanceCriteria); + storyDomain.setPoints(101); + storyDomain.setProgress(101); + storyDomain.setStatus(unitTestProperties.domainStatus); + storyDomain.setNotes(unitTestProperties.domainNotes); + storyDomain.setComments(unitTestProperties.domainComment); + storyDomain.setStart_date(unitTestProperties.domainStartDate); + storyDomain.setDue_date(unitTestProperties.domainDueDate); + storyDomain.setPriority(unitTestProperties.domainPriority); + storyDomain.setAssignee_id(unitTestProperties.domainAssigneeId); + storyDomain.setHistory(historyList); + return storyDomain; + } + + public static StoryModel getStoryModelPointsProgressInvalid() { + StoryModel storyModel = new StoryModel(); + List historyList = new ArrayList<>(); + historyList.add(unitTestProperties.domainHistory1); + historyList.add(unitTestProperties.domainHistory2); + storyModel.set_id(unitTestProperties.domainId); + storyModel.setSprint_id(unitTestProperties.domainSprintId); + storyModel.setTechnology(unitTestProperties.domainTechnology); + storyModel.setName(unitTestProperties.domainName); + storyModel.setDescription(unitTestProperties.domainDescription); + storyModel.setAcceptance_criteria(unitTestProperties.domainAcceptanceCriteria); + storyModel.setPoints(101); + storyModel.setProgress(101); + storyModel.setStatus(unitTestProperties.modelStatus); + storyModel.setNotes(unitTestProperties.domainNotes); + storyModel.setComments(unitTestProperties.domainComment); + storyModel.setStart_date(unitTestProperties.modelStartDate); + storyModel.setDue_date(unitTestProperties.domainDueDate); + storyModel.setPriority(unitTestProperties.domainPriority); + storyModel.setAssignee_id(unitTestProperties.domainAssigneeId); + storyModel.setHistory(historyList); + return storyModel; + } + + public static StoryModel getStoryTaskNullModel() { + StoryModel storyModel = new StoryModel(); + ArrayList historyList = new ArrayList<>(); + ArrayList taskList = new ArrayList<>(); + TaskModel taskModel = new TaskModel(); + historyList.add(unitTestProperties.modelHistory1); + historyList.add(unitTestProperties.modelHistory2); + storyModel.set_id(unitTestProperties.modelId); + storyModel.setSprint_id(unitTestProperties.modelSprintid); + storyModel.setTechnology(unitTestProperties.modelTechnology); + storyModel.setName(unitTestProperties.modelName); + storyModel.setDescription(unitTestProperties.modelDescription); + storyModel.setAcceptance_criteria(unitTestProperties.modelAcceptanceCriteria); + storyModel.setPoints(unitTestProperties.modelPoints); + storyModel.setProgress(unitTestProperties.modelProgress); + storyModel.setStatus(unitTestProperties.modelStatus); + storyModel.setNotes(unitTestProperties.modelNotes); + storyModel.setComments(unitTestProperties.modelComments); + storyModel.setStart_date(unitTestProperties.modelStartDate); + storyModel.setDue_date(unitTestProperties.modelDueDate); + storyModel.setPriority(unitTestProperties.modelPriority); + storyModel.setAssignee_id(unitTestProperties.modelAssigneeId); + storyModel.setHistory(historyList); + storyModel.setTasks(taskList); + + return storyModel; + } + + public static TasksDomain getTasksDomainStatusValid() { + TasksDomain tasksDomain = new TasksDomain(); + tasksDomain.set_id(unitTestProperties.TasksdomainId); + tasksDomain.setName(unitTestProperties.TasksdomainName); + tasksDomain.setDescription(unitTestProperties.TasksdomainDescription); + tasksDomain.setStatus(unitTestProperties.TasksdomainStatus + "asd"); + tasksDomain.setComments(unitTestProperties.TasksdomainComments); + tasksDomain.setAssignee(""); + return tasksDomain; + } + + public static TasksDomain getTasksNameNullDomain() { + TasksDomain tasksDomain = new TasksDomain(); + tasksDomain.set_id(unitTestProperties.TasksdomainId); + tasksDomain.setName(""); + tasksDomain.setDescription(unitTestProperties.TasksdomainDescription); + tasksDomain.setStatus(unitTestProperties.TasksdomainStatus); + tasksDomain.setComments(unitTestProperties.TasksdomainComments); + tasksDomain.setAssignee(unitTestProperties.TasksdomainAssignee); + return tasksDomain; + } + + public static TasksDomain getTasksStatusNullDomain() { + TasksDomain tasksDomain = new TasksDomain(); + tasksDomain.set_id(unitTestProperties.TasksdomainId); + tasksDomain.setName(unitTestProperties.TasksdomainName); + tasksDomain.setDescription(unitTestProperties.TasksdomainDescription); + tasksDomain.setStatus(""); + tasksDomain.setComments(unitTestProperties.TasksdomainComments); + tasksDomain.setAssignee(unitTestProperties.TasksdomainAssignee); + return tasksDomain; + } +} diff --git a/src/test/java/com/stories/utils/UnitTestProperties.java b/src/test/java/com/stories/utils/UnitTestProperties.java new file mode 100644 index 0000000..b4d93a4 --- /dev/null +++ b/src/test/java/com/stories/utils/UnitTestProperties.java @@ -0,0 +1,78 @@ +package com.stories.utils; + +import java.time.LocalDate; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.PropertySource; +import org.springframework.stereotype.Component; + +import lombok.Data; + +@PropertySource("classpath:unittest.properties") +@ConfigurationProperties(prefix = "unittest") +@Data +@Component +public class UnitTestProperties { + + protected String urlId; + protected String sprintClientUri; + + protected String domainId; + protected String domainSprintId; + protected String domainTechnology; + protected String domainName; + protected String domainDescription; + protected String domainAcceptanceCriteria; + protected int domainPoints; + protected int domainProgress; + protected String domainStatus; + protected String domainNotes; + protected String domainComment; + protected LocalDate domainStartDate = LocalDate.now(); + protected LocalDate domainDueDate = LocalDate.now(); + protected String domainPriority; + protected String domainAssigneeId; + protected String domainHistory1; + protected String domainHistory2; + + protected String TasksdomainId; + protected String TasksdomainName; + protected String TasksdomainDescription; + protected String TasksdomainStatus; + protected String TasksdomainComments; + protected String TasksdomainAssignee; + + protected String TasksModelId; + protected String TasksModelName; + protected String TasksModelDescription; + protected String TasksModelStatus; + protected String TasksModelComments; + protected String TasksModelAssignee; + + protected String modelId; + protected String modelSprintid; + protected String modelTechnology; + protected String modelName; + protected String modelDescription; + protected String modelAcceptanceCriteria; + protected int modelPoints; + protected int modelProgress; + protected String modelStatus; + protected String modelNotes; + protected String modelComments; + protected LocalDate modelStartDate = LocalDate.now(); + protected LocalDate modelDueDate = LocalDate.now(); + protected String modelPriority; + protected String modelAssigneeId; + protected String modelHistory1; + protected String modelHistory2; + + protected String sprintClientId; + protected String sprintClientName; + protected String sprintClientTechnology; + protected boolean sprintClientActive; + protected boolean sprintClientIsBacklog; + protected LocalDate sprintClientStartDate = LocalDate.now(); + protected LocalDate sprintClientEndDate = LocalDate.now(); + +} diff --git a/src/test/resources/unittest.properties b/src/test/resources/unittest.properties new file mode 100644 index 0000000..ccf9415 --- /dev/null +++ b/src/test/resources/unittest.properties @@ -0,0 +1,50 @@ +unittest.urlId = 5e7668cfacfc726352dc5abc +unittest.domainId = 5e8159b4604e96227eee02b3 +unittest.domainSprintid = 5e78f5e792675632e42d1a96 +unittest.domainTechnology = Java +unittest.domainName = Create Stories POST endpoint +unittest.domainDescription = none +unittest.domainAcceptanceCriteria = none +unittest.domainPoints = 1 +unittest.domainProgress = 1 +unittest.domainStatus = Working +unittest.domainNotes = none +unittest.domainComments = Test +unittest.domainPriority = High +unittest.domainAssigneeId = UUID +unittest.domainHistory1 = 1 +unittest.domainHistory2 = 2 +unittest.modelId = 5e7668cfacfc726352dc5abc +unittest.modelSprintid = 5e78f5e792675632e42d1a96 +unittest.modelTechnology = Java +unittest.modelName = Create Stories POST endpoint +unittest.modelDescription = none +unittest.modelAcceptanceCriteria = none +unittest.modelPoints = 1 +unittest.modelProgress = 1 +unittest.modelStatus = Working +unittest.modelNotes = none +unittest.modelComments = Test +unittest.modelPriority = High +unittest.modelAssigneeId = UUID +unittest.modelHistory1 = 1 +unittest.modelHistory2 = 2 +unittest.modelTaskId = 5e7668cfacfc726352dc5abc +unittest.sprintClientUri = http://sprints-qa.us-east-2.elasticbeanstalk.com/sprints/ +unittest.sprintClientId = 5e78f5e792675632e42d1a96 +unittest.sprintClientName = Sprint-Test1 +unittest.sprintClientTechnology = PEGA +unittest.sprintClientActive = false +unittest.sprintClientIsBacklog = false +unittest.TasksdomainId = 5e7668cfacfc726352dc5 +unittest.TasksdomainName = UUID +unittest.TasksdomainDescription = +unittest.TasksdomainStatus = Working +unittest.TasksdomainComments = +unittest.TasksdomainAssignee = 5e78f5e792675632e42d1 +unittest.TasksModelId = 5e7668cfacfc726352dc5abc +unittest.TasksModelName = UUID +unittest.TasksModelDescription = +unittest.TasksModelStatus = Working +unittest.TasksModelComments = +unittest.TasksModelAssignee = 5e78f5e792675632e42d1 \ No newline at end of file