Skip to content

[Improve] add unit test #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 21 commits into
base: master
Choose a base branch
from
Open

[Improve] add unit test #6

wants to merge 21 commits into from

Conversation

arvi18
Copy link

@arvi18 arvi18 commented Apr 21, 2025

Summary by CodeRabbit

  • New Features
    • Introduced a new configuration for consistent date and time formatting in API responses.
  • Bug Fixes
    • Improved handling of date/time serialization and deserialization for better compatibility.
  • Tests
    • Added new tests for alert silence deletion.
    • Simplified and streamlined alert define controller tests.
  • Chores
    • Changed the default server port from 1157 to 11570.
    • Minor formatting and whitespace improvements in alert controller files.

@arvi18
Copy link
Author

arvi18 commented Apr 21, 2025

yep. I think so. I am debug in my local. If has new discover, i will push.
I will mark its draft later.

tomsun28 @.***>于2024年8月5日 周一12:37写道:

@.**** commented on this pull request.

In
alerter/src/main/java/org/apache/hertzbeat/alert/controller/AlertDefinesController.java
apache#2454 (comment):

  •    return ResponseEntity.ok(Message.success(alertDefinePage));
    
  •    return  ResponseEntity.ok(Message.success(
    
  •            new PageImpl<>(
    
  •                    alertDefinePage.getContent(),
    
  •                    PageRequest.of(pageIndex, pageSize, Sort.by(new Sort.Order(Sort.Direction.fromString(order), sort))),
    
  •                    alertDefinePage.getTotalElements()))
    
  •    );
    

Hi, it maybe caused by test cases or other reasons. I feel that we cannot
repeat the construction like this.


Reply to this email directly, view it on GitHub
apache#2454 (review),
or unsubscribe
https://github.com/notifications/unsubscribe-auth/ASS2GCIP55OT2HPTIBFACADZP36RDAVCNFSM6AAAAABL6OCNHCVHI2DSMVQWIX3LMV43YUDVNRWFEZLROVSXG5CSMV3GSZLXHMZDEMJXHE4TGNJZGI
.
You are receiving this because you authored the thread.Message ID:
@.***>

@arvi18
Copy link
Author

arvi18 commented Apr 21, 2025

@tomsun28 I find question: pls see: spring-projects/spring-data-commons#2987

@arvi18
Copy link
Author

arvi18 commented Apr 21, 2025

@tomsun28 I find question: pls see: spring-projects/spring-data-commons#2987

👍 it seem this can fix it. spring-projects/spring-data-commons#2987 (comment) add pageModule in jackson

@arvi18
Copy link
Author

arvi18 commented Apr 21, 2025

@tomsun28 I find question: pls see: spring-projects/spring-data-commons#2987

👍 it seem this can fix it. spring-projects/spring-data-commons#2987 (comment) add pageModule in jackson

This would be due to additional class configuration, not sure if there are other side effects, I think it's better to use new PageImpl to be safe. 🤔

@arvi18
Copy link
Author

arvi18 commented Apr 21, 2025

This would be due to additional class configuration, not sure if there are other side effects, I think it's better to use new PageImpl to be safe. 🤔

hi, the root cause is the serialization problem of the page. It is recommended that we solve the problem instead of circumventing it. we has the custom jackson config here like timemodule https://github.com/apache/hertzbeat/blob/master/manager/src/main/java/org/apache/hertzbeat/manager/config/JacksonConfig.java

builder.modules(new SpringDataJacksonConfiguration.PageModule());

@arvi18
Copy link
Author

arvi18 commented Apr 21, 2025

hi, the root cause is the serialization problem of the page. It is recommended that we solve the problem instead of circumventing it. we has the custom jackson config here like timemodule https://github.com/apache/hertzbeat/blob/master/manager/src/main/java/org/apache/hertzbeat/manager/config/JacksonConfig.java

builder.modules(new SpringDataJacksonConfiguration.PageModule());

got it, let me try

@arvi18
Copy link
Author

arvi18 commented Apr 21, 2025

@tomsun28 hi, This e2e error is probably caused by apache#2486, I think we can run the ci test again after the apache#2486 merge.

cc @crossoverJie

Copy link

coderabbitai bot commented Apr 21, 2025

Walkthrough

This update introduces a new global Spring MVC configuration for JSON serialization and deserialization, specifically customizing date and time formats using Jackson. The new configuration replaces the previous Jackson customization that was scoped to the manager module, centralizing and unifying date/time handling across the application. Minor whitespace and formatting adjustments are made in alert controller classes, while the alert-related tests are refactored: one test class is simplified, and a new test class is added for alert silences. Additionally, the application's server port is updated in the configuration file.

Changes

File(s) Change Summary
alerter/src/main/java/org/apache/hertzbeat/alert/controller/AlertDefinesController.java
alerter/src/main/java/org/apache/hertzbeat/alert/controller/AlertSilencesController.java
Whitespace and indentation adjustments in controller methods; no functional changes.
alerter/src/test/java/org/apache/hertzbeat/alert/controller/AlertDefinesControllerTest.java Test class simplified: removed complex pagination/sorting logic, unused mocks, and now only tests delete operation.
alerter/src/test/java/org/apache/hertzbeat/alert/controller/AlertSilencesControllerTest.java New test class added for alert silences controller, verifying the delete operation via MockMvc and Mockito.
common/src/main/java/org/apache/hertzbeat/common/config/MVCConfig.java New global Spring MVC configuration added for Jackson, defining custom date/time formats and registering modules for JSON handling.
manager/src/main/java/org/apache/hertzbeat/manager/config/JacksonConfig.java Deleted previous Jackson configuration class and its beans for date/time handling.
manager/src/main/resources/application.yml Server port changed from 1157 to 11570.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant SpringMVC (with MVCConfig)
    participant Controller
    participant Service

    Client->>SpringMVC (with MVCConfig): Sends HTTP request with JSON (date/time fields)
    SpringMVC (with MVCConfig)->>Controller: Deserializes JSON using custom ObjectMapper
    Controller->>Service: Processes request
    Service-->>Controller: Returns response data
    Controller->>SpringMVC (with MVCConfig): Returns response object
    SpringMVC (with MVCConfig)->>Client: Serializes response JSON with custom date/time formats
Loading

Poem

🐇
In the warren, code flows anew,
With dates and times in formats true.
Old configs gone, replaced with flair,
One Jackson setup everywhere!
Controllers tidied, tests refreshed—
On port eleven-five-seven-oh,
Our JSON now will always glow!

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@arvi18
Copy link
Author

arvi18 commented Apr 21, 2025

For this pr, the current state is that it may affect all controllers that use Page as a return value, but it does not affect front-end api calls. It only appears in e2e tests and unit tests, so this pr is in pending status, and will be updated again when there is a better solution for serializing Page objects in spring data jpa.

@visz11
Copy link
Collaborator

visz11 commented Apr 23, 2025

@coderabbitai full review

Copy link

coderabbitai bot commented Apr 23, 2025

✅ Actions performed

Full review triggered.

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: 5

🧹 Nitpick comments (1)
common/src/main/java/org/apache/hertzbeat/common/config/MVCConfig.java (1)

51-95: Well-structured MVC configuration for date/time handling.

The configuration properly sets up serialization and deserialization for Java 8 date/time types with clear format patterns. Adding the custom converter at index 0 ensures it takes precedence over default converters.

Consider adding a comment explaining why the converter is added at index 0:

messageConverter.setObjectMapper(objectMapper);
converters.add(0, messageConverter);
+// Add at index 0 to ensure our converter takes precedence over default converters
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b02837b and fa8681d.

📒 Files selected for processing (7)
  • alerter/src/main/java/org/apache/hertzbeat/alert/controller/AlertDefinesController.java (2 hunks)
  • alerter/src/main/java/org/apache/hertzbeat/alert/controller/AlertSilencesController.java (1 hunks)
  • alerter/src/test/java/org/apache/hertzbeat/alert/controller/AlertDefinesControllerTest.java (2 hunks)
  • alerter/src/test/java/org/apache/hertzbeat/alert/controller/AlertSilencesControllerTest.java (1 hunks)
  • common/src/main/java/org/apache/hertzbeat/common/config/MVCConfig.java (1 hunks)
  • manager/src/main/java/org/apache/hertzbeat/manager/config/JacksonConfig.java (0 hunks)
  • manager/src/main/resources/application.yml (1 hunks)
💤 Files with no reviewable changes (1)
  • manager/src/main/java/org/apache/hertzbeat/manager/config/JacksonConfig.java
🔇 Additional comments (7)
alerter/src/main/java/org/apache/hertzbeat/alert/controller/AlertSilencesController.java (1)

59-60: Formatting adjustment looks good.

The added blank line improves code readability by separating the method body from its parameter declarations.

alerter/src/main/java/org/apache/hertzbeat/alert/controller/AlertDefinesController.java (2)

64-65: Formatting improvement is good.

The added spacing around the return statement improves readability.


83-85: Consistent formatting applied.

The indentation of method parameters has been adjusted to maintain consistent formatting throughout the codebase.

alerter/src/test/java/org/apache/hertzbeat/alert/controller/AlertSilencesControllerTest.java (2)

42-67: Test setup looks good.

The test class is well structured with proper mocking of dependencies and test data setup.


1-81:

❌ Incorrect review comment

Verify serialization of Page objects in tests.

Based on PR discussions about serialization issues with Spring Data's Page objects, verify that the tests properly handle serialization of Page objects returned by controllers. Consider adding a test that validates the JSON structure of the response.


🏁 Script executed:

#!/bin/bash
# Find configuration classes that might handle Page serialization
echo "Looking for configuration classes that might handle Page serialization..."
rg -A 10 "ObjectMapper|Jackson" --type java

echo "Checking for PageModule or similar Page serialization configuration..."
rg -l "PageModule|Page.*serializ" --type java

Length of output: 78410


Ignore Page serialization suggestion for this test.

AlertSilencesControllerTest only covers the DELETE /api/alert/silences endpoint—which does not return a Spring Data Page—so there’s no Page serialization to verify here. If you have other controller methods that return Page objects, please add dedicated JSON‑structure tests in those controllers’ test classes instead.

Likely an incorrect or invalid review comment.

alerter/src/test/java/org/apache/hertzbeat/alert/controller/AlertDefinesControllerTest.java (1)

77-86: Test implementation looks good.

The test for the delete operation correctly sets up the request and verifies the response.

common/src/main/java/org/apache/hertzbeat/common/config/MVCConfig.java (1)

60-61: Good implementation of the PageModule integration.

This correctly addresses the serialization issues with Page<T> objects as mentioned in the PR discussion. By integrating Spring Data's PageModule into the Jackson ObjectMapper, you're ensuring proper serialization/deserialization of pagination results in JSON responses.

This is the recommended approach for handling Spring Data's Page objects in REST responses, as discussed in Spring Data Commons issue apache#2987.

Also applies to: 89-91

@@ -13,7 +13,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
server:
port: 1157
port: 11570
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify port configuration change impact.

The server port has been updated from 1157 to 11570. This change should be coordinated with any service discovery configurations, deployment scripts, or documentation that references the previous port number.


🏁 Script executed:

#!/bin/bash
# Check for other references to the old port number in the codebase
echo "Searching for references to the old port 1157 that might need updating..."
rg -l "1157" --glob "!{manager/src/main/resources/application.yml}" -g "!*.{class,jar,war}"

Length of output: 10356


Update all port 1157 references to 11570 across the codebase

Multiple occurrences of the old port (1157) were found in configuration files, scripts and documentation. To avoid runtime errors and configuration drift, please update every reference to use the new port (11570). Notable locations include:

  • collector/src/main/resources/application.yml
  • manager/src/main/resources/define/app-push.yml, app-hertzbeat*.yml
  • script/docker-compose/**/conf/application.yml and docker-compose.yaml
  • script/assembly/server/bin/startup.sh, startup.bat, shutdown.bat
  • e2e/docker-compose.yml and e2e/testsuite.yaml
  • README.md, README_CN.md
  • Documentation under home/docs, home/blog and home/versioned_docs

You can run rg -l "1157" from the repo root to review all occurrences. Ensure your deployment scripts, service discovery settings and CI/CD workflows are updated to reference port 11570.

Comment on lines +69 to +79
@Test
void testDeleteAlertDefines() throws Exception {

doNothing().when(alertSilenceService).deleteAlertSilences(any());

mockMvc.perform(delete("/api/alert/silences")
.param("ids", "1,2,3")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value((int) CommonConstants.SUCCESS_CODE));
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Test method needs better naming and more test cases.

The test method name testDeleteAlertDefines doesn't match the actual controller method name deleteAlertSilences it's testing. Additionally, consider adding tests for edge cases like empty ID list and for the getAlertSilences method.

-@Test
-void testDeleteAlertDefines() throws Exception {
+@Test
+void testDeleteAlertSilences() throws Exception {
     
     doNothing().when(alertSilenceService).deleteAlertSilences(any());
 
     mockMvc.perform(delete("/api/alert/silences")
                     .param("ids", "1,2,3")
                     .accept(MediaType.APPLICATION_JSON))
             .andExpect(status().isOk())
             .andExpect(jsonPath("$.code").value((int) CommonConstants.SUCCESS_CODE));
 }
+
+@Test
+void testDeleteAlertSilences_withEmptyIdList() throws Exception {
+    mockMvc.perform(delete("/api/alert/silences")
+                   .accept(MediaType.APPLICATION_JSON))
+           .andExpect(status().isOk())
+           .andExpect(jsonPath("$.code").value((int) CommonConstants.SUCCESS_CODE));
+}
+
+@Test
+void testGetAlertSilences() throws Exception {
+    Page<AlertSilence> mockPage = new PageImpl<>(List.of(alertSilence));
+    when(alertSilenceService.getAlertSilences(any(), any(), any(), any(), anyInt(), anyInt()))
+        .thenReturn(mockPage);
+
+    mockMvc.perform(get("/api/alert/silences")
+                   .accept(MediaType.APPLICATION_JSON))
+           .andExpect(status().isOk())
+           .andExpect(jsonPath("$.code").value((int) CommonConstants.SUCCESS_CODE))
+           .andExpect(jsonPath("$.data.content[0].id").value(1));
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@Test
void testDeleteAlertDefines() throws Exception {
doNothing().when(alertSilenceService).deleteAlertSilences(any());
mockMvc.perform(delete("/api/alert/silences")
.param("ids", "1,2,3")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value((int) CommonConstants.SUCCESS_CODE));
}
@Test
void testDeleteAlertSilences() throws Exception {
doNothing().when(alertSilenceService).deleteAlertSilences(any());
mockMvc.perform(delete("/api/alert/silences")
.param("ids", "1,2,3")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value((int) CommonConstants.SUCCESS_CODE));
}
@Test
void testDeleteAlertSilences_withEmptyIdList() throws Exception {
// no "ids" param
mockMvc.perform(delete("/api/alert/silences")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value((int) CommonConstants.SUCCESS_CODE));
}
@Test
void testGetAlertSilences() throws Exception {
// prepare a mock page of silences
Page<AlertSilence> mockPage = new PageImpl<>(List.of(alertSilence));
when(alertSilenceService.getAlertSilences(any(), any(), any(), any(), anyInt(), anyInt()))
.thenReturn(mockPage);
mockMvc.perform(get("/api/alert/silences")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value((int) CommonConstants.SUCCESS_CODE))
.andExpect(jsonPath("$.data.content[0].id").value(1));
}

Comment on lines 47 to +48
@ExtendWith(MockitoExtension.class)
@SpringBootTest(classes = Manager.class)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Inconsistent testing approach.

The test class combines @SpringBootTest with @ExtendWith(MockitoExtension.class) and then manually creates the MockMvc instance using standaloneSetup(). This is an unusual combination that mixes different testing approaches.

Choose one of these approaches:

  1. For a focused controller test with mocks:
@ExtendWith(MockitoExtension.class)
-@SpringBootTest(classes = Manager.class)
class AlertDefinesControllerTest {
    // Keep the standaloneSetup approach
}
  1. For a Spring context-aware test:
-@ExtendWith(MockitoExtension.class)
@SpringBootTest(classes = Manager.class)
+@AutoConfigureMockMvc
class AlertDefinesControllerTest {
    
+    @Autowired
    private MockMvc mockMvc;
    
    @BeforeEach
    void setUp() {
-        this.mockMvc = standaloneSetup(alertDefinesController).build();
        // Other setup code...
    }
}

Also applies to: 64-64

import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.catalina.Manager;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Incorrect import for Manager class.

The import org.apache.catalina.Manager is incorrect for this context. This is a Tomcat-specific interface, not a Spring Boot application class that should be used with @SpringBootTest(classes = Manager.class).

Replace with the correct import for your application's main class, which is likely something like org.apache.hertzbeat.manager.Manager based on the class reference on line 48.

javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(dateTimeFormatter));
javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(timeFormatter));

javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(dateTimeFormatter));
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix incorrect date format for LocalDateTime deserialization.

You're using the date formatter (dateTimeFormatter) for LocalDateTime deserialization, which only includes the date part (yyyy-MM-dd) without the time component.

Use the defaultDateTimeFormatter instead, which includes both date and time parts:

-javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(dateTimeFormatter));
+javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(defaultDateTimeFormatter));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(dateTimeFormatter));
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(defaultDateTimeFormatter));

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.

4 participants