Код: Выделить всё
com.intuit.karate
karate-core
1.4.1
com.intuit.karate
karate-junit5
1.4.1
test
org.json
json
20231013
net.masterthought
cucumber-reporting
5.7.4
com.atlassian.oai
swagger-request-validator-core
2.38.0
io.swagger.core.v3
swagger-models
2.2.21
io.swagger.core.v3
swagger-annotations
2.2.21
io.swagger.core.v3
swagger-core
2.2.21
com.fasterxml.jackson.core
jackson-annotations
2.15.4
com.fasterxml.jackson.core
jackson-databind
2.15.4
com.fasterxml.jackson.core
jackson-core
2.15.4
io.swagger.parser.v3
swagger-parser
2.1.19
com.github.java-json-tools
json-schema-validator
2.2.12
Код: Выделить всё
Utilities.javaКод: Выделить всё
import static com.atlassian.oai.validator.schema.SchemaValidator.ADDITIONAL_PROPERTIES_KEY;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import com.atlassian.oai.validator.report.LevelResolver;
import com.atlassian.oai.validator.report.MessageResolver;
import com.atlassian.oai.validator.report.ValidationReport;
import com.atlassian.oai.validator.report.ValidationReport.Message;
import com.atlassian.oai.validator.schema.SchemaValidator;
import io.swagger.parser.OpenAPIParser;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.parser.core.models.SwaggerParseResult;
public class Utilitties {
public static boolean validation(String response, String Name, String swagPath, String errorPath) {
try {
boolean result = false;
SwaggerParseResult parseResult = new OpenAPIParser().readLocation(swagPath, null, null);
System.out.println("parseResult" + parseResult);
OpenAPI openAPI = parseResult.getOpenAPI();
if (openAPI == null) {
System.err.println("Failed to load OpenAPI specification from " + swagPath);
return false;
}
final SchemaValidator validator = new SchemaValidator(openAPI, new MessageResolver(LevelResolver.create()
.withLevel(ADDITIONAL_PROPERTIES_KEY, ValidationReport.Level.IGNORE).build()));
Schema schema = new Schema();
schema.set$schema(Name);
ValidationReport rep = validator.validate(response, schema, null);
FileWriter file;
File f = new File(errorPath);
String newLine = System.getProperty("line.seperator");
if (f.exists() && !f.isDirectory()) {
f.delete();
}
file = new FileWriter(errorPath);
if (rep.hasErrors()) {
for (Message msg : rep.getMessages()) {
file.write(msg.toString() + newLine);
}
file.close();
} else {
result = true;
}
// System.out.println("openAPI" +openAPI);
return result;
} catch (IOException e) {
return false;
} catch (Exception e) {
return false;
}
}
public static void main(String[] args) {
String swagPath = "C:\\Users\\abc\\Documents\\Workspace\\org\\src\\test\\java\\orgJava\\swagger.yaml";
String errorPath = "C:\\Users\\abc\\Documents\\Workspace\\org\\src\\test\\java\\orgJava\\error.txt";
String response = "{\r\n" + " \"id\": \"54321\",\r\n" + " \"name\": \"Emily Johnson\",\r\n"
+ " \"email\": \"emily.johnson@example.com\",\r\n" + " \"age\": 28\r\n" + "}";
String Name = "#/definitions/User";
boolean abc = validation(response, Name, swagPath, errorPath);
System.out.println("abc" + abc);
}
}
Код: Выделить всё
Swagger.yamlКод: Выделить всё
---
swagger: '2.0'
info:
version: 1.0.0
title: Sample API
description: A simple API for managing users
basePath: /api/v1
schemes:
- http
paths:
/users:
get:
summary: Retrieve a list of users
description: Returns a list of users from the system
produces:
- application/json
responses:
'200':
description: A list of users
schema:
type: array
items:
$ref: '#/definitions/User'
post:
summary: Create a new user
description: Adds a new user to the system
consumes:
- application/json
parameters:
- in: body
name: user
description: The user to be created
required: true
schema:
$ref: '#/definitions/User'
responses:
'201':
description: User created
schema:
$ref: '#/definitions/User'
'400':
description: Invalid input
/users/{userId}:
get:
summary: Retrieve a specific user
description: Returns a single user by ID
parameters:
- in: path
name: userId
description: ID of the user to retrieve
required: true
type: string
produces:
- application/json
responses:
'200':
description: A user object
schema:
$ref: '#/definitions/User'
'404':
description: User not found
put:
summary: Update a specific user
description: Updates the details of an existing user
parameters:
- in: path
name: userId
description: ID of the user to update
required: true
type: string
- in: body
name: user
description: The updated user details
required: true
schema:
$ref: '#/definitions/User'
responses:
'200':
description: User updated
schema:
$ref: '#/definitions/User'
'400':
description: Invalid input
'404':
description: User not found
delete:
summary: Delete a specific user
description: Deletes a user from the system
parameters:
- in: path
name: userId
description: ID of the user to delete
required: true
type: string
responses:
'204':
description: User deleted
'404':
description: User not found
definitions:
User:
type: object
required:
- id
- name
properties:
id:
type: string
example: '12345'
name:
type: string
example: 'John Doe'
email:
type: string
example: 'john.doe@example.com'
age:
type: integer
example: 30
Этот код работает, когда мы использовали версию swagger-request-validator-core как 1.5.1, которая более старая версия, но когда мы обновляем нашу версию до 2.38.0 или последней, некоторые изменения были внесены с точки зрения кода. Я думаю, это вызывает проблемы компиляции в методе проверки, когда мы передаем строку и модель как входные данные, поэтому в соответствии с требованиями мы изменили код и передали значения String, Schema и String в метод проверки.
Но все же почему-то код не работает, как у меня есть 4 сценария, где код должен вернуть false.
- если вы передадите правильный ответ и неправильное определение имя, которого нет в файле swagger.yaml
- если вы передаете неверный ответ или какой-либо несовпадающий ответ с файлом swagger.yaml, соответствующим определению, который вы передали.
- если вы передадите оба ввода как неправильные.
- Если вы передадите неправильный swagger Путь к файлу.
Однако код не работает, даже если мы передаем неправильные значения, а также возвращает true.
Я попытался внести соответствующие изменения в код, чтобы исправить эту проблему. Каким-то образом ничего не получилось.
Можете ли вы помочь мне решить эту проблему?
Спасибо.
Подробнее здесь: https://stackoverflow.com/questions/788 ... how-to-fix
Мобильная версия