Skip to content

Test/test of report#71

Open
LolloGro wants to merge 54 commits intomainfrom
test/testOfReport
Open

Test/test of report#71
LolloGro wants to merge 54 commits intomainfrom
test/testOfReport

Conversation

@LolloGro
Copy link
Contributor

@LolloGro LolloGro commented Dec 10, 2025

Test for report controller:

  • report is succesfully created
  • throws error if not valid data
  • return reports

Summary by CodeRabbit

  • Refactor

    • Simplified report payload: removed submitter, status, and timestamp fields from the report data structure.
  • Tests

    • Added/updated integration and unit tests for creating and retrieving reports, including validation and image handling.
  • Chores

    • Minor build metadata comment added; no functional or dependency changes.

✏️ Tip: You can customize this high-level summary in your review settings.

Kirill9m and others added 30 commits November 26, 2025 16:04
New dependency
Flyway migration
New Repository
Bonus: GlobalExceptionhandler
…tOfReport

# Conflicts:
#	backend/pom.xml
#	backend/src/main/resources/application.properties
* Add ADR for database schema management strategy detailing transition from Hibernate `ddl-auto=update` to Flyway

* Update ADR for database schema management strategy and adjust editorconfig indentation settings
* Add Spring Security and OAuth2 dependencies - Done with Henrik and emily

* got OAuth working, but need to configure login and logout

* Changes by Alfred

* Oauth functioning, CustomOAuth2UserService for handling of user(work in progress). flyway migration V2 up. working on logic for user check, oversee entity with role?

* added another field for user - role,updated id to use uuid, removed flyway, added support for .env file in root.

* pulled in main before push.

* added test, and worked out some issues with the oAuth

* Add enum for role

* Add Role to User entity and add in Service to new user in database

* Add Role to User entity and add in Service to new user in database

* Add Role to Service to new user in database

---------

Co-authored-by: Henrik <Henrikmattsson89@gmail.com>
Co-authored-by: Emilyempa <emilypettersson@hotmail.com>
* First setup

* Adjusted margin.

* Logo

* Removed HTML suggested by code rabbit to make fragments pure and adjusted css styling

* Additional css adjustments

* Merged main. Commented out ("/") in AuthenticationController because RestController uses same endpoint as Controller. Adjusted styling for focus.

* ...and so it goes on... css

* Changes L to l
* Docs: Add DEVLOG.md

* Chore: Add dependencies CI-pipeline

* modified .github/workflows/ci.yml

* Fixed errors from CodeRabbit

* Fix: Delete plugins not compatible with java25

* Fix: resolve Checkstyle failures in CI job

* Fix: Restored BackendApplication.java- trying to handle CI blockages

* Fix: Resolve CI issues in BackendApplication.java

* Fix: BackendApplication.java = final

* Fix: Remove constructor and allow Spring to initiate this class

* Fix: Add constructor,I think coderabbit is having a stroke

* Fix: Checkstyle problems

* Add CI plugins: Spotless, Checkstyle, SpotBugs, JaCoCo, OWASP

* Add CI plugins: Spotless, Checkstyle, SpotBugs, JaCoCo, OWASP

* Hunted errors in pom.xml, BackendApplication, checkstyle.xml manualy tested with mvn spotless:check mvn checkstyle:check mvn clean verify mvn pmd:check

* Hunted errors in pom.xml, BackendApplication, checkstyle.xml manualy tested with mvn spotless:check mvn checkstyle:check mvn clean verify mvn pmd:check

* fixed checkstyle errors

* fixed Test-files errors

* deleted owasp dependency-check-maven

* deleted owasp dependency-check-maven

* deleted public in AuthenticationIntegrationTest

* Fix class naming convention in IndexController

* Remove redundant SpotBugs exclusion file and improve constructor clarity in User entity

* Remove redundant comment in User entity constructor

---------

Co-authored-by: Ronja Fagerdahl <ronjafagerdahl@gmail.com>
Co-authored-by: Jörgen Lindström <jorlind@telia.com>
Co-authored-by: Martin Blomberg <martin.blomberg@outlook.com>
@jenkins-cd-for-zipp
Copy link

Jenkins Build #6 Summary (for PR #71)

  • Status: SUCCESS
  • Duration: 1 min 36 sec
  • Branch: PR-71
  • Commit: b76968d
  • Docker Image: 192.168.0.82:5000/zipp:b76968d (pushed to registry)

Details:

  • Checkout: Successful
  • Build & Scan: Passed
  • Push: Successful

All stages passed—no issues detected.

jennymakki
jennymakki previously approved these changes Dec 14, 2025
Copy link
Contributor

@jennymakki jennymakki left a comment

Choose a reason for hiding this comment

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

Really nice test coverage for ReportController.
The tests clearly cover the happy path, validation errors, and fetching submitted reports.

@LolloGro LolloGro linked an issue Dec 15, 2025 that may be closed by this pull request
Copy link
Contributor

@alfredbrannare alfredbrannare left a comment

Choose a reason for hiding this comment

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

For some reason the test just loops this for me:
2025-12-15T10:46:52.311+01:00 INFO 7940 --- [backend] [backend-admin-0] o.a.k.c.a.i.AdminMetadataManager : [AdminClient clientId=backend-admin-0] Rebootstrapping with Cluster(id = null, nodes = [localhost:9092 (id: -1 rack: null isFenced: false)], partitions = [], controller = null)

Image

Is there something I am missing?

I don't think Kafka was there last I review it?

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
backend/src/test/java/org/fungover/zipp/controller/ReportControllerTest.java (2)

60-64: Consider extracting shared ObjectMapper and completing the future.

The ObjectMapper with JavaTimeModule is instantiated in multiple tests. Additionally, the CompletableFuture is never completed - if the controller awaits the result synchronously, this could cause issues.

Consider extracting the ObjectMapper as a class field and completing the future:

+    private static final ObjectMapper mapper = new ObjectMapper()
+            .registerModule(new JavaTimeModule());
+
     @Test
     void createReport() throws Exception {
         Report firstReport = new Report("Candy paper", ReportType.DEBRIS, 50.0, 50.0,
                 Instant.parse("2025-12-03T15:30:00Z"), ReportStatus.ACTIVE, null);
 
-        ObjectMapper mapper = new ObjectMapper();
-        mapper.registerModule(new JavaTimeModule());
-
         CompletableFuture<SendResult<String, ReportResponse>> future = new CompletableFuture<>();
+        future.complete(null); // Complete the future to avoid potential blocking
         when(template.send(anyString(), any())).thenReturn(future);

66-74: Consider extracting the OAuth2 login configuration.

The oauth2Login().attributes(...) pattern is repeated across all three tests. Extracting this to a helper method would improve maintainability.

private static SecurityMockMvcRequestPostProcessors.OAuth2LoginConfigurer mockOAuth2Login() {
    return SecurityMockMvcRequestPostProcessors.oauth2Login().attributes(user -> {
        user.put("name", "Test User");
        user.put("email", "test@gmail.com");
        user.put("role", "USER");
    });
}

Then use: .with(mockOAuth2Login()).with(csrf())

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b76968d and 19df7cc.

📒 Files selected for processing (1)
  • backend/src/test/java/org/fungover/zipp/controller/ReportControllerTest.java (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
backend/src/test/java/org/fungover/zipp/controller/ReportControllerTest.java (1)
backend/src/test/java/org/fungover/zipp/authtest/AuthenticationIntegrationTest.java (1)
  • SpringBootTest (24-66)
🔇 Additional comments (3)
backend/src/test/java/org/fungover/zipp/controller/ReportControllerTest.java (3)

39-44: Test configuration looks well-structured.

The combination of @Import(TestcontainersConfiguration.class) for database connectivity, @EnableAutoConfiguration(exclude = {KafkaAutoConfiguration.class}) for Kafka isolation, and @Transactional for test rollback is appropriate for this integration test.


46-53: Appropriate use of autowiring and mocking.

The ReportService is properly autowired for real integration testing while KafkaTemplate is correctly mocked to avoid external Kafka dependencies.


77-93: Validation test is well-structured.

The test correctly validates that a null description triggers a 400 Bad Request response. The absence of Kafka mock setup is appropriate since validation occurs before any Kafka publishing.

@LolloGro
Copy link
Contributor Author

@alfredbrannare I merged main into the branch. Now when you make a post , the report is send with kafka. Thats why I hade to mock it.
The issus should be solved know.

alfredbrannare
alfredbrannare previously approved these changes Dec 15, 2025
Copy link
Contributor

@alfredbrannare alfredbrannare left a comment

Choose a reason for hiding this comment

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

LG2M!

Fagerdahl
Fagerdahl previously approved these changes Dec 16, 2025
Copy link
Contributor

@Fagerdahl Fagerdahl left a comment

Choose a reason for hiding this comment

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

This is a solid test addition!

The coverage is good and it’s great to see both happy path and validation scenarios tested, including security context and CSRF handling.

A few small suggestions that could make the tests even clearer and less repetative going forward:

The test currently mixes integration-style setup (@SpringBootTest, Testcontainers, real ReportService) with mocked infrastructure (Kafka). This works, but it might be worth clarifying the intent: either a full integration test or a more focused controller/MVC test with a mocked service.

ObjectMapper setup is duplicated across tests and I don´t think we need that double set of JSON mappers.
I would consider reusing a single instance to keep the config in one place. for example:
private final ObjectMapper mapper = new ObjectMapper() .registerModule(new JavaTimeModule()); This would give us a little more dry code 🏜️

None of these are blocking a merge, the tests are already in good shape. These are mostly about clarity and long-term maintainability. And also educational SUBSTANCE for me as a reviewer 🥰

Nice work overall! Keep up the good work.
Christmas magic is just around the corner ✨

@Fagerdahl
Copy link
Contributor

Fagerdahl commented Dec 16, 2025

what happened- all were green five minutes ago??? I approved and all looked good.

I did not see I was assigned to review this until now!! Sorry that you had to wait 🌸 @LolloGro

@LolloGro LolloGro dismissed stale reviews from Fagerdahl and alfredbrannare via e92f3b6 December 17, 2025 13:57
@jenkins-cd-for-zipp
Copy link

Jenkins Build #8 Summary (for PR #71)

  • Status: SUCCESS
  • Duration: 1 min 43 sec
  • Branch: PR-71
  • Commit: 6ae4df9
  • Docker Image: 192.168.0.82:5000/zipp:6ae4df9 (pushed to registry)

Details:

  • Checkout: Successful
  • Build & Scan: Passed
  • Push: Successful

All stages passed—no issues detected.

@sonarqubecloud
Copy link

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
backend/src/test/java/org/fungover/zipp/controller/ReportControllerTest.java (1)

91-94: Remove unused attacker variable.

Same issue as the previous test—the attacker User is never used and should be removed.

Apply this diff:

     @Test
     void createReportWithImagesShouldReturnCreatedReport() {
-        User attacker = new User();
-        attacker.setId(UUID.randomUUID());
-        attacker.setEmail("attacker@example.com");
-        attacker.setProviderId("attacker-999");
-
         Report inputReport = new Report("Report with images", ReportType.DEBRIS, 59.3293, 18.0686,
                 List.of("https://example.com/image1.jpg", "https://example.com/image2.jpg"));
🧹 Nitpick comments (3)
backend/src/main/java/org/fungover/zipp/repository/UserRepository.java (1)

5-5: LGTM! The @Repository annotation is explicit but optional.

Spring Data JPA automatically detects repositories that extend JpaRepository, so @Repository is technically redundant. However, it explicitly documents the component's role and causes no harm.

Also applies to: 10-10

backend/src/test/java/org/fungover/zipp/controller/ReportControllerEndpointTest.java (1)

97-98: Remove unnecessary JavaTimeModule registration.

The JavaTimeModule is no longer needed since the Report DTO no longer contains Instant fields after the refactoring.

Apply this diff:

-        ObjectMapper mapper = new ObjectMapper();
-        mapper.registerModule(new JavaTimeModule());
+        ObjectMapper mapper = new ObjectMapper();
backend/src/test/java/org/fungover/zipp/controller/ReportControllerTest.java (1)

67-70: Remove unused attacker variable.

The attacker User created here is never used in the test. This is leftover dead code from the DTO refactoring that removed the attacker field from the Report constructor.

Apply this diff:

     @Test
     void createReportShouldReturnCreatedReportWithStatus201() {
-        User attacker = new User();
-        attacker.setId(UUID.randomUUID());
-        attacker.setEmail("attacker@example.com");
-        attacker.setProviderId("attacker-999");
-
         Report inputReport = new Report("Test description", ReportType.ACCIDENT, 59.3293, 18.0686, null);
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 19df7cc and e92f3b6.

📒 Files selected for processing (5)
  • backend/pom.xml (1 hunks)
  • backend/src/main/java/org/fungover/zipp/dto/Report.java (1 hunks)
  • backend/src/main/java/org/fungover/zipp/repository/UserRepository.java (1 hunks)
  • backend/src/test/java/org/fungover/zipp/controller/ReportControllerEndpointTest.java (1 hunks)
  • backend/src/test/java/org/fungover/zipp/controller/ReportControllerTest.java (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/pom.xml
🧰 Additional context used
🧬 Code graph analysis (1)
backend/src/test/java/org/fungover/zipp/controller/ReportControllerEndpointTest.java (1)
backend/src/test/java/org/fungover/zipp/authtest/AuthenticationIntegrationTest.java (1)
  • SpringBootTest (24-66)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: PR Build
  • GitHub Check: Jenkins
  • GitHub Check: Build, Test & Analyze
🔇 Additional comments (3)
backend/src/test/java/org/fungover/zipp/controller/ReportControllerEndpointTest.java (1)

73-91: LGTM! Proper Kafka mock setup for POST test.

The test correctly mocks the KafkaTemplate.send() method before performing the POST request, ensuring the asynchronous Kafka publish doesn't cause test failures.

backend/src/test/java/org/fungover/zipp/controller/ReportControllerTest.java (1)

72-72: LGTM! Constructor calls correctly updated.

The Report constructor calls have been properly updated to match the new DTO signature, including the imageUrls parameter.

Also applies to: 96-97

backend/src/main/java/org/fungover/zipp/dto/Report.java (1)

11-17: LGTM! DTO refactoring improves API design.

The simplified Report DTO correctly separates client input concerns from server-managed fields (user, timestamp, status). This improves security and consistency by preventing clients from setting these values. All usages throughout the codebase have been updated to match the new constructor signature: (description, eventType, latitude, longitude, imageUrls).

Comment on lines +110 to +121
@Test
void returnsSubmittedReport() throws Exception {
Report firstReport = new Report("Candy paper", ReportType.DEBRIS, 50.0, 50.0, null);

reportService.createReport(reportUser, firstReport);

mockMvc.perform(get("/api/reports").with(SecurityMockMvcRequestPostProcessors.oauth2Login().attributes(user -> {
user.put("name", "Test User");
user.put("email", "test@gmail.com");
user.put("role", "USER");
})).with(csrf())).andExpect(status().isOk()).andExpect(jsonPath("$[0].status").value("ACTIVE"));
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Add Kafka mock setup to prevent potential NPE.

The reportService.createReport() call on line 114 likely triggers Kafka publishing internally. Unlike the createReport test (lines 79-80), this test doesn't configure the mock's behavior with when(template.send(...)).thenReturn(...). If the service tries to access methods on the SendResult, this could cause a NullPointerException.

Apply this diff to add the Kafka mock setup:

     @Test
     void returnsSubmittedReport() throws Exception {
         Report firstReport = new Report("Candy paper", ReportType.DEBRIS, 50.0, 50.0, null);

+        CompletableFuture<SendResult<String, ReportResponse>> future = new CompletableFuture<>();
+        when(template.send(anyString(), any())).thenReturn(future);
+
         reportService.createReport(reportUser, firstReport);

Note: The csrf() on line 120 is unnecessary for GET requests but harmless.

🤖 Prompt for AI Agents
In
backend/src/test/java/org/fungover/zipp/controller/ReportControllerEndpointTest.java
around lines 110 to 121, the test calls reportService.createReport(...) but does
not configure the Kafka template mock, which can cause an NPE when the service
publishes; before invoking createReport, stub the Kafka template's send(...) to
return a completed future containing a mocked SendResult (or otherwise a
non-null Future/SendResult) so any accessors on the result won't NPE — create a
mock SendResult, wrap it in a completed CompletableFuture (or the project's
equivalent) and set up when(template.send(any())).thenReturn(thatFuture)
immediately before reportService.createReport(...).

Copy link

@0x0xoscar 0x0xoscar left a comment

Choose a reason for hiding this comment

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

Tests look good and are easy to follow.
Agree with CodeRabbits note about mocking Kafka in the last test to be safe, but otherwise looks good to merge. Well done!

Copy link
Contributor

@alfredbrannare alfredbrannare left a comment

Choose a reason for hiding this comment

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

Nice job,

LG2M

@LolloGro LolloGro enabled auto-merge December 18, 2025 13:38
Copy link
Contributor

@Fagerdahl Fagerdahl left a comment

Choose a reason for hiding this comment

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

This is a solid test addition!

The coverage is good and it’s great to see both happy path and validation scenarios tested, including security context and CSRF handling.

A few small suggestions that could make the tests even clearer and less repetative going forward:

The test currently mixes integration-style setup (https://github.com/SpringBootTest, Testcontainers, real ReportService) with mocked infrastructure (Kafka). This works, but it might be worth clarifying the intent: either a full integration test or a more focused controller/MVC test with a mocked service.

ObjectMapper setup is duplicated across tests and I don´t think we need that double set of JSON mappers.
I would consider reusing a single instance to keep the config in one place. for example:
private final ObjectMapper mapper = new ObjectMapper() .registerModule(new JavaTimeModule()); This would give us a little more dry code 🏜️

None of these are blocking a merge, the tests are already in good shape. These are mostly about clarity and long-term maintainability. And also educational SUBSTANCE for me as a reviewer 🥰

Nice work overall! Keep up the good work.
Christmas magic is just around the corner ✨

@jenkins-cd-for-zipp
Copy link

Jenkins Build #9 Summary (for PR #71)

  • Status: SUCCESS
  • Duration: 3 min 4 sec
  • Branch: PR-71
  • Commit: 6eb4765
  • Docker Image: 192.168.0.82:5000/zipp:6eb4765 (pushed to registry)

Details:

  • Checkout: Successful
  • Build & Scan: Passed
  • Push: Successful

All stages passed—no issues detected.

Copy link

@Patseroni Patseroni left a comment

Choose a reason for hiding this comment

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

Late review. =)
But all tests worked for me without any issues.

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.

Test of Rest API for new reports