Skip to content

Commit

Permalink
Merge pull request #6 from DiSSCo/feature/additional-unit-tests
Browse files Browse the repository at this point in the history
Add unit tests and integration tests
  • Loading branch information
samleeflang authored Nov 2, 2022
2 parents 6f3cedd + b8969db commit 92c30aa
Show file tree
Hide file tree
Showing 11 changed files with 355 additions and 25 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/build.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ jobs:
run: mvn -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar
-Dsonar.projectKey=DiSSCo_${{ github.event.repository.name }}
-Dsonar.exclusions=**/jooq/**
-Dsonar.coverage.exclusions=**/properties/**,**/configuration/**
-Dsonar.coverage.exclusions=**/properties/**,**/configuration/**,**/domain/**,**/exception/**
- name: Login to Public ECR
if: github.event_name != 'pull_request'
uses: docker/login-action@v1
Expand Down
52 changes: 47 additions & 5 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
<jakarta.json.version>2.1.1</jakarta.json.version>
<json-patch.version>1.13</json-patch.version>
<keycloak-adapter-bom.version>16.1.1</keycloak-adapter-bom.version>
<testcontainers.version>1.17.5</testcontainers.version>
<sonar.organization>dissco</sonar.organization>
<sonar.host.url>https://sonarcloud.io</sonar.host.url>
<sonar.coverage.jacoco.xmlReportPaths>../app-it/target/site/jacoco-aggregate/jacoco.xml
Expand All @@ -34,6 +35,13 @@
<scope>import</scope>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-bom</artifactId>
<version>${testcontainers.version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
Expand Down Expand Up @@ -115,6 +123,26 @@
<version>4.8.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
Expand All @@ -135,19 +163,33 @@
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>prepare-agent-integration</id>
<goals>
<goal>prepare-agent-integration</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<formats>
<format>XML</format>
</formats>
</configuration>
</execution>
<execution>
<id>report-integration</id>
<goals>
<goal>report-integration</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<configuration>
<useSystemClassLoader>false</useSystemClassLoader>
</configuration>
</plugin>
<plugin>
<groupId>org.jooq</groupId>
<artifactId>jooq-codegen-maven</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import java.time.Instant;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.jooq.DSLContext;
import org.jooq.JSONB;
Expand All @@ -24,15 +23,6 @@ public class DigitalSpecimenRepository {
private final DSLContext context;
private final ObjectMapper mapper;

public Optional<DigitalSpecimenRecord> getDigitalSpecimen(String physicalSpecimenId) {
return context.select(NEW_DIGITAL_SPECIMEN.asterisk())
.distinctOn(NEW_DIGITAL_SPECIMEN.ID)
.from(NEW_DIGITAL_SPECIMEN)
.where(NEW_DIGITAL_SPECIMEN.PHYSICAL_SPECIMEN_ID.eq(physicalSpecimenId))
.orderBy(NEW_DIGITAL_SPECIMEN.ID, NEW_DIGITAL_SPECIMEN.VERSION.desc())
.fetchOptional(this::mapDigitalSpecimen);
}

private DigitalSpecimenRecord mapDigitalSpecimen(Record dbRecord) {
DigitalSpecimen digitalSpecimen = null;
try {
Expand All @@ -58,7 +48,8 @@ private DigitalSpecimenRecord mapDigitalSpecimen(Record dbRecord) {
digitalSpecimen);
}

public int[] createDigitalSpecimenRecord(Collection<DigitalSpecimenRecord> digitalSpecimenRecords) {
public int[] createDigitalSpecimenRecord(
Collection<DigitalSpecimenRecord> digitalSpecimenRecords) {
var queries = digitalSpecimenRecords.stream().map(this::specimenToQuery).toList();
return context.batch(queries).execute();
}
Expand All @@ -83,7 +74,8 @@ private Query specimenToQuery(DigitalSpecimenRecord digitalSpecimenRecord) {
.set(NEW_DIGITAL_SPECIMEN.SOURCE_SYSTEM_ID,
digitalSpecimenRecord.digitalSpecimen().sourceSystemId())
.set(NEW_DIGITAL_SPECIMEN.CREATED, digitalSpecimenRecord.created())
.set(NEW_DIGITAL_SPECIMEN.LAST_CHECKED, Instant.now()).set(NEW_DIGITAL_SPECIMEN.DATA,
.set(NEW_DIGITAL_SPECIMEN.LAST_CHECKED, Instant.now())
.set(NEW_DIGITAL_SPECIMEN.DATA,
JSONB.valueOf(digitalSpecimenRecord.digitalSpecimen().data().toString()))
.set(NEW_DIGITAL_SPECIMEN.ORIGINAL_DATA,
JSONB.valueOf(digitalSpecimenRecord.digitalSpecimen().originalData().toString()))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,9 @@ private Set<DigitalSpecimenRecord> updateExistingDigitalSpecimen(
var handleUpdates = updatedDigitalSpecimenTuples.stream().filter(
tuple -> handleNeedsUpdate(tuple.currentSpecimen().digitalSpecimen(),
tuple.digitalSpecimen())).toList();
handleService.updateHandles(handleUpdates);
if (!handleUpdates.isEmpty()){
handleService.updateHandles(handleUpdates);
}

var digitalSpecimenRecords = updatedDigitalSpecimenTuples.stream().collect(Collectors.toMap(
tuple -> new DigitalSpecimenRecord(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package eu.dissco.core.digitalspecimenprocessor.repository;

import static org.testcontainers.containers.PostgreSQLContainer.IMAGE;

import com.zaxxer.hikari.HikariDataSource;
import org.flywaydb.core.Flyway;
import org.jooq.DSLContext;
import org.jooq.SQLDialect;
import org.jooq.impl.DefaultDSLContext;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;

@Testcontainers
public class BaseRepositoryIT {

private static final DockerImageName POSTGIS =
DockerImageName.parse("postgres:13.7").asCompatibleSubstituteFor(IMAGE);

@Container
private static final PostgreSQLContainer<?> CONTAINER = new PostgreSQLContainer<>(POSTGIS);
protected DSLContext context;
private HikariDataSource dataSource;

@BeforeEach
void prepareDatabase() {
dataSource = new HikariDataSource();
dataSource.setJdbcUrl(CONTAINER.getJdbcUrl());
dataSource.setUsername(CONTAINER.getUsername());
dataSource.setPassword(CONTAINER.getPassword());
dataSource.setMaximumPoolSize(1);
dataSource.setConnectionInitSql(CONTAINER.getTestQueryString());
Flyway.configure().mixed(true).dataSource(dataSource).load().migrate();
context = new DefaultDSLContext(dataSource, SQLDialect.POSTGRES);
}

@AfterEach
void disposeDataSource() {
dataSource.close();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package eu.dissco.core.digitalspecimenprocessor.repository;

import static eu.dissco.core.digitalspecimenprocessor.database.jooq.Tables.NEW_DIGITAL_SPECIMEN;
import static eu.dissco.core.digitalspecimenprocessor.utils.TestUtils.HANDLE;
import static eu.dissco.core.digitalspecimenprocessor.utils.TestUtils.MAPPER;
import static eu.dissco.core.digitalspecimenprocessor.utils.TestUtils.PHYSICAL_SPECIMEN_ID;
import static eu.dissco.core.digitalspecimenprocessor.utils.TestUtils.givenDigitalSpecimenRecord;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mockStatic;

import java.sql.BatchUpdateException;
import java.time.Instant;
import java.util.List;
import org.jooq.Record1;
import org.jooq.exception.DataAccessException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.postgresql.util.PSQLException;

class DigitalSpecimenRepositoryIT extends BaseRepositoryIT {

private static final Instant UPDATED_TIMESTAMP = Instant.parse("2022-11-02T13:05:24.00Z");


private DigitalSpecimenRepository repository;

@BeforeEach
void setup() {
repository = new DigitalSpecimenRepository(context, MAPPER);
}

@AfterEach
void destroy() {
context.truncate(NEW_DIGITAL_SPECIMEN).execute();
}

@Test
void testGetDigitalSpecimensEmpty() {
// Given

// When
var result = repository.getDigitalSpecimens(List.of(PHYSICAL_SPECIMEN_ID));

// Then
assertThat(result).isEmpty();
}

@Test
void testGetDigitalSpecimens() {
// Given
repository.createDigitalSpecimenRecord(
List.of(
givenDigitalSpecimenRecord(),
givenDigitalSpecimenRecord("20.5000.1025/XXX-XXX-XXX", "TEST_1"),
givenDigitalSpecimenRecord("20.5000.1025/YYY-YYY-YYY", "TEST_2")));

// When
var result = repository.getDigitalSpecimens(List.of(PHYSICAL_SPECIMEN_ID));

// Then
assertThat(result.get(0)).isEqualTo(givenDigitalSpecimenRecord());
}

@Test
void testUpdateVersionSpecimens() {
// Given
repository.createDigitalSpecimenRecord(
List.of(
givenDigitalSpecimenRecord(),
givenDigitalSpecimenRecord("20.5000.1025/XXX-XXX-XXX", "TEST_1"),
givenDigitalSpecimenRecord("20.5000.1025/YYY-YYY-YYY", "TEST_2")));

// When
var result = repository.createDigitalSpecimenRecord(List.of(givenDigitalSpecimenRecord(2)));

// Then
assertThat(result).isEqualTo(new int[]{1});
}

@Test
void testUpdateLastChecked() {
// Given
repository.createDigitalSpecimenRecord(
List.of(
givenDigitalSpecimenRecord(),
givenDigitalSpecimenRecord("20.5000.1025/XXX-XXX-XXX", "TEST_1"),
givenDigitalSpecimenRecord("20.5000.1025/YYY-YYY-YYY", "TEST_2")));

// When
try (MockedStatic<Instant> mockedStatic = mockStatic(Instant.class)) {
mockedStatic.when(Instant::now).thenReturn(UPDATED_TIMESTAMP);
repository.updateLastChecked(List.of(HANDLE));
}

// Then
var result = context.select(NEW_DIGITAL_SPECIMEN.LAST_CHECKED)
.from(NEW_DIGITAL_SPECIMEN)
.where(NEW_DIGITAL_SPECIMEN.ID.eq(HANDLE)).fetchOne(Record1::value1);
assertThat(result).isEqualTo(UPDATED_TIMESTAMP);
}

@Test
void testInsertDuplicateSpecimens() {
// Given
var records = List.of(
givenDigitalSpecimenRecord(),
givenDigitalSpecimenRecord("20.5000.1025/XXX-XXX-XXX", "TEST_1"),
givenDigitalSpecimenRecord("20.5000.1025/XXX-XXX-XXX", "TEST_2"));

// When
var exception = assertThrows(DataAccessException.class, () -> {
repository.createDigitalSpecimenRecord(records);
});

// Then
assertThat(exception).hasCauseInstanceOf(BatchUpdateException.class).hasRootCauseInstanceOf(
PSQLException.class);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package eu.dissco.core.digitalspecimenprocessor.repository;

import static eu.dissco.core.digitalspecimenprocessor.database.jooq.Tables.HANDLES;
import static eu.dissco.core.digitalspecimenprocessor.utils.TestUtils.CREATED;
import static eu.dissco.core.digitalspecimenprocessor.utils.TestUtils.HANDLE;
import static org.assertj.core.api.Assertions.assertThat;

import eu.dissco.core.digitalspecimenprocessor.domain.HandleAttribute;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.jooq.Record1;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

class HandleRepositoryIT extends BaseRepositoryIT {

private HandleRepository repository;

@BeforeEach
void setup() {
repository = new HandleRepository(context);
}

@AfterEach
void destroy() {
context.truncate(HANDLES).execute();
}

@Test
void testCreateHandle() {
// Given
var handleAttributes = givenHandleAttributes();

// When
repository.createHandle(HANDLE, CREATED, handleAttributes);

// Then
var handles = context.selectFrom(HANDLES).fetch();
assertThat(handles).hasSize(handleAttributes.size());
}

@Test
void testUpdateHandleAttributes(){
// Given
var handleAttributes = givenHandleAttributes();
repository.createHandle(HANDLE, CREATED, handleAttributes);
var updatedHandle = new HandleAttribute(11, "pidKernelMetadataLicense",
"anotherLicenseType".getBytes(StandardCharsets.UTF_8));

// When
repository.updateHandleAttributes(HANDLE, CREATED, List.of(updatedHandle));

// Then
var result = context.select(HANDLES.DATA)
.from(HANDLES)
.where(HANDLES.HANDLE.eq(HANDLE.getBytes(StandardCharsets.UTF_8)))
.and(HANDLES.TYPE.eq("issueNumber".getBytes(StandardCharsets.UTF_8)))
.fetchOne(Record1::value1);
assertThat(result).isEqualTo("2".getBytes(StandardCharsets.UTF_8));
}

private List<HandleAttribute> givenHandleAttributes() {
return List.of(
new HandleAttribute(1, "pid",
("https://hdl.handle.net/" + HANDLE).getBytes(StandardCharsets.UTF_8)),
new HandleAttribute(11, "pidKernelMetadataLicense",
"https://creativecommons.org/publicdomain/zero/1.0/".getBytes(StandardCharsets.UTF_8)),
new HandleAttribute(7, "issueNumber", "1".getBytes(StandardCharsets.UTF_8)),
new HandleAttribute(100, "HS_ADMIN", "TEST_ADMIN_STRING".getBytes(StandardCharsets.UTF_8))
);
}

}
Loading

0 comments on commit 92c30aa

Please sign in to comment.