Skip to content

Commit

Permalink
API-59 Errors.ErrorObjects (jmlue42#46)
Browse files Browse the repository at this point in the history
This commit introduces a new set of Spectral rules specifically tailored for validating JSON:API error object structures within OpenAPI documents. Key highlights include:

- Creation of Spectral rules to ensure compliance with JSON:API standards, focusing on error object structures such as array structure, object properties, links, source, and meta-information.
- Development of a comprehensive OpenAPI test document (`validArrayStructureDocument`) that adheres to JSON:API specifications, particularly in defining error responses.
- Implementation of various utility functions to enhance the testing framework, including functions for setting up Spectral, processing test results, and dynamically managing rule sets based on test requirements.
- Debugging and refinement of rules and test document structure to align with JSONPath expressions and Spectral's schema validation requirements.

These additions significantly improve our capability to automatically validate and ensure the consistency of API responses with the JSON:API standard.

* Pushing changes to repo to resolve out-of-date with base branch

* resolving linting errors

* Rule Explanation for OpenAPI TestCase Document.

* Full compatibility with OpenAPI 3.1.0

Some new features were added such as, Path Item Object, which allows you to define more complex structures for paths, however our current usage is adequate.

* Refactor testFile name.

* feat: Implement dynamic debug logging with environment variable control

this commit introduces a centralized debugging utility () that enhances the logging mechanism across multiple test files. Key changes include:

- creation of  with functions for different log levels (log, debug, warn, error, info), each controlled by specific environment variables (LOG_DEBUG, DEBUG_DEBUG, WARN_DEBUG, ERROR_DEBUG, INFO_DEBUG).
- Refactoring test file to use the new debug utility, replacing direct  calls with  functions.
- Documentation of the debug utility with comprehensive JSDOC comments, explaining usage and configuration.

These changes allow for finer control over log outputs and a more consistent debugging experience across the project. Debugging can now be easily toggled on or off and customized via environment variables without altering code in individual test files.

* fix: Strings must use single quotes

* Fix: Rebase Error

- Correcting the failed rebase conflict.

* Disabling linting rules:

- no-invalid-this
  - Used for obtaining the ruleset title to determine which rule is being used for that specific TestCase.
- no-console
  - Currently using environmental variables to enable console logs for testing

* Fix: Correct JSDoc paramter type annotation

- Updated the JSDoc commet to correctly annotate the `error` parameter.
- Changed from `@param{Error}` to `@param{error}` to accurately represent the parameter type.

* Refactor: Severity Change

- Spectral changed how the severity is obtained.
- Changed from type to string

* Refactor: OpenAPI Format Validated

- Changed the format to match OpenAPI requirements

* Feat: Invalid OpenAPI Document for Error Objects

- This file will contain all invalid data for negative test cases

* Feat: Debug Utility

- A module for handling debug logs with different levels (log, debug, warn, error, info).
- Each level can be independently enabled via specific environment variables

* Refactor: Change structure of helper functions

- To follow pattern of other test cases, restructure how the helper utils are being utilized.
- Implemented use of Debug Utility

* Feat: Created utility for setting up Spectral

* Feat: Custom Function - validatePropertyType

- This is a solution to resolve the '$ref' dereferencing. Spectrals Pre-Define functions do not obtain the JSONPath values for '$ref' properties.
- This cusotm function will check if the provided options property is provided in the JSONPath; if it is true the property type will then be validated against the expected type providing in the functionOptions.

* Refactor: Following other test case formats

- will provide will cases for each rule, same as other test cases:

* Validate JSONPath
* Positive Scenario
* Negative Scenario

NOTE: Currently the 'Validate JSONPath' will need additional research since `JSONPath` does not inherently resolve '$ref' references found in JSON documents or OpenAPI specifications.

POTENTIAL SOLUTION:
* Preprcess the Document
  - Before applying JSONPath queries, preprocess the JSON document to resolve and replace all `$ref` references with the actual content they point to. This `dereferencing1 process can be accomplised using a library called 'json-schema-ref-parser'. This would allow us to use `jsonpath-plus`.
* Custom Handling
  - Can write custom logic to handle `$ref` references. This does require more work and would need to know the specific JSON document structure.

* Comprehensive Overhaul of Testing Infrastructure and Refactoring

This commit represents a thorough update and enhancement of the unit testing setup and various utility functions in the spectral-jsonapi-ruleset project. Key changes over the past two days include:

- Expanded and refined unit testing framework, integrating `sinon` for stubs and spies, enhancing test isolation and precision.
- Refactored existing unit tests for consistency, readability, and improved coverage.
- Updated and standardized utility functions, including `disableAllRulesets`, `displayRulesets`, `enableSpecificRuleset`, `formattedErrorMessage`, `getEnabledRules`, `handleSpectralResults`, `processErrors`, and `setupSpectral`. Each of these received improvements for better functionality and compliance with project standards.
- Implemented an optional parameter in `setupSpectralBeforeEach` utility to allow custom Spectral setup, enhancing testing flexibility.
- Resolved issues with `AggregateError` handling and mock console outputs, leading to cleaner and more reliable test execution.
- Modified `package.json` to include revised testing scripts, integrating the updated test suite into the project's workflow.
- Enhanced JSDoc comments for improved clarity and documentation quality across multiple utility functions.

These changes collectively enhance the robustness, maintainability, and clarity of the project's testing infrastructure and associated utility functions.

---

Note: This commit captures extensive collaborative work focused on elevating the project's code quality and testing standards, spanning over multiple days.

* Feat: Enhance `$ref` Resolution in OpenAPI Document Parsing

This commit introduces significant improvements in the way `$ref` references are resolved within OpenAPI documents. Key changes include:

- `mockApiDocument.js`: Updated mock data to more accurately represent real-world OpenAPI document structures, ensuring it aligns with testing and resolution logic.
- `refResolver.js`: Refined the logic to recursively resolve `$ref` references in both objects and arrays. Added circular reference detection to prevent infinite loops during resolution. Enhanced function documentation with updated JSDoc comments for better clarity and maintainability.
- `refResolver.test.js`: Revised unit tests to validate the correct resolution of `$ref` references, including tests for nested structures, arrays, and root-level references. Adjusted test cases to align with the updated reference resolution logic and mock data.

These changes aim to provide more robust and accurate parsing of OpenAPI documents, ensuring `$ref` references are resolved correctly in various scenarios, including complex nested structures and arrays.

* Style: Provide clean display for passing test cases in console

* Style: Implemented visual displays of the type of message being displayed to console.

* Refactor: correct usage of what to be displayed to adhere with the environment variables enablement.

* Refactor: Commented out certain debugging code

- Enabling these debugging is needed on a cases by cases basis and will leave for future usage with other test cases

* Refactor: Error Object Rulesets

This commit introduces new rules for JSON:API error object validation. The ruleset includes a comprehensive set of rules designed to enforce the JSON:API specifications for error objects, ensuring adherence to standard practices and enhancing the quality of API responses. Each rule in the ruleset is accompanied by detailed JSDOC comments that explain its purpose, functionality, and usage, making the ruleset easy to understand and maintain. This addition is a significant step towards robust API error handling and standardization.

* Fix: debugUtils being displayed in github jobs

* Feat: Complete initial set of test cases and refine JSONPath expressions for JSON:API rules

This commit marks the completion of detailed test cases for several JSON:API error object rulesets, including:
- errors-error-objects-array-structure
- errors-error-objects-object-structure
- errors-error-objects-object-structure-length
- errors-error-objects-items-id-type
- errors-error-objects-items-links-type
- errors-error-objects-items-links
- errors-error-objects-items-links-structure-length
- errors-error-objects-items-links-about-type
- errors-error-objects-items-links-about-format
- errors-error-objects-items-links-type-type
- errors-error-objects-items-links-type-format

Significant changes have been made to the JSONPath expressions and functions within these rulesets to enhance accuracy and efficiency. Notably, an issue with the 'errors-error-objects-array-structure' rule has been resolved by switching from a custom function to the 'enumeration' predefined function, simplifying the validation process and adhering to the prerequisite of using only predefined functions.

Remaining tasks include completing test cases for the following rulesets:
- errors-error-objects-items-status-type
- errors-error-objects-items-code-type
- errors-error-objects-items-title-type
- errors-error-objects-items-detail-type
- errors-error-objects-items-source-type
- errors-error-objects-items-source
- errors-error-objects-items-source-pointer-type
- errors-error-objects-items-source-parameter-type
- errors-error-objects-items-source-header-type
- errors-error-objects-items-source-structure-length
- errors-error-objects-items-items-type

These updates significantly improve the robustness and reliability of the JSON:API error object validation process.

* Completion of remaining JSON:API Errors.ErrorObjects Ruels and Test Cases

- Fully implemented and documented Spectral rules for JSON:API Errors.ErrorObjects as per JSON:API Specifications.
- Each rule checks specific aspects of the error objects, ensuring adherence to standards like array structure, member types, and URI formats.
- Added comprehensive test cases for all rules covering both positive and negative scenarios. This includes checks for array structures, object member validation, type enforcement, and specific member values.
- Enhanced documentation with detail jsdocs for key areas including helper functions, complex rule logic, JSONPath expressions, and individual test cases. This aims to improve code readability and maintainability.
- Included specific test documents for both valid and invalid API structures to validate each rule thoroughly.
- Conducted rigorous testing to ensure all rules and test cases function as expected, with a focus on reliability and accuracy in error object validation.

This commit represents a complete and robust solution for validation JSON:API error objects, ensuring compliance with the JSON:API specification and enhacning the overall quality of API error handling.

* Refactor: Removal of custom function

- No longer needed due to resolving issue the function was created for.

* Feat: Provided a way to test a valid/invalid OpenApi Document against the rules created using Spectrals CLI command.

* Refactor: Series of requested changes

- Removed unnecessary Spectral rulesets.
- Refactored OpenAPI Documents for better clarity and compliance with JSON:API v1.0
- Eliminated redundant test cases
- Refactored rulesets to comply with JSON:API v1.0

* fix: eslint rules

* Refactor: Updated YAML OpenAPI Document for Spectrals CLI Testing
  • Loading branch information
ezenity authored Dec 7, 2023
1 parent 397af11 commit 25786e1
Show file tree
Hide file tree
Showing 57 changed files with 7,452 additions and 6 deletions.
1 change: 1 addition & 0 deletions .eslintrc.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
env:
mocha: true
node: true
es6: true
extends: "eslint:recommended"
Expand Down
195 changes: 195 additions & 0 deletions cliTest/errorsErrorObject/failing-rules.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
# This OpenAPI Document provides a way of testing all the rules for `jsonapi-errors-error-object.js`
# using Spectrals CLI Command
#
# Usage:
# spectral lint cliTest/errorsErrorObject/failing-rules.yaml --ruleset rules/jsonapi-errors-error-object.js
#
# This document will generate `22 errors` as expected for each rule.
openapi: 3.1.0
info:
title: User Information API
version: 1.0.0
description: API for retrieving user information
paths:
/users/{userId}:
get:
tags:
- users
summary: Get User by ID
description: Retrieves information for a specific user by their ID.
operationId: getUserById
parameters:
- name: userId
in: path
required: true
description: Unique identifier of the user
schema:
type: string
responses:
'200':
description: Successful response with user information
content:
application/vnd.api+json:
schema:
type: object
properties:
data:
type: object
properties:
id:
type: string
type:
type: string
enum:
- user
attributes:
type: object
properties:
name:
type: string
email:
type: string
examples:
user:
summary: User Example
value:
data:
id: '12345'
type: user
attributes:
name: John Doe
email: [email protected]
'400':
description: Bad Request
content:
application/vnd.api+json:
schema:
type: object
properties:
errors:
type: string
items:
type: object
properties:
idd:
type: string
id:
type: object
links:
type: string
properties:
about:
type: object
format: urie
aboutt:
type: string
format: uri
status:
type: object
code:
type: object
title:
type: object
detail:
type: object
source:
type: string
properties:
pointer:
type: object
parameter:
type: object
parameterr:
type: object
meta:
type: string
additionalProperties: true
required:
- detail
'404':
description: User Not Found
content:
application/vnd.api+json:
schema:
type: object
properties:
errors:
type: array
items:
type: object
properties:
id:
type: string
links:
type: object
properties:
about:
type: string
format: uri
status:
type: string
code:
type: string
title:
type: string
detail:
type: string
source:
type: object
properties:
pointer:
type: string
parameter:
type: string
meta:
type: object
additionalProperties: true
required:
- detail
'500':
description: Internal Server Error
content:
application/vnd.api+json:
schema:
type: object
properties:
errors:
type: array
items:
type: object
properties:
id:
type: string
links:
type: object
properties:
about:
type: string
format: uri
status:
type: string
code:
type: string
title:
type: string
detail:
type: string
source:
type: object
properties:
pointer:
type: string
parameter:
type: string
meta:
type: object
additionalProperties: true
required:
- detail
components:
schemas:
Test:
type: object
properties:
test:
type: string
188 changes: 188 additions & 0 deletions cliTest/errorsErrorObject/passing-rules.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
# This OpenAPI Document provides a way of testing all the rules for `jsonapi-errors-error-object.js`
# using Spectrals CLI Command
#
# Usage:
# spectral lint cliTest/errorsErrorObject/passing-rules.yaml --ruleset rules/jsonapi-errors-error-object.js
#
# This document will generate `0 errors` as expected for each rule.
openapi: 3.1.0
info:
title: User Information API
version: 1.0.0
description: API for retrieving user information
paths:
/users/{userId}:
get:
tags:
- users
summary: Get User by ID
description: Retrieves information for a specific user by their ID.
operationId: getUserById
parameters:
- name: userId
in: path
required: true
description: Unique identifier of the user
schema:
type: string
responses:
'200':
description: Successful response with user information
content:
application/vnd.api+json:
schema:
type: object
properties:
data:
type: object
properties:
id:
type: string
type:
type: string
enum:
- user
attributes:
type: object
properties:
name:
type: string
email:
type: string
examples:
user:
summary: User Example
value:
data:
id: '12345'
type: user
attributes:
name: John Doe
email: [email protected]
'400':
description: Bad Request
content:
application/vnd.api+json:
schema:
type: object
properties:
errors:
type: array
items:
type: object
properties:
id:
type: string
links:
type: object
properties:
about:
type: string
format: uri
status:
type: string
code:
type: string
title:
type: string
detail:
type: string
source:
type: object
properties:
pointer:
type: string
parameter:
type: string
meta:
type: object
additionalProperties: true
required:
- detail
'404':
description: User Not Found
content:
application/vnd.api+json:
schema:
type: object
properties:
errors:
type: array
items:
type: object
properties:
id:
type: string
links:
type: object
properties:
about:
type: string
format: uri
status:
type: string
code:
type: string
title:
type: string
detail:
type: string
source:
type: object
properties:
pointer:
type: string
parameter:
type: string
meta:
type: object
additionalProperties: true
required:
- detail
'500':
description: Internal Server Error
content:
application/vnd.api+json:
schema:
type: object
properties:
errors:
type: array
items:
type: object
properties:
id:
type: string
links:
type: object
properties:
about:
type: string
format: uri
status:
type: string
code:
type: string
title:
type: string
detail:
type: string
source:
type: object
properties:
pointer:
type: string
parameter:
type: string
meta:
type: object
additionalProperties: true
required:
- detail
components:
schemas:
Test:
type: object
properties:
test:
type: string
Loading

0 comments on commit 25786e1

Please sign in to comment.