Skip to content

Commit b5f95db

Browse files
hospelmartintaylor1635AndyFlintAnswerDigitalAudriusPutysMohammadIqbalAD
authored
Bench-173: Aligining Category with API spec (#77)
* BENCH-63 Added MapStruct dependency into the POM * BENCH-63 Added maven compiler plugin to add MapStruct support to POM * BENCH-63 Added CategoryMapper interface. * BENCH-63 Added ItemMapper interface. * BENCH-63 Added OrderMapper interface * BENCH-63 Renamed AddOrderRequest.java to OrderRequest.java * BENCH-63 Integration of MapStruct into service layer. * BENCH-63 Added update order endpoint, fixed issue relating to get all orders * BENCH-63 Fixed bug relating to get all orders by adding the fetch type as EAGER, also initialised the status within the zero-argument constructor * BENCH-63 Added setters as these are required by the MapStruct library to map objects successfully * BENCH-63 Added unit test. * BENCH-63 Removed star import to comply with check style * BENCH-63 Fixed validation bug, reverted back to parameter-level validation * BENCH-63 Improved readability * BENCH-36 (WIP) - Refactoring in progress * BENCH-81 added unit tests for Category * BENCH-81 adding verification to Category service tests * BENCH-81 checkstyle fixes * BENCH-81 fixing category tests * BENCH-81 updated category tests * BENCH-63 Improved readability * BENCH-63 Added unit test to test update order. * BENCH-63 Updated unit test. * BENCH-46 @builder added to help with tests, also equal and hashcodes with ToString methods manually added to entities * BENCH-85: adding logging to different classes (#17) * BENCH-63 Added MapStruct dependency into the POM * BENCH-63 Added maven compiler plugin to add MapStruct support to POM * adding logging to different classes * BENCH-63 Added CategoryMapper interface. * BENCH-63 Added ItemMapper interface. * BENCH-63 Added OrderMapper interface * BENCH-63 Renamed AddOrderRequest.java to OrderRequest.java * BENCH-63 Integration of MapStruct into service layer. * BENCH-63 Added update order endpoint, fixed issue relating to get all orders * BENCH-63 Fixed bug relating to get all orders by adding the fetch type as EAGER, also initialised the status within the zero-argument constructor * BENCH-63 Added setters as these are required by the MapStruct library to map objects successfully * putting a proper annotation for class level * BENCH-63 Added unit test. * BENCH-63 Removed star import to comply with check style * standardizing API code * reverting test changes * BENCH-63 Fixed validation bug, reverted back to parameter-level validation * BENCH-63 Improved readability * merge conflicts * merge conflict * merge conflicts resolution * reverting test changes * BENCH-63 Improved readability * BENCH-63 Added unit test to test update order. * BENCH-63 Updated unit test. * enabling lombok with mapstruct * merge conflicts * reverting test changes * merge conflicts * merge conflict * merge conflicts resolution * reverting test changes * enabling lombok with mapstruct * merge conflicts * reverting test changes * merge resolution * reverting test changes Co-authored-by: Martin Taylor <[email protected]> * BENCH-87 Updated Category and Item controller tests to reflect endpoint naming changes. * Renamed request mappings to plural * BENCH-46 Conflicts resolved * BENCH-87 Updated Category and Item controller tests to reflect endpoint naming changes. * Updated README to link to Amazon Correto 17 * Bench 85 cleanup (#20) * cleanup and adding missing spring-security-test * pom revert * cleanup * BENCH-87 Updated Category and Item controller tests to reflect endpoint naming changes. * Renamed request mappings to plural * Updated README to link to Amazon Correto 17 * BENCH-87 Updated Category and Item controller tests to reflect endpoint naming changes. * BENCH-86 order total price added * BENCH-46 add and remove item functions added to category. also items ignored on json in category request * BENCH-46 category equals updated to check name not id. * BENCH-86 Order total price included * BENCH-86 OrderItem total price updated * BENCH-86 imports optimized * BENCH-81: fixing rest endpoint issue (#23) * fixing rest endpoint issue * transaction update * fixing order adding issue (#24) * BENCH-NONE Added start-answerking.sh script for docker * fixing persistance loading issues (#25) * adding jacoco (#26) * BENCH-69: build workflow (#27) * build workflow * change workflow name * adding jacoco (#26) * adding cache to speed up build process * build workflow * change workflow name * adding cache to speed up build process * BENCH-58 Refactored package names, also changed package names from plural to singular as per BENCH-58 description. * BENCH-58 Fixed PR comment, renamed AnswerkingApplication to AnswerKingApplication and subsequent tests * BENCH-58-FIX Temporarily removed redundant test agreed with Oleksii, will integrate later when more purpose is added. * BENCH-58-FIX Removed OrderControllerIT.java as it was empty and served no purpose. Will re-write. * BENCH-58-FIX Temporarily removed redundant test agreed with Oleksii, will integrate later when more purpose is added. * BENCH-58-FIX Removed OrderControllerIT.java as it was empty and served no purpose. Will re-write. * adding docker build pipeline (#31) * BENCH-108: Bench 108 push images (#32) * build docker images * change branch name * renaming branches * docker image workflow (#33) * adjusting repo name (#34) * BENCH-108: Bench 108 push images4 (#35) * adjusting repo name * docker compose push adjustment * permission change (#37) * BENCH-108: Bench 108 push images6 (#38) * permission change * permission delete * permission delete * change log in (#39) * BENCH-108: Bench 108 push images8 (#40) * change log in * adding another push * BENCH-108: Bench 108 push images9 (#41) * change log in * adding another push * syntax error * syntax error * adding repo name (#42) * push changes (#43) * docker push config (#45) * BENCH-125 refactored error responses to RFC-7807 format * BENCH-125 refactored handling for MethodArgumentNotValidException * BENCH-125 adding errors & traceId fields to RFC-7807 error responses * adjusting github repo name (#46) * repo name update (#47) * tag image (#48) * BENCH-108-REFACTORING Refactored build_docker_package.yml as per requirements by Oleksii. * BENCH-96 Static code analysis added * BENCH-96 Static code analysis property added * BENCH-96 java version specified * BENCH-161 Refactored codebase * BENCH-161 Fixed README.md * BENCH-161 Updated CategoryServiceTest * BENCH-161 Changes reflecting Andrews observations * BENCH-159: change to be compliant with the latest openapi version (#54) * change to be compliant with the latest openapi version * BENCH-161 Refactored codebase * BENCH-161 Fixed README.md * change to be compliant with the latest openapi version * BENCH-161 Updated CategoryServiceTest * rebase with main * add permission * BENCH-161 Changes reflecting Andrews observations * swagger config changes * change to be compliant with the latest openapi version * rebase with main * rebase conflict * add permission * swagger config changes Co-authored-by: martintaylor1635 <[email protected]> * adding api tags (#56) * BENCH-153 Updated SQL files to reflect new retired fields added in models. * BENCH-153 Created RetirementException to be thrown when dealing with retirements. * BENCH-153 Added retired field to category * BENCH-153 Updated CategoryController to reflect changes * BENCH-153 Added logic to CategoryService and ItemService * BENCH-153 Updated ItemController to reflect changes * BENCH-153 Updated unit tests in accordance with the new features * BENCH-161 Test * BENCH-161 Test * BENCH-153 Removed available field from Item, and reflected it thoughout * BENCH-153 Addressed PR comments from Andrew * BENCH-153 Addressed PR comments from Andrew * BENCH-153 Updated RetirementException to reflect 404 not found rather than bad request * BENCH-153 Refactored RetirementException returning 410 GONE status * BENCH-153 Refactored Product model, added retired field to constructor * BENCH-153 Explicitly configured the ProductMapper to default the retired field to false when mapping a ProductRequest to a Product * BENCH-153 Addressed Andrews PR Comment: relocated constructor in Category model * BENCH-153 Addressed Andrews PR Comment: renamed local variable name within retireProduct in ProductService * BENCH-153 Addressed Andrews PR Comment: I would also suggest searching the codebase for any strings matching 'available' and see if there are any other ones we've missed * BENCH-153 Addressed Andrews PR Comment: Was this a mistake with the rebase? Seems a bit sparse * BENCH-56 v2 academy package removed. * BENCH-108-REFACTORING Refactored build_docker_package.yml as per requirements by Oleksii. * BENCH-108-REFACTORING Added the develop branc * BENCH-108-REFACTORING Added the master branch * BENCH-108-REFACTORING Added develop branch to the build_integration_and_code_analysis.yml workflow * Dependabot Yaml Set Up * Automatically approve dependabot pull requests * Updated package-ecosystem to Maven * Bump springdoc-openapi-maven-plugin from 0.2 to 1.4 Bumps [springdoc-openapi-maven-plugin](https://github.com/springdoc/springdoc-openapi-maven-plugin) from 0.2 to 1.4. - [Release notes](https://github.com/springdoc/springdoc-openapi-maven-plugin/releases) - [Commits](springdoc/springdoc-openapi-maven-plugin@v0.2...v1.4) --- updated-dependencies: - dependency-name: org.springdoc:springdoc-openapi-maven-plugin dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] <[email protected]> * Added github-actions ecosystem to dependabot.yml * Bump dependabot/fetch-metadata from 1.1.1 to 1.3.5 Bumps [dependabot/fetch-metadata](https://github.com/dependabot/fetch-metadata) from 1.1.1 to 1.3.5. - [Release notes](https://github.com/dependabot/fetch-metadata/releases) - [Commits](dependabot/fetch-metadata@v1.1.1...v1.3.5) --- updated-dependencies: - dependency-name: dependabot/fetch-metadata dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <[email protected]> * Bump actions/cache from 1 to 3 Bumps [actions/cache](https://github.com/actions/cache) from 1 to 3. - [Release notes](https://github.com/actions/cache/releases) - [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md) - [Commits](actions/cache@v1...v3) --- updated-dependencies: - dependency-name: actions/cache dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] <[email protected]> * BENCH-108-REFACTORING Refactored build_docker_package.yml as per requirements by Oleksii. * BENCH-108-REFACTORING Added the develop branc * BENCH-108-REFACTORING Added the master branch * BENCH-108-REFACTORING Added develop branch to the build_integration_and_code_analysis.yml workflow * Bump maven-wrapper-plugin from 3.1.0 to 3.1.1 (#60) Bumps [maven-wrapper-plugin](https://github.com/apache/maven-wrapper) from 3.1.0 to 3.1.1. - [Release notes](https://github.com/apache/maven-wrapper/releases) - [Commits](apache/maven-wrapper@maven-wrapper-parent-3.1.0...maven-wrapper-3.1.1) --- updated-dependencies: - dependency-name: org.apache.maven.plugins:maven-wrapper-plugin dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <[email protected]> Signed-off-by: dependabot[bot] <[email protected]> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * BENCH-108-REFACTORING Refactored build_docker_package.yml as per requirements by Oleksii. * BENCH-108-REFACTORING Added the develop branc * BENCH-108-REFACTORING Added the master branch * BENCH-108-REFACTORING Added develop branch to the build_integration_and_code_analysis.yml workflow * Added github.actor check to dependabot workflow * sonar key update to project name. * github action checkout updated to v3 * Updated dependabot.yml pull request limit + prefix * BENCH-174 Added get category by ID endpoint * BENCH-172 Created NameUnavailableException and ProductAlreadyPresentException * BENCH-172 Updated services to reflect changes * BENCH-172 Updated tests to reflect changes * BENCH-148 Refactored SecurityConfig and added dependency for Snake YAML * BENCH-148 Fixed checkstyle complaints * BENCH-148 Added scope to POM dependency * Replaced primitive longs with Wrapper Class Longs * adding missing fields as per API spec * adding missing fields as per API spec * BENCH-179 Updated the MySQL dependency within the POM * BENCH-180 Refactored Spring Security Config and resolved warnings * BENCH-180 Addressed checkstyle warnings * test adjustments * test adjustments * small method optimization * small method optimization * adding missing fields as per API spec * adding missing fields as per API spec * test adjustments * test adjustments * small method optimization * small method optimization * BENCH-184 getting order 500 error fixed on all endpoints. * BENCH-162 Updated status codes for create product and category * BENCH-162 Reflected changes within tests * BENCH-185 Refactored Dockerfile, removed maintainer reference and switched to corretto image * BENCH-185 Created a batch script from Windows users to initialise Docker * BENCH-185 Updated bash script to initialise Docker * BENCH-185 Updated bash and batch script * BENCH-185 Updated bash script, changed operations order * BENCH-185 Overridden the banner for startup * adding more swagger docs (#80) * adding missing fields as per API spec * adding missing fields as per API spec * test adjustments * test adjustments * small method optimization * small method optimization * rebase with main * rebase with main * rebase with main * rebase with main * adding full stops * adding full stops * BENCH-184 made removing item from basket transactional * added missed final * adding missing fields as per API spec * test adjustments * small method optimization * rebase with main * rebase with main * rebase * rebase * rebase * rebase * rebase * adding full stops * added missed final * rebase * rebase * rebase with main * rebase with main * rebase * rebase * rebase * removing empty lines * rebase * rebase with main * rebase with main * rebase * rebase * added missed final * rebase * rebase with main * rebase with main * rebase * rebase * rebase Signed-off-by: dependabot[bot] <[email protected]> Co-authored-by: Martin Taylor <[email protected]> Co-authored-by: Andy Flint <[email protected]> Co-authored-by: AudriusPutys <[email protected]> Co-authored-by: AndyFlintAnswerDigital <[email protected]> Co-authored-by: MohammadIqbalAD <[email protected]> Co-authored-by: AudriusPutys <[email protected]> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: MohammadIqbalAD <[email protected]>
1 parent f310976 commit b5f95db

File tree

8 files changed

+79
-33
lines changed

8 files changed

+79
-33
lines changed

.env

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
COMPOSE_PROJECT_NAME=answer-king-rest-api
2+
MYSQLDB_ROOT_PASSWORD=
3+
MYSQLDB_DATABASE=answer_king
4+
MYSQLDB_USER=test_user
5+
MYSQLDB_PASSWORD=

src/main/java/com/answerdigital/answerking/config/SecurityConfig.java

Lines changed: 13 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,11 @@
55
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
66
import org.springframework.security.config.http.SessionCreationPolicy;
77
import org.springframework.security.core.userdetails.User;
8-
import org.springframework.security.core.userdetails.UserDetails;
98
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
109
import org.springframework.security.web.SecurityFilterChain;
1110

11+
import java.util.List;
12+
1213
@EnableWebSecurity
1314
public class SecurityConfig {
1415
private static final String[] PERMITTED_PATTERNS = {
@@ -44,26 +45,17 @@ public SecurityFilterChain securityFilterChain(final HttpSecurity http) throws E
4445

4546
@Bean
4647
public InMemoryUserDetailsManager userDetailsManager() {
47-
final UserDetails paul = User.withUsername("paul")
48-
.password(COMMON_PASSWORD)
49-
.authorities(COMMON_ROLE)
50-
.build();
51-
52-
final UserDetails john = User.withUsername("john")
53-
.password(COMMON_PASSWORD)
54-
.authorities(COMMON_ROLE)
55-
.build();
56-
57-
final UserDetails ringo = User.withUsername("ringo")
58-
.password(COMMON_PASSWORD)
59-
.authorities(COMMON_ROLE)
60-
.build();
6148

62-
final UserDetails george = User.withUsername("george")
63-
.password(COMMON_PASSWORD)
64-
.authorities(COMMON_ROLE)
65-
.build();
66-
67-
return new InMemoryUserDetailsManager(paul, john, ringo, george);
49+
return new InMemoryUserDetailsManager(
50+
List.of("paul", "john", "ringo", "george")
51+
.stream()
52+
.map(user -> {
53+
return User.withUsername(user)
54+
.password(COMMON_PASSWORD)
55+
.authorities(COMMON_ROLE)
56+
.build();
57+
}).toList()
58+
);
6859
}
60+
6961
}

src/main/java/com/answerdigital/answerking/controller/CategoryController.java

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ public CategoryController(final CategoryService categoryService) {
4242
this.categoryService = categoryService;
4343
}
4444

45-
@Operation(summary = "Create a new category")
45+
@Operation(summary = "Create a new category.")
4646
@ApiResponses(value = {
4747
@ApiResponse(responseCode = "201", description = "When the category has been created.",
4848
content = { @Content(mediaType = "application/json", schema = @Schema(implementation = Category.class)) }),
@@ -56,9 +56,9 @@ public ResponseEntity<Category> addCategory(@Valid @RequestBody final AddCategor
5656
errors.hasErrors() ? HttpStatus.BAD_REQUEST : HttpStatus.CREATED);
5757
}
5858

59-
@Operation(summary = "Get all categories")
59+
@Operation(summary = "Get all categories.")
6060
@ApiResponses(value = {
61-
@ApiResponse(responseCode = "200", description = "Found the list of categories",
61+
@ApiResponse(responseCode = "200", description = "Found the list of categories.",
6262
content = { @Content(mediaType = "application/json", schema = @Schema(implementation = Category.class)) })
6363
})
6464
@GetMapping
@@ -67,19 +67,19 @@ public ResponseEntity<Collection<Category>> getAllCategories() {
6767
return new ResponseEntity<>(categories, categories.isEmpty() ? HttpStatus.NO_CONTENT : HttpStatus.OK);
6868
}
6969

70-
@Operation(summary = "Get a single category")
70+
@Operation(summary = "Get a single category.")
7171
@ApiResponses(value = {
7272
@ApiResponse(responseCode = "200", description = "When the category with the provided id has been found.",
7373
content = { @Content(mediaType = "application/json", schema = @Schema(implementation = Category.class)) }),
74-
@ApiResponse(responseCode = "404", description = "When the category with the given id does not exist",
74+
@ApiResponse(responseCode = "404", description = "When the category with the given id does not exist.",
7575
content = { @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class)) })
7676
})
7777
@GetMapping("/{categoryId}")
7878
public ResponseEntity<Category> getCategoryById(@PathVariable @NotNull final Long categoryId) {
7979
return new ResponseEntity<>(categoryService.findById(categoryId), HttpStatus.OK);
8080
}
8181

82-
@Operation(summary = "Add product to a category")
82+
@Operation(summary = "Add product to a category.")
8383
@ApiResponses(value = {
8484
@ApiResponse(responseCode = "200", description = "Add product to a category.",
8585
content = { @Content(mediaType = "application/json", schema = @Schema(implementation = Category.class)) })
@@ -90,7 +90,7 @@ public ResponseEntity<Category> addProductToCategory(@PathVariable @NotNull fina
9090
return new ResponseEntity<>(categoryService.addProductToCategory(categoryId, productId), HttpStatus.OK);
9191
}
9292

93-
@Operation(summary = "Remove product from a category")
93+
@Operation(summary = "Remove product from a category.")
9494
@ApiResponses(value = {
9595
@ApiResponse(responseCode = "200", description = "Remove product from a category.",
9696
content = { @Content(mediaType = "application/json", schema = @Schema(implementation = Category.class)) })

src/main/java/com/answerdigital/answerking/mapper/CategoryMapper.java

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,26 @@
44
import com.answerdigital.answerking.request.AddCategoryRequest;
55
import com.answerdigital.answerking.request.UpdateCategoryRequest;
66
import org.mapstruct.Mapper;
7+
import org.mapstruct.Mapping;
78
import org.mapstruct.MappingTarget;
9+
import java.time.ZonedDateTime;
10+
import java.time.format.DateTimeFormatter;
11+
import java.time.temporal.ChronoUnit;
12+
import java.time.ZoneOffset;
813

9-
@Mapper(componentModel = "spring")
14+
@Mapper(componentModel = "spring", imports = {DateTimeFormatter.class, ZoneOffset.class, ZonedDateTime.class, ChronoUnit.class})
1015
public interface CategoryMapper {
16+
17+
@Mapping(target = "createdOn", expression = "java( ZonedDateTime.now(ZoneOffset.UTC)" +
18+
".truncatedTo( ChronoUnit.SECONDS )" +
19+
".format( DateTimeFormatter.ofPattern( \"yyyy-MM-dd HH:mm:ss\" ) ) )")
20+
@Mapping(target = "lastUpdated", expression = "java( ZonedDateTime.now(ZoneOffset.UTC)" +
21+
".truncatedTo( ChronoUnit.SECONDS )" +
22+
".format( DateTimeFormatter.ofPattern( \"yyyy-MM-dd HH:mm:ss\" ) ) )")
1123
Category addRequestToCategory(AddCategoryRequest addCategoryRequest);
1224

25+
@Mapping(target = "lastUpdated", expression = "java( ZonedDateTime.now(ZoneOffset.UTC)" +
26+
".truncatedTo( ChronoUnit.SECONDS )" +
27+
".format( DateTimeFormatter.ofPattern( \"yyyy-MM-dd HH:mm:ss\" ) ) )")
1328
Category updateRequestToCategory(@MappingTarget Category category, UpdateCategoryRequest updateCategoryRequest);
1429
}

src/main/java/com/answerdigital/answerking/model/Category.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import com.answerdigital.answerking.request.AddCategoryRequest;
44
import com.fasterxml.jackson.annotation.JsonIgnore;
5+
import com.fasterxml.jackson.annotation.JsonProperty;
56
import lombok.AllArgsConstructor;
67
import lombok.Builder;
78
import lombok.Getter;
@@ -19,6 +20,10 @@
1920
import javax.persistence.ManyToMany;
2021
import javax.validation.constraints.NotBlank;
2122
import javax.validation.constraints.Pattern;
23+
import java.time.ZoneOffset;
24+
import java.time.ZonedDateTime;
25+
import java.time.format.DateTimeFormatter;
26+
import java.time.temporal.ChronoUnit;
2227
import java.util.HashSet;
2328
import java.util.Objects;
2429
import java.util.Set;
@@ -44,6 +49,12 @@ public class Category {
4449
message = "Category description can only contain letters, numbers, spaces and !?-.,' punctuation")
4550
private String description;
4651

52+
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
53+
private String createdOn;
54+
55+
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
56+
private String lastUpdated;
57+
4758
private boolean retired;
4859

4960
@ManyToMany(fetch = FetchType.LAZY)
@@ -57,13 +68,21 @@ public class Category {
5768
public Category(final AddCategoryRequest categoryRequest) {
5869
this.name = categoryRequest.name();
5970
this.description = categoryRequest.description();
71+
this.createdOn = ZonedDateTime.now(ZoneOffset.UTC)
72+
.truncatedTo( ChronoUnit.SECONDS )
73+
.format( DateTimeFormatter.ofPattern( "yyyy-MM-dd HH:mm::ss" ) );
74+
this.lastUpdated = this.createdOn;
6075
this.retired = false;
6176
}
6277

6378
public Category(final String name, final String description) {
6479
this.name = name;
6580
this.description = description;
6681
this.retired = false;
82+
this.createdOn = ZonedDateTime.now(ZoneOffset.UTC)
83+
.truncatedTo( ChronoUnit.SECONDS )
84+
.format( DateTimeFormatter.ofPattern( "yyyy-MM-dd HH:mm::ss" ) );
85+
this.lastUpdated = this.createdOn;
6786
}
6887

6988
public void addProduct(final Product product) {

src/main/resources/application.yaml

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ spring:
1616

1717
jpa:
1818
hibernate:
19-
ddl-auto: none
19+
ddl-auto: update
2020

2121
properties:
2222
hibernate:
@@ -32,7 +32,7 @@ spring:
3232

3333
datasource:
3434
username: test_user
35-
password: ***REMOVED***
35+
password: GS3ef_fsd^!
3636
url: jdbc:mysql://localhost:3306/answer_king
3737

3838
---
@@ -43,7 +43,7 @@ spring:
4343

4444
datasource:
4545
username: test_user
46-
password: ***REMOVED***
46+
password: GS3ef_fsd^!
4747
url: jdbc:mysql://localhost:3306/answer_king_test
4848

4949
---
@@ -54,5 +54,5 @@ spring:
5454

5555
datasource:
5656
username: test_user
57-
password: ***REMOVED***
57+
password: GS3ef_fsd^!
5858
url: jdbc:mysql://mysqldb:3306/answer_king

src/main/resources/schema.sql

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ CREATE TABLE IF NOT EXISTS category (
1212
id BIGINT NOT NULL AUTO_INCREMENT,
1313
name VARCHAR(255),
1414
description VARCHAR(255) NOT NULL,
15+
createdOn VARCHAR(255) NOT NULL,
16+
lastUpdated VARCHAR(255) NOT NULL,
1517
retired BIT(1) NOT NULL,
1618

1719
PRIMARY KEY (id)

src/test/java/com/answerdigital/answerking/controller/CategoryControllerTest.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,11 @@
1515
import org.springframework.test.context.junit.jupiter.SpringExtension;
1616
import org.springframework.test.web.servlet.MockMvc;
1717

18+
import java.time.ZoneId;
19+
import java.time.ZonedDateTime;
20+
import java.time.format.DateTimeFormatter;
21+
import java.time.temporal.ChronoUnit;
22+
1823
import static org.junit.jupiter.api.Assertions.assertTrue;
1924
import static org.junit.jupiter.api.Assertions.assertFalse;
2025
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -63,6 +68,9 @@ void addCategoryTest() throws Exception {
6368
final var addCategoryRequest = new AddCategoryRequest("random name", "random description");
6469
final var category = new Category(addCategoryRequest);
6570
final var categoryRequest = "{\"name\": \"random name\",\"description\": \"random description\"}";
71+
final String testDate = ZonedDateTime.now( ZoneId.of( "Etc/UTC" ) )
72+
.truncatedTo( ChronoUnit.SECONDS )
73+
.format( DateTimeFormatter.ofPattern( "yyyy-MM-dd HH:mm:ss" ) );
6674

6775
doReturn(category).when(categoryService).addCategory(addCategoryRequest);
6876
final var response = mvc.perform(post("/categories")
@@ -76,6 +84,7 @@ void addCategoryTest() throws Exception {
7684
assertFalse(response.getContentAsString().isEmpty());
7785
assertEquals(addCategoryRequest.name(), resultJsonNode.get("name").textValue());
7886
assertEquals(addCategoryRequest.description(), resultJsonNode.get("description").textValue());
87+
assertEquals(testDate.split(" ")[0], resultJsonNode.get("createdOn").textValue().split(" ")[0]);
7988
}
8089

8190
@Test
@@ -115,6 +124,9 @@ void updateCategoryTest() throws Exception {
115124
final var category = new Category(newRandomName, newRandomDesc);
116125
final var categoryId = 112L;
117126
final var updateCategoryRequestJson = "{\"name\": \"random name\",\"description\": \"random description\"}";
127+
String testDate = ZonedDateTime.now( ZoneId.of( "Etc/UTC" ) )
128+
.truncatedTo( ChronoUnit.SECONDS )
129+
.format( DateTimeFormatter.ofPattern( "yyyy-MM-dd HH:mm:ss" ) );
118130

119131
doReturn(category).when(categoryService).updateCategory(updateCategoryRequest, categoryId);
120132
final var response = mvc.perform(put("/categories/{categoryId}", categoryId)
@@ -128,6 +140,7 @@ void updateCategoryTest() throws Exception {
128140
assertFalse(response.getContentAsString().isEmpty());
129141
assertEquals(newRandomName, resultJsonNode.get("name").textValue());
130142
assertEquals(newRandomDesc, resultJsonNode.get("description").textValue());
143+
assertEquals(testDate.split(" ")[0], resultJsonNode.get("lastUpdated").textValue().split(" ")[0]);
131144
}
132145

133146
@Test

0 commit comments

Comments
 (0)