-
Notifications
You must be signed in to change notification settings - Fork 64
feat: Implement comprehensive unit testing for platform #1369
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
base: main
Are you sure you want to change the base?
Conversation
WalkthroughSeveral new test suites were introduced across multiple modules to rigorously validate schema creation, attribute validation, and W3C-compliant schema building. Enhancements were made to schema builder and attribute validation logic to support additional constraints and robust error handling. No exported function signatures were changed; all modifications are additive or internal. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant API Gateway
participant Issuance Service
participant Ledger Service
participant Schema Builder
Client->>API Gateway: Submit schema creation DTO
API Gateway->>API Gateway: Validate DTO (class-validator)
API Gateway->>Ledger Service: Forward valid schema DTO
Ledger Service->>Schema Builder: Build W3C JSON schema
Schema Builder-->>Ledger Service: Return JSON schema
Ledger Service-->>API Gateway: Respond with schema details
API Gateway-->>Client: Return schema creation result
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
Note ⚡️ Unit Test Generation is now available in beta!Learn more here, or try it out under "Finishing Touches" below. ✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
|
There was a problem hiding this 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 (5)
apps/issuance/libs/helpers/attributes.validator.ts (1)
47-47
: Minor style: Consider yoda condition for consistencyESLint suggests using yoda conditions (literals on the left side) for consistency with the project's style guide.
- if (attributeValue !== 'true' && attributeValue !== 'false') { + if ('true' !== attributeValue && 'false' !== attributeValue) {apps/issuance/src/issuance.service.spec.ts (1)
1-1
: Remove unused importsThe
Test
andTestingModule
imports are not used in this test file since it directly tests the validation function without requiring NestJS testing module setup.-import { Test, TestingModule } from '@nestjs/testing'; import { BadRequestException } from '@nestjs/common';
apps/ledger/src/schema/schema.spec.ts (1)
1-1
: Remove unused NestJS testing importsThe
Test
andTestingModule
imports are not used since this test suite uses direct mocking rather than NestJS testing module setup.-import { Test, TestingModule } from '@nestjs/testing'; import { BadRequestException, NotFoundException } from '@nestjs/common';
apps/api-gateway/src/dtos/create-schema-dto.spec.ts (2)
177-325
: Solid validation logic with minor formatting improvements neededThe number and array validation tests provide excellent coverage of constraints and edge cases. However, consider improving array formatting for better readability.
For better code formatting, consider adding line breaks in array literals:
- items: [{ + items: [ + { attributeName: 'skill', displayName: 'Skill', schemaDataType: W3CSchemaDataType.STRING, isRequired: true - }] + } + ]
634-692
: Valuable cross-field validation testing with minor style fix neededExcellent tests that validate conditional validations based on attribute data types. These integration-style tests ensure the validation rules work correctly together.
Fix the yoda condition for better readability:
-expect(errors.some(error => error.property === 'attributes')).toBe(true); +expect(errors.some(error => 'attributes' === error.property)).toBe(true);Wait, that's backwards. The current code is actually correct. The static analysis tool is suggesting the wrong fix. The current code
error.property === 'attributes'
is more readable than'attributes' === error.property
.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (7)
apps/api-gateway/src/dtos/create-schema-dto.spec.ts
(1 hunks)apps/issuance/libs/helpers/attributes.validator.spec.ts
(1 hunks)apps/issuance/libs/helpers/attributes.validator.ts
(1 hunks)apps/issuance/src/issuance.service.spec.ts
(1 hunks)apps/ledger/libs/helpers/w3c.schema.builder.spec.ts
(1 hunks)apps/ledger/libs/helpers/w3c.schema.builder.ts
(5 hunks)apps/ledger/src/schema/schema.spec.ts
(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (5)
apps/ledger/libs/helpers/w3c.schema.builder.ts (3)
libs/validations/maximum.ts (1)
Maximum
(3-28)libs/validations/exclusiveMinimum.ts (1)
ExclusiveMinimum
(3-28)libs/validations/exclusiveMaximum.ts (1)
ExclusiveMaximum
(3-28)
apps/issuance/src/issuance.service.spec.ts (1)
apps/issuance/libs/helpers/attributes.validator.ts (1)
validateW3CSchemaAttributes
(5-87)
apps/issuance/libs/helpers/attributes.validator.spec.ts (1)
apps/issuance/libs/helpers/attributes.validator.ts (1)
validateW3CSchemaAttributes
(5-87)
apps/ledger/src/schema/schema.spec.ts (1)
apps/ledger/src/schema/interfaces/schema.interface.ts (1)
ICreateW3CSchema
(90-95)
apps/ledger/libs/helpers/w3c.schema.builder.spec.ts (1)
apps/ledger/libs/helpers/w3c.schema.builder.ts (1)
w3cSchemaBuilder
(16-468)
🪛 ESLint
apps/issuance/src/issuance.service.spec.ts
[error] 1-1: 'Test' is defined but never used.
(@typescript-eslint/no-unused-vars)
[error] 1-1: 'TestingModule' is defined but never used.
(@typescript-eslint/no-unused-vars)
apps/issuance/libs/helpers/attributes.validator.ts
[error] 47-47: Expected literal to be on the left side of !==.
(yoda)
[error] 47-47: Expected literal to be on the left side of !==.
(yoda)
apps/ledger/src/schema/schema.spec.ts
[error] 1-1: 'Test' is defined but never used.
(@typescript-eslint/no-unused-vars)
[error] 1-1: 'TestingModule' is defined but never used.
(@typescript-eslint/no-unused-vars)
[error] 13-13: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 19-19: Unexpected trailing comma.
(comma-dangle)
apps/ledger/libs/helpers/w3c.schema.builder.spec.ts
[error] 17-17: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 39-39: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 55-55: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 76-76: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 77-77: Use object destructuring.
(prefer-destructuring)
[error] 97-97: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 115-115: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 134-134: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 155-155: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 175-175: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 193-193: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 210-210: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 229-229: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 248-248: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 284-284: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 309-309: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 373-373: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 374-374: Use object destructuring.
(prefer-destructuring)
[error] 385-385: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 392-392: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 406-406: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 410-410: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 417-417: Unexpected trailing comma.
(comma-dangle)
[error] 419-419: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 428-428: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 436-436: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
apps/api-gateway/src/dtos/create-schema-dto.spec.ts
[error] 248-248: A linebreak is required after '['.
(array-bracket-newline)
[error] 253-253: A linebreak is required before ']'.
(array-bracket-newline)
[error] 269-269: A linebreak is required after '['.
(array-bracket-newline)
[error] 274-274: A linebreak is required before ']'.
(array-bracket-newline)
[error] 290-290: A linebreak is required after '['.
(array-bracket-newline)
[error] 295-295: A linebreak is required before ']'.
(array-bracket-newline)
[error] 311-311: A linebreak is required after '['.
(array-bracket-newline)
[error] 316-316: A linebreak is required before ']'.
(array-bracket-newline)
[error] 550-550: Expected literal to be on the left side of ===.
(yoda)
[error] 678-678: A linebreak is required after '['.
(array-bracket-newline)
[error] 683-683: A linebreak is required before ']'.
(array-bracket-newline)
🔇 Additional comments (21)
apps/ledger/libs/helpers/w3c.schema.builder.ts (5)
4-14
: LGTM: Import statements properly organizedThe import paths have been updated to use consistent relative paths, and the new
ExclusiveMaximum
andMaximum
validators are properly imported to support the enhanced validation logic.
37-50
: Enhanced string validation supportGood addition of enum, contentEncoding, and contentMediaType validation for string attributes. These enhancements align with JSON Schema specifications and expand the schema builder's validation capabilities.
60-63
: Complete number validation coverageExcellent addition of
maximum
andexclusiveMaximum
validations for number attributes. The implementation is consistent with existing validation patterns and provides comprehensive constraint coverage for numeric types.Also applies to: 70-73
114-117
: Improved error handling with defensive programmingGood addition of validation to skip attributes missing essential properties (
attributeName
orschemaDataType
). This defensive approach prevents potential runtime errors and improves the function's robustness when handling malformed input.
243-245
: Enhanced array handling for edge casesGood improvement to handle arrays without items definition by applying validations directly to the base property. This makes the schema builder more flexible and ensures array-specific constraints (minItems, maxItems, uniqueItems) are still applied even when items aren't defined.
apps/issuance/libs/helpers/attributes.validator.ts (1)
30-66
: Well-designed string-based validation approachThe shift to string-based validation is well-implemented and appropriate for web API scenarios where attribute values are received as strings. The validation logic is sound:
- String validation: Always accepts strings ✓
- Number/Integer: Proper NaN checking after conversion ✓
- Boolean: Strict 'true'/'false' validation for type safety ✓
- DateTime: Standard Date.parse() validation ✓
- Graceful fallback for other types ✓
This approach handles the common web API pattern effectively while maintaining type safety.
apps/issuance/src/issuance.service.spec.ts (1)
6-77
: Well-structured integration testsThe test suite effectively validates the core validation scenarios:
- ✓ Valid attributes with proper data types
- ✓ Invalid numeric attribute handling
- ✓ Missing required attribute detection
The test structure follows Jest best practices with clear descriptions and appropriate assertions using
BadRequestException
.apps/issuance/libs/helpers/attributes.validator.spec.ts (1)
5-248
: Exceptional test coverage and qualityThis test suite demonstrates excellent testing practices with comprehensive coverage:
Strengths:
- ✓ Complete data type validation coverage (string, number, boolean, integer, datetime)
- ✓ Thorough edge case testing (decimal numbers for integers, complex datetime formats)
- ✓ Proper error boundary testing with
BadRequestException
- ✓ Clear test structure with descriptive names
- ✓ Realistic test data using proper W3C schema data types
- ✓ Good documentation of validation behavior (line 204 comment about decimal handling)
Coverage includes:
- Valid/invalid attribute scenarios
- Required vs optional field handling
- Type conversion validation
- Extra attribute detection
- Null/undefined value handling
This level of test coverage significantly enhances the reliability of the validation logic.
apps/ledger/src/schema/schema.spec.ts (2)
12-425
: Outstanding comprehensive test suiteThis test suite demonstrates exceptional testing practices with thorough coverage across multiple dimensions:
Schema Creation Testing:
- ✓ Success scenarios with realistic payloads
- ✓ Comprehensive error handling (agent not found, builder failures, invalid types)
- ✓ Proper validation of schema attributes and required fields
W3C Schema Builder Validation:
- ✓ Complete attribute type coverage (string, number, array, datetime, boolean)
- ✓ Constraint validation (min/max length, patterns, numeric ranges, array constraints)
- ✓ Edge cases (empty attributes, complex nested structures)
Error Handling:
- ✓ Network and infrastructure failures
- ✓ Invalid DID format handling
- ✓ Service unavailability scenarios
- ✓ Configuration issues (missing endpoints)
Test Quality:
- ✓ Realistic test data and payloads
- ✓ Effective mocking strategy for external dependencies
- ✓ Clear test organization and descriptive names
- ✓ Proper assertion patterns with expected exceptions
This level of test coverage significantly enhances confidence in the schema creation and validation functionality.
13-13
: Test mocking patterns are acceptableThe
any
type usage formockSchemaService
is appropriate in test contexts where flexible mocking is needed. The trailing comma follows modern JavaScript/TypeScript conventions for easier array/object maintenance.Also applies to: 19-19
apps/ledger/libs/helpers/w3c.schema.builder.spec.ts (7)
1-4
: LGTM: Clean imports and test setupThe imports are well-organized and include all necessary dependencies for comprehensive testing.
63-140
: Comprehensive string validation testingExcellent coverage of string attribute validations including the newly added features like
enum
,contentEncoding
, andcontentMediaType
. The tests properly verify that constraints are applied to the generated schema properties.
142-216
: Thorough number validation coverageWell-structured tests that verify all numeric constraints including minimum/maximum bounds, exclusive bounds, multipleOf, and integer type handling. The test cases align well with JSON Schema validation requirements.
218-253
: Proper datetime and boolean validationGood validation of type mappings - datetime-local correctly maps to string with date-time format, and boolean attributes are properly handled.
255-316
: Excellent array validation with nested structuresComprehensive testing of array attributes including complex nested object items, constraint validation (minItems, maxItems, uniqueItems), and proper handling of required fields propagation. The edge case of arrays without items definition is also well covered.
318-401
: Strong integration testing with mixed attribute typesExcellent integration tests that validate the schema builder's ability to handle complex schemas with mixed attribute types. The schema ID generation test and $defs structure validation ensure the output conforms to W3C standards.
403-441
: Robust error handling and edge case coverageExcellent defensive testing that ensures the schema builder gracefully handles edge cases like null inputs, missing properties, special characters, and extremely long names. This demonstrates good resilience in the implementation.
apps/api-gateway/src/dtos/create-schema-dto.spec.ts (4)
1-82
: Well-structured DTO validation foundationExcellent setup with proper imports and comprehensive basic validation tests for W3CAttributeValue. The tests correctly verify required field validation and rejection of invalid values using class-validator patterns.
83-175
: Thorough string validation testingComprehensive coverage of string attribute validations including length constraints, patterns, and enums. The negative test cases properly validate boundary conditions like negative minLength and zero maxLength.
327-402
: Complete object validation coverageExcellent testing of object attribute validations including property constraints and nested property handling. The tests properly validate the complex object schema scenarios.
405-632
: Comprehensive schema-level validationExcellent coverage of CreateW3CSchemaDto and GenericSchemaDTO validation including edge cases like whitespace trimming, empty values, and nested validation error propagation. The tests ensure robust input validation at the API gateway level.
} | ||
]; | ||
|
||
const result = w3cSchemaBuilder(attributes, 'Person Schema', 'A schema for person credentials') as any; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Improve type safety by avoiding any
type casting
The excessive use of any
type casting reduces type safety and could hide potential runtime issues. Consider defining a proper interface for the schema builder's return type or using the actual return type.
-const result = w3cSchemaBuilder(attributes, 'Person Schema', 'A schema for person credentials') as any;
+const result = w3cSchemaBuilder(attributes, 'Person Schema', 'A schema for person credentials');
If you need to access nested properties that TypeScript can't infer, create a proper interface:
interface W3CSchemaResult {
$schema: string;
$id: string;
title: string;
description: string;
type: string;
required: string[];
properties: Record<string, any>;
$defs: {
credentialSubject: {
properties: Record<string, any>;
required: string[];
};
// ... other definitions
};
}
const result = w3cSchemaBuilder(attributes, 'Person Schema', 'A schema for person credentials') as W3CSchemaResult;
Also applies to: 39-39, 55-55
🧰 Tools
🪛 ESLint
[error] 17-17: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
🤖 Prompt for AI Agents
In apps/ledger/libs/helpers/w3c.schema.builder.spec.ts at lines 17, 39, and 55,
the code casts the result of w3cSchemaBuilder to 'any', which reduces type
safety. Define a proper TypeScript interface representing the expected structure
of the schema builder's return value, then replace the 'any' cast with this
interface to ensure type safety and better code clarity.
@Aiyaret-Sandhu - can you please fix the DCO & Sonar issues? |
Overview
This PR implements comprehensive unit testing for the NestJS SSI Platform, completing Week 1 objectives of the testing roadmap. The implementation includes 78 passing unit tests across 4 critical modules with complete coverage of issuance attribute validation and schema creation functionality.
Tasks Completed
Test Coverage Summary
Test Execution Commands
#Run individual test suites
Refer to the document for complete report :
https://drive.google.com/file/d/1Ku87zvpbK6jsEmrh8n6bx79LuJ8s2_wF/view?usp=drive_link
Summary by CodeRabbit
New Features
Bug Fixes
Tests
Refactor