Skip to content

Commit

Permalink
feat: update tests for modification count
Browse files Browse the repository at this point in the history
  • Loading branch information
andrejpetras committed Feb 9, 2024
1 parent 2ba971e commit af91904
Show file tree
Hide file tree
Showing 11 changed files with 95 additions and 22 deletions.
20 changes: 20 additions & 0 deletions src/main/java/org/tkit/onecx/theme/domain/daos/ImageDAO.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,28 @@ public Image findByRefIdAndRefType(String refId, String refType) {
}
}

@Transactional(value = Transactional.TxType.REQUIRED, rollbackOn = DAOException.class)
public void deleteQueryByRefId(String refId) throws DAOException {
if (refId == null) {
return;
}
try {
var cq = deleteQuery();
var root = cq.from(Image.class);
var cb = this.getEntityManager().getCriteriaBuilder();

cq.where(cb.equal(root.get(Image_.REF_ID), refId));
getEntityManager().createQuery(cq).executeUpdate();
getEntityManager().flush();
} catch (Exception e) {
throw handleConstraint(e, ErrorKeys.FAILED_TO_DELETE_BY_REF_ID_QUERY);
}
}

public enum ErrorKeys {

FAILED_TO_DELETE_BY_REF_ID_QUERY,

FIND_ENTITY_BY_REF_ID_REF_TYPE_FAILED,

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.persistence.OptimisticLockException;
import jakarta.transaction.Transactional;
import jakarta.validation.ConstraintViolationException;
import jakarta.ws.rs.core.Context;
Expand All @@ -12,6 +13,7 @@

import org.jboss.resteasy.reactive.RestResponse;
import org.jboss.resteasy.reactive.server.ServerExceptionMapper;
import org.tkit.onecx.theme.domain.daos.ImageDAO;
import org.tkit.onecx.theme.domain.daos.ThemeDAO;
import org.tkit.onecx.theme.rs.internal.mappers.ExceptionMapper;
import org.tkit.onecx.theme.rs.internal.mappers.ThemeMapper;
Expand All @@ -31,6 +33,9 @@ public class ThemesRestController implements ThemesInternalApi {
@Inject
ThemeDAO dao;

@Inject
ImageDAO imageDAO;

@Inject
ThemeMapper mapper;

Expand All @@ -54,7 +59,15 @@ public Response createNewTheme(CreateThemeDTO createThemeDTO) {
@Override
@Transactional
public Response deleteTheme(String id) {
var image = dao.findById(id);
if (image == null) {
return Response.noContent().build();
}
dao.deleteQueryById(id);

// workaround for images
imageDAO.deleteQueryByRefId(image.getName());

return Response.noContent().build();
}

Expand Down Expand Up @@ -96,7 +109,6 @@ public Response searchThemes(ThemeSearchCriteriaDTO themeSearchCriteriaDTO) {
}

@Override
@Transactional
public Response updateTheme(String id, UpdateThemeDTO updateThemeDTO) {

var theme = dao.findById(id);
Expand All @@ -118,4 +130,9 @@ public RestResponse<ProblemDetailResponseDTO> exception(ConstraintException ex)
public RestResponse<ProblemDetailResponseDTO> constraint(ConstraintViolationException ex) {
return exceptionMapper.constraint(ex);
}

@ServerExceptionMapper
public RestResponse<ProblemDetailResponseDTO> optimisticLockException(OptimisticLockException ex) {
return exceptionMapper.optimisticLock(ex);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import java.util.Map;
import java.util.Set;

import jakarta.persistence.OptimisticLockException;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Path;
Expand All @@ -13,6 +14,7 @@
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.tkit.quarkus.jpa.exceptions.ConstraintException;
import org.tkit.quarkus.log.cdi.LogService;
import org.tkit.quarkus.rs.mappers.OffsetDateTimeMapper;

import gen.org.tkit.onecx.theme.rs.internal.model.ProblemDetailInvalidParamDTO;
Expand All @@ -36,6 +38,12 @@ public RestResponse<ProblemDetailResponseDTO> exception(ConstraintException ex)
return RestResponse.status(Response.Status.BAD_REQUEST, dto);
}

@LogService(log = false)
public RestResponse<ProblemDetailResponseDTO> optimisticLock(OptimisticLockException ex) {
var dto = exception(ErrorKeys.OPTIMISTIC_LOCK.name(), ex.getMessage());
return RestResponse.status(Response.Status.BAD_REQUEST, dto);
}

@Mapping(target = "removeParamsItem", ignore = true)
@Mapping(target = "params", ignore = true)
@Mapping(target = "invalidParams", ignore = true)
Expand Down Expand Up @@ -68,6 +76,8 @@ public String mapPath(Path path) {
}

public enum ErrorKeys {

OPTIMISTIC_LOCK,
CONSTRAINT_VIOLATIONS;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -62,24 +62,11 @@ public ThemeInfoListDTO mapInfoList(Stream<ThemeInfo> data) {
@Mapping(target = "modificationDate", ignore = true)
@Mapping(target = "modificationUser", ignore = true)
@Mapping(target = "controlTraceabilityManual", ignore = true)
@Mapping(target = "modificationCount", ignore = true)
@Mapping(target = "persisted", ignore = true)
@Mapping(target = "properties", qualifiedByName = "properties")
@Mapping(target = "tenantId", ignore = true)
public abstract void update(UpdateThemeDTO themeDTO, @MappingTarget Theme entity);

@Mapping(target = "id", ignore = true)
@Mapping(target = "controlTraceabilityManual", ignore = true)
@Mapping(target = "modificationCount", ignore = true)
@Mapping(target = "creationDate", ignore = true)
@Mapping(target = "creationUser", ignore = true)
@Mapping(target = "modificationDate", ignore = true)
@Mapping(target = "modificationUser", ignore = true)
@Mapping(target = "persisted", ignore = true)
@Mapping(target = "properties", qualifiedByName = "properties")
@Mapping(target = "tenantId", ignore = true)
public abstract Theme map(UpdateThemeDTO object);

@Named("properties")
public String mapToString(Object properties) {

Expand Down
1 change: 1 addition & 0 deletions src/main/openapi/onecx-image-internal-openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ paths:
required: true
schema:
minimum: 1
maximum: 20000
type: integer
- name: refId
in: path
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/db/v1/2023-11-09-create-tables.xml
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
<column name="modificationuser" type="VARCHAR(255)"/>
<column name="data" type="BYTEA"/>
</createTable>
<addUniqueConstraint columnNames="ref_id, tenant_id" constraintName="image_constraints" tableName="image"/>
<addUniqueConstraint columnNames="ref_id, ref_type, tenant_id" constraintName="image_constraints" tableName="image"/>

</changeSet>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ void beforeAll() {

@Test
void methodExceptionTests() {
Assertions.assertDoesNotThrow(() -> dao.deleteQueryByRefId(null));
methodExceptionTests(() -> dao.deleteQueryByRefId("1"),
ImageDAO.ErrorKeys.FAILED_TO_DELETE_BY_REF_ID_QUERY);
methodExceptionTests(() -> dao.findByRefIdAndRefType(null, null),
ImageDAO.ErrorKeys.FIND_ENTITY_BY_REF_ID_REF_TYPE_FAILED);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,16 @@
import static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;
import static jakarta.ws.rs.core.Response.Status.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.tkit.onecx.theme.rs.internal.mappers.ExceptionMapper.ErrorKeys.CONSTRAINT_VIOLATIONS;

import java.io.File;
import java.util.Objects;
import java.util.Random;

import jakarta.ws.rs.core.HttpHeaders;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.tkit.onecx.theme.rs.internal.mappers.ExceptionMapper;
import org.tkit.quarkus.test.WithDBData;

import gen.org.tkit.onecx.image.rs.internal.model.ImageInfoDTO;
Expand Down Expand Up @@ -61,7 +62,7 @@ void uploadImageEmptyBody() {
.statusCode(BAD_REQUEST.getStatusCode())
.extract().as(ProblemDetailResponseDTO.class);

assertThat(exception.getErrorCode()).isEqualTo(ExceptionMapper.ErrorKeys.CONSTRAINT_VIOLATIONS.name());
assertThat(exception.getErrorCode()).isEqualTo(CONSTRAINT_VIOLATIONS.name());
assertThat(exception.getDetail()).isEqualTo("uploadImage.contentLength: must be greater than or equal to 1");
}

Expand Down Expand Up @@ -94,7 +95,7 @@ void uploadImage_shouldReturnBadRequest_whenImageIs() {

assertThat(exception.getErrorCode()).isEqualTo("PERSIST_ENTITY_FAILED");
assertThat(exception.getDetail()).isEqualTo(
"could not execute statement [ERROR: duplicate key value violates unique constraint 'image_constraints' Detail: Key (ref_id, tenant_id)=(themeNameUpload, default) already exists.]");
"could not execute statement [ERROR: duplicate key value violates unique constraint 'image_constraints' Detail: Key (ref_id, ref_type, tenant_id)=(themeNameUpload, logo, default) already exists.]");
}

@Test
Expand Down Expand Up @@ -254,4 +255,28 @@ void updateImage_returnNotFound_whenEntryNotExists() {
Assertions.assertNotNull(exception);
}

@Test
void testMaxUploadSize() {

var refId = "themeMaxUpload";

byte[] body = new byte[20001];
new Random().nextBytes(body);

var exception = given()
.pathParam("refId", refId)
.pathParam("refType", RefTypeDTO.LOGO)
.when()
.body(body)
.contentType(MEDIA_TYPE_IMAGE_PNG)
.post()
.then()
.statusCode(BAD_REQUEST.getStatusCode())
.extract().as(ProblemDetailResponseDTO.class);

assertThat(exception.getErrorCode()).isEqualTo(CONSTRAINT_VIOLATIONS.name());
assertThat(exception.getDetail()).isEqualTo(
"uploadImage.contentLength: must be less than or equal to 20000");

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@ void updateThemeTest() {
// update none existing theme
var themeDto = new UpdateThemeDTO();
themeDto.setName("test01");
themeDto.setModificationCount(2);
themeDto.setModificationCount(0);
themeDto.setDescription("description-update");

given()
Expand Down Expand Up @@ -346,7 +346,7 @@ void updateThemeWithExistingNameTest() {

var themeDto = new UpdateThemeDTO();
themeDto.setName("themeWithoutPortal");
themeDto.setModificationCount(2);
themeDto.setModificationCount(0);
themeDto.setDescription("description");

var exception = given()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ void updateThemeTest() {
// update none existing theme
var themeDto = new UpdateThemeDTO();
themeDto.setName("test01");
themeDto.setModificationCount(2);
themeDto.setModificationCount(0);
themeDto.setDescription("description-update");

given()
Expand Down Expand Up @@ -290,6 +290,15 @@ void updateThemeTest() {
.extract()
.body().as(ThemeDTO.class);

// update theme with wrong modificationCount
given()
.contentType(APPLICATION_JSON)
.body(themeDto)
.when()
.pathParam("id", "11-111")
.put("{id}")
.then().statusCode(BAD_REQUEST.getStatusCode());

assertThat(dto).isNotNull();
assertThat(dto.getDescription()).isEqualTo(themeDto.getDescription());

Expand All @@ -300,7 +309,7 @@ void updateThemeWithExistingNameTest() {

var themeDto = new UpdateThemeDTO();
themeDto.setName("themeWithoutPortal");
themeDto.setModificationCount(2);
themeDto.setModificationCount(0);
themeDto.setDescription("description");

var exception = given()
Expand Down
1 change: 1 addition & 0 deletions src/test/resources/data/testdata-external.xml
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@


<IMAGE guid="i1" optlock="0" mime_type="image/x-icon" data_length="3" data="123456667890123456" ref_type="favicon" ref_id="test1" tenant_id="default" />
<IMAGE guid="i2" optlock="0" mime_type="image/x-icon" data_length="3" data="123456667890123456" ref_type="favicon" ref_id="test1" tenant_id="tenant-100" />
</dataset>

0 comments on commit af91904

Please sign in to comment.