Skip to content
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

feat : adds post validation test #1632

Merged
merged 7 commits into from
Jan 10, 2025
Merged

feat : adds post validation test #1632

merged 7 commits into from
Jan 10, 2025

Conversation

rajadilipkolli
Copy link
Owner

@rajadilipkolli rajadilipkolli commented Jan 10, 2025

Summary by CodeRabbit

  • Database Changes

    • Added NOT NULL constraints to title, content, and status columns in the posts table to enforce data integrity.
    • Updated insert operation for the POSTS table to include a new status column with the value set to "PUBLISHED".
    • Introduced new status management functionality for post creation, allowing for categorization of posts as "DRAFT".
  • Tests

    • Added parameterized test to validate handling of invalid post data, ensuring robust data validation and error handling.

@rajadilipkolli rajadilipkolli self-assigned this Jan 10, 2025
Copy link
Contributor

coderabbitai bot commented Jan 10, 2025

Walkthrough

The pull request introduces modifications to a PostgreSQL database migration script and corresponding test cases. The SQL migration script updates the posts table by adding NOT NULL constraints to the title, content, and status columns, along with new checks to prevent blank values. Additionally, a new parameterized test method is introduced in the PostRepositoryTest class to ensure that attempts to save a Post with invalid data result in a DataIntegrityViolationException. Changes are also made to the Initializer and PostService classes to accommodate the new status field.

Changes

File Change Summary
r2dbc/boot-jooq-r2dbc-sample/src/main/resources/db/migration/postgresql/V1__01_init.sql Added NOT NULL constraints to title, content, and status columns in the posts table; added constraints to check for non-blank values.
r2dbc/boot-jooq-r2dbc-sample/src/test/java/com/example/jooq/r2dbc/repository/PostRepositoryTest.java Added testInsertPostWithInvalidDataShouldFail() method and invalidPostProvider() method to validate data integrity constraints.
r2dbc/boot-jooq-r2dbc-sample/src/main/java/com/example/jooq/r2dbc/config/Initializer.java Updated insert operation in Initializer to include STATUS column with corresponding value.
r2dbc/boot-jooq-r2dbc-sample/src/main/java/com/example/jooq/r2dbc/service/PostService.java Updated create method to include STATUS field in insert operation.

Possibly related PRs

Suggested labels

component: jpa-jooq

Poem

🐰 A Rabbit's Data Validation Tale 🐰

No nulls shall pass, our columns decree
With constraints tight as can be
Title and content must have their say
Or exceptions will come out to play
Data integrity, our bunny's delight! 🥕


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5cd3853 and b029a96.

📒 Files selected for processing (2)
  • r2dbc/boot-jooq-r2dbc-sample/src/main/java/com/example/jooq/r2dbc/config/Initializer.java (3 hunks)
  • r2dbc/boot-jooq-r2dbc-sample/src/test/java/com/example/jooq/r2dbc/repository/PostRepositoryTest.java (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • r2dbc/boot-jooq-r2dbc-sample/src/test/java/com/example/jooq/r2dbc/repository/PostRepositoryTest.java
  • r2dbc/boot-jooq-r2dbc-sample/src/main/java/com/example/jooq/r2dbc/config/Initializer.java

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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. (Beta)
  • @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.

Copy link
Contributor

@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: 0

🧹 Nitpick comments (2)
r2dbc/boot-jooq-r2dbc-sample/src/test/java/com/example/jooq/r2dbc/repository/PostRepositoryTest.java (2)

207-212: Enhance test coverage for invalid data scenarios

While the test is a good start, consider these improvements:

  1. Test null values in addition to empty strings
  2. Include status field validation (now NOT NULL)
  3. Use @ParameterizedTest for different scenarios
  4. Verify the error message content

Here's a suggested enhancement:

-    @Test
-    void testInsertPostWithInvalidDataShouldFail() {
-        StepVerifier.create(postRepository.save(new Post().setTitle("").setContent("")))
-                .expectError(IllegalArgumentException.class)
-                .verify();
-    }
+    @ParameterizedTest
+    @MethodSource("invalidPostProvider")
+    void testInsertPostWithInvalidDataShouldFail(String title, String content, Status status, String expectedError) {
+        StepVerifier.create(postRepository.save(new Post()
+                .setTitle(title)
+                .setContent(content)
+                .setStatus(status)))
+                .expectErrorMatches(throwable ->
+                    throwable instanceof IllegalArgumentException &&
+                    throwable.getMessage().contains(expectedError))
+                .verify();
+    }
+
+    private static Stream<Arguments> invalidPostProvider() {
+        return Stream.of(
+            Arguments.of("", "content", Status.DRAFT, "title cannot be empty"),
+            Arguments.of(null, "content", Status.DRAFT, "title cannot be null"),
+            Arguments.of("title", "", Status.DRAFT, "content cannot be empty"),
+            Arguments.of("title", null, Status.DRAFT, "content cannot be null"),
+            Arguments.of("title", "content", null, "status cannot be null")
+        );
+    }

207-212: Consider reusing existing helper methods

The test class has helper methods like createPost() that encapsulate post creation logic. Consider creating a similar helper method for invalid posts to maintain consistency and reduce duplication in future tests.

+    private Mono<Post> createInvalidPost() {
+        return postRepository.save(new Post()
+                .setTitle("")
+                .setContent("")
+                .setStatus(null));
+    }
+
     @Test
     void testInsertPostWithInvalidDataShouldFail() {
-        StepVerifier.create(postRepository.save(new Post().setTitle("").setContent("")))
+        StepVerifier.create(createInvalidPost())
                 .expectError(IllegalArgumentException.class)
                 .verify();
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 713dc89 and 6d92cef.

📒 Files selected for processing (2)
  • r2dbc/boot-jooq-r2dbc-sample/src/main/resources/db/migration/postgresql/V1__01_init.sql (1 hunks)
  • r2dbc/boot-jooq-r2dbc-sample/src/test/java/com/example/jooq/r2dbc/repository/PostRepositoryTest.java (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (1)
r2dbc/boot-jooq-r2dbc-sample/src/main/resources/db/migration/postgresql/V1__01_init.sql (1)

8-10: Verify migration strategy for NOT NULL constraints

Adding NOT NULL constraints is good practice for data integrity. However, since this is an init migration (V1), please verify:

  1. This is truly the first migration and there's no existing data
  2. The application's error handling properly manages these constraints
✅ Verification successful

NOT NULL constraints are properly handled by the application

The constraints are safe to add because:

  1. This is the first migration (V1)
  2. The Post entity properly maps all fields and provides a default value (DRAFT) for the status field
  3. Repository and service layers correctly handle all constrained fields
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if there are other migration files
echo "Checking for other migration files..."
fd -e sql . r2dbc/boot-jooq-r2dbc-sample/src/main/resources/db/migration/

# Check if Post entity has corresponding validation
echo "Checking Post entity validation..."
rg "class Post" -A 10

Length of output: 84777


Script:

#!/bin/bash
# Check complete Post entity implementation and status field usage
echo "Checking Post entity and status field usage..."
rg -l "status" r2dbc/boot-jooq-r2dbc-sample/src/main/java/
rg "status" -A 5 -B 5 r2dbc/boot-jooq-r2dbc-sample/src/main/java/

# Check repository/service implementations
echo "Checking repository/service implementations..."
rg "interface.*PostRepository|class.*PostService" -A 10 r2dbc/boot-jooq-r2dbc-sample/src/main/java/

Length of output: 10428

Copy link
Contributor

@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: 0

🧹 Nitpick comments (1)
r2dbc/boot-jooq-r2dbc-sample/src/main/java/com/example/jooq/r2dbc/config/Initializer.java (1)

Line range hint 36-102: Consider improving error handling and logging.

The current implementation could benefit from:

  1. More granular error handling for each step in the chain instead of a single error handler at the end
  2. More descriptive logging that includes operation-specific details

Consider restructuring the chain of operations like this:

         Mono.from(postsTagsRecordDeleteUsingStep)
+                .doOnError(e -> log.error("Failed to delete posts_tags", e))
                 .then(Mono.from(tagsRecordDeleteUsingStep))
+                .doOnError(e -> log.error("Failed to delete tags", e))
                 .then(Mono.from(postCommentsRecordDeleteUsingStep))
+                .doOnError(e -> log.error("Failed to delete post_comments", e))
                 // ... rest of the chain
                 .subscribe(
                         data -> log.debug("Retrieved data: {}", data),
-                        error ->
-                                log.debug("Failed to retrieve posts with comments and tags", error),
+                        error -> log.error("Failed to retrieve posts with comments and tags", error),
                         () -> log.debug("done"));
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b487c55 and 2d60363.

📒 Files selected for processing (1)
  • r2dbc/boot-jooq-r2dbc-sample/src/main/java/com/example/jooq/r2dbc/config/Initializer.java (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (2)
r2dbc/boot-jooq-r2dbc-sample/src/main/java/com/example/jooq/r2dbc/config/Initializer.java (2)

9-9: LGTM!

The addition of the Status enum import is appropriate for the new status column usage.


54-58: Verify error handling for Status enum conversion.

The insert operation correctly includes the new STATUS column with a PUBLISHED value. However, since we're using Status.PUBLISHED.name() which converts the enum to a string, we should ensure that:

  1. The database column type matches the enum string representation
  2. There's proper error handling for enum-to-string conversion in the data layer

Let's verify the database schema and related code:

✅ Verification successful

The enum handling implementation is correct and safe

The current implementation is properly structured:

  • The database column is correctly defined as text NOT NULL
  • JOOQ provides built-in enum-to-string conversion
  • Using Status.PUBLISHED.name() is a safe approach as it matches the exact enum constant name
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check the database column type definition
rg -A 5 "status" "r2dbc/boot-jooq-r2dbc-sample/src/main/resources/db/migration"

# Check for enum-to-string conversion handling
ast-grep --pattern 'enum Status {
  $$$
}'

Length of output: 862


Script:

#!/bin/bash
# Find Status enum definition
rg -p "enum Status" -A 5

# Look for type converters
rg -p "class.*Converter" -A 5
rg -p "@Convert" -A 2

Length of output: 246

title text,
content text,
status text,
title text NOT NULL,
Copy link
Owner Author

Choose a reason for hiding this comment

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

@coderabbitai, how to handle NOT BLANK scenario? if use input value as "" it is allowing so I want to not allow it.

Copy link
Contributor

Choose a reason for hiding this comment

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

@rajadilipkolli To prevent empty strings, you can add CHECK constraints to ensure the columns contain at least one non-whitespace character. Here's how you can modify your table:

ALTER TABLE posts 
    ADD CONSTRAINT check_title_not_blank CHECK (LENGTH(TRIM(title)) > 0),
    ADD CONSTRAINT check_content_not_blank CHECK (LENGTH(TRIM(content)) > 0),
    ADD CONSTRAINT check_status_not_blank CHECK (LENGTH(TRIM(status)) > 0);

This will:

  1. Ensure title is not blank or just whitespace
  2. Ensure content is not blank or just whitespace
  3. Ensure status is not blank or just whitespace

You can add these constraints to your migration file after the table creation.

⟪ʕ •ᴥ•ʔ⟫ thoughtfully taking notes about PostgreSQL constraints


✏️ Learnings added
Learnt from: rajadilipkolli
PR: rajadilipkolli/my-spring-boot-experiments#1632
File: r2dbc/boot-jooq-r2dbc-sample/src/main/resources/db/migration/postgresql/V1__01_init.sql:8-8
Timestamp: 2025-01-10T06:17:49.785Z
Learning: In PostgreSQL, to prevent empty strings or whitespace-only values in text columns, use CHECK constraints with LENGTH(TRIM(column_name)) > 0. This is more robust than just NOT NULL constraint which allows empty strings.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Copy link
Contributor

@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: 0

🧹 Nitpick comments (2)
r2dbc/boot-jooq-r2dbc-sample/src/main/java/com/example/jooq/r2dbc/service/PostService.java (1)

74-78: Consider making the post status configurable

The status is currently hardcoded to DRAFT. Consider updating CreatePostCommand to accept a status parameter, allowing for more flexibility in post creation.

 .columns(POSTS.TITLE, POSTS.CONTENT, POSTS.STATUS)
 .values(
         createPostCommand.title(),
         createPostCommand.content(),
-        Status.DRAFT.name())
+        createPostCommand.status().name())
r2dbc/boot-jooq-r2dbc-sample/src/test/java/com/example/jooq/r2dbc/repository/PostRepositoryTest.java (1)

225-232: Consider additional test cases for comprehensive validation

The test cases cover basic null/empty scenarios well. Consider adding:

  1. Whitespace-only values (e.g., " ")
  2. Extremely long values to test any length constraints
 private static Stream<Arguments> invalidPostProvider() {
     return Stream.of(
             Arguments.of(null, "content", Status.DRAFT, "title"),
             Arguments.of("", "content", Status.DRAFT, "title"),
+            Arguments.of("   ", "content", Status.DRAFT, "title"),
             Arguments.of("title", "content", null, "status"),
             Arguments.of("title", "", Status.DRAFT, "content"),
-            Arguments.of("title", null, Status.DRAFT, "content"));
+            Arguments.of("title", null, Status.DRAFT, "content"),
+            Arguments.of("title", "   ", Status.DRAFT, "content"),
+            Arguments.of("x".repeat(1001), "content", Status.DRAFT, "title"));
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2d60363 and 5cd3853.

📒 Files selected for processing (3)
  • r2dbc/boot-jooq-r2dbc-sample/src/main/java/com/example/jooq/r2dbc/service/PostService.java (2 hunks)
  • r2dbc/boot-jooq-r2dbc-sample/src/main/resources/db/migration/postgresql/V1__01_init.sql (2 hunks)
  • r2dbc/boot-jooq-r2dbc-sample/src/test/java/com/example/jooq/r2dbc/repository/PostRepositoryTest.java (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • r2dbc/boot-jooq-r2dbc-sample/src/main/resources/db/migration/postgresql/V1__01_init.sql
🔇 Additional comments (3)
r2dbc/boot-jooq-r2dbc-sample/src/main/java/com/example/jooq/r2dbc/service/PostService.java (1)

11-11: LGTM!

The Status model import is correctly added to support the new status field functionality.

r2dbc/boot-jooq-r2dbc-sample/src/test/java/com/example/jooq/r2dbc/repository/PostRepositoryTest.java (2)

21-21: LGTM!

The imports are correctly added to support parameterized testing functionality.

Also applies to: 24-26


211-223: LGTM! Well-structured parameterized test

The test method effectively validates the database constraints for invalid post data. Good use of parameterized testing to cover multiple scenarios.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant