Skip to content

Task/critical tests#40

Merged
Tyreviel merged 10 commits into
mainfrom
task/critical-tests
Apr 9, 2026
Merged

Task/critical tests#40
Tyreviel merged 10 commits into
mainfrom
task/critical-tests

Conversation

@Tyreviel

@Tyreviel Tyreviel commented Apr 9, 2026

Copy link
Copy Markdown
Collaborator

closes #33

Summary by CodeRabbit

  • Tests
    • Added integration tests for audit: request logging, URI-derived context capture, and sensitive-data sanitization (query params and JSON fields).
    • Added unit tests for case and employee services enforcing role-based access control and error cases.
    • Added REST controller tests for audit, case, and employee endpoints validating HTTP responses, filters, pagination, and security.
    • Added service-level tests for audit listing and authorization rules.
    • Updated security adapter tests to use AssertJ assertions.
  • Chores
    • Removed extraneous trailing blank lines in two DTO/entity files.

@coderabbitai

coderabbitai Bot commented Apr 9, 2026

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 1eed1ba8-2b4c-4e08-ace3-7e7c0b416e7d

📥 Commits

Reviewing files that changed from the base of the PR and between b3c5af8 and 79874ae.

📒 Files selected for processing (9)
  • src/main/java/org/example/projektarendehantering/infrastructure/persistence/EmployeeEntity.java
  • src/main/java/org/example/projektarendehantering/presentation/dto/EmployeeDTO.java
  • src/test/java/org/example/projektarendehantering/application/service/AuditServiceTest.java
  • src/test/java/org/example/projektarendehantering/application/service/CaseServiceTest.java
  • src/test/java/org/example/projektarendehantering/application/service/EmployeeServiceTest.java
  • src/test/java/org/example/projektarendehantering/infrastructure/security/SecurityActorAdapterTest.java
  • src/test/java/org/example/projektarendehantering/presentation/rest/AuditControllerTest.java
  • src/test/java/org/example/projektarendehantering/presentation/rest/CaseControllerTest.java
  • src/test/java/org/example/projektarendehantering/presentation/rest/EmployeeControllerTest.java
💤 Files with no reviewable changes (2)
  • src/main/java/org/example/projektarendehantering/presentation/dto/EmployeeDTO.java
  • src/main/java/org/example/projektarendehantering/infrastructure/persistence/EmployeeEntity.java
✅ Files skipped from review due to trivial changes (2)
  • src/test/java/org/example/projektarendehantering/application/service/CaseServiceTest.java
  • src/test/java/org/example/projektarendehantering/application/service/AuditServiceTest.java
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/test/java/org/example/projektarendehantering/presentation/rest/AuditControllerTest.java
  • src/test/java/org/example/projektarendehantering/application/service/EmployeeServiceTest.java
  • src/test/java/org/example/projektarendehantering/presentation/rest/EmployeeControllerTest.java
  • src/test/java/org/example/projektarendehantering/presentation/rest/CaseControllerTest.java

📝 Walkthrough

Walkthrough

Adds multiple new unit and integration tests for audit logging, controllers, and services, plus minor whitespace cleanups in two DTO/entity files. Tests exercise audit sanitization, URI-derived context capture, and role-based authorization across Case and Employee APIs.

Changes

Cohort / File(s) Summary
Audit tests
src/test/java/org/example/projektarendehantering/AuditIntegrationTest.java, src/test/java/org/example/projektarendehantering/application/service/AuditServiceTest.java, src/test/java/org/example/projektarendehantering/presentation/rest/AuditControllerTest.java
New integration and unit tests verifying audit persistence, sanitization of sensitive query params/JSON (e.g., password, token, secret, ssn), controller listing/filter parameters, and URI-derived caseId capture.
Case tests
src/test/java/org/example/projektarendehantering/application/service/CaseServiceTest.java, src/test/java/org/example/projektarendehantering/presentation/rest/CaseControllerTest.java
Unit and MVC tests for CaseService/CaseController covering role-based access (DOCTOR, NURSE, MANAGER, PATIENT), get/create flows, and HTTP response cases (200, 404).
Employee tests
src/test/java/org/example/projektarendehantering/application/service/EmployeeServiceTest.java, src/test/java/org/example/projektarendehantering/presentation/rest/EmployeeControllerTest.java
Unit and MVC tests validating manager permissions, denial for other roles, and employee list/get/create endpoints (including CSRF usage in POST).
Security adapter test
src/test/java/org/example/projektarendehantering/infrastructure/security/SecurityActorAdapterTest.java
Updated assertions to AssertJ and added a private generic doReturn(Object) test helper; tests cover authenticated/anonymous behavior and authority-to-actor mapping.
Whitespace cleanup
src/main/java/org/example/projektarendehantering/infrastructure/persistence/EmployeeEntity.java, src/main/java/org/example/projektarendehantering/presentation/dto/EmployeeDTO.java
Removed trailing blank lines; no behavioral changes.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 I hopped through code to plant a test,
Redacted secrets tucked in their nest,
Roles checked kindly, endpoints probed bright,
Audit logs whisper each HTTP byte,
Hoppity hooray — tests sleep tight!

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (1 warning, 2 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 2.08% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Task/critical tests' is vague and generic; it uses non-descriptive terms that don't convey meaningful information about the specific changes (e.g., which tests, for which components). Consider using a more specific title like 'Add comprehensive test suite for audit, case, employee, and security components' that clearly describes the scope of test additions.
Linked Issues check ❓ Inconclusive The PR description references 'closes #33' but the linked issue #33 has only a title with no description; without understanding the specific requirements from issue #33, full compliance validation is not possible. Provide the full description and requirements from linked issue #33 to validate whether the test coverage meets all specified coding objectives.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Out of Scope Changes check ✅ Passed The PR primarily adds comprehensive test classes; minor trailing whitespace cleanups in EmployeeEntity.java and EmployeeDTO.java appear incidental and are appropriately scoped.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch task/critical-tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/test/java/org/example/projektarendehantering/AuditIntegrationTest.java`:
- Around line 56-60: The test uses auditEventRepository.findAll() and picks the
last element (events.get(events.size() - 1)), which is nondeterministic; change
the test to fetch a deterministically ordered event (for example use a
repository query that orders by timestamp or id such as
findFirstByOrderByTimestampDesc or findTopByOrderByIdDesc, or sort the returned
list by AuditEventEntity.getTimestamp() before selecting the latest) and update
assertions that reference latest.getRequestPath() accordingly; apply the same
change pattern for the other occurrences flagged (lines around the other
assertions in AuditIntegrationTest).

In
`@src/test/java/org/example/projektarendehantering/presentation/rest/AuditControllerTest.java`:
- Around line 76-87: The test list_withFilters_shouldPassParameters currently
only asserts HTTP 200 but doesn't verify that controller forwarded
caseId/page/size to auditService.listEvents; update the test to verify
auditService.listEvents was called (e.g., verify(auditService).listEvents(...))
and assert the Pageable argument reflects page=1 and size=10 by using an
ArgumentCaptor<Pageable> or Mockito.argThat(Pageable ->
pageable.getPageNumber()==1 && pageable.getPageSize()==10), and also assert the
caseId is passed via eq(caseId) and the method is invoked once. Ensure you
reference the existing test method name list_withFilters_shouldPassParameters
and the target method auditService.listEvents when adding the verify/assertion.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e1b4acee-d0a2-4a3d-bebc-48d84576a8ac

📥 Commits

Reviewing files that changed from the base of the PR and between 7416cec and 0a69e2b.

📒 Files selected for processing (7)
  • src/test/java/org/example/projektarendehantering/AuditIntegrationTest.java
  • src/test/java/org/example/projektarendehantering/application/service/CaseServiceTest.java
  • src/test/java/org/example/projektarendehantering/application/service/EmployeeServiceTest.java
  • src/test/java/org/example/projektarendehantering/infrastructure/security/SecurityActorAdapterTest.java
  • src/test/java/org/example/projektarendehantering/presentation/rest/AuditControllerTest.java
  • src/test/java/org/example/projektarendehantering/presentation/rest/CaseControllerTest.java
  • src/test/java/org/example/projektarendehantering/presentation/rest/EmployeeControllerTest.java

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (3)
src/test/java/org/example/projektarendehantering/application/service/AuditServiceTest.java (3)

59-67: Strengthen success-path assertions to validate DTO mapping output.

At Line 66 and Line 81, asserting only size can pass even if auditEventMapper.toDTO(...) returns wrong/null content. Assert the mapped DTO instance (or critical fields) to make these tests regression-resistant.

Suggested test assertion hardening
@@
-        when(auditEventMapper.toDTO(any())).thenReturn(new AuditEventDTO());
+        AuditEventDTO expectedDto = new AuditEventDTO();
+        when(auditEventMapper.toDTO(any())).thenReturn(expectedDto);
@@
-        assertThat(result.getContent()).hasSize(1);
+        assertThat(result.getContent()).containsExactly(expectedDto);
@@
-        when(auditEventMapper.toDTO(any())).thenReturn(new AuditEventDTO());
+        AuditEventDTO expectedDto = new AuditEventDTO();
+        when(auditEventMapper.toDTO(any())).thenReturn(expectedDto);
@@
-        assertThat(result.getContent()).hasSize(1);
+        assertThat(result.getContent()).containsExactly(expectedDto);

Also applies to: 75-82

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@src/test/java/org/example/projektarendehantering/application/service/AuditServiceTest.java`
around lines 59 - 67, The test currently only asserts page size, which won't
catch incorrect or null mapping results from auditEventMapper.toDTO; update
AuditServiceTest to assert the actual DTO content returned by
auditService.listEvents by stubbing auditEventMapper.toDTO to return a DTO with
known values (e.g., set an identifiable field on AuditEventDTO) and then assert
that result.getContent().get(0) (or its critical fields) equals those expected
values; target the test block that builds PageImpl<AuditEventEntity>, the
when(auditEventMapper.toDTO(...)) stub, and the final assertions so the test
validates both presence and correctness of the mapped AuditEventDTO.

85-91: Assert no audit-event repository access on denied requests.

For Line 88 and Line 97 denial paths, add interaction assertions to guarantee no audit read is performed before/while denying access.

Suggested security-focused interaction assertions
@@
 import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.verifyNoInteractions;
@@
     void listEvents_shouldDenyDoctorAccessToUnownedCase() {
         when(caseRepository.findAllByOwnerId(doctorActor.userId())).thenReturn(Collections.emptyList());
@@
                 .isInstanceOf(NotAuthorizedException.class)
                 .hasMessageContaining("Not allowed to view audit events for this case");
+
+        verifyNoInteractions(auditEventRepository);
     }
@@
     void listEvents_shouldDenyPatient() {
         Actor patientActor = new Actor(UUID.randomUUID(), Role.PATIENT);
@@
         assertThatThrownBy(() -> auditService.listEvents(patientActor, null, null, null, Pageable.unpaged()))
                 .isInstanceOf(NotAuthorizedException.class);
+
+        verifyNoInteractions(auditEventRepository, caseRepository);
     }

Also applies to: 97-99

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@src/test/java/org/example/projektarendehantering/application/service/AuditServiceTest.java`
around lines 85 - 91, The test currently asserts that auditService.listEvents
throws NotAuthorizedException but doesn't verify the audit repository wasn't
queried; update AuditServiceTest (e.g., in
listEvents_shouldDenyDoctorAccessToUnownedCase and the other denial test around
lines 97-99) to assert no audit reads occur by adding interaction assertions
such as verifyNoInteractions(auditEventRepository) or
verify(auditEventRepository, never()).find*(...) after the exception assertion
to guarantee auditEventRepository is not accessed when access is denied.

57-109: Add tests for remaining authorization branches in AuditService.listEvents.

Based on src/main/java/org/example/projektarendehantering/application/service/AuditService.java (Line 214 onward), two key branches are still untested here: manager with explicit caseId, and nurse access path. Adding these would close meaningful RBAC coverage gaps.

Suggested additional test cases
+    `@Test`
+    void listEvents_shouldAllowManagerToFilterByCaseId() {
+        when(auditEventRepository.findAllByCaseIdAndOccurredAtBetweenOrderByOccurredAtDesc(eq(caseId), any(), any(), any()))
+                .thenReturn(new PageImpl<>(List.of(new AuditEventEntity())));
+        when(auditEventMapper.toDTO(any())).thenReturn(new AuditEventDTO());
+
+        Page<AuditEventDTO> result = auditService.listEvents(managerActor, null, null, caseId, Pageable.unpaged());
+
+        assertThat(result.getContent()).hasSize(1);
+    }
+
+    `@Test`
+    void listEvents_shouldAllowNurseToSeeOnlyHandledCases() {
+        // Arrange a nurse actor + handled case and assert filtered audit access path.
+    }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@src/test/java/org/example/projektarendehantering/application/service/AuditServiceTest.java`
around lines 57 - 109, Add two unit tests exercising the remaining
AuditService.listEvents branches: one where managerActor passes an explicit
caseId and should be allowed to view events, and one for nurseActor's access
path. For the manager case, mock
auditEventRepository.findAllByCaseIdInAndOccurredAtBetweenOrderByOccurredAtDesc(Set.of(caseId),
...) to return a Page of AuditEventEntity and mock auditEventMapper.toDTO(...)
then call auditService.listEvents(managerActor, ..., caseId, ...) and assert the
page contains the expected DTOs. For the nurse case, create a nurseActor, stub
caseRepository.findAllByOwnerId(nurseActor.userId()) (or the repository method
used for nurse filtering) and auditEventRepository calls similarly, then call
auditService.listEvents(nurseActor, ...) and assert allowed/denied behavior
consistent with AuditService.listEvents; use the existing managerActor, caseId,
auditEventRepository, caseRepository, auditEventMapper, and auditService symbols
to locate where to add these tests.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In
`@src/test/java/org/example/projektarendehantering/application/service/AuditServiceTest.java`:
- Around line 59-67: The test currently only asserts page size, which won't
catch incorrect or null mapping results from auditEventMapper.toDTO; update
AuditServiceTest to assert the actual DTO content returned by
auditService.listEvents by stubbing auditEventMapper.toDTO to return a DTO with
known values (e.g., set an identifiable field on AuditEventDTO) and then assert
that result.getContent().get(0) (or its critical fields) equals those expected
values; target the test block that builds PageImpl<AuditEventEntity>, the
when(auditEventMapper.toDTO(...)) stub, and the final assertions so the test
validates both presence and correctness of the mapped AuditEventDTO.
- Around line 85-91: The test currently asserts that auditService.listEvents
throws NotAuthorizedException but doesn't verify the audit repository wasn't
queried; update AuditServiceTest (e.g., in
listEvents_shouldDenyDoctorAccessToUnownedCase and the other denial test around
lines 97-99) to assert no audit reads occur by adding interaction assertions
such as verifyNoInteractions(auditEventRepository) or
verify(auditEventRepository, never()).find*(...) after the exception assertion
to guarantee auditEventRepository is not accessed when access is denied.
- Around line 57-109: Add two unit tests exercising the remaining
AuditService.listEvents branches: one where managerActor passes an explicit
caseId and should be allowed to view events, and one for nurseActor's access
path. For the manager case, mock
auditEventRepository.findAllByCaseIdInAndOccurredAtBetweenOrderByOccurredAtDesc(Set.of(caseId),
...) to return a Page of AuditEventEntity and mock auditEventMapper.toDTO(...)
then call auditService.listEvents(managerActor, ..., caseId, ...) and assert the
page contains the expected DTOs. For the nurse case, create a nurseActor, stub
caseRepository.findAllByOwnerId(nurseActor.userId()) (or the repository method
used for nurse filtering) and auditEventRepository calls similarly, then call
auditService.listEvents(nurseActor, ...) and assert allowed/denied behavior
consistent with AuditService.listEvents; use the existing managerActor, caseId,
auditEventRepository, caseRepository, auditEventMapper, and auditService symbols
to locate where to add these tests.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f605c1a2-06e8-49f0-9ce4-36200bb1857d

📥 Commits

Reviewing files that changed from the base of the PR and between 0a69e2b and b3c5af8.

📒 Files selected for processing (4)
  • src/test/java/org/example/projektarendehantering/AuditIntegrationTest.java
  • src/test/java/org/example/projektarendehantering/application/service/AuditServiceTest.java
  • src/test/java/org/example/projektarendehantering/infrastructure/security/SecurityActorAdapterTest.java
  • src/test/java/org/example/projektarendehantering/presentation/rest/AuditControllerTest.java
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/test/java/org/example/projektarendehantering/AuditIntegrationTest.java
  • src/test/java/org/example/projektarendehantering/infrastructure/security/SecurityActorAdapterTest.java
  • src/test/java/org/example/projektarendehantering/presentation/rest/AuditControllerTest.java

@Tyreviel
Tyreviel merged commit 7c3580c into main Apr 9, 2026
2 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Apr 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Skriva tester Audit

1 participant