├── .github
└── workflows
│ └── main.yml
├── .gitignore
├── .npmrc
├── LICENSE
├── README.md
├── USAGE-EXAMPLES.md
├── cypress.config.js
├── cypress.env.json
├── cypress
├── e2e
│ ├── test-multiple-api-with-cy-api-override-style.js
│ ├── test-multiple-api-with-cy-api.js
│ ├── test-multiple-api-with-cypress-plugin-api.js
│ ├── test-plain-json-schema-fail.js
│ ├── test-plain-json-schema-pass.js
│ ├── tests-openapi-swagger-fail.js
│ └── tests-openapi-swagger-pass.js
├── fixtures
│ ├── mock-data-openapi-swagger
│ │ ├── fail
│ │ │ ├── GET
│ │ │ │ ├── service1_200.json
│ │ │ │ ├── service1_401.json
│ │ │ │ ├── service2_200.json
│ │ │ │ └── service2_401.json
│ │ │ └── POST
│ │ │ │ ├── service1_201.json
│ │ │ │ ├── service1_401.json
│ │ │ │ ├── service2_201.json
│ │ │ │ └── service2_401.json
│ │ ├── pass
│ │ │ ├── GET
│ │ │ │ ├── service1_200.json
│ │ │ │ ├── service1_401.json
│ │ │ │ ├── service2_200.json
│ │ │ │ └── service2_401.json
│ │ │ └── POST
│ │ │ │ ├── service1_201.json
│ │ │ │ ├── service1_401.json
│ │ │ │ ├── service2_201.json
│ │ │ │ └── service2_401.json
│ │ └── tests.json
│ ├── mock-data-plainjson
│ │ ├── fail.json
│ │ └── pass.json
│ └── schemas
│ │ ├── openapi-schema.json
│ │ ├── petstore-swagger-errors.json
│ │ ├── petstore-swagger.json
│ │ ├── plainjson-schema.json
│ │ └── swagger-schema.json
└── support
│ ├── commands.js
│ ├── e2e.js
│ ├── run-tests-openapi-swagger.js
│ └── run-tests-plainjson.js
├── images
├── cy_api_1_a.png
├── cy_api_1_details_a.png
├── cy_api_2_a.png
├── cy_api_2_details_a.png
├── disabled_a.png
├── error11_a.png
├── error12_a.png
├── error21_a.png
├── error23_a.png
├── overview_a.png
├── pass1_a.png
└── path_a.png
├── package-lock.json
├── package.json
├── src
├── StyleHandler.js
├── custom-log.js
├── index.d.ts
└── index.js
└── videos
├── README.md
├── overview.gif
└── overview.mp4
/.github/workflows/main.yml:
--------------------------------------------------------------------------------
1 | name: Cypress Tests
2 |
3 | on: push
4 |
5 | jobs:
6 | cypress-run:
7 | runs-on: ubuntu-22.04
8 | steps:
9 | - name: Checkout
10 | uses: actions/checkout@v4
11 | - name: Cypress run
12 | uses: cypress-io/github-action@v6
13 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Cypress generated files
2 | /cypress/videos/
3 | /cypress/screenshots/
4 | /cypress/downloads/
5 |
6 | # Node.js dependencies
7 | /node_modules/
8 |
9 | # Editor-specific files
10 | /.vscode/
11 | /.idea/
12 |
13 | # Common ignore patterns for Windows and macOS
14 | .DS_Store
15 | Thumbs.db
--------------------------------------------------------------------------------
/.npmrc:
--------------------------------------------------------------------------------
1 | registry=https://registry.npmjs.org
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2024 Sebastian Clavijo Suero (Personal)
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # cypress-ajv-schema-validator
2 |
3 | A Cypress plugin for API schema validation against plain JSON schemas, Swagger schema documents, or OpenAPI schema documents, leveraging the core-ajv-schema-validator powered by the Ajv JSON Schema Validator..
4 |
5 | 
6 |
7 | For a detailed guide on setting up and using this plugin to maximize its benefits, please refer to my articles:
8 | - ["CYPRESS-AJV-SCHEMA-VALIDATOR Plugin: The Brave Vigilante for Your API Contracts"](https://dev.to/sebastianclavijo/cypress-ajv-schema-validator-plugin-the-brave-vigilante-for-your-api-contracts-5cfe)
9 | - ["CYPRESS-AJV-SCHEMA-VALIDATOR v1.2.0: Boost Debugging Skills from Vigilante to Superhero with Advanced Schema Error Insights!"](https://dev.to/sebastianclavijo/cypress-ajv-schema-validator-v120-boost-debugging-skills-from-vigilante-to-superhero-with-advanced-schema-error-insights-1hld)
10 |
11 | Or the video:
12 | - ["CYPRESS AJV SCHEMA VALIDATOR VIDEO TUTORIAL"](https://www.youtube.com/watch?v=Dd6MMZ6qd7g)
13 |
14 | ---
15 |
16 | If you'd like to support my work, consider buying me a coffee or contributing to a training session, so I can keep learning and sharing cool stuff with all of you. Thank you for your support!
17 |
18 |
19 |
20 | ## Main Features
21 |
22 | - Cypress command **`cy.validateSchema()`** to report JSON Schema validation errors in the response obtained from any network request with `cy.request()`.
23 |
24 | - The command `cy.validateSchema()` is chainable and returns the original API response yielded.
25 |
26 | - Schema is provided as a JSON object, that could come from a Cypress fixture.
27 |
28 | - Uses the **core-ajv-schema-validator** plugin, which leverages the **Ajv JSON Schema Validator** as its engine **_(NEW in v2.0.0)_**.
29 |
30 | - Supports schemas provided as **plain JSON schema**, **OpenAPI 3.0.1 schema document** and **Swagger 2.0 schema document**.
31 |
32 | - Provides in the Cypress log a summary of the schema errors as well as a list of the individual errors in the schema validation.
33 |
34 | - By clicking on the summary of schema errors in the Cypress log, the console will output:
35 | - Number of schema errors.
36 | - Full list of schema errors as provided by Ajv.
37 | - A nested tree view of the validated data, clearly indicating the errors and where they occurred in an easy-to-understand format.
38 |
39 | - New environment variable `disableSchemaValidation` to disable schema validation in your tests **_(NEW in v1.2.0)_**.
40 |
41 | - Provides full integration with **Gleb Bahmutov**'s [@bahmutov/cy-api](https://github.com/bahmutov/cy-api) and **Filip Hric**'s [cypress-plugin-api](https://github.com/filiphric/cypress-plugin-api) plugins, enabling JSON schema validations to be performed directly after the `cy.api()` command.
42 |
43 | When enabled via the new environment variable `enableMismatchesOnUI`, schema errors are displayed directly in the user interfaces of these plugins **_(NEW in v1.2.0)_**.
44 |
45 | > ⭐⭐⭐⭐⭐
46 | > Example usage with these two API plugins:
47 | > `cy.api('/users/1').validateSchema(schema);`
48 | >
49 | > To see an example of `cypress-ajv-schema-validator` working with the `@bahmutov/cy-api` and `cypress-plugin-api` plugins for the Swagger PetStore API, check the sample tests files [test-petstore-with-cypress-plugin-api.js](cypress/e2e/test-petstore-with-cypress-plugin-api.js) and [test-multiple-api.js](cypress/e2e/test-multiple-api.js).
50 |
51 |
52 |
53 | ## About JSON Schemas and Ajv JSON Schema Validator
54 |
55 | ### JSON Schema
56 |
57 | JSON Schema is a hierarchical, declarative language that describes and validates JSON data.
58 |
59 | ### OpenAPI 3.0.1 and Swagger 2.0 Schema Documents
60 |
61 | The OpenAPI Specification (formerly Swagger Specification) are schema documents to describe your entire API (in JSON format or XML format). So a schema document will contain multiple schemas, one for each supported combination of **_Endpoint - Method - Expected Response Status_** (also called _path_) by that API.
62 |
63 | ### Ajv JSON Schema Validator
64 |
65 | AJV, or Another JSON Schema Validator, is a JavaScript library that validates data objects against a JSON Schema structure.
66 |
67 | It was chosen as the core engine of the `cypress-ajv-schema-validator` plugin because of its versatility, speed, capabilities, continuous maintenance, and excellent documentation. For more information on Ajv, visit the [Ajv official website](https://ajv.js.org/).
68 |
69 | Ajv supports validation of the following schema formats: **JSON Schema**, **OpenAPI 3.0.1** specification, and **Swagger 2.0** specification. However, Ajv needs to be provided with the specific schema to be validated for an endpoint, method, and expected response; it cannot process a full OpenAPI 3.0.1 or Swagger 2.0 schema document by itself.
70 |
71 | The `cypress-ajv-schema-validator` plugin simplifies this by obtaining the correct schema definition for the endpoint you want to test. You just need to provide the full schema document (OpenAPI or Swagger) and the path to the schema definition of the service you want to validate for your API (_Endpoint - Method - Expected Response Status_).
72 |
73 | > **Note:** The Ajv instance used in this plugin (`cypress-ajv-schema-validator`) is configured with the options `{ allErrors: true, strict: false }` to display all validation errors and disable strict mode.
74 |
75 |
76 |
77 | ## Installation
78 |
79 | ```sh
80 | npm install -D cypress-ajv-schema-validator
81 | ```
82 |
83 | ## Compatibility
84 |
85 | - Cypress 12.0.0 or higher
86 | - Ajv 8.16.0 or higher
87 | - ajv-formats 3.0.1 or higher
88 |
89 | ## Configuration
90 |
91 | - Add the following lines either to your `cypress/support/commands.js` to include the custom command and function globally, or directly in the test file that will host the schema validation tests:
92 |
93 | ```js
94 | import 'cypress-ajv-schema-validator';
95 | ```
96 |
97 | - To **disable schema validation** even when the `cy.validateSchema()` command is present in the test, set the Cypress environment variable `disableSchemaValidation` to `true`. By default, schema validation is enabled.
98 |
99 | - To **enable the display of schema errors** directly in the user interfaces of the `@bahmutov/cy-api` and `cypress-plugin-api` plugins, set the Cypress environment variable `enableMismatchesOnUI` to `true`. By default, this feature is disabled.
100 |
101 |
102 | ## API Reference
103 |
104 | ### `cy.validateSchema(schema, path)`
105 |
106 | It is expected to be chained to an API response (from a `cy.request()` or `cy.api()`). It validates the response body against the provided schema.
107 |
108 | #### Parameters
109 |
110 | - `schema` (object): The schema to validate against. Supported formats are plain JSON schema, Swagger, and OpenAPI documents.
111 | - `path` (object, optional): This second parameter only applies to Swagger or OpenAPI documents.
112 | It represents the path to the schema definition in a Swagger or OpenAPI document and is determined by three properties:
113 | - `endpoint` (string, optional): The endpoint path.
114 | - `method` (string, optional): The HTTP method. Defaults to 'GET'.
115 | - `status` (integer, optional): The response status code. If not provided, defaults to 200.
116 |
117 | #### Returns
118 |
119 | - `Cypress.Chainable`: The response object wrapped in a Cypress.Chainable.
120 |
121 | #### Throws
122 |
123 | - `Error`: If any of the required parameters are missing or if the schema or schema definition is not found.
124 |
125 | Example providing a Plain JSON schema:
126 |
127 | ```js
128 | cy.request('GET', 'https://awesome.api.com/users/1')
129 | .validateSchema(schema);
130 | ```
131 |
132 | Example providing an OpenAPI 3.0.1 or Swagger 2.0 schema documents and path to the schema definition:
133 |
134 | ```js
135 | cy.request('GET', 'https://awesome.api.com/users/1')
136 | .validateSchema(schema, { endpoint: '/users/{id}', method: 'GET', status: 200 });
137 | ```
138 |
139 | Using the path defined by `{ endpoint, method, status }`, the plugin will automatically take the schema `$ref` for that definition, find it in the `components` section, and use it in the schema validation.
140 |
141 | 
142 |
143 | ## Usage Examples
144 |
145 | For detailed usage examples, check the document [USAGE-EXAMPLES.md](USAGE-EXAMPLES.md).
146 |
147 | The examples included are for using:
148 |
149 | - `cy.validateSchema()` command with a **Plain JSON schema**.
150 |
151 | - `cy.validateSchema()` command with an **OpenAPI 3.0.1 schema** document.
152 |
153 | - `cy.validateSchema()` command with a **Swagger 2.0 schema** document.
154 |
155 | - `cy.validateSchema()` command in conjunction with **`cy.api()` from the `cypress-plugin-api` or `@bahmutov/cy-api` plugins**.
156 |
157 |
158 | ## Validation Results
159 |
160 | Here are some screenshots of schema validation tests run in Cypress.
161 |
162 | ### Test Passed
163 |
164 | When a test passes, the Cypress log will show the message: "✔️ **PASSED - THE RESPONSE BODY IS VALID AGAINST THE SCHEMA.**".
165 |
166 | 
167 |
168 | ### Test Failed
169 |
170 | When a test fails, the Cypress log will show the message: "❌ **FAILED - THE RESPONSE BODY IS NOT VALID AGAINST THE SCHEMA**"; indicating the total number of errors: _(Number of schema errors: N_).
171 |
172 | Also, the Cypress log will show an entry for each of the individual schema validation errors as provided by Ajv. The errors that correspond to missing fields in the data validated are marked with the symbol 😡, and the rest of the errors with the symbol 😱.
173 |
174 | 
175 |
176 | #### Detailed Error View in the Console
177 |
178 | If you open the Console in the browser DevTools, and click on the summary line for the schema validation error in the Cypress log, the console will display detailed information about all the errors. This includes:
179 |
180 | - The total number of errors
181 | - The full list of errors as provided by the Ajv.
182 | - A user-friendly view of the mismatches between the validated data and the JSON schema, highlighting where each validation error occurred and the exact reason for the mismatch.
183 |
184 | 
185 |
186 | ### Test Failed with More than 10 Errors
187 |
188 | When there are more than 10 schema validation errors, the Cypress log will show only the first 10 and, at the end of the list, an additional line indicating "**...and _N_ more errors.**".
189 |
190 | 
191 |
192 | #### More Errors in the Console
193 |
194 | When clicking on the "**...and N more errors.**" line in the Cypress log, the browser console will show additional details for the errors grouped under that entry as provided by Ajv.
195 |
196 | 
197 |
198 |
199 | ## Integration with Gleb Bahmutov's `@bahmutov/cy-api` and Filip Hric's `cypress-plugin-api` Plugins
200 |
201 | ### @bahmutov/cy-api Plugin
202 |
203 | When the Cypress environment variable `enableMismatchesOnUI` is set to `true`, and you have imported the `@bahmutov/cy-api` plugin into your `cypress/support/commands.js` or test file, schema validation mismatches will be displayed directly in the plugin's UI in a user-friendly format.
204 |
205 | 
206 |
207 | It will follow the the same color legend as in the Cypress Log.
208 |
209 | 
210 |
211 | ### cypress-plugin-api Plugin
212 |
213 | Similarly, when the Cypress environment variable `enableMismatchesOnUI` is set to `true`, and the `cypress-plugin-api` plugin is imported into your `cypress/support/commands.js` or test file, schema violations will be shown in the plugin's UI.
214 |
215 | 
216 |
217 | 
218 |
219 |
220 | ## Disable JSON Schema Validation in your Tests
221 |
222 | You can disable schema validation in your tests by setting the Cypress environment variable `disableSchemaValidation` to `true`.
223 |
224 | The environment variable can be set in various locations, depending on the specific contexts in which you want to disable the functionality.
225 | - **Cypress Configuration File (`cypress.config.js`)**: This is useful for applying settings globally across all tests.
226 | - **Cypress Environment File `(cypress.env.json)`**: Use this for setting environment variables to be accessible during specific test runs.
227 | - **Command Line Interface (CLI) using `--env`**: This is ideal for temporary overrides during specific test executions without affecting other configurations.
228 | - **Within Test Configuration**: Set it directly in the test file for precise control over individual test behaviors.
229 |
230 | When schema validation is disabled for a test, the Cypress log and the browser console will display the following message:
231 |
232 | 
233 |
234 |
235 |
236 | ## License
237 |
238 | This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for more details.
239 |
240 |
241 | ## Contributing
242 |
243 | First off, thanks for taking the time to contribute!
244 |
245 | To contribute, please follow the best practices promoted by GitHub on the [Contributing to a project](https://docs.github.com/en/get-started/exploring-projects-on-github/contributing-to-a-project "Contributing to a project") page.
246 |
247 | And if you like the project but just don't have the time to contribute, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about:
248 | - Star the project
249 | - Promote it on social media
250 | - Refer this project in your project's readme
251 | - Mention the project at local meetups and tell your friends/colleagues
252 | - Buying me a coffee or contributing to a training session, so I can keep learning and sharing cool stuff with all of you.
253 |
254 |
255 |
256 | Thank you for your support!
257 |
258 |
259 | ## Changelog
260 |
261 | ### [2.0.1]
262 | - Fix dependency issue with `core-ajv-schema-validator`.
263 |
264 | ### [2.0.0]
265 | - Use of the plugin `core-ajv-schema-validator`.
266 | - Remove public API function **`validateSchema()`**. The function `validateSchema()` is now available in the plugin `core-ajv-schema-validator`.
267 | - Change in the icons for property error 😱, and property missing 😡.
268 |
269 | ### [1.4.0]
270 | - Added types for command validateSchema (contribution by Murat K Ozcan).
271 | - Fixed issue with package-lock.json
272 | - Added .npmrc
273 |
274 | ### [1.3.0]
275 | - Improved error messages when not chained to an API response.
276 | - Updated icons for disable validation message.
277 | - Improved API documentation.
278 |
279 | ### [1.2.0]
280 | - Integration with bahmutov/cy-api and filiphric/cypress-plugin-api to show JSON violations directly in their outputs on the UI.
281 | - New Cypress environment variable to disable schema validation.
282 | - Change in the icons to flag schema issues.
283 |
284 | ### [1.1.1]
285 | - Added details to documentation.
286 |
287 | ### [1.1.0]
288 | - Added GitHub CI/CD workflow.
289 |
290 | ### [1.0.0]
291 | - Initial release.
292 |
293 |
294 | ## External references
295 |
296 | - [Murat Ozcan](https://www.linkedin.com/in/murat-ozcan-3489898/ "Murat Ozcan")
297 | - Video [Schema validation using cypress-ajv-schema-validator vs Optic](https://www.youtube.com/watch?v=ysCADOh9aJU "Schema validation using cypress-ajv-schema-validator vs Optic")
298 | - Video [Demo comparing API e2e vs Schema testing](https://www.youtube.com/watch?v=ePjcKMq4c2o "Demo comparing API e2e vs Schema testing")
299 | - Course [Epic Test Arch. - test everything, everywhere all at once](https://www.udemy.com/course/epic-test-arch-test-everything-everywhere-all-at-once/?referralCode=97449422709A69966E4B "Epic Test Arch. - test everything, everywhere all at once")
300 |
301 | - [Joan Esquivel Montero](https://www.linkedin.com/in/joanesquivel/ " Joan Esquivel Montero") - Video [Cypress API Testing: AJV SCHEMA VALIDATOR](https://www.youtube.com/watch?v=SPmJvH5mYaU "Cypress API Testing: AJV SCHEMA VALIDATOR")
302 |
303 | - [json-schema.org](https://json-schema.org/ "https://json-schema.org/") - Website [JSON Schema Tooling](https://json-schema.org/tools?query=&sortBy=name&sortOrder=ascending&groupBy=toolingTypes&licenses=&languages=&drafts=&toolingTypes=#json-schema-tooling "JSON Schema Tooling")
304 |
305 | - [cypress.io](https://www.cypress.io/ "https://www.cypress.io/") - Blog [Elevate Your Cypress Testing: Top 10 Essential Plugins](https://www.cypress.io/blog/elevate-your-cypress-testing-top-10-essential-plugins "Elevate Your Cypress Testing: Top 10 Essential Plugins")
306 |
307 |
--------------------------------------------------------------------------------
/USAGE-EXAMPLES.md:
--------------------------------------------------------------------------------
1 | ## Usage Examples
2 |
3 | ### Example: Using `cy.validateSchema` Command
4 |
5 | #### Plain JSON Schema
6 |
7 | ```js
8 | describe('API Schema Validation with Plain JSON', () => {
9 | it('should validate the user data using plain JSON schema', () => {
10 | const schema = {
11 | "type": "object",
12 | "properties": {
13 | "name": { "type": "string" },
14 | "age": { "type": "number" }
15 | },
16 | "required": ["name", "age"]
17 | };
18 |
19 | cy.request('GET', 'https://awesome.api.com/users/1')
20 | .validateSchema(schema)
21 | .then(response => {
22 | // Further assertions
23 | });
24 | });
25 | });
26 | ```
27 |
28 | #### OpenAPI 3.0.1
29 |
30 | ```js
31 | describe('API Schema Validation with OpenAPI 3.0.1', () => {
32 | it('should validate the user data using OpenAPI 3.0.1 schema', () => {
33 | const schema = {
34 | "openapi": "3.0.1",
35 | "paths": {
36 | "/users/{id}": {
37 | "get": {
38 | "responses": {
39 | "200": {
40 | "content": {
41 | "application/json": {
42 | "schema": { "$ref": "#/components/schemas/User" }
43 | }
44 | }
45 | }
46 | }
47 | }
48 | }
49 | },
50 | "components": {
51 | "schemas": {
52 | "User": {
53 | "type": "object",
54 | "properties": {
55 | "name": { "type": "string" },
56 | "age": { "type": "number" }
57 | },
58 | "required": ["name", "age"]
59 | }
60 | }
61 | }
62 | };
63 |
64 | const path = { endpoint: '/users/{id}', method: 'GET', status: 200 };
65 |
66 | cy.request('GET', 'https://awesome.api.com/users/1')
67 | .validateSchema(schema, path)
68 | .then(response => {
69 | // Further assertions
70 | });
71 | });
72 | });
73 | ```
74 |
75 | #### Swagger 2.0
76 |
77 | ```js
78 | describe('API Schema Validation with Swagger 2.0', () => {
79 | it('should validate the user data using Swagger 2.0 schema', () => {
80 | const schema = {
81 | "swagger": "2.0",
82 | "paths": {
83 | "/users/{id}": {
84 | "get": {
85 | "responses": {
86 | "200": {
87 | "schema": { "$ref": "#/definitions/User" }
88 | }
89 | }
90 | }
91 | }
92 | },
93 | "definitions": {
94 | "User": {
95 | "type": "object",
96 | "properties": {
97 | "name": { "type": "string" },
98 | "age": { "type": "number" }
99 | },
100 | "required": ["name", "age"]
101 | }
102 | }
103 | };
104 |
105 | const path = { endpoint: '/users/{id}', method: 'GET', status: 200 };
106 |
107 | cy.request('GET', 'https://awesome.api.com/users/1')
108 | .validateSchema(schema, path)
109 | .then(response => {
110 | // Further assertions
111 | });
112 | });
113 | });
114 | ```
115 |
116 | ### Example: Using `cy.api()` from Plugin `cypress-plugin-api` or `@bahmutov/cy-api`
117 |
118 | ```js
119 | import 'cypress-plugin-api';
120 | // or
121 | // import '@bahmutov/cy-api'
122 |
123 | describe('API Schema Validation using cy.api()', () => {
124 | it('should validate the user data using OpenAPI 3.0.1 schema', () => {
125 | const schema = {
126 | "openapi": "3.0.1",
127 | "paths": {
128 | "/users/{id}": {
129 | "get": {
130 | "responses": {
131 | "200": {
132 | "content": {
133 | "application/json": {
134 | "schema": { "$ref": "#/components/schemas/User" }
135 | }
136 | }
137 | }
138 | }
139 | }
140 | }
141 | },
142 | "components": {
143 | "schemas": {
144 | "User": {
145 | "type": "object",
146 | "properties": {
147 | "name": { "type": "string" },
148 | "age": { "type": "number" }
149 | },
150 | "required": ["name", "age"]
151 | }
152 | }
153 | }
154 | };
155 |
156 | const path = { endpoint: '/users/{id}', method: 'GET', status: 200 };
157 |
158 | cy.api('/users/1').validateSchema(schema, path);
159 | });
160 | });
161 | ```
162 |
--------------------------------------------------------------------------------
/cypress.config.js:
--------------------------------------------------------------------------------
1 | const { defineConfig } = require("cypress");
2 |
3 | module.exports = defineConfig({
4 | viewportWidth: 1920,
5 | viewportHeight: 1080,
6 |
7 | watchForFileChanges: false,
8 |
9 | e2e: {
10 | setupNodeEvents(on, config) {
11 | // implement node event listeners here
12 | },
13 | specPattern: 'cypress/e2e/**/*.{js,jsx,ts,tsx}',
14 | baseUrl: 'https://www.google.com',
15 | },
16 | });
17 |
--------------------------------------------------------------------------------
/cypress.env.json:
--------------------------------------------------------------------------------
1 | {
2 | "enableMismatchesOnUI": true,
3 | "disableSchemaValidation": false
4 | }
--------------------------------------------------------------------------------
/cypress/e2e/test-multiple-api-with-cy-api-override-style.js:
--------------------------------------------------------------------------------
1 | ///
2 |
3 | // Import cypress-ajv-schema-validator plugin
4 | import '../../src/index.js'
5 |
6 | import '@bahmutov/cy-api'
7 |
8 | // API Doc: https://petstore.swagger.io/
9 | // OpenAPI: https://petstore.swagger.io/v2/swagger.json
10 |
11 | import petstoreSchema from '../fixtures/schemas/petstore-swagger-errors.json'
12 |
13 | const issuesStylesOverride = {
14 | iconPropertyError: '🟦',
15 | colorPropertyError: '#5178eb',
16 | iconPropertyMissing: '🟪',
17 | colorPropertyMissing: '#800080'
18 | }
19 |
20 |
21 | describe('Petstore API', () => {
22 |
23 | it('should validate the OpenAPI schema for GET findByStatus "pending" - Styles override', () => {
24 |
25 | const findByStatusReq = {
26 | url: 'https://petstore.swagger.io/v2/pet/findByStatus?status=pending',
27 | headers: { 'Content-Type': 'application/json' }
28 | }
29 |
30 | cy.api(findByStatusReq)
31 | .validateSchema(petstoreSchema, { endpoint: '/pet/findByStatus', method: 'get', status: 200 }, issuesStylesOverride)
32 | })
33 |
34 | it('should validate the OpenAPI schema for GET findByStatus "available - Styles override', () => {
35 |
36 | const findByStatusReq = {
37 | url: 'https://petstore.swagger.io/v2/pet/findByStatus?status=available',
38 | headers: { 'Content-Type': 'application/json' }
39 | }
40 |
41 | cy.api(findByStatusReq)
42 | .validateSchema(petstoreSchema, { endpoint: '/pet/findByStatus', method: 'get', status: 200 }, issuesStylesOverride)
43 | })
44 |
45 | it('should validate the OpenAPI schema for GET store inventory - Styles override', () => {
46 |
47 | const storeInventoryReq = {
48 | url: 'https://petstore.swagger.io/v2/store/inventory',
49 | headers: { 'Content-Type': 'application/json' }
50 | }
51 |
52 | cy.api(storeInventoryReq)
53 | .validateSchema(petstoreSchema, { endpoint: '/store/inventory', method: 'get', status: 200 }, issuesStylesOverride)
54 | })
55 |
56 | })
57 |
--------------------------------------------------------------------------------
/cypress/e2e/test-multiple-api-with-cy-api.js:
--------------------------------------------------------------------------------
1 | ///
2 |
3 | // Import cypress-ajv-schema-validator plugin
4 | import '../../src/index.js'
5 |
6 | import '@bahmutov/cy-api'
7 |
8 | // API Doc: https://petstore.swagger.io/
9 | // OpenAPI: https://petstore.swagger.io/v2/swagger.json
10 |
11 | import petstoreSchema from '../fixtures/schemas/petstore-swagger-errors.json'
12 |
13 |
14 | describe('Petstore API', () => {
15 |
16 | it('should validate the OpenAPI schema for GET findByStatus "pending"', () => {
17 |
18 | const findByStatusReq = {
19 | url: 'https://petstore.swagger.io/v2/pet/findByStatus?status=pending',
20 | headers: { 'Content-Type': 'application/json' }
21 | }
22 |
23 | cy.api(findByStatusReq)
24 | .validateSchema(petstoreSchema, { endpoint: '/pet/findByStatus', method: 'get', status: 200 } )
25 | })
26 |
27 | it('should validate the OpenAPI schema for GET findByStatus "available', () => {
28 |
29 | const findByStatusReq = {
30 | url: 'https://petstore.swagger.io/v2/pet/findByStatus?status=available',
31 | headers: { 'Content-Type': 'application/json' }
32 | }
33 |
34 | cy.api(findByStatusReq)
35 | .validateSchema(petstoreSchema, { endpoint: '/pet/findByStatus', method: 'get', status: 200 })
36 | })
37 |
38 | it('should validate the OpenAPI schema for GET store inventory', () => {
39 |
40 | const storeInventoryReq = {
41 | url: 'https://petstore.swagger.io/v2/store/inventory',
42 | headers: { 'Content-Type': 'application/json' }
43 | }
44 |
45 | cy.api(storeInventoryReq)
46 | .validateSchema(petstoreSchema, { endpoint: '/store/inventory', method: 'get', status: 200 })
47 | })
48 |
49 | })
50 |
--------------------------------------------------------------------------------
/cypress/e2e/test-multiple-api-with-cypress-plugin-api.js:
--------------------------------------------------------------------------------
1 | ///
2 |
3 | // Import cypress-ajv-schema-validator plugin
4 | import '../../src/index.js'
5 |
6 | import 'cypress-plugin-api'
7 |
8 | // API Doc: https://petstore.swagger.io/
9 | // OpenAPI: https://petstore.swagger.io/v2/swagger.json
10 |
11 | import petstoreSchema from '../fixtures/schemas/petstore-swagger-errors.json'
12 |
13 |
14 | describe('Petstore API', () => {
15 |
16 | it('should validate the OpenAPI schema for GET findByStatus "pending"', () => {
17 |
18 | const findByStatusReq = {
19 | url: 'https://petstore.swagger.io/v2/pet/findByStatus?status=pending',
20 | headers: { 'Content-Type': 'application/json' }
21 | }
22 |
23 | cy.api(findByStatusReq)
24 | .validateSchema(petstoreSchema, { endpoint: '/pet/findByStatus', method: 'get', status: 200 } )
25 | })
26 |
27 | it('should validate the OpenAPI schema for GET findByStatus "available', () => {
28 |
29 | const findByStatusReq = {
30 | url: 'https://petstore.swagger.io/v2/pet/findByStatus?status=available',
31 | headers: { 'Content-Type': 'application/json' }
32 | }
33 |
34 | cy.api(findByStatusReq)
35 | .validateSchema(petstoreSchema, { endpoint: '/pet/findByStatus', method: 'get', status: 200 })
36 | })
37 |
38 | it('should validate the OpenAPI schema for GET store inventory', () => {
39 |
40 | const storeInventoryReq = {
41 | url: 'https://petstore.swagger.io/v2/store/inventory',
42 | headers: { 'Content-Type': 'application/json' }
43 | }
44 |
45 | cy.api(storeInventoryReq)
46 | .validateSchema(petstoreSchema, { endpoint: '/store/inventory', method: 'get', status: 200 })
47 | })
48 |
49 | })
50 |
--------------------------------------------------------------------------------
/cypress/e2e/test-plain-json-schema-fail.js:
--------------------------------------------------------------------------------
1 | import runTestsPlainJson from '../support/run-tests-plainjson.js'
2 |
3 | describe('ALL TESTS SHOULD FAIL', () => {
4 | runTestsPlainJson('fail')
5 | })
6 |
--------------------------------------------------------------------------------
/cypress/e2e/test-plain-json-schema-pass.js:
--------------------------------------------------------------------------------
1 | import runTestsPlainJson from '../support/run-tests-plainjson.js'
2 |
3 | describe('ALL TESTS SHOULD PASS', () => {
4 | runTestsPlainJson('pass')
5 | })
6 |
--------------------------------------------------------------------------------
/cypress/e2e/tests-openapi-swagger-fail.js:
--------------------------------------------------------------------------------
1 | import runTestsOpenapiSwagger from '../support/run-tests-openapi-swagger.js'
2 |
3 | describe('ALL TESTS SHOULD FAIL', () => {
4 | runTestsOpenapiSwagger('fail')
5 | })
--------------------------------------------------------------------------------
/cypress/e2e/tests-openapi-swagger-pass.js:
--------------------------------------------------------------------------------
1 | import runTestsOpenapiSwagger from '../support/run-tests-openapi-swagger.js'
2 |
3 | describe('ALL TESTS SHOULD PASS', () => {
4 | runTestsOpenapiSwagger('pass')
5 | })
6 |
--------------------------------------------------------------------------------
/cypress/fixtures/mock-data-openapi-swagger/fail/GET/service1_200.json:
--------------------------------------------------------------------------------
1 | {
2 | "id": 123456,
3 | "name": null,
4 | "status": 1,
5 | "email": "invalid-email-format",
6 | "createdAt": null,
7 | "isActive": "yes",
8 | "age": null,
9 | "tags": ["tag1", 2, true],
10 | "preferences": {
11 | "notifications": "yes",
12 | "theme": "dark",
13 | "itemsPerPage": "ten"
14 | }
15 | }
--------------------------------------------------------------------------------
/cypress/fixtures/mock-data-openapi-swagger/fail/GET/service1_401.json:
--------------------------------------------------------------------------------
1 | {
2 | "code": "abc123",
3 | "message": null
4 | }
--------------------------------------------------------------------------------
/cypress/fixtures/mock-data-openapi-swagger/fail/GET/service2_200.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "id": 54321,
4 | "description": null,
5 | "createdDate": 20230101,
6 | "priority": "high",
7 | "completed": "no",
8 | "details": {
9 | "detail1": 123,
10 | "detail2": "one-two-three"
11 | }
12 | },
13 | {
14 | "description": "Missing ID and createdDate",
15 | "completed": true,
16 | "priority": null,
17 | "details": {
18 | "detail1": null,
19 | "detail2": 456
20 | }
21 | }
22 | ]
--------------------------------------------------------------------------------
/cypress/fixtures/mock-data-openapi-swagger/fail/GET/service2_401.json:
--------------------------------------------------------------------------------
1 | {
2 | "code": 401,
3 | "message": null
4 | }
--------------------------------------------------------------------------------
/cypress/fixtures/mock-data-openapi-swagger/fail/POST/service1_201.json:
--------------------------------------------------------------------------------
1 | {
2 | "id": 67890,
3 | "name": 123,
4 | "status": null,
5 | "email": "not-an-email",
6 | "createdAt": 20230102,
7 | "isActive": "no",
8 | "age": 25,
9 | "tags": ["tagA", null, false],
10 | "preferences": {
11 | "notifications": false,
12 | "theme": null,
13 | "itemsPerPage": "fifteen"
14 | }
15 | }
--------------------------------------------------------------------------------
/cypress/fixtures/mock-data-openapi-swagger/fail/POST/service1_401.json:
--------------------------------------------------------------------------------
1 | {
2 | "code": null,
3 | "message": 123456
4 | }
--------------------------------------------------------------------------------
/cypress/fixtures/mock-data-openapi-swagger/fail/POST/service2_201.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "id": "abc123",
4 | "description": null,
5 | "createdDate": "abc123",
6 | "priority": 3,
7 | "completed": true,
8 | "details": {
9 | "detail1": 789
10 | }
11 | },
12 | {
13 | "id": null,
14 | "description": "New Entry",
15 | "completed": "false",
16 | "priority": true,
17 | "details": {
18 | "detail2": 260
19 | }
20 | }
21 | ]
--------------------------------------------------------------------------------
/cypress/fixtures/mock-data-openapi-swagger/fail/POST/service2_401.json:
--------------------------------------------------------------------------------
1 | {
2 | "code": 401
3 | }
--------------------------------------------------------------------------------
/cypress/fixtures/mock-data-openapi-swagger/pass/GET/service1_200.json:
--------------------------------------------------------------------------------
1 | {
2 | "id": "123e4567-e89b-12d3-a456-426614174000",
3 | "name": "John Doe",
4 | "status": "active",
5 | "email": "john.doe@example.com",
6 | "createdAt": "2023-01-01T12:00:00Z",
7 | "isActive": true,
8 | "age": 30,
9 | "tags": ["tag1", "tag2", "tag3"],
10 | "preferences": {
11 | "notifications": true,
12 | "theme": "dark",
13 | "itemsPerPage": 20
14 | }
15 | }
--------------------------------------------------------------------------------
/cypress/fixtures/mock-data-openapi-swagger/pass/GET/service1_401.json:
--------------------------------------------------------------------------------
1 | {
2 | "code": 401,
3 | "message": "Unauthorized access. Please provide valid credentials."
4 | }
--------------------------------------------------------------------------------
/cypress/fixtures/mock-data-openapi-swagger/pass/GET/service2_200.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "id": "543e4567-e89b-12d3-a456-426614174000",
4 | "description": "Detailed description of service 2 - item 1",
5 | "createdDate": "2023-01-01T12:00:00Z",
6 | "priority": 1,
7 | "completed": false,
8 | "details": {
9 | "detail1": "Detail 1 - item 1",
10 | "detail2": 123
11 | }
12 | },
13 | {
14 | "id": "678e4567-e89b-12d3-a456-426614174001",
15 | "description": "Detailed description of service 2 - item 2",
16 | "createdDate": "2023-01-03T12:00:00Z",
17 | "priority": 2,
18 | "completed": true,
19 | "details": {
20 | "detail1": "Detail 1 - item 2",
21 | "detail2": 456
22 | }
23 | },
24 | {
25 | "id": "789e4567-e89b-12d3-a456-426614174002",
26 | "description": "Detailed description of service 2 - item 3",
27 | "createdDate": "2023-01-05T12:00:00Z",
28 | "priority": 3,
29 | "completed": false,
30 | "details": {
31 | "detail1": "Detail 1 - item 3",
32 | "detail2": 789
33 | }
34 | },
35 | {
36 | "id": "890e4567-e89b-12d3-a456-426614174003",
37 | "description": "Detailed description of service 2 - item 4",
38 | "createdDate": "2023-01-07T12:00:00Z",
39 | "priority": 4,
40 | "completed": false,
41 | "details": {
42 | "detail1": "Detail 1 - item 4",
43 | "detail2": 101
44 | }
45 | },
46 | {
47 | "id": "901e4567-e89b-12d3-a456-426614174004",
48 | "description": "Detailed description of service 2 - item 5",
49 | "createdDate": "2023-01-09T12:00:00Z",
50 | "priority": 5,
51 | "completed": true,
52 | "details": {
53 | "detail1": "Detail 1 - item 5",
54 | "detail2": 202
55 | }
56 | }
57 | ]
--------------------------------------------------------------------------------
/cypress/fixtures/mock-data-openapi-swagger/pass/GET/service2_401.json:
--------------------------------------------------------------------------------
1 | {
2 | "code": 401,
3 | "message": "Unauthorized access. Please provide valid credentials."
4 | }
--------------------------------------------------------------------------------
/cypress/fixtures/mock-data-openapi-swagger/pass/POST/service1_201.json:
--------------------------------------------------------------------------------
1 | {
2 | "id": "678e4567-e89b-12d3-a456-426614174000",
3 | "name": "Jane Doe",
4 | "status": "pending",
5 | "email": "jane.doe@example.com",
6 | "createdAt": "2023-01-02T12:00:00Z",
7 | "isActive": false,
8 | "age": 25,
9 | "tags": ["tagA", "tagB"],
10 | "preferences": {
11 | "notifications": false,
12 | "theme": "light",
13 | "itemsPerPage": 15
14 | }
15 | }
--------------------------------------------------------------------------------
/cypress/fixtures/mock-data-openapi-swagger/pass/POST/service1_401.json:
--------------------------------------------------------------------------------
1 | {
2 | "code": 401,
3 | "message": "Unauthorized access. Please provide valid credentials."
4 | }
--------------------------------------------------------------------------------
/cypress/fixtures/mock-data-openapi-swagger/pass/POST/service2_201.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "id": "890e4567-e89b-12d3-a456-426614174002",
4 | "description": "New Service 2 Entry - item 1",
5 | "createdDate": "2023-01-02T12:00:00Z",
6 | "priority": 3,
7 | "completed": true,
8 | "details": {
9 | "detail1": "New detail 1 - item 1",
10 | "detail2": 789
11 | }
12 | },
13 | {
14 | "id": "901e4567-e89b-12d3-a456-426614174005",
15 | "description": "New Service 2 Entry - item 2",
16 | "createdDate": "2023-01-12T12:00:00Z",
17 | "priority": 2,
18 | "completed": false,
19 | "details": {
20 | "detail1": "New detail 1 - item 2",
21 | "detail2": 260
22 | }
23 | },
24 | {
25 | "id": "912e4567-e89b-12d3-a456-426614174006",
26 | "description": "New Service 2 Entry - item 3",
27 | "createdDate": "2023-01-15T12:00:00Z",
28 | "priority": 1,
29 | "completed": false,
30 | "details": {
31 | "detail1": "New detail 1 - item 3",
32 | "detail2": 340
33 | }
34 | }
35 | ]
--------------------------------------------------------------------------------
/cypress/fixtures/mock-data-openapi-swagger/pass/POST/service2_401.json:
--------------------------------------------------------------------------------
1 | {
2 | "code": 401,
3 | "message": "Unauthorized access. Please provide valid credentials."
4 | }
--------------------------------------------------------------------------------
/cypress/fixtures/mock-data-openapi-swagger/tests.json:
--------------------------------------------------------------------------------
1 | [
2 | { "endpoint": "/service1", "method": "GET", "status": 200 },
3 | { "endpoint": "/service1", "method": "GET", "status": 401 },
4 |
5 | { "endpoint": "/service1", "method": "POST", "status": 201 },
6 | { "endpoint": "/service1", "method": "POST", "status": 401 },
7 |
8 | { "endpoint": "/service2", "method": "GET", "status": 200 },
9 | { "endpoint": "/service2", "method": "GET", "status": 401 },
10 |
11 | { "endpoint": "/service2", "method": "POST", "status": 201 },
12 | { "endpoint": "/service2", "method": "POST", "status": 401 }
13 | ]
--------------------------------------------------------------------------------
/cypress/fixtures/mock-data-plainjson/fail.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "id": 123456,
4 | "age": "thirty",
5 | "email": "invalid-email-format",
6 | "created_at": "not-a-date",
7 | "is_active": "yes",
8 | "tags": ["developer", 123],
9 | "address": {
10 | "street": 789,
11 | "city": "Anytown"
12 | },
13 | "preferences": {
14 | "notifications": "yes",
15 | "theme": "dark",
16 | "items_per_page": "unknown"
17 | }
18 | },
19 | {
20 | "id": "223e4567-e89b-12d3-a456-426614174001",
21 | "name": null,
22 | "age": 35,
23 | "email": "jane.smith@example",
24 | "created_at": null,
25 | "is_active": false,
26 | "tags": ["manager", false],
27 | "address": {
28 | "street": "456 Elm St",
29 | "postal_code": "67890"
30 | },
31 | "preferences": {
32 | "notifications": false,
33 | "theme": null,
34 | "items_per_page": 10
35 | }
36 | },
37 | {
38 | "id": null,
39 | "name": "Alice Johnson",
40 | "age": null,
41 | "email": "alice.johnson@example.com",
42 | "created_at": "2023-03-10",
43 | "is_active": "yes",
44 | "tags": null,
45 | "address": {
46 | "street": "789 Oak St",
47 | "postal_code": "10112"
48 | },
49 | "preferences": {
50 | "notifications": true,
51 | "theme": "light",
52 | "items_per_page": "fifteen"
53 | }
54 | }
55 | ]
--------------------------------------------------------------------------------
/cypress/fixtures/mock-data-plainjson/pass.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "id": "123e4567-e89b-12d3-a456-426614174000",
4 | "name": "John Doe",
5 | "age": 30,
6 | "email": "john.doe@example.com",
7 | "created_at": "2023-01-01T12:00:00Z",
8 | "is_active": true,
9 | "tags": ["developer", "tester"],
10 | "address": {
11 | "street": "123 Main St",
12 | "city": "Anytown",
13 | "postal_code": "12345"
14 | },
15 | "preferences": {
16 | "notifications": true,
17 | "theme": "dark",
18 | "items_per_page": 20
19 | }
20 | },
21 | {
22 | "id": "223e4567-e89b-12d3-a456-426614174001",
23 | "name": "Jane Smith",
24 | "age": 28,
25 | "email": "jane.smith@example.com",
26 | "created_at": "2023-02-15T08:30:00Z",
27 | "is_active": false,
28 | "tags": ["manager", "designer"],
29 | "address": {
30 | "street": "456 Elm St",
31 | "city": "Othertown",
32 | "postal_code": "67890"
33 | },
34 | "preferences": {
35 | "notifications": false,
36 | "theme": "light",
37 | "items_per_page": 10
38 | }
39 | },
40 | {
41 | "id": "323e4567-e89b-12d3-a456-426614174002",
42 | "name": "Alice Johnson",
43 | "age": 35,
44 | "email": "alice.johnson@example.com",
45 | "created_at": "2023-03-10T14:45:00Z",
46 | "is_active": true,
47 | "tags": ["developer", "team lead"],
48 | "address": {
49 | "street": "789 Oak St",
50 | "city": "Sometown",
51 | "postal_code": "10112"
52 | },
53 | "preferences": {
54 | "notifications": true,
55 | "theme": "dark",
56 | "items_per_page": 15
57 | }
58 | }
59 | ]
--------------------------------------------------------------------------------
/cypress/fixtures/schemas/openapi-schema.json:
--------------------------------------------------------------------------------
1 | {
2 | "openapi": "3.0.1",
3 | "info": {
4 | "title": "Example API",
5 | "version": "1.0.0",
6 | "description": "An example API with GET and POST methods."
7 | },
8 | "servers": [
9 | {
10 | "url": "https://api.example.com"
11 | }
12 | ],
13 | "paths": {
14 | "/service1": {
15 | "get": {
16 | "summary": "Get details for service 1",
17 | "operationId": "getService1",
18 | "responses": {
19 | "200": {
20 | "description": "Successful response",
21 | "content": {
22 | "application/json": {
23 | "schema": {
24 | "$ref": "#/components/schemas/Service1Response"
25 | }
26 | }
27 | }
28 | },
29 | "401": {
30 | "description": "Unauthorized",
31 | "content": {
32 | "application/json": {
33 | "schema": {
34 | "$ref": "#/components/schemas/ErrorResponse"
35 | }
36 | }
37 | }
38 | }
39 | }
40 | },
41 | "post": {
42 | "summary": "Create a new entry for service 1",
43 | "operationId": "createService1",
44 | "requestBody": {
45 | "content": {
46 | "application/json": {
47 | "schema": {
48 | "$ref": "#/components/schemas/Service1Request"
49 | }
50 | }
51 | }
52 | },
53 | "responses": {
54 | "201": {
55 | "description": "Resource created",
56 | "content": {
57 | "application/json": {
58 | "schema": {
59 | "$ref": "#/components/schemas/Service1Response"
60 | }
61 | }
62 | }
63 | },
64 | "401": {
65 | "description": "Unauthorized",
66 | "content": {
67 | "application/json": {
68 | "schema": {
69 | "$ref": "#/components/schemas/ErrorResponse"
70 | }
71 | }
72 | }
73 | }
74 | }
75 | }
76 | },
77 | "/service2": {
78 | "get": {
79 | "summary": "Get details for service 2",
80 | "operationId": "getService2",
81 | "responses": {
82 | "200": {
83 | "description": "Successful response",
84 | "content": {
85 | "application/json": {
86 | "schema": {
87 | "type": "array",
88 | "items": {
89 | "$ref": "#/components/schemas/Service2Response"
90 | }
91 | }
92 | }
93 | }
94 | },
95 | "401": {
96 | "description": "Unauthorized",
97 | "content": {
98 | "application/json": {
99 | "schema": {
100 | "$ref": "#/components/schemas/ErrorResponse"
101 | }
102 | }
103 | }
104 | }
105 | }
106 | },
107 | "post": {
108 | "summary": "Create a new entry for service 2",
109 | "operationId": "createService2",
110 | "requestBody": {
111 | "content": {
112 | "application/json": {
113 | "schema": {
114 | "$ref": "#/components/schemas/Service2Request"
115 | }
116 | }
117 | }
118 | },
119 | "responses": {
120 | "201": {
121 | "description": "Resource created",
122 | "content": {
123 | "application/json": {
124 | "schema": {
125 | "type": "array",
126 | "items": {
127 | "$ref": "#/components/schemas/Service2Response"
128 | }
129 | }
130 | }
131 | }
132 | },
133 | "default": {
134 | "description": "Unauthorized",
135 | "content": {
136 | "application/json": {
137 | "schema": {
138 | "$ref": "#/components/schemas/ErrorResponse"
139 | }
140 | }
141 | }
142 | }
143 | }
144 | }
145 | }
146 | },
147 | "components": {
148 | "schemas": {
149 | "Service1Response": {
150 | "type": "object",
151 | "required": ["id", "name", "status", "createdAt", "isActive", "age"],
152 | "properties": {
153 | "id": {
154 | "type": "string",
155 | "format": "uuid"
156 | },
157 | "name": {
158 | "type": "string",
159 | "nullable": false
160 | },
161 | "status": {
162 | "type": "string"
163 | },
164 | "email": {
165 | "type": "string",
166 | "format": "email",
167 | "nullable": true
168 | },
169 | "createdAt": {
170 | "type": "string",
171 | "format": "date-time"
172 | },
173 | "isActive": {
174 | "type": "boolean"
175 | },
176 | "age": {
177 | "type": "integer",
178 | "nullable": false
179 | },
180 | "tags": {
181 | "type": "array",
182 | "items": {
183 | "type": "string"
184 | }
185 | },
186 | "preferences": {
187 | "$ref": "#/components/schemas/Preferences"
188 | }
189 | }
190 | },
191 | "Service1Request": {
192 | "type": "object",
193 | "required": ["name", "status", "createdAt", "isActive", "age"],
194 | "properties": {
195 | "name": {
196 | "type": "string",
197 | "nullable": false
198 | },
199 | "status": {
200 | "type": "string"
201 | },
202 | "email": {
203 | "type": "string",
204 | "format": "email",
205 | "nullable": true
206 | },
207 | "createdAt": {
208 | "type": "string",
209 | "format": "date-time"
210 | },
211 | "isActive": {
212 | "type": "boolean"
213 | },
214 | "age": {
215 | "type": "integer",
216 | "nullable": false
217 | },
218 | "tags": {
219 | "type": "array",
220 | "items": {
221 | "type": "string"
222 | },
223 | "nullable": true
224 | },
225 | "meta": {
226 | "$ref": "#/components/schemas/Meta"
227 | }
228 | }
229 | },
230 | "Service2Response": {
231 | "type": "object",
232 | "required": ["id", "description", "createdDate", "priority", "completed"],
233 | "properties": {
234 | "id": {
235 | "type": "string",
236 | "format": "uuid"
237 | },
238 | "description": {
239 | "type": "string",
240 | "nullable": false
241 | },
242 | "createdDate": {
243 | "type": "string",
244 | "format": "date-time"
245 | },
246 | "priority": {
247 | "type": "integer",
248 | "nullable": false
249 | },
250 | "completed": {
251 | "type": "boolean"
252 | },
253 | "details": {
254 | "type": "object",
255 | "properties": {
256 | "detail1": {
257 | "type": "string",
258 | "nullable": true
259 | },
260 | "detail2": {
261 | "type": "integer"
262 | }
263 | },
264 | "required": ["detail2"]
265 | }
266 | }
267 | },
268 | "Service2Request": {
269 | "type": "object",
270 | "required": ["description"],
271 | "properties": {
272 | "description": {
273 | "type": "string",
274 | "nullable": false
275 | }
276 | }
277 | },
278 | "ErrorResponse": {
279 | "type": "object",
280 | "required": ["code", "message"],
281 | "properties": {
282 | "code": {
283 | "type": "integer"
284 | },
285 | "message": {
286 | "type": "string"
287 | }
288 | }
289 | },
290 | "Preferences": {
291 | "type": "object",
292 | "properties": {
293 | "notifications": {
294 | "type": "boolean"
295 | },
296 | "theme": {
297 | "type": "string",
298 | "nullable": true
299 | },
300 | "itemsPerPage": {
301 | "type": "integer"
302 | }
303 | }
304 | },
305 | "Meta": {
306 | "type": "object",
307 | "required": ["createdBy", "createdDate"],
308 | "properties": {
309 | "createdBy": {
310 | "type": "string",
311 | "nullable": false
312 | },
313 | "createdDate": {
314 | "type": "string",
315 | "format": "date-time"
316 | }
317 | }
318 | }
319 | }
320 | }
321 | }
--------------------------------------------------------------------------------
/cypress/fixtures/schemas/petstore-swagger-errors.json:
--------------------------------------------------------------------------------
1 | {
2 | "swagger": "2.0",
3 | "info": {
4 | "description": "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.",
5 | "version": "1.0.7",
6 | "title": "Swagger Petstore",
7 | "termsOfService": "http://swagger.io/terms/",
8 | "contact": {
9 | "email": "apiteam@swagger.io"
10 | },
11 | "license": {
12 | "name": "Apache 2.0",
13 | "url": "http://www.apache.org/licenses/LICENSE-2.0.html"
14 | }
15 | },
16 | "host": "petstore.swagger.io",
17 | "basePath": "/v2",
18 | "tags": [
19 | {
20 | "name": "pet",
21 | "description": "Everything about your Pets",
22 | "externalDocs": {
23 | "description": "Find out more",
24 | "url": "http://swagger.io"
25 | }
26 | },
27 | {
28 | "name": "store",
29 | "description": "Access to Petstore orders"
30 | },
31 | {
32 | "name": "user",
33 | "description": "Operations about user",
34 | "externalDocs": {
35 | "description": "Find out more about our store",
36 | "url": "http://swagger.io"
37 | }
38 | }
39 | ],
40 | "schemes": [
41 | "https",
42 | "http"
43 | ],
44 | "paths": {
45 | "/pet/{petId}/uploadImage": {
46 | "post": {
47 | "tags": [
48 | "pet"
49 | ],
50 | "summary": "uploads an image",
51 | "description": "",
52 | "operationId": "uploadFile",
53 | "consumes": [
54 | "multipart/form-data"
55 | ],
56 | "produces": [
57 | "application/json"
58 | ],
59 | "parameters": [
60 | {
61 | "name": "petId",
62 | "in": "path",
63 | "description": "ID of pet to update",
64 | "required": true,
65 | "type": "integer",
66 | "format": "int64"
67 | },
68 | {
69 | "name": "additionalMetadata",
70 | "in": "formData",
71 | "description": "Additional data to pass to server",
72 | "required": false,
73 | "type": "string"
74 | },
75 | {
76 | "name": "file",
77 | "in": "formData",
78 | "description": "file to upload",
79 | "required": false,
80 | "type": "file"
81 | }
82 | ],
83 | "responses": {
84 | "200": {
85 | "description": "successful operation",
86 | "schema": {
87 | "$ref": "#/definitions/ApiResponse"
88 | }
89 | }
90 | },
91 | "security": [
92 | {
93 | "petstore_auth": [
94 | "write:pets",
95 | "read:pets"
96 | ]
97 | }
98 | ]
99 | }
100 | },
101 | "/pet": {
102 | "post": {
103 | "tags": [
104 | "pet"
105 | ],
106 | "summary": "Add a new pet to the store",
107 | "description": "",
108 | "operationId": "addPet",
109 | "consumes": [
110 | "application/json",
111 | "application/xml"
112 | ],
113 | "produces": [
114 | "application/json",
115 | "application/xml"
116 | ],
117 | "parameters": [
118 | {
119 | "in": "body",
120 | "name": "body",
121 | "description": "Pet object that needs to be added to the store",
122 | "required": true,
123 | "schema": {
124 | "$ref": "#/definitions/Pet"
125 | }
126 | }
127 | ],
128 | "responses": {
129 | "405": {
130 | "description": "Invalid input"
131 | }
132 | },
133 | "security": [
134 | {
135 | "petstore_auth": [
136 | "write:pets",
137 | "read:pets"
138 | ]
139 | }
140 | ]
141 | },
142 | "put": {
143 | "tags": [
144 | "pet"
145 | ],
146 | "summary": "Update an existing pet",
147 | "description": "",
148 | "operationId": "updatePet",
149 | "consumes": [
150 | "application/json",
151 | "application/xml"
152 | ],
153 | "produces": [
154 | "application/json",
155 | "application/xml"
156 | ],
157 | "parameters": [
158 | {
159 | "in": "body",
160 | "name": "body",
161 | "description": "Pet object that needs to be added to the store",
162 | "required": true,
163 | "schema": {
164 | "$ref": "#/definitions/Pet"
165 | }
166 | }
167 | ],
168 | "responses": {
169 | "400": {
170 | "description": "Invalid ID supplied"
171 | },
172 | "404": {
173 | "description": "Pet not found"
174 | },
175 | "405": {
176 | "description": "Validation exception"
177 | }
178 | },
179 | "security": [
180 | {
181 | "petstore_auth": [
182 | "write:pets",
183 | "read:pets"
184 | ]
185 | }
186 | ]
187 | }
188 | },
189 | "/pet/findByStatus": {
190 | "get": {
191 | "tags": [
192 | "pet"
193 | ],
194 | "summary": "Finds Pets by status",
195 | "description": "Multiple status values can be provided with comma separated strings",
196 | "operationId": "findPetsByStatus",
197 | "produces": [
198 | "application/json",
199 | "application/xml"
200 | ],
201 | "parameters": [
202 | {
203 | "name": "status",
204 | "in": "query",
205 | "description": "Status values that need to be considered for filter",
206 | "required": true,
207 | "type": "array",
208 | "items": {
209 | "type": "string",
210 | "enum": [
211 | "available",
212 | "pending",
213 | "sold"
214 | ],
215 | "default": "available"
216 | },
217 | "collectionFormat": "multi"
218 | }
219 | ],
220 | "responses": {
221 | "200": {
222 | "description": "successful operation",
223 | "schema": {
224 | "type": "array",
225 | "items": {
226 | "$ref": "#/definitions/Pet"
227 | }
228 | }
229 | },
230 | "400": {
231 | "description": "Invalid status value"
232 | }
233 | },
234 | "security": [
235 | {
236 | "petstore_auth": [
237 | "write:pets",
238 | "read:pets"
239 | ]
240 | }
241 | ]
242 | }
243 | },
244 | "/pet/findByTags": {
245 | "get": {
246 | "tags": [
247 | "pet"
248 | ],
249 | "summary": "Finds Pets by tags",
250 | "description": "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.",
251 | "operationId": "findPetsByTags",
252 | "produces": [
253 | "application/json",
254 | "application/xml"
255 | ],
256 | "parameters": [
257 | {
258 | "name": "tags",
259 | "in": "query",
260 | "description": "Tags to filter by",
261 | "required": true,
262 | "type": "array",
263 | "items": {
264 | "type": "string"
265 | },
266 | "collectionFormat": "multi"
267 | }
268 | ],
269 | "responses": {
270 | "200": {
271 | "description": "successful operation",
272 | "schema": {
273 | "type": "array",
274 | "items": {
275 | "$ref": "#/definitions/Pet"
276 | }
277 | }
278 | },
279 | "400": {
280 | "description": "Invalid tag value"
281 | }
282 | },
283 | "security": [
284 | {
285 | "petstore_auth": [
286 | "write:pets",
287 | "read:pets"
288 | ]
289 | }
290 | ],
291 | "deprecated": true
292 | }
293 | },
294 | "/pet/{petId}": {
295 | "get": {
296 | "tags": [
297 | "pet"
298 | ],
299 | "summary": "Find pet by ID",
300 | "description": "Returns a single pet",
301 | "operationId": "getPetById",
302 | "produces": [
303 | "application/json",
304 | "application/xml"
305 | ],
306 | "parameters": [
307 | {
308 | "name": "petId",
309 | "in": "path",
310 | "description": "ID of pet to return",
311 | "required": true,
312 | "type": "integer",
313 | "format": "int64"
314 | }
315 | ],
316 | "responses": {
317 | "200": {
318 | "description": "successful operation",
319 | "schema": {
320 | "$ref": "#/definitions/Pet"
321 | }
322 | },
323 | "400": {
324 | "description": "Invalid ID supplied"
325 | },
326 | "404": {
327 | "description": "Pet not found"
328 | }
329 | },
330 | "security": [
331 | {
332 | "api_key": []
333 | }
334 | ]
335 | },
336 | "post": {
337 | "tags": [
338 | "pet"
339 | ],
340 | "summary": "Updates a pet in the store with form data",
341 | "description": "",
342 | "operationId": "updatePetWithForm",
343 | "consumes": [
344 | "application/x-www-form-urlencoded"
345 | ],
346 | "produces": [
347 | "application/json",
348 | "application/xml"
349 | ],
350 | "parameters": [
351 | {
352 | "name": "petId",
353 | "in": "path",
354 | "description": "ID of pet that needs to be updated",
355 | "required": true,
356 | "type": "integer",
357 | "format": "int64"
358 | },
359 | {
360 | "name": "name",
361 | "in": "formData",
362 | "description": "Updated name of the pet",
363 | "required": false,
364 | "type": "string"
365 | },
366 | {
367 | "name": "status",
368 | "in": "formData",
369 | "description": "Updated status of the pet",
370 | "required": false,
371 | "type": "string"
372 | }
373 | ],
374 | "responses": {
375 | "405": {
376 | "description": "Invalid input"
377 | }
378 | },
379 | "security": [
380 | {
381 | "petstore_auth": [
382 | "write:pets",
383 | "read:pets"
384 | ]
385 | }
386 | ]
387 | },
388 | "delete": {
389 | "tags": [
390 | "pet"
391 | ],
392 | "summary": "Deletes a pet",
393 | "description": "",
394 | "operationId": "deletePet",
395 | "produces": [
396 | "application/json",
397 | "application/xml"
398 | ],
399 | "parameters": [
400 | {
401 | "name": "api_key",
402 | "in": "header",
403 | "required": false,
404 | "type": "string"
405 | },
406 | {
407 | "name": "petId",
408 | "in": "path",
409 | "description": "Pet id to delete",
410 | "required": true,
411 | "type": "integer",
412 | "format": "int64"
413 | }
414 | ],
415 | "responses": {
416 | "400": {
417 | "description": "Invalid ID supplied"
418 | },
419 | "404": {
420 | "description": "Pet not found"
421 | }
422 | },
423 | "security": [
424 | {
425 | "petstore_auth": [
426 | "write:pets",
427 | "read:pets"
428 | ]
429 | }
430 | ]
431 | }
432 | },
433 | "/store/inventory": {
434 | "get": {
435 | "tags": [
436 | "store"
437 | ],
438 | "summary": "Returns pet inventories by status",
439 | "description": "Returns a map of status codes to quantities",
440 | "operationId": "getInventory",
441 | "produces": [
442 | "application/json"
443 | ],
444 | "parameters": [],
445 | "responses": {
446 | "200": {
447 | "description": "successful operation",
448 | "schema": {
449 | "type": "object",
450 | "additionalProperties": {
451 | "type": "string"
452 | }
453 | }
454 | }
455 | },
456 | "security": [
457 | {
458 | "api_key": []
459 | }
460 | ]
461 | }
462 | },
463 | "/store/order": {
464 | "post": {
465 | "tags": [
466 | "store"
467 | ],
468 | "summary": "Place an order for a pet",
469 | "description": "",
470 | "operationId": "placeOrder",
471 | "consumes": [
472 | "application/json"
473 | ],
474 | "produces": [
475 | "application/json",
476 | "application/xml"
477 | ],
478 | "parameters": [
479 | {
480 | "in": "body",
481 | "name": "body",
482 | "description": "order placed for purchasing the pet",
483 | "required": true,
484 | "schema": {
485 | "$ref": "#/definitions/Order"
486 | }
487 | }
488 | ],
489 | "responses": {
490 | "200": {
491 | "description": "successful operation",
492 | "schema": {
493 | "$ref": "#/definitions/Order"
494 | }
495 | },
496 | "400": {
497 | "description": "Invalid Order"
498 | }
499 | }
500 | }
501 | },
502 | "/store/order/{orderId}": {
503 | "get": {
504 | "tags": [
505 | "store"
506 | ],
507 | "summary": "Find purchase order by ID",
508 | "description": "For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions",
509 | "operationId": "getOrderById",
510 | "produces": [
511 | "application/json",
512 | "application/xml"
513 | ],
514 | "parameters": [
515 | {
516 | "name": "orderId",
517 | "in": "path",
518 | "description": "ID of pet that needs to be fetched",
519 | "required": true,
520 | "type": "integer",
521 | "maximum": 10,
522 | "minimum": 1,
523 | "format": "int64"
524 | }
525 | ],
526 | "responses": {
527 | "200": {
528 | "description": "successful operation",
529 | "schema": {
530 | "$ref": "#/definitions/Order"
531 | }
532 | },
533 | "400": {
534 | "description": "Invalid ID supplied"
535 | },
536 | "404": {
537 | "description": "Order not found"
538 | }
539 | }
540 | },
541 | "delete": {
542 | "tags": [
543 | "store"
544 | ],
545 | "summary": "Delete purchase order by ID",
546 | "description": "For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors",
547 | "operationId": "deleteOrder",
548 | "produces": [
549 | "application/json",
550 | "application/xml"
551 | ],
552 | "parameters": [
553 | {
554 | "name": "orderId",
555 | "in": "path",
556 | "description": "ID of the order that needs to be deleted",
557 | "required": true,
558 | "type": "integer",
559 | "minimum": 1,
560 | "format": "int64"
561 | }
562 | ],
563 | "responses": {
564 | "400": {
565 | "description": "Invalid ID supplied"
566 | },
567 | "404": {
568 | "description": "Order not found"
569 | }
570 | }
571 | }
572 | },
573 | "/user/createWithList": {
574 | "post": {
575 | "tags": [
576 | "user"
577 | ],
578 | "summary": "Creates list of users with given input array",
579 | "description": "",
580 | "operationId": "createUsersWithListInput",
581 | "consumes": [
582 | "application/json"
583 | ],
584 | "produces": [
585 | "application/json",
586 | "application/xml"
587 | ],
588 | "parameters": [
589 | {
590 | "in": "body",
591 | "name": "body",
592 | "description": "List of user object",
593 | "required": true,
594 | "schema": {
595 | "type": "array",
596 | "items": {
597 | "$ref": "#/definitions/User"
598 | }
599 | }
600 | }
601 | ],
602 | "responses": {
603 | "default": {
604 | "description": "successful operation"
605 | }
606 | }
607 | }
608 | },
609 | "/user/{username}": {
610 | "get": {
611 | "tags": [
612 | "user"
613 | ],
614 | "summary": "Get user by user name",
615 | "description": "",
616 | "operationId": "getUserByName",
617 | "produces": [
618 | "application/json",
619 | "application/xml"
620 | ],
621 | "parameters": [
622 | {
623 | "name": "username",
624 | "in": "path",
625 | "description": "The name that needs to be fetched. Use user1 for testing. ",
626 | "required": true,
627 | "type": "string"
628 | }
629 | ],
630 | "responses": {
631 | "200": {
632 | "description": "successful operation",
633 | "schema": {
634 | "$ref": "#/definitions/User"
635 | }
636 | },
637 | "400": {
638 | "description": "Invalid username supplied"
639 | },
640 | "404": {
641 | "description": "User not found"
642 | }
643 | }
644 | },
645 | "put": {
646 | "tags": [
647 | "user"
648 | ],
649 | "summary": "Updated user",
650 | "description": "This can only be done by the logged in user.",
651 | "operationId": "updateUser",
652 | "consumes": [
653 | "application/json"
654 | ],
655 | "produces": [
656 | "application/json",
657 | "application/xml"
658 | ],
659 | "parameters": [
660 | {
661 | "name": "username",
662 | "in": "path",
663 | "description": "name that need to be updated",
664 | "required": true,
665 | "type": "string"
666 | },
667 | {
668 | "in": "body",
669 | "name": "body",
670 | "description": "Updated user object",
671 | "required": true,
672 | "schema": {
673 | "$ref": "#/definitions/User"
674 | }
675 | }
676 | ],
677 | "responses": {
678 | "400": {
679 | "description": "Invalid user supplied"
680 | },
681 | "404": {
682 | "description": "User not found"
683 | }
684 | }
685 | },
686 | "delete": {
687 | "tags": [
688 | "user"
689 | ],
690 | "summary": "Delete user",
691 | "description": "This can only be done by the logged in user.",
692 | "operationId": "deleteUser",
693 | "produces": [
694 | "application/json",
695 | "application/xml"
696 | ],
697 | "parameters": [
698 | {
699 | "name": "username",
700 | "in": "path",
701 | "description": "The name that needs to be deleted",
702 | "required": true,
703 | "type": "string"
704 | }
705 | ],
706 | "responses": {
707 | "400": {
708 | "description": "Invalid username supplied"
709 | },
710 | "404": {
711 | "description": "User not found"
712 | }
713 | }
714 | }
715 | },
716 | "/user/login": {
717 | "get": {
718 | "tags": [
719 | "user"
720 | ],
721 | "summary": "Logs user into the system",
722 | "description": "",
723 | "operationId": "loginUser",
724 | "produces": [
725 | "application/json",
726 | "application/xml"
727 | ],
728 | "parameters": [
729 | {
730 | "name": "username",
731 | "in": "query",
732 | "description": "The user name for login",
733 | "required": true,
734 | "type": "string"
735 | },
736 | {
737 | "name": "password",
738 | "in": "query",
739 | "description": "The password for login in clear text",
740 | "required": true,
741 | "type": "string"
742 | }
743 | ],
744 | "responses": {
745 | "200": {
746 | "description": "successful operation",
747 | "headers": {
748 | "X-Expires-After": {
749 | "type": "string",
750 | "format": "date-time",
751 | "description": "date in UTC when token expires"
752 | },
753 | "X-Rate-Limit": {
754 | "type": "integer",
755 | "format": "int32",
756 | "description": "calls per hour allowed by the user"
757 | }
758 | },
759 | "schema": {
760 | "type": "string"
761 | }
762 | },
763 | "400": {
764 | "description": "Invalid username/password supplied"
765 | }
766 | }
767 | }
768 | },
769 | "/user/logout": {
770 | "get": {
771 | "tags": [
772 | "user"
773 | ],
774 | "summary": "Logs out current logged in user session",
775 | "description": "",
776 | "operationId": "logoutUser",
777 | "produces": [
778 | "application/json",
779 | "application/xml"
780 | ],
781 | "parameters": [],
782 | "responses": {
783 | "default": {
784 | "description": "successful operation"
785 | }
786 | }
787 | }
788 | },
789 | "/user/createWithArray": {
790 | "post": {
791 | "tags": [
792 | "user"
793 | ],
794 | "summary": "Creates list of users with given input array",
795 | "description": "",
796 | "operationId": "createUsersWithArrayInput",
797 | "consumes": [
798 | "application/json"
799 | ],
800 | "produces": [
801 | "application/json",
802 | "application/xml"
803 | ],
804 | "parameters": [
805 | {
806 | "in": "body",
807 | "name": "body",
808 | "description": "List of user object",
809 | "required": true,
810 | "schema": {
811 | "type": "array",
812 | "items": {
813 | "$ref": "#/definitions/User"
814 | }
815 | }
816 | }
817 | ],
818 | "responses": {
819 | "default": {
820 | "description": "successful operation"
821 | }
822 | }
823 | }
824 | },
825 | "/user": {
826 | "post": {
827 | "tags": [
828 | "user"
829 | ],
830 | "summary": "Create user",
831 | "description": "This can only be done by the logged in user.",
832 | "operationId": "createUser",
833 | "consumes": [
834 | "application/json"
835 | ],
836 | "produces": [
837 | "application/json",
838 | "application/xml"
839 | ],
840 | "parameters": [
841 | {
842 | "in": "body",
843 | "name": "body",
844 | "description": "Created user object",
845 | "required": true,
846 | "schema": {
847 | "$ref": "#/definitions/User"
848 | }
849 | }
850 | ],
851 | "responses": {
852 | "default": {
853 | "description": "successful operation"
854 | }
855 | }
856 | }
857 | }
858 | },
859 | "securityDefinitions": {
860 | "api_key": {
861 | "type": "apiKey",
862 | "name": "api_key",
863 | "in": "header"
864 | },
865 | "petstore_auth": {
866 | "type": "oauth2",
867 | "authorizationUrl": "https://petstore.swagger.io/oauth/authorize",
868 | "flow": "implicit",
869 | "scopes": {
870 | "read:pets": "read your pets",
871 | "write:pets": "modify pets in your account"
872 | }
873 | }
874 | },
875 | "definitions": {
876 | "ApiResponse": {
877 | "type": "object",
878 | "properties": {
879 | "code": {
880 | "type": "integer",
881 | "format": "int32"
882 | },
883 | "type": {
884 | "type": "string"
885 | },
886 | "message": {
887 | "type": "string"
888 | }
889 | }
890 | },
891 | "Category": {
892 | "type": "object",
893 | "required": [
894 | "id",
895 | "color"
896 | ],
897 | "properties": {
898 | "id": {
899 | "type": "integer",
900 | "format": "int64"
901 | },
902 | "name": {
903 | "type": "integer"
904 | },
905 | "color": {
906 | "type": "string"
907 | }
908 | },
909 | "xml": {
910 | "name": "Category"
911 | }
912 | },
913 | "Pet": {
914 | "type": "object",
915 | "required": [
916 | "name",
917 | "photoUrls",
918 | "age"
919 | ],
920 | "properties": {
921 | "id": {
922 | "type": "string"
923 | },
924 | "age": {
925 | "type": "integer"
926 | },
927 | "category": {
928 | "$ref": "#/definitions/Category"
929 | },
930 | "name": {
931 | "type": "integer",
932 | "example": 1
933 | },
934 | "photoUrls": {
935 | "type": "array",
936 | "minItems": 2,
937 | "xml": {
938 | "wrapped": true
939 | },
940 | "items": {
941 | "type": "string",
942 | "xml": {
943 | "name": "photoUrl"
944 | }
945 | }
946 | },
947 | "tags": {
948 | "type": "array",
949 | "minItems": 1,
950 | "xml": {
951 | "wrapped": true
952 | },
953 | "items": {
954 | "xml": {
955 | "name": "tag"
956 | },
957 | "$ref": "#/definitions/Tag"
958 | }
959 | },
960 | "status": {
961 | "type": "string",
962 | "description": "pet status in the store",
963 | "enum": [
964 | "available",
965 | "sold"
966 | ]
967 | }
968 | },
969 | "xml": {
970 | "name": "Pet"
971 | }
972 | },
973 | "Tag": {
974 | "type": "object",
975 | "required": [
976 | "id",
977 | "type"
978 | ],
979 | "properties": {
980 | "id": {
981 | "type": "integer",
982 | "format": "int64"
983 | },
984 | "name": {
985 | "type": "string"
986 | },
987 | "type": {
988 | "type": "string"
989 | }
990 | },
991 | "xml": {
992 | "name": "Tag"
993 | }
994 | },
995 | "Order": {
996 | "type": "object",
997 | "properties": {
998 | "id": {
999 | "type": "integer",
1000 | "format": "int64"
1001 | },
1002 | "petId": {
1003 | "type": "integer",
1004 | "format": "int64"
1005 | },
1006 | "quantity": {
1007 | "type": "integer",
1008 | "format": "int32"
1009 | },
1010 | "shipDate": {
1011 | "type": "string",
1012 | "format": "date-time"
1013 | },
1014 | "status": {
1015 | "type": "string",
1016 | "description": "Order Status",
1017 | "enum": [
1018 | "placed",
1019 | "approved",
1020 | "delivered"
1021 | ]
1022 | },
1023 | "complete": {
1024 | "type": "boolean"
1025 | }
1026 | },
1027 | "xml": {
1028 | "name": "Order"
1029 | }
1030 | },
1031 | "User": {
1032 | "type": "object",
1033 | "properties": {
1034 | "id": {
1035 | "type": "integer",
1036 | "format": "int64"
1037 | },
1038 | "username": {
1039 | "type": "string"
1040 | },
1041 | "firstName": {
1042 | "type": "string"
1043 | },
1044 | "lastName": {
1045 | "type": "string"
1046 | },
1047 | "email": {
1048 | "type": "string"
1049 | },
1050 | "password": {
1051 | "type": "string"
1052 | },
1053 | "phone": {
1054 | "type": "string"
1055 | },
1056 | "userStatus": {
1057 | "type": "integer",
1058 | "format": "int32",
1059 | "description": "User Status"
1060 | }
1061 | },
1062 | "xml": {
1063 | "name": "User"
1064 | }
1065 | }
1066 | },
1067 | "externalDocs": {
1068 | "description": "Find out more about Swagger",
1069 | "url": "http://swagger.io"
1070 | }
1071 | }
--------------------------------------------------------------------------------
/cypress/fixtures/schemas/petstore-swagger.json:
--------------------------------------------------------------------------------
1 | {
2 | "swagger": "2.0",
3 | "info": {
4 | "description": "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.",
5 | "version": "1.0.7",
6 | "title": "Swagger Petstore",
7 | "termsOfService": "http://swagger.io/terms/",
8 | "contact": {
9 | "email": "apiteam@swagger.io"
10 | },
11 | "license": {
12 | "name": "Apache 2.0",
13 | "url": "http://www.apache.org/licenses/LICENSE-2.0.html"
14 | }
15 | },
16 | "host": "petstore.swagger.io",
17 | "basePath": "/v2",
18 | "tags": [
19 | {
20 | "name": "pet",
21 | "description": "Everything about your Pets",
22 | "externalDocs": {
23 | "description": "Find out more",
24 | "url": "http://swagger.io"
25 | }
26 | },
27 | {
28 | "name": "store",
29 | "description": "Access to Petstore orders"
30 | },
31 | {
32 | "name": "user",
33 | "description": "Operations about user",
34 | "externalDocs": {
35 | "description": "Find out more about our store",
36 | "url": "http://swagger.io"
37 | }
38 | }
39 | ],
40 | "schemes": [
41 | "https",
42 | "http"
43 | ],
44 | "paths": {
45 | "/pet/{petId}/uploadImage": {
46 | "post": {
47 | "tags": [
48 | "pet"
49 | ],
50 | "summary": "uploads an image",
51 | "description": "",
52 | "operationId": "uploadFile",
53 | "consumes": [
54 | "multipart/form-data"
55 | ],
56 | "produces": [
57 | "application/json"
58 | ],
59 | "parameters": [
60 | {
61 | "name": "petId",
62 | "in": "path",
63 | "description": "ID of pet to update",
64 | "required": true,
65 | "type": "integer",
66 | "format": "int64"
67 | },
68 | {
69 | "name": "additionalMetadata",
70 | "in": "formData",
71 | "description": "Additional data to pass to server",
72 | "required": false,
73 | "type": "string"
74 | },
75 | {
76 | "name": "file",
77 | "in": "formData",
78 | "description": "file to upload",
79 | "required": false,
80 | "type": "file"
81 | }
82 | ],
83 | "responses": {
84 | "200": {
85 | "description": "successful operation",
86 | "schema": {
87 | "$ref": "#/definitions/ApiResponse"
88 | }
89 | }
90 | },
91 | "security": [
92 | {
93 | "petstore_auth": [
94 | "write:pets",
95 | "read:pets"
96 | ]
97 | }
98 | ]
99 | }
100 | },
101 | "/pet": {
102 | "post": {
103 | "tags": [
104 | "pet"
105 | ],
106 | "summary": "Add a new pet to the store",
107 | "description": "",
108 | "operationId": "addPet",
109 | "consumes": [
110 | "application/json",
111 | "application/xml"
112 | ],
113 | "produces": [
114 | "application/json",
115 | "application/xml"
116 | ],
117 | "parameters": [
118 | {
119 | "in": "body",
120 | "name": "body",
121 | "description": "Pet object that needs to be added to the store",
122 | "required": true,
123 | "schema": {
124 | "$ref": "#/definitions/Pet"
125 | }
126 | }
127 | ],
128 | "responses": {
129 | "405": {
130 | "description": "Invalid input"
131 | }
132 | },
133 | "security": [
134 | {
135 | "petstore_auth": [
136 | "write:pets",
137 | "read:pets"
138 | ]
139 | }
140 | ]
141 | },
142 | "put": {
143 | "tags": [
144 | "pet"
145 | ],
146 | "summary": "Update an existing pet",
147 | "description": "",
148 | "operationId": "updatePet",
149 | "consumes": [
150 | "application/json",
151 | "application/xml"
152 | ],
153 | "produces": [
154 | "application/json",
155 | "application/xml"
156 | ],
157 | "parameters": [
158 | {
159 | "in": "body",
160 | "name": "body",
161 | "description": "Pet object that needs to be added to the store",
162 | "required": true,
163 | "schema": {
164 | "$ref": "#/definitions/Pet"
165 | }
166 | }
167 | ],
168 | "responses": {
169 | "400": {
170 | "description": "Invalid ID supplied"
171 | },
172 | "404": {
173 | "description": "Pet not found"
174 | },
175 | "405": {
176 | "description": "Validation exception"
177 | }
178 | },
179 | "security": [
180 | {
181 | "petstore_auth": [
182 | "write:pets",
183 | "read:pets"
184 | ]
185 | }
186 | ]
187 | }
188 | },
189 | "/pet/findByStatus": {
190 | "get": {
191 | "tags": [
192 | "pet"
193 | ],
194 | "summary": "Finds Pets by status",
195 | "description": "Multiple status values can be provided with comma separated strings",
196 | "operationId": "findPetsByStatus",
197 | "produces": [
198 | "application/json",
199 | "application/xml"
200 | ],
201 | "parameters": [
202 | {
203 | "name": "status",
204 | "in": "query",
205 | "description": "Status values that need to be considered for filter",
206 | "required": true,
207 | "type": "array",
208 | "items": {
209 | "type": "string",
210 | "enum": [
211 | "available",
212 | "pending",
213 | "sold"
214 | ],
215 | "default": "available"
216 | },
217 | "collectionFormat": "multi"
218 | }
219 | ],
220 | "responses": {
221 | "200": {
222 | "description": "successful operation",
223 | "schema": {
224 | "type": "array",
225 | "items": {
226 | "$ref": "#/definitions/Pet"
227 | }
228 | }
229 | },
230 | "400": {
231 | "description": "Invalid status value"
232 | }
233 | },
234 | "security": [
235 | {
236 | "petstore_auth": [
237 | "write:pets",
238 | "read:pets"
239 | ]
240 | }
241 | ]
242 | }
243 | },
244 | "/pet/findByTags": {
245 | "get": {
246 | "tags": [
247 | "pet"
248 | ],
249 | "summary": "Finds Pets by tags",
250 | "description": "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.",
251 | "operationId": "findPetsByTags",
252 | "produces": [
253 | "application/json",
254 | "application/xml"
255 | ],
256 | "parameters": [
257 | {
258 | "name": "tags",
259 | "in": "query",
260 | "description": "Tags to filter by",
261 | "required": true,
262 | "type": "array",
263 | "items": {
264 | "type": "string"
265 | },
266 | "collectionFormat": "multi"
267 | }
268 | ],
269 | "responses": {
270 | "200": {
271 | "description": "successful operation",
272 | "schema": {
273 | "type": "array",
274 | "items": {
275 | "$ref": "#/definitions/Pet"
276 | }
277 | }
278 | },
279 | "400": {
280 | "description": "Invalid tag value"
281 | }
282 | },
283 | "security": [
284 | {
285 | "petstore_auth": [
286 | "write:pets",
287 | "read:pets"
288 | ]
289 | }
290 | ],
291 | "deprecated": true
292 | }
293 | },
294 | "/pet/{petId}": {
295 | "get": {
296 | "tags": [
297 | "pet"
298 | ],
299 | "summary": "Find pet by ID",
300 | "description": "Returns a single pet",
301 | "operationId": "getPetById",
302 | "produces": [
303 | "application/json",
304 | "application/xml"
305 | ],
306 | "parameters": [
307 | {
308 | "name": "petId",
309 | "in": "path",
310 | "description": "ID of pet to return",
311 | "required": true,
312 | "type": "integer",
313 | "format": "int64"
314 | }
315 | ],
316 | "responses": {
317 | "200": {
318 | "description": "successful operation",
319 | "schema": {
320 | "$ref": "#/definitions/Pet"
321 | }
322 | },
323 | "400": {
324 | "description": "Invalid ID supplied"
325 | },
326 | "404": {
327 | "description": "Pet not found"
328 | }
329 | },
330 | "security": [
331 | {
332 | "api_key": []
333 | }
334 | ]
335 | },
336 | "post": {
337 | "tags": [
338 | "pet"
339 | ],
340 | "summary": "Updates a pet in the store with form data",
341 | "description": "",
342 | "operationId": "updatePetWithForm",
343 | "consumes": [
344 | "application/x-www-form-urlencoded"
345 | ],
346 | "produces": [
347 | "application/json",
348 | "application/xml"
349 | ],
350 | "parameters": [
351 | {
352 | "name": "petId",
353 | "in": "path",
354 | "description": "ID of pet that needs to be updated",
355 | "required": true,
356 | "type": "integer",
357 | "format": "int64"
358 | },
359 | {
360 | "name": "name",
361 | "in": "formData",
362 | "description": "Updated name of the pet",
363 | "required": false,
364 | "type": "string"
365 | },
366 | {
367 | "name": "status",
368 | "in": "formData",
369 | "description": "Updated status of the pet",
370 | "required": false,
371 | "type": "string"
372 | }
373 | ],
374 | "responses": {
375 | "405": {
376 | "description": "Invalid input"
377 | }
378 | },
379 | "security": [
380 | {
381 | "petstore_auth": [
382 | "write:pets",
383 | "read:pets"
384 | ]
385 | }
386 | ]
387 | },
388 | "delete": {
389 | "tags": [
390 | "pet"
391 | ],
392 | "summary": "Deletes a pet",
393 | "description": "",
394 | "operationId": "deletePet",
395 | "produces": [
396 | "application/json",
397 | "application/xml"
398 | ],
399 | "parameters": [
400 | {
401 | "name": "api_key",
402 | "in": "header",
403 | "required": false,
404 | "type": "string"
405 | },
406 | {
407 | "name": "petId",
408 | "in": "path",
409 | "description": "Pet id to delete",
410 | "required": true,
411 | "type": "integer",
412 | "format": "int64"
413 | }
414 | ],
415 | "responses": {
416 | "400": {
417 | "description": "Invalid ID supplied"
418 | },
419 | "404": {
420 | "description": "Pet not found"
421 | }
422 | },
423 | "security": [
424 | {
425 | "petstore_auth": [
426 | "write:pets",
427 | "read:pets"
428 | ]
429 | }
430 | ]
431 | }
432 | },
433 | "/store/inventory": {
434 | "get": {
435 | "tags": [
436 | "store"
437 | ],
438 | "summary": "Returns pet inventories by status",
439 | "description": "Returns a map of status codes to quantities",
440 | "operationId": "getInventory",
441 | "produces": [
442 | "application/json"
443 | ],
444 | "parameters": [],
445 | "responses": {
446 | "200": {
447 | "description": "successful operation",
448 | "schema": {
449 | "type": "object",
450 | "additionalProperties": {
451 | "type": "integer",
452 | "format": "int32"
453 | }
454 | }
455 | }
456 | },
457 | "security": [
458 | {
459 | "api_key": []
460 | }
461 | ]
462 | }
463 | },
464 | "/store/order": {
465 | "post": {
466 | "tags": [
467 | "store"
468 | ],
469 | "summary": "Place an order for a pet",
470 | "description": "",
471 | "operationId": "placeOrder",
472 | "consumes": [
473 | "application/json"
474 | ],
475 | "produces": [
476 | "application/json",
477 | "application/xml"
478 | ],
479 | "parameters": [
480 | {
481 | "in": "body",
482 | "name": "body",
483 | "description": "order placed for purchasing the pet",
484 | "required": true,
485 | "schema": {
486 | "$ref": "#/definitions/Order"
487 | }
488 | }
489 | ],
490 | "responses": {
491 | "200": {
492 | "description": "successful operation",
493 | "schema": {
494 | "$ref": "#/definitions/Order"
495 | }
496 | },
497 | "400": {
498 | "description": "Invalid Order"
499 | }
500 | }
501 | }
502 | },
503 | "/store/order/{orderId}": {
504 | "get": {
505 | "tags": [
506 | "store"
507 | ],
508 | "summary": "Find purchase order by ID",
509 | "description": "For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions",
510 | "operationId": "getOrderById",
511 | "produces": [
512 | "application/json",
513 | "application/xml"
514 | ],
515 | "parameters": [
516 | {
517 | "name": "orderId",
518 | "in": "path",
519 | "description": "ID of pet that needs to be fetched",
520 | "required": true,
521 | "type": "integer",
522 | "maximum": 10,
523 | "minimum": 1,
524 | "format": "int64"
525 | }
526 | ],
527 | "responses": {
528 | "200": {
529 | "description": "successful operation",
530 | "schema": {
531 | "$ref": "#/definitions/Order"
532 | }
533 | },
534 | "400": {
535 | "description": "Invalid ID supplied"
536 | },
537 | "404": {
538 | "description": "Order not found"
539 | }
540 | }
541 | },
542 | "delete": {
543 | "tags": [
544 | "store"
545 | ],
546 | "summary": "Delete purchase order by ID",
547 | "description": "For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors",
548 | "operationId": "deleteOrder",
549 | "produces": [
550 | "application/json",
551 | "application/xml"
552 | ],
553 | "parameters": [
554 | {
555 | "name": "orderId",
556 | "in": "path",
557 | "description": "ID of the order that needs to be deleted",
558 | "required": true,
559 | "type": "integer",
560 | "minimum": 1,
561 | "format": "int64"
562 | }
563 | ],
564 | "responses": {
565 | "400": {
566 | "description": "Invalid ID supplied"
567 | },
568 | "404": {
569 | "description": "Order not found"
570 | }
571 | }
572 | }
573 | },
574 | "/user/createWithList": {
575 | "post": {
576 | "tags": [
577 | "user"
578 | ],
579 | "summary": "Creates list of users with given input array",
580 | "description": "",
581 | "operationId": "createUsersWithListInput",
582 | "consumes": [
583 | "application/json"
584 | ],
585 | "produces": [
586 | "application/json",
587 | "application/xml"
588 | ],
589 | "parameters": [
590 | {
591 | "in": "body",
592 | "name": "body",
593 | "description": "List of user object",
594 | "required": true,
595 | "schema": {
596 | "type": "array",
597 | "items": {
598 | "$ref": "#/definitions/User"
599 | }
600 | }
601 | }
602 | ],
603 | "responses": {
604 | "default": {
605 | "description": "successful operation"
606 | }
607 | }
608 | }
609 | },
610 | "/user/{username}": {
611 | "get": {
612 | "tags": [
613 | "user"
614 | ],
615 | "summary": "Get user by user name",
616 | "description": "",
617 | "operationId": "getUserByName",
618 | "produces": [
619 | "application/json",
620 | "application/xml"
621 | ],
622 | "parameters": [
623 | {
624 | "name": "username",
625 | "in": "path",
626 | "description": "The name that needs to be fetched. Use user1 for testing. ",
627 | "required": true,
628 | "type": "string"
629 | }
630 | ],
631 | "responses": {
632 | "200": {
633 | "description": "successful operation",
634 | "schema": {
635 | "$ref": "#/definitions/User"
636 | }
637 | },
638 | "400": {
639 | "description": "Invalid username supplied"
640 | },
641 | "404": {
642 | "description": "User not found"
643 | }
644 | }
645 | },
646 | "put": {
647 | "tags": [
648 | "user"
649 | ],
650 | "summary": "Updated user",
651 | "description": "This can only be done by the logged in user.",
652 | "operationId": "updateUser",
653 | "consumes": [
654 | "application/json"
655 | ],
656 | "produces": [
657 | "application/json",
658 | "application/xml"
659 | ],
660 | "parameters": [
661 | {
662 | "name": "username",
663 | "in": "path",
664 | "description": "name that need to be updated",
665 | "required": true,
666 | "type": "string"
667 | },
668 | {
669 | "in": "body",
670 | "name": "body",
671 | "description": "Updated user object",
672 | "required": true,
673 | "schema": {
674 | "$ref": "#/definitions/User"
675 | }
676 | }
677 | ],
678 | "responses": {
679 | "400": {
680 | "description": "Invalid user supplied"
681 | },
682 | "404": {
683 | "description": "User not found"
684 | }
685 | }
686 | },
687 | "delete": {
688 | "tags": [
689 | "user"
690 | ],
691 | "summary": "Delete user",
692 | "description": "This can only be done by the logged in user.",
693 | "operationId": "deleteUser",
694 | "produces": [
695 | "application/json",
696 | "application/xml"
697 | ],
698 | "parameters": [
699 | {
700 | "name": "username",
701 | "in": "path",
702 | "description": "The name that needs to be deleted",
703 | "required": true,
704 | "type": "string"
705 | }
706 | ],
707 | "responses": {
708 | "400": {
709 | "description": "Invalid username supplied"
710 | },
711 | "404": {
712 | "description": "User not found"
713 | }
714 | }
715 | }
716 | },
717 | "/user/login": {
718 | "get": {
719 | "tags": [
720 | "user"
721 | ],
722 | "summary": "Logs user into the system",
723 | "description": "",
724 | "operationId": "loginUser",
725 | "produces": [
726 | "application/json",
727 | "application/xml"
728 | ],
729 | "parameters": [
730 | {
731 | "name": "username",
732 | "in": "query",
733 | "description": "The user name for login",
734 | "required": true,
735 | "type": "string"
736 | },
737 | {
738 | "name": "password",
739 | "in": "query",
740 | "description": "The password for login in clear text",
741 | "required": true,
742 | "type": "string"
743 | }
744 | ],
745 | "responses": {
746 | "200": {
747 | "description": "successful operation",
748 | "headers": {
749 | "X-Expires-After": {
750 | "type": "string",
751 | "format": "date-time",
752 | "description": "date in UTC when token expires"
753 | },
754 | "X-Rate-Limit": {
755 | "type": "integer",
756 | "format": "int32",
757 | "description": "calls per hour allowed by the user"
758 | }
759 | },
760 | "schema": {
761 | "type": "string"
762 | }
763 | },
764 | "400": {
765 | "description": "Invalid username/password supplied"
766 | }
767 | }
768 | }
769 | },
770 | "/user/logout": {
771 | "get": {
772 | "tags": [
773 | "user"
774 | ],
775 | "summary": "Logs out current logged in user session",
776 | "description": "",
777 | "operationId": "logoutUser",
778 | "produces": [
779 | "application/json",
780 | "application/xml"
781 | ],
782 | "parameters": [],
783 | "responses": {
784 | "default": {
785 | "description": "successful operation"
786 | }
787 | }
788 | }
789 | },
790 | "/user/createWithArray": {
791 | "post": {
792 | "tags": [
793 | "user"
794 | ],
795 | "summary": "Creates list of users with given input array",
796 | "description": "",
797 | "operationId": "createUsersWithArrayInput",
798 | "consumes": [
799 | "application/json"
800 | ],
801 | "produces": [
802 | "application/json",
803 | "application/xml"
804 | ],
805 | "parameters": [
806 | {
807 | "in": "body",
808 | "name": "body",
809 | "description": "List of user object",
810 | "required": true,
811 | "schema": {
812 | "type": "array",
813 | "items": {
814 | "$ref": "#/definitions/User"
815 | }
816 | }
817 | }
818 | ],
819 | "responses": {
820 | "default": {
821 | "description": "successful operation"
822 | }
823 | }
824 | }
825 | },
826 | "/user": {
827 | "post": {
828 | "tags": [
829 | "user"
830 | ],
831 | "summary": "Create user",
832 | "description": "This can only be done by the logged in user.",
833 | "operationId": "createUser",
834 | "consumes": [
835 | "application/json"
836 | ],
837 | "produces": [
838 | "application/json",
839 | "application/xml"
840 | ],
841 | "parameters": [
842 | {
843 | "in": "body",
844 | "name": "body",
845 | "description": "Created user object",
846 | "required": true,
847 | "schema": {
848 | "$ref": "#/definitions/User"
849 | }
850 | }
851 | ],
852 | "responses": {
853 | "default": {
854 | "description": "successful operation"
855 | }
856 | }
857 | }
858 | }
859 | },
860 | "securityDefinitions": {
861 | "api_key": {
862 | "type": "apiKey",
863 | "name": "api_key",
864 | "in": "header"
865 | },
866 | "petstore_auth": {
867 | "type": "oauth2",
868 | "authorizationUrl": "https://petstore.swagger.io/oauth/authorize",
869 | "flow": "implicit",
870 | "scopes": {
871 | "read:pets": "read your pets",
872 | "write:pets": "modify pets in your account"
873 | }
874 | }
875 | },
876 | "definitions": {
877 | "ApiResponse": {
878 | "type": "object",
879 | "properties": {
880 | "code": {
881 | "type": "integer",
882 | "format": "int32"
883 | },
884 | "type": {
885 | "type": "string"
886 | },
887 | "message": {
888 | "type": "string"
889 | }
890 | }
891 | },
892 | "Category": {
893 | "type": "object",
894 | "properties": {
895 | "id": {
896 | "type": "integer",
897 | "format": "int64"
898 | },
899 | "name": {
900 | "type": "string"
901 | }
902 | },
903 | "xml": {
904 | "name": "Category"
905 | }
906 | },
907 | "Pet": {
908 | "type": "object",
909 | "required": [
910 | "name",
911 | "photoUrls"
912 | ],
913 | "properties": {
914 | "id": {
915 | "type": "integer",
916 | "format": "int64"
917 | },
918 | "category": {
919 | "$ref": "#/definitions/Category"
920 | },
921 | "name": {
922 | "type": "string",
923 | "example": "doggie"
924 | },
925 | "photoUrls": {
926 | "type": "array",
927 | "xml": {
928 | "wrapped": true
929 | },
930 | "items": {
931 | "type": "string",
932 | "xml": {
933 | "name": "photoUrl"
934 | }
935 | }
936 | },
937 | "tags": {
938 | "type": "array",
939 | "xml": {
940 | "wrapped": true
941 | },
942 | "items": {
943 | "xml": {
944 | "name": "tag"
945 | },
946 | "$ref": "#/definitions/Tag"
947 | }
948 | },
949 | "status": {
950 | "type": "string",
951 | "description": "pet status in the store",
952 | "enum": [
953 | "available",
954 | "pending",
955 | "sold"
956 | ]
957 | }
958 | },
959 | "xml": {
960 | "name": "Pet"
961 | }
962 | },
963 | "Tag": {
964 | "type": "object",
965 | "properties": {
966 | "id": {
967 | "type": "integer",
968 | "format": "int64"
969 | },
970 | "name": {
971 | "type": "string"
972 | }
973 | },
974 | "xml": {
975 | "name": "Tag"
976 | }
977 | },
978 | "Order": {
979 | "type": "object",
980 | "properties": {
981 | "id": {
982 | "type": "integer",
983 | "format": "int64"
984 | },
985 | "petId": {
986 | "type": "integer",
987 | "format": "int64"
988 | },
989 | "quantity": {
990 | "type": "integer",
991 | "format": "int32"
992 | },
993 | "shipDate": {
994 | "type": "string",
995 | "format": "date-time"
996 | },
997 | "status": {
998 | "type": "string",
999 | "description": "Order Status",
1000 | "enum": [
1001 | "placed",
1002 | "approved",
1003 | "delivered"
1004 | ]
1005 | },
1006 | "complete": {
1007 | "type": "boolean"
1008 | }
1009 | },
1010 | "xml": {
1011 | "name": "Order"
1012 | }
1013 | },
1014 | "User": {
1015 | "type": "object",
1016 | "properties": {
1017 | "id": {
1018 | "type": "integer",
1019 | "format": "int64"
1020 | },
1021 | "username": {
1022 | "type": "string"
1023 | },
1024 | "firstName": {
1025 | "type": "string"
1026 | },
1027 | "lastName": {
1028 | "type": "string"
1029 | },
1030 | "email": {
1031 | "type": "string"
1032 | },
1033 | "password": {
1034 | "type": "string"
1035 | },
1036 | "phone": {
1037 | "type": "string"
1038 | },
1039 | "userStatus": {
1040 | "type": "integer",
1041 | "format": "int32",
1042 | "description": "User Status"
1043 | }
1044 | },
1045 | "xml": {
1046 | "name": "User"
1047 | }
1048 | }
1049 | },
1050 | "externalDocs": {
1051 | "description": "Find out more about Swagger",
1052 | "url": "http://swagger.io"
1053 | }
1054 | }
--------------------------------------------------------------------------------
/cypress/fixtures/schemas/plainjson-schema.json:
--------------------------------------------------------------------------------
1 | {
2 | "type": "array",
3 | "items": {
4 | "type": "object",
5 | "properties": {
6 | "id": {
7 | "type": "string",
8 | "format": "uuid"
9 | },
10 | "name": {
11 | "type": "string"
12 | },
13 | "age": {
14 | "type": "integer"
15 | },
16 | "email": {
17 | "type": "string",
18 | "format": "email"
19 | },
20 | "created_at": {
21 | "type": "string",
22 | "format": "date-time"
23 | },
24 | "is_active": {
25 | "type": "boolean"
26 | },
27 | "tags": {
28 | "type": "array",
29 | "items": {
30 | "type": "string"
31 | }
32 | },
33 | "address": {
34 | "type": "object",
35 | "properties": {
36 | "street": {
37 | "type": "string"
38 | },
39 | "city": {
40 | "type": "string"
41 | },
42 | "postal_code": {
43 | "type": "string"
44 | }
45 | },
46 | "required": [
47 | "street",
48 | "city",
49 | "postal_code"
50 | ]
51 | },
52 | "preferences": {
53 | "type": "object",
54 | "properties": {
55 | "notifications": {
56 | "type": "boolean"
57 | },
58 | "theme": {
59 | "type": "string"
60 | },
61 | "items_per_page": {
62 | "type": "integer"
63 | }
64 | }
65 | }
66 | },
67 | "required": [
68 | "id",
69 | "name",
70 | "age",
71 | "email",
72 | "created_at",
73 | "is_active"
74 | ]
75 | }
76 | }
--------------------------------------------------------------------------------
/cypress/fixtures/schemas/swagger-schema.json:
--------------------------------------------------------------------------------
1 | {
2 | "swagger": "2.0",
3 | "info": {
4 | "title": "Example API",
5 | "version": "1.0.0",
6 | "description": "An example API with GET and POST methods."
7 | },
8 | "host": "api.example.com",
9 | "schemes": [
10 | "https"
11 | ],
12 | "paths": {
13 | "/service1": {
14 | "get": {
15 | "summary": "Get details for service 1",
16 | "operationId": "getService1",
17 | "responses": {
18 | "200": {
19 | "description": "Successful response",
20 | "schema": {
21 | "$ref": "#/definitions/Service1Response"
22 | }
23 | },
24 | "401": {
25 | "description": "Unauthorized",
26 | "schema": {
27 | "$ref": "#/definitions/ErrorResponse"
28 | }
29 | }
30 | }
31 | },
32 | "post": {
33 | "summary": "Create a new entry for service 1",
34 | "operationId": "createService1",
35 | "parameters": [
36 | {
37 | "in": "body",
38 | "name": "body",
39 | "required": true,
40 | "schema": {
41 | "$ref": "#/definitions/Service1Request"
42 | }
43 | }
44 | ],
45 | "responses": {
46 | "201": {
47 | "description": "Resource created",
48 | "schema": {
49 | "$ref": "#/definitions/Service1Response"
50 | }
51 | },
52 | "401": {
53 | "description": "Unauthorized",
54 | "schema": {
55 | "$ref": "#/definitions/ErrorResponse"
56 | }
57 | }
58 | }
59 | }
60 | },
61 | "/service2": {
62 | "get": {
63 | "summary": "Get details for service 2",
64 | "operationId": "getService2",
65 | "responses": {
66 | "200": {
67 | "description": "Successful response",
68 | "schema": {
69 | "type": "array",
70 | "items": {
71 | "$ref": "#/definitions/Service2Response"
72 | }
73 | }
74 | },
75 | "401": {
76 | "description": "Unauthorized",
77 | "schema": {
78 | "$ref": "#/definitions/ErrorResponse"
79 | }
80 | }
81 | }
82 | },
83 | "post": {
84 | "summary": "Create a new entry for service 2",
85 | "operationId": "createService2",
86 | "parameters": [
87 | {
88 | "in": "body",
89 | "name": "body",
90 | "required": true,
91 | "schema": {
92 | "$ref": "#/definitions/Service2Request"
93 | }
94 | }
95 | ],
96 | "responses": {
97 | "201": {
98 | "description": "Resource created",
99 | "schema": {
100 | "type": "array",
101 | "items": {
102 | "$ref": "#/definitions/Service2Response"
103 | }
104 | }
105 | },
106 | "default": {
107 | "description": "Unauthorized",
108 | "schema": {
109 | "$ref": "#/definitions/ErrorResponse"
110 | }
111 | }
112 | }
113 | }
114 | }
115 | },
116 | "definitions": {
117 | "Service1Response": {
118 | "type": "object",
119 | "required": ["id", "name", "status", "createdAt", "isActive", "age"],
120 | "properties": {
121 | "id": {
122 | "type": "string",
123 | "format": "uuid"
124 | },
125 | "name": {
126 | "type": "string",
127 | "nullable": false
128 | },
129 | "status": {
130 | "type": "string"
131 | },
132 | "email": {
133 | "type": "string",
134 | "format": "email",
135 | "nullable": true
136 | },
137 | "createdAt": {
138 | "type": "string",
139 | "format": "date-time"
140 | },
141 | "isActive": {
142 | "type": "boolean"
143 | },
144 | "age": {
145 | "type": "integer",
146 | "nullable": false
147 | },
148 | "tags": {
149 | "type": "array",
150 | "items": {
151 | "type": "string"
152 | }
153 | },
154 | "preferences": {
155 | "$ref": "#/definitions/Preferences"
156 | }
157 | }
158 | },
159 | "Service1Request": {
160 | "type": "object",
161 | "required": ["name", "status", "createdAt", "isActive", "age"],
162 | "properties": {
163 | "name": {
164 | "type": "string",
165 | "nullable": false
166 | },
167 | "status": {
168 | "type": "string"
169 | },
170 | "email": {
171 | "type": "string",
172 | "format": "email",
173 | "nullable": true
174 | },
175 | "createdAt": {
176 | "type": "string",
177 | "format": "date-time"
178 | },
179 | "isActive": {
180 | "type": "boolean"
181 | },
182 | "age": {
183 | "type": "integer",
184 | "nullable": false
185 | },
186 | "tags": {
187 | "type": "array",
188 | "items": {
189 | "type": "string"
190 | },
191 | "nullable": true
192 | },
193 | "meta": {
194 | "$ref": "#/definitions/Meta"
195 | }
196 | }
197 | },
198 | "Service2Response": {
199 | "type": "object",
200 | "required": ["id", "description", "createdDate", "priority", "completed"],
201 | "properties": {
202 | "id": {
203 | "type": "string",
204 | "format": "uuid"
205 | },
206 | "description": {
207 | "type": "string",
208 | "nullable": false
209 | },
210 | "createdDate": {
211 | "type": "string",
212 | "format": "date-time"
213 | },
214 | "priority": {
215 | "type": "integer",
216 | "nullable": false
217 | },
218 | "completed": {
219 | "type": "boolean"
220 | },
221 | "details": {
222 | "type": "object",
223 | "properties": {
224 | "detail1": {
225 | "type": "string",
226 | "nullable": true
227 | },
228 | "detail2": {
229 | "type": "integer"
230 | }
231 | },
232 | "required": ["detail2"]
233 | }
234 | }
235 | },
236 | "Service2Request": {
237 | "type": "object",
238 | "required": ["description"],
239 | "properties": {
240 | "description": {
241 | "type": "string",
242 | "nullable": false
243 | }
244 | }
245 | },
246 | "ErrorResponse": {
247 | "type": "object",
248 | "required": ["code", "message"],
249 | "properties": {
250 | "code": {
251 | "type": "integer"
252 | },
253 | "message": {
254 | "type": "string"
255 | }
256 | }
257 | },
258 | "Preferences": {
259 | "type": "object",
260 | "properties": {
261 | "notifications": {
262 | "type": "boolean"
263 | },
264 | "theme": {
265 | "type": "string",
266 | "nullable": true
267 | },
268 | "itemsPerPage": {
269 | "type": "integer"
270 | }
271 | }
272 | },
273 | "Meta": {
274 | "type": "object",
275 | "required": ["createdBy", "createdDate"],
276 | "properties": {
277 | "createdBy": {
278 | "type": "string",
279 | "nullable": false
280 | },
281 | "createdDate": {
282 | "type": "string",
283 | "format": "date-time"
284 | }
285 | }
286 | }
287 | }
288 | }
--------------------------------------------------------------------------------
/cypress/support/commands.js:
--------------------------------------------------------------------------------
1 | // ***********************************************
2 | // This example commands.js shows you how to
3 | // create various custom commands and overwrite
4 | // existing commands.
5 | //
6 | // For more comprehensive examples of custom
7 | // commands please read more here:
8 | // https://on.cypress.io/custom-commands
9 | // ***********************************************
10 | //
11 | //
12 | // -- This is a parent command --
13 | // Cypress.Commands.add('login', (email, password) => { ... })
14 | //
15 | //
16 | // -- This is a child command --
17 | // Cypress.Commands.add('drag', { prevSubject: 'element'}, (subject, options) => { ... })
18 | //
19 | //
20 | // -- This is a dual command --
21 | // Cypress.Commands.add('dismiss', { prevSubject: 'optional'}, (subject, options) => { ... })
22 | //
23 | //
24 | // -- This will overwrite an existing command --
25 | // Cypress.Commands.overwrite('visit', (originalFn, url, options) => { ... })
--------------------------------------------------------------------------------
/cypress/support/e2e.js:
--------------------------------------------------------------------------------
1 | // ***********************************************************
2 | // This example support/e2e.js is processed and
3 | // loaded automatically before your test files.
4 | //
5 | // This is a great place to put global configuration and
6 | // behavior that modifies Cypress.
7 | //
8 | // You can change the location of this file or turn off
9 | // automatically serving support files with the
10 | // 'supportFile' configuration option.
11 | //
12 | // You can read more here:
13 | // https://on.cypress.io/configuration
14 | // ***********************************************************
15 |
16 | // Import commands.js using ES2015 syntax:
17 | import "./commands";
18 |
19 | // Alternatively you can use CommonJS syntax:
20 | // require('./commands')
21 |
22 | // beforeEach(() => {
23 | // cy.on("fail", (err) => {
24 | // // We expected a validation failure, so don't re-throw the error.
25 | // // Returning false here prevents the test from failing.
26 | // return false;
27 | // });
28 | // });
29 |
--------------------------------------------------------------------------------
/cypress/support/run-tests-openapi-swagger.js:
--------------------------------------------------------------------------------
1 | ///
2 |
3 | import '../../src/index.js'
4 |
5 | import openApiSchema from '../fixtures/schemas/openapi-schema.json'
6 | import swaggerSchema from '../fixtures/schemas/swagger-schema.json'
7 | import tests from '../fixtures/mock-data-openapi-swagger/tests.json'
8 |
9 |
10 | const runTestsOpenapiSwagger = (scenario) => {
11 |
12 | [openApiSchema, swaggerSchema].forEach(schema => {
13 |
14 | const schemaSpecVersion = schema.swagger ? `Swagger ${schema.swagger}` : `OpenAPI ${schema.openapi}`
15 |
16 | context(`Schema Validation for ${schemaSpecVersion}`, () => {
17 |
18 | tests.forEach(test => {
19 |
20 | it(`${test.method} ${test.endpoint} (${test.status} Response)`, () => {
21 | cy.fixture(`mock-data-openapi-swagger/${scenario}/${test.method}${test.endpoint}_${test.status}.json`).then((data) => {
22 | cy.wrap({ status: test.status, body: data }, { log: false }).validateSchema(schema, { endpoint: test.endpoint, method: test.method, status: test.status })
23 | })
24 | })
25 |
26 | })
27 | })
28 | })
29 | }
30 |
31 | export default runTestsOpenapiSwagger
--------------------------------------------------------------------------------
/cypress/support/run-tests-plainjson.js:
--------------------------------------------------------------------------------
1 | ///
2 |
3 | import '../../src/index.js'
4 |
5 | import schema from '../fixtures/schemas/plainjson-schema.json'
6 |
7 |
8 | const runTestsPlainJson = (scenario) => {
9 | it(`Test Plain JSON Schema`, () => {
10 | cy.fixture(`mock-data-plainjson/${scenario}.json`).then((data) => {
11 | cy.wrap({ status: 200, body: data }, { log: false }).validateSchema(schema)
12 | })
13 | })
14 |
15 | }
16 |
17 | export default runTestsPlainJson
--------------------------------------------------------------------------------
/images/cy_api_1_a.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sclavijosuero/cypress-ajv-schema-validator/df9a3b3a2d82ef1351a813832978a44fff347dc0/images/cy_api_1_a.png
--------------------------------------------------------------------------------
/images/cy_api_1_details_a.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sclavijosuero/cypress-ajv-schema-validator/df9a3b3a2d82ef1351a813832978a44fff347dc0/images/cy_api_1_details_a.png
--------------------------------------------------------------------------------
/images/cy_api_2_a.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sclavijosuero/cypress-ajv-schema-validator/df9a3b3a2d82ef1351a813832978a44fff347dc0/images/cy_api_2_a.png
--------------------------------------------------------------------------------
/images/cy_api_2_details_a.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sclavijosuero/cypress-ajv-schema-validator/df9a3b3a2d82ef1351a813832978a44fff347dc0/images/cy_api_2_details_a.png
--------------------------------------------------------------------------------
/images/disabled_a.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sclavijosuero/cypress-ajv-schema-validator/df9a3b3a2d82ef1351a813832978a44fff347dc0/images/disabled_a.png
--------------------------------------------------------------------------------
/images/error11_a.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sclavijosuero/cypress-ajv-schema-validator/df9a3b3a2d82ef1351a813832978a44fff347dc0/images/error11_a.png
--------------------------------------------------------------------------------
/images/error12_a.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sclavijosuero/cypress-ajv-schema-validator/df9a3b3a2d82ef1351a813832978a44fff347dc0/images/error12_a.png
--------------------------------------------------------------------------------
/images/error21_a.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sclavijosuero/cypress-ajv-schema-validator/df9a3b3a2d82ef1351a813832978a44fff347dc0/images/error21_a.png
--------------------------------------------------------------------------------
/images/error23_a.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sclavijosuero/cypress-ajv-schema-validator/df9a3b3a2d82ef1351a813832978a44fff347dc0/images/error23_a.png
--------------------------------------------------------------------------------
/images/overview_a.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sclavijosuero/cypress-ajv-schema-validator/df9a3b3a2d82ef1351a813832978a44fff347dc0/images/overview_a.png
--------------------------------------------------------------------------------
/images/pass1_a.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sclavijosuero/cypress-ajv-schema-validator/df9a3b3a2d82ef1351a813832978a44fff347dc0/images/pass1_a.png
--------------------------------------------------------------------------------
/images/path_a.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sclavijosuero/cypress-ajv-schema-validator/df9a3b3a2d82ef1351a813832978a44fff347dc0/images/path_a.png
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "cypress-ajv-schema-validator",
3 | "version": "2.0.1",
4 | "description": "Lightweight Cypress plugin for API schema validation against plain JSON schemas, Swagger schema documents, or OpenAPI schema documents, leveraging the core-ajv-schema-validator powered by the Ajv JSON Schema Validator.",
5 | "main": "src/index.js",
6 | "types": "src/index.d.ts",
7 | "scripts": {
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "repository": {
11 | "type": "git",
12 | "url": "git+https://github.com/sclavijosuero/cypress-ajv-schema-validator.git"
13 | },
14 | "keywords": [
15 | "plugin",
16 | "cypress",
17 | "ajv",
18 | "schema",
19 | "validator",
20 | "json"
21 | ],
22 | "author": "Sebastian Clavijo Suero",
23 | "license": "MIT",
24 | "bugs": {
25 | "url": "https://github.com/sclavijosuero/cypress-ajv-schema-validator/issues"
26 | },
27 | "homepage": "https://github.com/sclavijosuero/cypress-ajv-schema-validator#readme",
28 | "devDependencies": {
29 | "@bahmutov/cy-api": "^2.2.6",
30 | "cypress": "^13.16.1"
31 | },
32 | "dependencies": {
33 | "core-ajv-schema-validator": "^1.0.0",
34 | "cypress-plugin-api": "^2.11.2",
35 | "highlight.js": "^11.10.0"
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/StyleHandler.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Class representing a StyleHandler.
3 | */
4 | export default class StyleHandler {
5 |
6 | /**
7 | * A Set to store the cached styles.
8 | * @private
9 | *
10 | * @type {Set}
11 | */
12 | static _cachedStyles = new Set()
13 |
14 | /**
15 | * Get the style name for the given hex color.
16 | * @public
17 | *
18 | * @param {string} hexColor - The hex color code.
19 | *
20 | * @returns {string} The style name.
21 | */
22 | static getStyleName = (hexColor = '#FFFFFF') => {
23 | const styleName = `colorLog${hexColor.replace("#", "-")}`
24 |
25 | if (!StyleHandler._cachedStyles.has(styleName)) {
26 | StyleHandler._createStyle(styleName, hexColor) // Create style element in the document
27 | StyleHandler._cachedStyles.add(styleName) // Cache the style name
28 | }
29 |
30 | return styleName
31 | }
32 |
33 | /**
34 | * Create a style element in the web document.
35 | * @private
36 | *
37 | * @param {string} styleName - The style name.
38 | * @param {string} hexColor - The hex color code.
39 | */
40 | static _createStyle = (styleName, hexColor) => {
41 | const style = document.createElement('style')
42 |
43 | style.textContent = `
44 | .command.command-name-${styleName} span.command-method {
45 | color: ${hexColor} !important;
46 | text-transform: uppercase;
47 | font-weight: bold;
48 | background-color: none;
49 | border-color: none;
50 | }
51 |
52 | .command.command-name-${styleName} span.command-message{
53 | color: ${hexColor} !important;
54 | font-weight: normal;
55 | background-color: none;
56 | border-color: none;
57 | }
58 |
59 | .command.command-name-${styleName} span.command-message strong,
60 | .command.command-name-${styleName} span.command-message em {
61 | color: ${hexColor} !important;
62 | background-color: none;
63 | border-color: none;
64 | }
65 | `
66 |
67 | Cypress.$(window.top.document.head).append(style)
68 | }
69 | }
--------------------------------------------------------------------------------
/src/custom-log.js:
--------------------------------------------------------------------------------
1 | ///
2 |
3 | import StyleHandler from './StyleHandler'
4 |
5 |
6 | /**
7 | * Custom comant that kogs a message in Cypress Log with a specified color.
8 | * Additional properties are shown in the console when the log message is clicked.
9 | * @public
10 | *
11 | * @param {string} message - The message to be logged.
12 | * @param {string} hexColor - The hexadecimal color code to be used for the log message.
13 | * @param {Object} options - Additional options for the log message.
14 | * @param {string} options.displayName - The display name for the log message.
15 | * @param {Object} options.$el - The element associated with the log message.
16 | * @param {Object} [options.info={}] - Additional info to be included in the log message.
17 | *
18 | * @example
19 | * cy.colorLog('You did not pass the test!', '#FF0000',
20 | * { displayName: "ERROR:", info: { comments: 'Wrong!', toDo: 'Need way more practice.' } })
21 | */
22 | Cypress.Commands.add('colorLog',
23 | (message, hexColor, { displayName, $el, info = {}}) => {
24 | const name = StyleHandler.getStyleName(hexColor)
25 | Cypress.log({
26 | displayName,
27 | message,
28 | name,
29 | $el,
30 | consoleProps: () => {
31 | // return an object which will
32 | // print to dev tools console on click
33 | return {
34 | displayName,
35 | message,
36 | name,
37 | $el,
38 | ...info
39 | }
40 | },
41 | })
42 | }
43 | )
44 |
--------------------------------------------------------------------------------
/src/index.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 |
3 | declare global {
4 | namespace Cypress {
5 | interface Chainable {
6 | /**
7 | * Validates the response body against the provided JSON schema.
8 | *
9 | * @param {object} schema - The schema to validate against. Supported formats are plain JSON schema, Swagger, and OpenAPI documents. See https://ajv.js.org/json-schema.html for more information.
10 | * @param {object} [path] - The path object to the schema definition in a Swagger or OpenAPI document. Not required if the schema is a plain JSON schema.
11 | * @param {string} [path.endpoint] - The endpoint path. Required if the schema is a Swagger or OpenAPI document.
12 | * @param {string} [path.method] - The HTTP method. If not provided, it will use 'GET'.
13 | * @param {integer} [path.status] - The response status code. If not provided, it will use 200.
14 | *
15 | * @returns {Cypress.Chainable} - The response object wrapped in a Cypress.Chainable.
16 | * @throws {Error} - If any of the required parameters are missing or if the schema or schema definition is not found.
17 | *
18 | * @example
19 | * ```js
20 | * cy.validateSchema(schema, {
21 | * endpoint: '/movies',
22 | * method: 'POST'
23 | * })
24 | * ```
25 | *
26 | * You can optionally specify `status`:
27 | *
28 | * @example
29 | * ```js
30 | * cy.validateSchema(schema, {
31 | * endpoint: '/movies',
32 | * method: 'POST',
33 | * status: 201 // Defaults to 200 if not provided
34 | * })
35 | * ```
36 | */
37 | validateSchema(
38 | schema: Record,
39 | path?: {
40 | endpoint: string;
41 | method?: string;
42 | status?: number;
43 | }
44 | ): Chainable;
45 | }
46 | }
47 | }
48 | export {};
49 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | ///
2 |
3 | import hljs from 'highlight.js'
4 | import { validateSchema } from 'core-ajv-schema-validator'
5 |
6 | import './custom-log.js'
7 |
8 |
9 | // ------------------------------------
10 | // MESSAGE ICONS
11 | // ------------------------------------
12 |
13 | const iconPassed = '✔️'
14 | const iconFailed = '❌'
15 | const iconMoreErrors = '➕'
16 |
17 | const issuesStylesDefault = {
18 | iconPropertyError: '⚠️',
19 | colorPropertyError: '#d67e09',
20 | iconPropertyMissing: '❌',
21 | colorPropertyMissing: '#c10000'
22 | }
23 |
24 | const warningDisableSchemaValidation = `⚠️ API SCHEMA VALIDATION DISABLED ⚠️`
25 | const msgDisableSchemaValidation = '- The Cypress environment variable "disableSchemaValidation" has been set to true.'
26 | const errorNoValidApiResponse = 'The element chained to the cy.validateSchema() command is expected to be an API response!'
27 | const errorResponseBodyAgainstSchema = 'The response body is not valid against the schema!'
28 |
29 | // ------------------------------------
30 | // PUBLIC CUSTOM COMMANDS
31 | // ------------------------------------
32 |
33 | /**
34 | * Custom command that validates the response body against the provided schema.
35 | * @public
36 | *
37 | * @param {object} schema - The schema to validate against. Supported formats are plain JSON schema, Swagger, and OpenAPI documents. See https://ajv.js.org/json-schema.html for more information.
38 | * @param {object} [path] - The path object to the schema definition in a Swagger or OpenAPI document. Not required if the schema is a plain JSON schema.
39 | * @param {string} [path.endpoint] - The endpoint path.
40 | * @param {string} [path.method] - The HTTP method. If not provided, it will use 'GET'.
41 | * @param {integer} [path.status] - The response status code. If not provided, it will use 200.
42 | * @param {object} [validationResults.issuesStyles] - An object with the icons and HEX colors used to flag the issues.
43 | * @param {string} [validationResults.issuesStyles.iconPropertyError] - The icon used to flag the property error.
44 | * @param {string} [validationResults.issuesStyles.iconPropertyMissing] - The icon used to flag the missing property.
45 | * @param {string} [validationResults.issuesStyles.colorPropertyError] - The HEX color used to flag the property error.
46 | * @param {string} [validationResults.issuesStyles.colorPropertyMissing] - The HEX color used to flag the missing property.
47 | *
48 | * @returns {Cypress.Chainable} - The response object wrapped in a Cypress.Chainable.
49 | * @throws {Error} - If any of the required parameters are missing or if the schema or schema definition is not found.
50 | *
51 | * @example
52 | * const schema = {
53 | * "swagger": "2.0",
54 | * "paths": {
55 | * "/users": {
56 | * "get": {
57 | * "responses": {
58 | * "200": {
59 | * "schema": { $ref: "#/definitions/User" }
60 | * }
61 | * }
62 | * }
63 | * }
64 | * },
65 | * "definitions": {
66 | * "User": {
67 | * "type": "object",
68 | * "properties": {
69 | * "name": { "type": "string" },
70 | * "age": { "type": "number" }
71 | * }
72 | * }
73 | * }
74 | * }
75 | *
76 | * const path = { endpoint: '/users', method: 'GET', status: '200' };
77 | *
78 | * cy.request('GET', `https://awesome.api.com/users`).validateSchema(schema, path).then(response => {});
79 | */
80 | Cypress.Commands.add("validateSchema",
81 | { prevSubject: true },
82 | (response, schema, path, issuesStyles) => {
83 |
84 | if (Cypress.env('disableSchemaValidation')) {
85 | cy.colorLog(msgDisableSchemaValidation,
86 | '#e0e030',
87 | { displayName: warningDisableSchemaValidation }
88 | )
89 |
90 | console.log(`${warningDisableSchemaValidation} ${msgDisableSchemaValidation}`)
91 | } else {
92 | // Check if it is a valid API Response object
93 | if (response == null || (!response.hasOwnProperty('body') && !response.hasOwnProperty('status') && !response.hasOwnProperty('headers'))) {
94 | console.log(errorNoValidApiResponse)
95 | throw new Error(errorNoValidApiResponse)
96 | }
97 |
98 | const data = response.body
99 |
100 | issuesStyles = { ...issuesStylesDefault, ...issuesStyles }
101 |
102 | // Validate the response body against the schema
103 | const validationResult = validateSchema(data, schema, path, issuesStyles)
104 |
105 | // Log the validation result
106 | _logValidationResult(data, validationResult, issuesStyles)
107 |
108 | // Return the response object so it can be chained with other commands
109 | }
110 | return cy.wrap(response, { log: false })
111 | }
112 | )
113 |
114 |
115 | /**
116 | * Logs the validation result and throws an error if the response body is not valid against the schema, otherwise logs a success message.
117 | * It shows the total number of errors and the first 'maxErrorsToShow' errors (by default 10). If there are more errors, it shows a line with the number of additional errors.
118 | * @private
119 | *
120 | * @param {any} data - The data to be validated.
121 | * @param {object} validationResults - An object containing:
122 | * @param {Array} validationResults.errors - An array of validation errors, or null if the data is valid against the schema.
123 | * @param {object} validationResults.dataMismatches - The original response data with all schema mismatches flagged directly.
124 | * @param {object} validationResults.issuesStyles - An object with the icons and HEX colors used to flag the issues.
125 | * @param {string} validationResults.issuesStyles.iconPropertyError - The icon used to flag the property error.
126 | * @param {string} validationResults.issuesStyles.iconPropertyMissing - The icon used to flag the missing property.
127 | * @param {string} validationResults.issuesStyles.colorPropertyError - The HEX color used to flag the property error.
128 | * @param {string} validationResults.issuesStyles.colorPropertyMissing - The HEX color used to flag the missing property.
129 | * @param {integer} [maxErrorsToShow=10] - The maximum number of errors to show in the log.
130 | *
131 | * @throws {Error} - If the response body is not valid against the schema.
132 | */
133 | const _logValidationResult = (data, validationResults, issuesStyles, maxErrorsToShow = 10) => {
134 |
135 | let { errors, dataMismatches } = validationResults
136 |
137 | if (!errors) {
138 | // PASSED
139 |
140 | // Show in Cypress Log an message saying that the schema validation passed
141 | cy.colorLog(`**THE RESPONSE BODY IS VALID AGAINST THE SCHEMA.**`,
142 | '#66d966',
143 | { displayName: `${iconPassed} PASSED -` }
144 | )
145 | } else {
146 | // FAILED
147 | let cy_api_type
148 |
149 | let $original, $cloned, $elem
150 | const enableMismatchesOnUI = mustEnableMismatchesOnUI()
151 |
152 | if (enableMismatchesOnUI) {
153 | $original = Cypress.$('[id="api-plugin-root"] [id="api-view"]')
154 | if ($original.length !== 0) {
155 | cy_api_type = "filip"
156 | // Create clone of the DOM tree
157 | $cloned = $original.clone()
158 | // Find the last section in the clone to add the mismatches
159 | $elem = $cloned.find('section:last-of-type [data-cy="responseBody"] code > details > summary')
160 | } else {
161 | $original = Cypress.$('.cy-api-response:last-of-type pre')
162 | if ($original.length !== 0) {
163 | cy_api_type = "gleb"
164 | }
165 | }
166 | }
167 |
168 | const { iconPropertyError, colorPropertyError, iconPropertyMissing, colorPropertyMissing } = issuesStyles
169 |
170 | if (cy_api_type === "filip") {
171 | // Filip's API View needs it's own processing to show the mismatches (similar logic as for package core-ajv-schema-validator)
172 |
173 | errors.forEach(error => {
174 | let instancePathArray = error.instancePath.replace(/^\//, '').split('/') // Remove the first '/' from the instance path "/0/name" => "0/name"
175 | let instancePath = instancePathArray.join('.')
176 |
177 | let errorDescription
178 | let value = Cypress._.get(data, instancePath)
179 |
180 | if (error.keyword === 'required') {
181 | const missingProperty = error.params.missingProperty
182 | instancePath = (instancePath === "") ? missingProperty : `${instancePath}.${missingProperty}`
183 |
184 | errorDescription = `${iconPropertyMissing} Missing property '${missingProperty}'`
185 | } else {
186 | const message = error.message
187 | errorDescription = `${iconPropertyError} ${String(JSON.stringify(value)).replaceAll("\"", "'")} ${message}` // We also use String() to handle the case of undefined values
188 | }
189 |
190 | if (enableMismatchesOnUI && $elem && $elem.length) {
191 | // Show in the API View the data with the mismatches
192 | showDataMismatchesApiViewFilip($elem, instancePathArray, errorDescription, error, issuesStyles, 0)
193 | }
194 | })
195 | }
196 |
197 | if (enableMismatchesOnUI) {
198 | // Replace the original DOM tree with the cloned one with the mismatches
199 | if (cy_api_type === "filip") {
200 | $original.replaceWith($cloned)
201 | } else if (cy_api_type === "gleb") {
202 | $original.replaceWith(Cypress.$(transformDataToHtmlGleb(dataMismatches, issuesStyles)))
203 | }
204 | }
205 |
206 | // Show in Cypress Log an error message saying that the schema validation failed and total number of errors
207 | // On click, it will show in the console:
208 | // - Total number of errors
209 | // - Full list of errors as provided by AJV
210 | // - User friendly representation of the mismatches in the data ❤️
211 | cy.colorLog(`**THE RESPONSE BODY IS NOT VALID AGAINST THE SCHEMA (Number of schema errors: ${errors.length}).**`,
212 | '#e34040',
213 | { displayName: `${iconFailed} FAILED -`, info: { number_of_schema_errors: errors.length, ajv_errors: errors, data_mismatches: dataMismatches } }
214 | )
215 |
216 | // Logic to create two group of errors: the first 'maxErrorsToShow' and the rest of errors (to avoid showing a huge amount of errors in the Cypress Log)
217 | // Note that if the total number of errors is 'maxErrorsToShow'+1 it will show all the errors since there will anyway one more line
218 | let errorsToShow, rest_of_errors
219 |
220 | if (errors.length > maxErrorsToShow + 1) {
221 | errorsToShow = errors.slice(0, maxErrorsToShow)
222 | rest_of_errors = errors.slice(maxErrorsToShow)
223 | } else {
224 | errorsToShow = errors
225 | }
226 |
227 | // Show in Cypress Log the first 'maxErrorsToShow' as provided by AJV
228 | errorsToShow.forEach(error => {
229 | const iconError = (error.keyword) === 'required' ? iconPropertyMissing : iconPropertyError
230 | const colorError = (error.keyword) === 'required' ? colorPropertyMissing : colorPropertyError
231 |
232 | cy.colorLog(`${JSON.stringify(error, "", 1)}`,
233 | colorError,
234 | { displayName: iconError, info: { schema_error: error } }
235 | )
236 | })
237 |
238 | // Show in Cypress Log the rest of errors if there are more than 'maxErrorsToShow' as provided by AJV
239 | if (rest_of_errors) {
240 | cy.colorLog(`...and ${errors.length - maxErrorsToShow} more errors.`,
241 | colorPropertyMissing,
242 | { displayName: iconMoreErrors, info: { rest_of_errors } }
243 | )
244 | }
245 |
246 | // Throw an error to fail the test
247 | cy.then(() => {
248 | console.log(errorResponseBodyAgainstSchema)
249 | throw new Error(errorResponseBodyAgainstSchema)
250 | })
251 | }
252 | }
253 |
254 |
255 |
256 | /**
257 | * Transforms a JSON object into an HTML string with syntax highlighting and custom styles for specific properties.
258 | *
259 | * @param {Object} jsonObject - The JSON object to be transformed into HTML.
260 | * @param {Object} issuesStyles - An object with the icons and HEX colors used to flag the issues. Constains: iconPropertyError, colorPropertyError, iconPropertyMissing, colorPropertyMissing.
261 | *
262 | * @returns {string} - An HTML string with syntax-highlighted JSON and custom styles applied.
263 | */
264 | const transformDataToHtmlGleb = (jsonObject, issuesStyles) => {
265 | const { iconPropertyError, colorPropertyError, iconPropertyMissing, colorPropertyMissing } = issuesStyles
266 |
267 | const fontStyles = `font-weight: bold; font-size: 1.3em;`
268 | let jsonString = JSON.stringify(jsonObject, null, 4)
269 |
270 | let json = hljs.highlight(jsonString, {
271 | language: 'json',
272 | }).value
273 |
274 | const regexpError = RegExp(`>"${iconPropertyError}`, 'g')
275 | json = json.replaceAll(regexpError, (match) => {
276 | return ` style="${fontStyles} color: ${colorPropertyError};"${match}`
277 | });
278 |
279 | const regexpMissing = RegExp(`>"${iconPropertyMissing}`, 'g')
280 | json = json.replaceAll(regexpMissing, (match) => {
281 | return ` style="${fontStyles}; color: ${colorPropertyMissing};"${match}`
282 | });
283 |
284 | return `${json}
`
285 | };
286 |
287 |
288 | /**
289 | * Recursively traverses and displays data mismatches in an API view, highlighting errors in arrays, objects, or properties.
290 | *
291 | * @param {JQuery} $content - The current DOM element being processed.
292 | * @param {string[]} instancePathArray - An array representing the path to the current data point in the JSON structure.
293 | * @param {string} errorDescription - A description of the error to display.
294 | * @param {Object} error - The error object containing details about the validation error.
295 | * @param {Object} issuesStyles - An object with the icons and HEX colors used to flag the issues.. Constains: iconPropertyError, colorPropertyError, iconPropertyMissing, colorPropertyMissing.
296 | * @param {number} depth - The current depth of recursion, used for indentation and styling.
297 | */
298 | const showDataMismatchesApiViewFilip = ($content, instancePathArray, errorDescription, error, issuesStyles, depth) => {
299 | const { colorPropertyError, iconPropertyError, colorPropertyMissing } = issuesStyles
300 |
301 | const fontStyles = `font-weight: bold; font-size: 1.3em;`
302 | let path0 = instancePathArray.shift()
303 |
304 | if ($content.hasClass('bracket')) {
305 | // It's an Array
306 | const $elem = $content.siblings(`details`).eq(parseInt(path0))
307 |
308 | if ($elem.length === 0) {
309 | Cypress.$(`${iconPropertyError} Array ${error.message} `).insertAfter($content.parent().next())
310 | } else {
311 | showDataMismatchesApiViewFilip($elem.children('summary'), instancePathArray, errorDescription, error, issuesStyles, depth + 1)
312 | }
313 | }
314 | else if ($content.hasClass('brace')) {
315 | // It's an Object
316 | const $elem = $content.siblings(`.token.property:contains(\"${path0}\")`).filter((i, e) => { // For exact match
317 | return Cypress.$(e).text() === `"${path0}"`
318 | })
319 |
320 | if ($elem.length === 0) {
321 | // Missing property
322 | Cypress.$(`
"${error.params.missingProperty}": ${errorDescription} `).insertAfter($content)
323 | } else {
324 | let $value = $elem.next().next()
325 | if ($value.is('details')) {
326 | $value = $value.children('summary')
327 | }
328 |
329 | showDataMismatchesApiViewFilip($value, instancePathArray, errorDescription, error, issuesStyles, depth + 1)
330 | }
331 | } else {
332 | // Error in a property
333 | Cypress.$(`${errorDescription} `).insertAfter($content)
334 | }
335 | }
336 |
337 | /**
338 | * Determines whether mismatches should be enabled on the UI.
339 | * This is based on the Cypress configuration and environment variables.
340 | *
341 | * @returns {boolean} - Returns `true` if the Cypress environment is interactive
342 | * and the `enableMismatchesOnUI` environment variable is set; otherwise, `false`.
343 | */
344 | const mustEnableMismatchesOnUI = () => {
345 | return Cypress.config('isInteractive') && Cypress.env('enableMismatchesOnUI')
346 | }
347 |
--------------------------------------------------------------------------------
/videos/README.md:
--------------------------------------------------------------------------------
1 | # Cypress-ajv-schema-validator Videos
2 |
3 | ## Integration with bahmutov/cy-api Plugin
4 |
5 | https://github.com/user-attachments/assets/8d94c347-17b8-497d-a000-728d6f420c8f
6 |
7 |
--------------------------------------------------------------------------------
/videos/overview.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sclavijosuero/cypress-ajv-schema-validator/df9a3b3a2d82ef1351a813832978a44fff347dc0/videos/overview.gif
--------------------------------------------------------------------------------
/videos/overview.mp4:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sclavijosuero/cypress-ajv-schema-validator/df9a3b3a2d82ef1351a813832978a44fff347dc0/videos/overview.mp4
--------------------------------------------------------------------------------