Paperless / rebuild
Course 2 28ef273

Tests as architectural evidence

Snapshot 28ef273Markdown

Assessment review: The review ran all 131 existing tests successfully. Five isolated diagnostic assertions still failed, exposing three correctness issues. See the evidence and scope.

Use tests to establish behavior at the boundary that can actually fail. A passing mocked service test does not establish database locking; a passing context startup does not establish authorization for every route.

Match evidence to the claim

Claim Relevant existing evidence Remaining limit
Business code avoids JPA imports PersistenceBoundaryTest Source-text checks are not a complete dependency analysis
Models retain optimistic version DomainVersionPersistenceTest Does not cover every concurrent schedule
Adapter mapping works with persistence JpaDocumentPersistenceTest Database/profile behavior still matters
Domain rules choose correct branches DocumentServiceImplTest Mocks do not reproduce transaction proxies
HTTP security is wired correctly DocumentSecurityIntegrationTest Cases tested define the evidence, not all possible inputs
Search semantics match the implementation SearchServiceImplTest No scalability guarantee

Read fixtures and assertions

Start at each test's setup. Determine whether it constructs a service directly, imports generated mapper implementations, loads Spring, or persists entities. Mockito injection targets ServiceImpl, while collaborators are mocked through service/persistence interfaces. An interface cannot be instantiated as the system under test.

Look for intentional failures and verify the resulting exception/status and absence of unwanted writes. For filesystem tests, inspect setup/cleanup and transaction-synchronization handling. A manually invoked callback is useful unit evidence but should not be described as a real commit test.

Run the practice checks

From a practice backend checkout with its Java 25 toolchain and wrapper dependencies available:

./gradlew test --tests '*PersistenceBoundaryTest'
./gradlew test --tests '*DomainVersionPersistenceTest' --tests '*JpaDocumentPersistenceTest'
./gradlew test --tests '*DocumentServiceImplTest' --tests '*DocumentSecurityIntegrationTest'
./gradlew test

Inspect the test resources and annotations to understand the active database. Reproduce database-sensitive constraints and concurrency behavior on the intended PostgreSQL configuration before drawing production conclusions from an embedded-database run. Do not run migration exercises against a database you want to preserve.

Practice

Deliberately break version propagation in a practice mapper and find which test fails. Restore it. Introduce a forbidden entity import and confirm the architecture tripwire fires. Then describe a dependency violation that the text scanner could miss and propose a more precise check.

Create an evidence ledger with command, environment, result, and limitation. “Test exists” and “test passed in this environment” are separate statements.

Verification gate

Choose the smallest meaningful test for a mapping change, service rule, and authorization wiring change. Explain why each needs its selected environment. The course site checks rendered content, source hashes, and navigation. The separate assessment review also ran the backend suite and diagnostic checks; those H2 results do not validate PostgreSQL migrations or the complete processing deployment.

Read the implementation

Complete source walkthrough

Read these pinned files alongside the explanation above. These are the inspected implementation, not the capstone solution.

PersistenceBoundaryTest.kt

Browse source

package at.fhtw.swen3.paperless.architecture

import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import java.nio.file.Files
import java.nio.file.Path

class PersistenceBoundaryTest {
    @Test
    fun business_layers_do_not_import_jpa_implementation_details_ok() {
        val sources = sourcesOutsidePersistence()

        assertThat(sources).isNotEmpty()
        assertThat(sources).allSatisfy { path ->
            assertThat(Files.readString(path)).describedAs(path.toString())
                .doesNotContain("import jakarta.persistence.", ".entity.", ".persistence.repository.")
                .doesNotContain(".persistence.mapper.", "import org.springframework.data.jpa.")
        }
    }

    @Test
    fun domain_persistence_interfaces_do_not_leak_jpa_types_ok() {
        val interfaces = persistenceInterfaces()

        assertThat(interfaces).isNotEmpty()
        assertThat(interfaces).allSatisfy { path ->
            assertThat(Files.readString(path)).describedAs(path.toString())
                .doesNotContain("jakarta.persistence.", ".entity.", ".persistence.repository.")
                .doesNotContain("JpaRepository", "EntityManager", ".persistence.mapper.")
        }
    }

    private fun sourcesOutsidePersistence(): List<Path> = Files.walk(Path.of("src/main/kotlin")).use { paths ->
        paths.filter { it.toString().endsWith(".kt") && !it.toString().contains("/persistence/") }
            .filter { path ->
                listOf("/service/", "/controller/", "/model/", "/mapper/").any { path.toString().contains(it) }
            }.toList()
    }

    private fun persistenceInterfaces(): List<Path> = Files.walk(Path.of("src/main/kotlin")).use { paths ->
        paths.filter { it.fileName.toString().endsWith("Persistence.kt") }
            .filter { !it.fileName.toString().startsWith("Jpa") }.toList()
    }
}

DomainVersionPersistenceTest.kt

Browse source

package at.fhtw.swen3.paperless.common.entity

import at.fhtw.swen3.paperless.common.mapper.MappingConverters

import at.fhtw.swen3.paperless.documenttype.model.DocumentType
import at.fhtw.swen3.paperless.documenttype.persistence.DocumentTypePersistence
import at.fhtw.swen3.paperless.documenttype.persistence.JpaDocumentTypePersistence
import at.fhtw.swen3.paperless.documenttype.persistence.mapper.DocumentTypeEntityMapperImpl

import at.fhtw.swen3.paperless.team.model.Team
import at.fhtw.swen3.paperless.team.persistence.JpaTeamPersistence
import at.fhtw.swen3.paperless.team.persistence.mapper.TeamEntityMapperImpl

import at.fhtw.swen3.paperless.team.persistence.TeamPersistence
import at.fhtw.swen3.paperless.user.model.User
import at.fhtw.swen3.paperless.user.persistence.JpaUserPersistence
import at.fhtw.swen3.paperless.user.persistence.mapper.UserEntityMapperImpl

import at.fhtw.swen3.paperless.user.persistence.UserPersistence
import jakarta.persistence.EntityManager
import java.time.Instant
import java.util.UUID
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest
import org.springframework.context.annotation.Import
import org.springframework.dao.OptimisticLockingFailureException

@DataJpaTest
@Import(
    JpaUserPersistence::class,
    JpaTeamPersistence::class,
    JpaDocumentTypePersistence::class,
    UserEntityMapperImpl::class,
    TeamEntityMapperImpl::class,
    DocumentTypeEntityMapperImpl::class,
    MappingConverters::class
)
class DomainVersionPersistenceTest(@Autowired private val entityManager: EntityManager) {
    @Autowired private lateinit var users: UserPersistence
    @Autowired private lateinit var teams: TeamPersistence
    @Autowired private lateinit var types: DocumentTypePersistence

    @Test
    fun user_updates_preserve_versions_and_reject_stale_models_ok() {
        // given
        val saved = users.save(User(null, "version-user", "unused", Instant.now(), null))
        flushAndClear()
        val id = requireNotNull(saved.id)
        val initial = users.findById(id).orElseThrow()

        // when
        users.save(initial.copy(username = "version-user-1"))
        flushAndClear()
        val updated = users.findById(id).orElseThrow()
        users.save(updated.copy(username = "version-user-2"))
        flushAndClear()

        // then
        assertThat(updated.version).isEqualTo(initial.version + 1)
        assertThat(users.findById(id).orElseThrow().version).isEqualTo(initial.version + 2)
        assertThatThrownBy { users.save(initial.copy(username = "stale-user")) }
            .isInstanceOf(OptimisticLockingFailureException::class.java)
    }

    @Test
    fun team_updates_preserve_versions_and_reject_stale_models_ok() {
        // given
        val saved = teams.save(Team(null, "Version team", null, Instant.now(), null, UUID.randomUUID()))
        flushAndClear()
        val id = requireNotNull(saved.id)
        val initial = teams.findById(id).orElseThrow()

        // when
        teams.save(initial.copy(name = "Version team 1"))
        flushAndClear()
        val updated = teams.findById(id).orElseThrow()
        teams.save(updated.copy(name = "Version team 2"))
        flushAndClear()

        // then
        assertThat(updated.version).isEqualTo(initial.version + 1)
        assertThat(teams.findById(id).orElseThrow().version).isEqualTo(initial.version + 2)
        assertThatThrownBy { teams.save(initial.copy(name = "Stale team")) }
            .isInstanceOf(OptimisticLockingFailureException::class.java)
    }

    @Test
    fun document_type_updates_preserve_versions_and_reject_stale_models_ok() {
        // given
        val saved = types.save(DocumentType(null, "Version type", null))
        flushAndClear()
        val id = requireNotNull(saved.id)
        val initial = types.findById(id).orElseThrow()

        // when
        types.save(initial.copy(name = "Version type 1"))
        flushAndClear()
        val updated = types.findById(id).orElseThrow()
        types.save(updated.copy(name = "Version type 2"))
        flushAndClear()

        // then
        assertThat(updated.version).isEqualTo(initial.version + 1)
        assertThat(types.findById(id).orElseThrow().version).isEqualTo(initial.version + 2)
        assertThatThrownBy { types.save(initial.copy(name = "Stale type")) }
            .isInstanceOf(OptimisticLockingFailureException::class.java)
    }

    private fun flushAndClear() {
        entityManager.flush()
        entityManager.clear()
    }
}

JpaDocumentPersistenceTest.kt

Browse source

package at.fhtw.swen3.paperless.document.persistence

import at.fhtw.swen3.paperless.common.mapper.MappingConverters

import at.fhtw.swen3.paperless.document.model.Document
import at.fhtw.swen3.paperless.document.model.ProcessingStatus
import at.fhtw.swen3.paperless.document.persistence.mapper.DocumentEntityMapperImpl

import at.fhtw.swen3.paperless.documenttype.entity.DocumentTypeEntity
import at.fhtw.swen3.paperless.documenttype.persistence.mapper.DocumentTypeEntityMapperImpl

import at.fhtw.swen3.paperless.team.model.Role
import at.fhtw.swen3.paperless.team.model.TeamMember
import at.fhtw.swen3.paperless.team.persistence.JpaTeamMemberPersistence
import at.fhtw.swen3.paperless.team.entity.TeamEntity
import at.fhtw.swen3.paperless.team.persistence.mapper.TeamEntityMapper
import at.fhtw.swen3.paperless.team.persistence.mapper.TeamEntityMapperImpl
import at.fhtw.swen3.paperless.team.persistence.mapper.TeamMemberEntityMapperImpl

import at.fhtw.swen3.paperless.team.persistence.repository.TeamMemberRepository
import at.fhtw.swen3.paperless.user.entity.UserEntity
import at.fhtw.swen3.paperless.user.persistence.mapper.UserEntityMapper
import at.fhtw.swen3.paperless.user.persistence.mapper.UserEntityMapperImpl

import jakarta.persistence.EntityManager
import java.time.Instant
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertAll
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest
import org.springframework.context.annotation.Import
import jakarta.persistence.OptimisticLockException

@DataJpaTest
@Import(
    JpaDocumentPersistence::class,
    JpaDocumentReferencesPersistence::class,
    JpaTeamMemberPersistence::class,
    DocumentEntityMapperImpl::class,
    DocumentTypeEntityMapperImpl::class,
    TeamEntityMapperImpl::class,
    UserEntityMapperImpl::class,
    TeamMemberEntityMapperImpl::class,
    MappingConverters::class
)
class JpaDocumentPersistenceTest(
    @Autowired private val persistence: DocumentPersistence,
    @Autowired private val references: DocumentReferencesPersistence,
    @Autowired private val memberships: JpaTeamMemberPersistence,
    @Autowired private val memberRepository: TeamMemberRepository,
    @Autowired private val entityManager: EntityManager,
    @Autowired private val teamEntityMapper: TeamEntityMapper,
    @Autowired private val userEntityMapper: UserEntityMapper
) {
    @Test
    fun document_mapping_resolves_associations_and_preserves_version_ok() {
        val user = UserEntity(username = "adapter-user", password = "hash", createdAt = Instant.now())
        val type = DocumentTypeEntity(name = "Invoice", description = "Bills")
        entityManager.persist(user)
        entityManager.persist(type)
        val document = document(requireNotNull(user.id)).copy(
            documentType = references.findDocumentType(requireNotNull(type.id))
        )

        val saved = persistence.save(document)
        persistence.flush()
        entityManager.clear()
        val loaded = persistence.findById(requireNotNull(saved.id)).orElseThrow()

        assertAll(
            { assertThat(saved.id).isNotNull() },
            { assertThat(saved.documentType?.name).isEqualTo("Invoice") },
            { assertThat(loaded.documentType?.description).isEqualTo("Bills") },
            { assertThat(loaded.ownerId).isEqualTo(user.id) }
        )
        persistence.save(loaded.copy(title = "Updated"))
        persistence.flush()
        entityManager.clear()
        val updated = persistence.findById(requireNotNull(saved.id)).orElseThrow()

        assertAll(
            { assertThat(updated.version).isEqualTo(loaded.version + 1) },
            { assertThat(updated.title).isEqualTo("Updated") }
        )
    }

    @Test
    fun refreshed_document_with_changed_version_ko() {
        val user = UserEntity(username = "stale-user", password = "hash", createdAt = Instant.now())
        entityManager.persist(user)
        val saved = persistence.save(document(requireNotNull(user.id)))
        persistence.flush()
        val initial = persistence.findById(requireNotNull(saved.id)).orElseThrow()
        persistence.save(initial.copy(title = "Concurrent update"))
        persistence.flush()

        assertThatThrownBy { persistence.refreshUnchanged(initial) }
            .isInstanceOf(OptimisticLockException::class.java)
    }

    @Test
    fun membership_role_update_keeps_identity_and_full_domain_relationships_ok() {
        val user = UserEntity(username = "member-user", password = "hash", createdAt = Instant.now())
        entityManager.persist(user)
        val team = TeamEntity(name = "Adapter team", ownerId = requireNotNull(user.id), createdAt = Instant.now())
        entityManager.persist(team)
        val member = TeamMember(
            teamEntityMapper.toModel(team), userEntityMapper.toModel(user), Role.READ_WRITE, Instant.now()
        )
        val created = memberships.save(member)
        entityManager.flush()
        val teamId = requireNotNull(team.id)
        val userId = requireNotNull(user.id)
        val originalId = requireNotNull(memberRepository.findByTeamIdAndUserId(teamId, userId)).id

        val updated = memberships.save(created.copy(role = Role.ADMIN))
        entityManager.flush()
        val stored = requireNotNull(memberRepository.findByTeamIdAndUserId(teamId, userId))

        assertAll(
            { assertThat(created.team.name).isEqualTo("Adapter team") },
            { assertThat(created.user.username).isEqualTo("member-user") },
            { assertThat(updated.role).isEqualTo(Role.ADMIN) },
            { assertThat(stored.id).isEqualTo(originalId) },
            { assertThat(memberRepository.count()).isEqualTo(1) }
        )
    }

    private fun document(ownerId: java.util.UUID) = Document(
        id = null,
        title = "Invoice",
        originalFilename = "invoice.txt",
        contentType = "text/plain",
        fileSize = 10,
        status = ProcessingStatus.PENDING,
        ocrContent = null,
        summary = null,
        storageKey = "documents/invoice.txt",
        documentType = null,
        createdAt = Instant.now(),
        updatedAt = Instant.now(),
        ownerId = ownerId
    )
}

application.yaml

Browse source

spring:
  application:
    name: paperless-test
  flyway:
    enabled: false
  datasource:
    url: jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MODE=PostgreSQL
    driver-class-name: org.h2.Driver
    username: sa
    password: ""
  jpa:
    database-platform: org.hibernate.dialect.H2Dialect
    hibernate:
      ddl-auto: create-drop
    open-in-view: false

springdoc:
  api-docs:
    enabled: false
  swagger-ui:
    enabled: false

elasticsearch:
  host: localhost
  port: 9200
  username: elastic
  password: ""
Ready to move on?

Complete the practice and verification gate first.

Search chapters, reference and source filenames.