Skip to content

Conversation

rrayst
Copy link
Member

@rrayst rrayst commented Jun 18, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced handling of nullable schemas by supporting explicit "null" types in validation.
    • Fixed potential null pointer exceptions during schema reference checks.
    • Updated string pattern validation to allow substring matches instead of full-string matches.
    • Refined number validation to reject numeric values represented as JSON strings.
    • Anchored header parameter regex patterns to match entire strings.
    • Anchored regex patterns in example API schemas for exact matching.
  • New Features

    • Added explicit support for validating JSON null values with a dedicated validator.
    • Introduced a new test suite for validating JSON Schema compliance using the official JSON-Schema-Test-Suite draft6.
    • Added new OpenAPI specification and tests for validating null types and arrays containing null or integers.
    • Added validation tests for schema properties with maximum constraints lacking explicit type declarations.
  • Tests

    • Updated number validator tests to reflect stricter validation rules for numeric strings.
    • Added comprehensive tests covering null value validation scenarios.
    • Added tests for maximum constraints without explicit types.
  • Chores

    • Updated Swagger parser dependencies to newer versions.

…ma test suite (needs to be downloaded seperately)
@rrayst rrayst requested a review from predic8 June 18, 2025 11:33
Copy link
Contributor

coderabbitai bot commented Jun 18, 2025

Walkthrough

The changes extend nullability detection in SchemaValidator to explicitly support the "null" type and update validation logic accordingly. A new NullValidator class was added. A comprehensive new test class runs the official JSON Schema Test Suite draft6 tests against the OpenAPI validator, adapting schemas and logging detailed results. Additional fixes include null checks, context updates, regex matching adjustments, new tests for integer maximum constraints without type, a new null-related OpenAPI spec and tests, and dependency version bumps.

Changes

File(s) Change Summary
core/src/main/java/com/predic8/membrane/core/openapi/validators/SchemaValidator.java Extended isNullable() to detect "null" type; updated validation to handle "null" via new NullValidator.
core/src/main/java/com/predic8/membrane/core/openapi/validators/NullValidator.java Added new NullValidator class to validate JSON null values.
core/src/main/java/com/predic8/membrane/core/openapi/validators/IJSONSchemaValidator.java Added constant NULL = "null" for null type identification.
core/src/test/java/com/predic8/membrane/core/openapi/validators/JsonSchemaTestSuiteTests.java Added new test class running JSON Schema Test Suite draft6 tests with schema adaptation and detailed logging.
core/src/main/java/com/predic8/membrane/core/openapi/validators/NumberValidator.java Updated to reject TextNode as number; returns validation error for string nodes.
core/src/test/java/com/predic8/membrane/core/openapi/validators/SchemaValidatorTest.java Modified test expectation for TextNode("123.45") to reject as number.
core/src/main/java/com/predic8/membrane/core/openapi/validators/StringValidator.java Changed regex matching from full-string match (matches()) to substring match (find()).
core/src/main/java/com/predic8/membrane/core/openapi/validators/ArrayValidator.java Updated validate method to assign updated context from schemaType("array").
core/src/main/java/com/predic8/membrane/core/openapi/validators/AbstractBodyValidator.java Added null check before accessing schema $ref; assigned updated context from schemaType(...).
core/src/test/resources/openapi/specs/header-params.yml Anchored regex pattern from \w* to ^\w*$ for header param schema.
pom.xml Updated Swagger parser dependencies to newer versions (1.0.75 and 2.1.30).
core/src/test/java/com/predic8/membrane/core/openapi/validators/IntegerTest.java Added tests for "maximum-without-type" property validating max constraints without explicit type.
core/src/test/resources/openapi/specs/integer.yml Added maximum-without-type property with max constraint but no type in schema.
core/src/test/java/com/predic8/membrane/core/openapi/validators/NullTest.java Added new test class validating null type and arrays with null or integer types against OpenAPI schemas.
core/src/test/resources/openapi/specs/null.yml Added new OpenAPI spec defining endpoints with request bodies using null type and arrays of null or integers.
distribution/examples/openapi/validation/contacts-xxl-api-v1.yml Anchored regex patterns for countryCode and zip properties to match entire strings exactly.

Sequence Diagram(s)

sequenceDiagram
    participant TestRunner as JsonSchemaTestSuiteTests
    participant FileSystem as TestSuite Directory
    participant Validator as OpenAPIValidator
    participant Logger as Logger

    TestRunner->>FileSystem: Read JSON test files
    loop For each test file
        TestRunner->>FileSystem: Parse schemas and test cases
        loop For each test case
            TestRunner->>Validator: Validate test data against schema
            Validator-->>TestRunner: Validation result (valid/invalid)
            TestRunner->>Logger: Log result and details
        end
    end
    TestRunner->>Logger: Print summary statistics
Loading

Poem

🐇 In fields of schema, nulls take flight,
Validators leap through day and night.
Tests unfold with JSON's lore,
Patterns shift, and errors no more.
A rabbit's hop through code so bright,
Ensuring data's just right! ✨🐰


📜 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 3b2816a and 7e1df20.

📒 Files selected for processing (2)
  • core/src/test/java/com/predic8/membrane/core/openapi/validators/JsonSchemaTestSuiteTests.java (1 hunks)
  • pom.xml (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • pom.xml
  • core/src/test/java/com/predic8/membrane/core/openapi/validators/JsonSchemaTestSuiteTests.java
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Automated tests
  • GitHub Check: Analyze (java)
✨ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.

@rrayst
Copy link
Member Author

rrayst commented Jun 18, 2025

/ok-to-test

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

🧹 Nitpick comments (2)
core/src/main/java/com/predic8/membrane/core/openapi/validators/SchemaValidator.java (1)

110-112: Nullable check looks correct – consider minor readability tweak

The added third condition correctly recognises a schema where the sole "type" is "null". That closes the NPE gap described in the PR title.
You could slightly improve readability/defensiveness with Objects.equals(schema.getType(), "null"), but functionally the change is solid.

core/src/test/java/com/predic8/membrane/core/openapi/validators/JsonSchemaTestSuiteTests.java (1)

62-69: Raw-type Map usage triggers unchecked casts

The numerous casts to raw Map produce unchecked warnings and hide type errors.
Introduce type parameters, e.g. Map<String, Object>, to improve safety and readability.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cdb691f and 00bb899.

📒 Files selected for processing (2)
  • core/src/main/java/com/predic8/membrane/core/openapi/validators/SchemaValidator.java (1 hunks)
  • core/src/test/java/com/predic8/membrane/core/openapi/validators/JsonSchemaTestSuiteTests.java (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Automated tests
  • GitHub Check: Analyze (java)
🔇 Additional comments (2)
core/src/test/java/com/predic8/membrane/core/openapi/validators/JsonSchemaTestSuiteTests.java (2)

110-126: Result evaluation logic can dereference errors when null

errors is only initialised inside the try block; if validation throws, the subsequent check dereferences errors == null.
Return early or initialise errors = new ValidationErrors() before the try.

ValidationErrors errors = new ValidationErrors();
try {
     errors = validator.validate(post.body(body));

Likely an incorrect or invalid review comment.


35-35: ```shell
#!/bin/bash

Show the locateTests method implementation for context

rg 'private void locateTests' -n -A 10 -B 5 core/src/test/java/com/predic8/membrane/core/openapi/validators/JsonSchemaTestSuiteTests.java


</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

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

🧹 Nitpick comments (2)
core/src/test/java/com/predic8/membrane/core/openapi/validators/JsonSchemaTestSuiteTests.java (2)

111-118: computeIgnoredReason heuristic is brittle

Matching on openapi.contains("http://") ignores legitimate https:// external refs, and substring matches in example strings.
Consider parsing the schema and checking $ref values explicitly instead of string contains.


43-54: Minor: counters should be long to avoid overflow

The full draft-4 suite easily runs >10 000 cases. Using int risks overflow if you later enable multiple drafts.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f53f1f5 and 83076e0.

📒 Files selected for processing (1)
  • core/src/test/java/com/predic8/membrane/core/openapi/validators/JsonSchemaTestSuiteTests.java (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
core/src/test/java/com/predic8/membrane/core/openapi/validators/JsonSchemaTestSuiteTests.java (2)
Learnt from: rrayst
PR: membrane/api-gateway#1906
File: core/src/test/java/com/predic8/membrane/core/openapi/validators/JsonSchemaTestSuiteTests.java:0-0
Timestamp: 2025-06-18T12:03:09.873Z
Learning: The mediaType method in the Request class throws jakarta.mail.internet.ParseException, not java.text.ParseException, making the jakarta.mail.internet.ParseException import necessary and correct in JsonSchemaTestSuiteTests.java.
Learnt from: rrayst
PR: membrane/api-gateway#1906
File: core/src/test/java/com/predic8/membrane/core/openapi/validators/JsonSchemaTestSuiteTests.java:0-0
Timestamp: 2025-06-18T12:03:09.873Z
Learning: The mediaType method in the Message class (which Request extends) throws jakarta.mail.internet.ParseException because it creates a ContentType object for parsing MIME media types. The jakarta.mail.internet.ParseException import is correct and necessary in test files that call mediaType().
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Automated tests
  • GitHub Check: Analyze (java)
🔇 Additional comments (1)
core/src/test/java/com/predic8/membrane/core/openapi/validators/JsonSchemaTestSuiteTests.java (1)

95-109: schema is blindly cast to Map – add defensive check

generateOpenAPIForSchema assumes every schema node is a JSON object.
A handful of draft-4 tests contain boolean schemas (true / false), which will throw ClassCastException here.

Either:

  1. Short-circuit boolean schemas (they are valid in draft-4), or
  2. Fail early with a clear message.
-        if (((Map) schema).containsKey("definitions")) {
+        if (schema instanceof Map && ((Map<?, ?>) schema).containsKey("definitions")) {
             oa.put("components", of("schemas", ((Map) schema).get("definitions")));
             System.out.println("    warning: The schema contains definitions. They have been moved from #/definitions/ to #/components/schemas/ .");
+        } else if (!(schema instanceof Map)) {
+            return yamlMapper.writeValueAsString(oa); // boolean schema – nothing to relocate
         }

@rrayst rrayst requested a review from predic8 June 23, 2025 06:21
rrayst added 2 commits June 23, 2025 17:21
- fixed NPE
- support "type":"null" in schema
- do not accept "123.45" as a valid number, when this appears in a JSON
- JSON Schema 'pattern' is not anchored
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: 1

♻️ Duplicate comments (3)
core/src/test/java/com/predic8/membrane/core/openapi/validators/JsonSchemaTestSuiteTests.java (3)

41-41: Use OS-independent path separators.

The hard-coded Windows backslashes will cause issues on Unix-based systems.

-public final String TEST_SUITE_BASE_PATH = "git\\JSON-Schema-Test-Suite\\tests\\draft6";
+public final String TEST_SUITE_BASE_PATH = "git/JSON-Schema-Test-Suite/tests/draft6";

Alternatively, use Path.of("git", "JSON-Schema-Test-Suite", "tests", "draft6").toString() for full OS independence.


64-64: Guard against NPE from listFiles().

File.listFiles() returns null when the path doesn't exist or isn't a directory, causing NPE in the enhanced for-loop.

-        for (File file : base.listFiles()) {
+        File[] files = base.listFiles();
+        if (files == null) {
+            throw new RuntimeException("Unable to list test files in directory: " + baseDir);
+        }
+        for (File file : files) {

159-161: Avoid silently swallowing validation exceptions.

The current exception handling only prints the stack trace but doesn't fail the test, making debugging difficult when validators throw unexpected exceptions.

-        } catch (Exception e) {
-            e.printStackTrace();
+        } catch (Exception e) {
+            throw new RuntimeException("Validator threw exception during test: " + description2, e);
         }
🧹 Nitpick comments (3)
core/src/main/java/com/predic8/membrane/core/openapi/validators/NullValidator.java (1)

22-24: Remove unused imports.

The imports for BigDecimal and parseDouble are not used in this class and should be removed.

-import java.math.BigDecimal;
-
-import static java.lang.Double.parseDouble;
core/src/test/java/com/predic8/membrane/core/openapi/validators/JsonSchemaTestSuiteTests.java (2)

110-110: Use consistent logging instead of System.out.println.

Replace System.out.println with the logger to maintain consistent output handling.

-            System.out.println("    warning: The schema contains definitions. They have been moved from #/$defs/ to #/components/schemas/ .");
+            LOG.warn("    The schema contains definitions. They have been moved from #/$defs/ to #/components/schemas/ .");

167-167: Use consistent logging instead of System.out.println.

Replace System.out.println with the logger for consistent output handling.

-            System.out.println("    Test: NOT OK!");
+            LOG.error("    Test: NOT OK!");
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1ed370d and 7b8109c.

📒 Files selected for processing (11)
  • core/src/main/java/com/predic8/membrane/core/openapi/validators/AbstractBodyValidator.java (1 hunks)
  • core/src/main/java/com/predic8/membrane/core/openapi/validators/ArrayValidator.java (1 hunks)
  • core/src/main/java/com/predic8/membrane/core/openapi/validators/IJSONSchemaValidator.java (1 hunks)
  • core/src/main/java/com/predic8/membrane/core/openapi/validators/NullValidator.java (1 hunks)
  • core/src/main/java/com/predic8/membrane/core/openapi/validators/NumberValidator.java (3 hunks)
  • core/src/main/java/com/predic8/membrane/core/openapi/validators/SchemaValidator.java (3 hunks)
  • core/src/main/java/com/predic8/membrane/core/openapi/validators/StringValidator.java (1 hunks)
  • core/src/test/java/com/predic8/membrane/core/openapi/validators/JsonSchemaTestSuiteTests.java (1 hunks)
  • core/src/test/java/com/predic8/membrane/core/openapi/validators/SchemaValidatorTest.java (1 hunks)
  • core/src/test/resources/openapi/specs/header-params.yml (1 hunks)
  • pom.xml (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • core/src/main/java/com/predic8/membrane/core/openapi/validators/IJSONSchemaValidator.java
  • pom.xml
🚧 Files skipped from review as they are similar to previous changes (1)
  • core/src/main/java/com/predic8/membrane/core/openapi/validators/SchemaValidator.java
🧰 Additional context used
🧠 Learnings (1)
core/src/test/java/com/predic8/membrane/core/openapi/validators/JsonSchemaTestSuiteTests.java (2)
Learnt from: rrayst
PR: membrane/api-gateway#1906
File: core/src/test/java/com/predic8/membrane/core/openapi/validators/JsonSchemaTestSuiteTests.java:0-0
Timestamp: 2025-06-18T12:03:09.873Z
Learning: The mediaType method in the Request class throws jakarta.mail.internet.ParseException, not java.text.ParseException, making the jakarta.mail.internet.ParseException import necessary and correct in JsonSchemaTestSuiteTests.java.
Learnt from: rrayst
PR: membrane/api-gateway#1906
File: core/src/test/java/com/predic8/membrane/core/openapi/validators/JsonSchemaTestSuiteTests.java:0-0
Timestamp: 2025-06-18T12:03:09.873Z
Learning: The mediaType method in the Message class (which Request extends) throws jakarta.mail.internet.ParseException because it creates a ContentType object for parsing MIME media types. The jakarta.mail.internet.ParseException import is correct and necessary in test files that call mediaType().
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Automated tests
  • GitHub Check: Analyze (java)
🔇 Additional comments (12)
core/src/main/java/com/predic8/membrane/core/openapi/validators/NullValidator.java (1)

28-37: LGTM! Correct null value detection.

The method properly handles both Java null values and Jackson NullNode instances, returning the appropriate NULL constant.

core/src/test/java/com/predic8/membrane/core/openapi/validators/SchemaValidatorTest.java (1)

89-89: LGTM! Stricter number validation is appropriate.

The test update correctly reflects that TextNode instances should not be validated as numbers, even if they contain numeric strings. This stricter type checking aligns with proper JSON Schema validation semantics.

core/src/main/java/com/predic8/membrane/core/openapi/validators/ArrayValidator.java (1)

50-50: LGTM! Proper context handling.

The assignment ensures that any modifications to the validation context are properly captured. This pattern suggests schemaType() returns a new or modified context instance rather than mutating in place.

core/src/test/resources/openapi/specs/header-params.yml (1)

93-93: LGTM! Pattern anchoring ensures complete string validation.

Adding ^ and $ anchors ensures the entire string consists only of word characters, providing stricter validation semantics. This change complements the regex matching adjustments in StringValidator.java.

core/src/main/java/com/predic8/membrane/core/openapi/validators/StringValidator.java (1)

207-207: Verify the regex matching behavior change is intentional.

Changing from matches() to find() alters the validation semantics from full-string matching to substring matching. This could allow patterns to match partially where they previously required complete string matches.

Ensure this change is intentional and consistent with the pattern anchoring seen in header-params.yml (line 93).

#!/bin/bash
# Description: Search for regex patterns in OpenAPI specs to verify anchoring consistency
# Expected: Most patterns should be anchored with ^ and $ if substring matching is used

echo "Searching for regex patterns in OpenAPI specs..."
fd -e yml -e yaml | xargs rg -n "pattern:" -A 1 -B 1

echo -e "\nSearching for unanchored patterns that might be affected..."
fd -e yml -e yaml | xargs rg -n 'pattern:.*[^$]"$' 
core/src/main/java/com/predic8/membrane/core/openapi/validators/AbstractBodyValidator.java (1)

46-47: Good defensive programming improvements.

The null check prevents potential NPE when accessing the schema's $ref property, and the assignment pattern correctly handles the immutable ValidationContext design where schemaType() returns a new instance.

core/src/main/java/com/predic8/membrane/core/openapi/validators/NumberValidator.java (4)

20-20: Import addition supports stricter type validation.

The TextNode import enables explicit handling of JSON string nodes in number validation.


26-30: Clear documentation of validation logic.

The comments effectively explain the distinction between valid numbers (in parameters as strings) and invalid numbers (JSON string nodes containing numeric text), aligning with JSON Schema specifications.


39-41: Correct JSON Schema compliance for TextNode handling.

Returning null for TextNode instances correctly indicates that JSON strings containing numbers should not be validated as numbers according to JSON Schema spec.


61-63: Consistent validation error for JSON string numbers.

The immediate validation error for TextNode instances aligns with the canValidate logic and enforces proper JSON Schema type validation.

core/src/test/java/com/predic8/membrane/core/openapi/validators/JsonSchemaTestSuiteTests.java (2)

13-13: Import is correct for mediaType() method usage.

Based on retrieved learnings, the jakarta.mail.internet.ParseException import is necessary because the mediaType() method in the Message class throws this exception when parsing MIME types.


34-38: Excellent addition of comprehensive JSON Schema compliance testing.

This test class provides valuable integration testing against the official JSON Schema Test Suite, which will help ensure the OpenAPI validators correctly implement JSON Schema specifications.

@membrane-ci-server
Copy link

This pull request needs "/ok-to-test" from an authorized committer.

@rrayst
Copy link
Member Author

rrayst commented Jun 24, 2025

/ok-to-test

@rrayst rrayst requested a review from predic8 June 24, 2025 07:20
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

♻️ Duplicate comments (5)
core/src/test/java/com/predic8/membrane/core/openapi/validators/JsonSchemaTestSuiteTests.java (5)

59-59: Method name doesn't match its behavior.

The method runTestsFoundInDirectory suggests it only finds tests, but it actually runs them. Consider renaming to runTestsInDirectory for clarity.


1-172: Consider extracting utility methods and improving logging.

The class has grown quite complex. Consider extracting utility methods for:

  1. OpenAPI spec generation (lines 98-118)
  2. Schema transformation logic (definitions/$defs handling)
  3. Test result evaluation

Also, replace direct System.out.println usage with proper logging throughout the class.


41-41: Use OS-independent path separators.

Based on past review feedback, the hard-coded Windows backslashes should be replaced with OS-independent paths:

-    public final String TEST_SUITE_BASE_PATH = "git\\JSON-Schema-Test-Suite\\tests\\draft6";
+    public final String TEST_SUITE_BASE_PATH = "git/JSON-Schema-Test-Suite/tests/draft6";

Forward slashes work on all operating systems, including Windows.


64-64: Potential NPE when listFiles() returns null.

The listFiles() method can return null if the directory doesn't exist or isn't readable:

-        for (File file : base.listFiles()) {
+        File[] files = base.listFiles();
+        if (files == null) {
+            throw new RuntimeException("Unable to list files in directory: " + baseDir);
+        }
+        for (File file : files) {

159-161: Exception handling may hide validation failures.

The current exception handling only prints the stack trace but doesn't fail the test, which could hide real validation issues:

         } catch (Exception e) {
-            e.printStackTrace();
+            log.error("Validation failed for test: " + description2, e);
+            throw new RuntimeException("Validator threw exception during test: " + description2, e);
         }

This ensures tests fail loudly when unexpected exceptions occur, making debugging easier.

🧹 Nitpick comments (1)
core/src/test/resources/openapi/specs/integer.yml (1)

59-60: LGTM - Clean addition for testing validation without explicit type.

The new maximum-without-type property is well-designed to test validation behavior when only constraints are specified without explicit type declarations.

However, fix the missing newline at the end of the file:

         maximum-without-type:
-          maximum: 5
+          maximum: 5
+
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ae23eb8 and 857fdac.

📒 Files selected for processing (6)
  • core/src/main/java/com/predic8/membrane/core/openapi/validators/NullValidator.java (1 hunks)
  • core/src/test/java/com/predic8/membrane/core/openapi/validators/IntegerTest.java (1 hunks)
  • core/src/test/java/com/predic8/membrane/core/openapi/validators/JsonSchemaTestSuiteTests.java (1 hunks)
  • core/src/test/java/com/predic8/membrane/core/openapi/validators/NullTest.java (1 hunks)
  • core/src/test/resources/openapi/specs/integer.yml (1 hunks)
  • core/src/test/resources/openapi/specs/null.yml (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • core/src/main/java/com/predic8/membrane/core/openapi/validators/NullValidator.java
🧰 Additional context used
🧠 Learnings (1)
core/src/test/java/com/predic8/membrane/core/openapi/validators/JsonSchemaTestSuiteTests.java (2)
Learnt from: rrayst
PR: membrane/api-gateway#1906
File: core/src/test/java/com/predic8/membrane/core/openapi/validators/JsonSchemaTestSuiteTests.java:0-0
Timestamp: 2025-06-18T12:03:09.873Z
Learning: The mediaType method in the Request class throws jakarta.mail.internet.ParseException, not java.text.ParseException, making the jakarta.mail.internet.ParseException import necessary and correct in JsonSchemaTestSuiteTests.java.
Learnt from: rrayst
PR: membrane/api-gateway#1906
File: core/src/test/java/com/predic8/membrane/core/openapi/validators/JsonSchemaTestSuiteTests.java:0-0
Timestamp: 2025-06-18T12:03:09.873Z
Learning: The mediaType method in the Message class (which Request extends) throws jakarta.mail.internet.ParseException because it creates a ContentType object for parsing MIME media types. The jakarta.mail.internet.ParseException import is correct and necessary in test files that call mediaType().
🪛 YAMLlint (1.37.1)
core/src/test/resources/openapi/specs/integer.yml

[error] 60-60: no new line character at the end of file

(new-line-at-end-of-file)

🪛 Checkov (3.2.334)
core/src/test/resources/openapi/specs/null.yml

[HIGH] 1-33: Ensure that the global security field has rules defined

(CKV_OPENAPI_4)


[HIGH] 1-33: Ensure that security operations is not empty.

(CKV_OPENAPI_5)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Automated tests
  • GitHub Check: Analyze (java)
🔇 Additional comments (3)
core/src/test/resources/openapi/specs/null.yml (1)

1-32: Excellent OpenAPI 3.1.0 spec for null type testing.

This spec effectively covers the key null validation scenarios:

  • Standalone null type validation
  • Array items with union types (integer or null)

The OpenAPI 3.1.0 version is correct since it properly supports null as a standalone type, which is essential for these test cases.

core/src/test/java/com/predic8/membrane/core/openapi/validators/IntegerTest.java (1)

109-121: Well-implemented test methods for maximum-without-type validation.

Both test methods follow the established pattern and properly test the boundary conditions:

  • invalidMaximumWithoutTypeInBody() correctly validates that 13 > 5 fails
  • validMaximumWithoutTypeInBody() correctly validates that 5 = 5 passes

The tests complement the new schema property and ensure validation works correctly even without explicit type declarations.

core/src/test/java/com/predic8/membrane/core/openapi/validators/NullTest.java (1)

36-63: Comprehensive null validation test coverage.

The test class provides excellent coverage for null type validation scenarios:

  1. Standalone null validation - Tests both valid null and invalid string inputs
  2. Array with union types - Tests arrays containing null/integer combinations and validates proper error handling for invalid types

The tests are well-structured, follow established patterns, and properly validate error messages. The use of mapToJson(null) correctly handles null serialization for testing.

Copy link
Member

@predic8 predic8 left a comment

Choose a reason for hiding this comment

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

ref

@predic8 predic8 added the Prio-1 label Jun 30, 2025
@rrayst rrayst requested a review from predic8 June 30, 2025 12:03
@predic8 predic8 merged commit 79e600c into master Jun 30, 2025
4 of 5 checks passed
@predic8 predic8 deleted the fix-npe-in-openapi-validation branch June 30, 2025 12:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants