Java Code Examples for io.swagger.v3.parser.OpenAPIV3Parser#readContents()

The following examples show how to use io.swagger.v3.parser.OpenAPIV3Parser#readContents() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 7 votes vote down vote up
/**
 * Remove x-examples from all the paths from the OpenAPI definition.
 *
 * @param apiDefinition OpenAPI definition as String
 */
public static String removeExamplesFromOpenAPI(String apiDefinition) throws APIManagementException {
    try {
        OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();
        SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(apiDefinition, null, null);
        if (CollectionUtils.isNotEmpty(parseAttemptForV3.getMessages())) {
            log.debug("Errors found when parsing OAS definition");
        }
        OpenAPI openAPI = parseAttemptForV3.getOpenAPI();
        for (Map.Entry<String, PathItem> entry : openAPI.getPaths().entrySet()) {
            String path = entry.getKey();
            List<Operation> operations = openAPI.getPaths().get(path).readOperations();
            for (Operation operation : operations) {
                if (operation.getExtensions() != null && operation.getExtensions().keySet()
                        .contains(APIConstants.SWAGGER_X_EXAMPLES)) {
                    operation.getExtensions().remove(APIConstants.SWAGGER_X_EXAMPLES);
                }
            }
        }
        return Yaml.pretty().writeValueAsString(openAPI);
    } catch (JsonProcessingException e) {
        throw new APIManagementException("Error while removing examples from OpenAPI definition", e,
                ExceptionCodes.ERROR_REMOVING_EXAMPLES);
    }
}
 
Example 2
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testLicense () {
    String yaml = "openapi: 3.0.0\n" +
            "servers: []\n" +
            "info:\n" +
            "  license:\n" +
            "    invalid: true\n" +
            "    x-valid:\n" +
            "      isValid: true\n" +
            "  version: ''\n";

    OpenAPIV3Parser parser = new OpenAPIV3Parser();

    SwaggerParseResult result = parser.readContents(yaml,null,null);
    List<String> messageList = result.getMessages();
    Set<String> messages = new HashSet<>(messageList);
    assertTrue(messages.contains("attribute info.license.invalid is unexpected"));
    assertTrue(messages.contains("attribute info.title is missing"));
    assertTrue(messages.contains("attribute paths is missing"));

    assertEquals(((Map)result.getOpenAPI().getInfo().getLicense().getExtensions().get("x-valid")).get("isValid"), true);
}
 
Example 3
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidatorIssue50() {
    String yaml = "openapi: 3.0.0\n" +
            "servers:\n" +
            "  - url: 'http://local.xxx.com/'\n" +
            "info:\n" +
            "  version: 2.0.0\n" +
            "  title: Beanhunter API\n" +
            "  description: Description of the api goes here.\n" +
            "paths:\n" +
            "  /city:\n" +
            "    get:\n" +
            "      description: test description\n" +
            "components:\n" +
            "  schemas:\n" +
            "    Endpoints:\n" +
            "      title: Endpoints object\n" +
            "      properties:\n" +
            "        links: {}";

    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    SwaggerParseResult result = parser.readContents(yaml, null, null);
    assertTrue(result.getMessages().size() == 1);
}
 
Example 4
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssue360() {
    OpenAPI openAPI = new OpenAPI();

    Schema model = new Schema();
    model.setEnum((List<String>) null);
    openAPI.components(new Components().addSchemas("modelWithNullEnum", model));

    String json = Json.pretty(openAPI);

    OpenAPIV3Parser parser = new OpenAPIV3Parser();

    SwaggerParseResult result = parser.readContents(json, null, null);
    OpenAPI rebuilt = result.getOpenAPI();
    assertNotNull(rebuilt);
}
 
Example 5
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testSecurityDeserialization() throws Exception {
    String yaml = "openapi: 3.0.0\n" +
            "security:\n" +
            "  - api_key1: []\n" +
            "    api_key2: []\n" +
            "  - api_key3: []\n";

    OpenAPIV3Parser parser = new OpenAPIV3Parser();

    SwaggerParseResult result = parser.readContents(yaml, null, null);
    OpenAPI openAPI = result.getOpenAPI();
    assertNotNull(openAPI);

    List<SecurityRequirement> security = openAPI.getSecurity();
    assertTrue(security.size() == 2);

}
 
Example 6
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeserializeWithMessages() {
    String yaml = "openapi: '3.0.0'\n" +
            "info:\n" +
            "  version: 0.0.0\n" +
            "  title:\n" +
            "    - bar";
    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    SwaggerParseResult result = parser.readContents(yaml,null, null);

    Set<String> messages = new HashSet<>(result.getMessages());
    assertTrue(messages.size() == 2);

    assertTrue(messages.contains("attribute info.title is not of type `string`"));
    assertTrue(messages.contains("attribute paths is missing"));
}
 
Example 7
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testIssue() {
    String yaml =
            "openapi: 3.0.0\n" +
                    "servers: []\n" +
                    "info:\n" +
                    "  description: No description provided.\n" +
                    "  version: '2.0'\n" +
                    "  title: My web service\n" +
                    "  x-endpoint-name: default\n" +
                    "paths:\n" +
                    "  x-nothing: sorry not supported\n" +
                    "  /foo:\n" +
                    "    x-something: 'yes, it is supported'\n" +
                    "    get:\n" +
                    "      responses:\n" +
                    "        '200':\n" +
                    "          description: OpenAPI API document for this service\n" +
                    "x-some-vendor:\n" +
                    "  sometesting: bye!";
    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    SwaggerParseResult result = parser.readContents(yaml,null,null);

    OpenAPI openAPI = result.getOpenAPI();

    assertEquals(((Map) openAPI.getExtensions().get("x-some-vendor")).get("sometesting"), "bye!");
    assertEquals(openAPI.getPaths().get("/foo").getExtensions().get("x-something"), "yes, it is supported");
}
 
Example 8
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testSchemaExample(@Injectable List<AuthorizationValue> auths){
    String yaml = "openapi: '3.0.1'\n" +
            "components:\n" +
            "  schemas:\n"+
            "    Address:\n" +
            "      required:\n" +
            "      - street\n" +
            "      type: object\n" +
            "      x-swagger-router-model: io.swagger.oas.test.models.Address\n" +
            "      properties:\n" +
            "        street:\n" +
            "          type: string\n" +
            "          example: 12345 El Monte Road\n" +
            "        city:\n" +
            "          type: string\n" +
            "          example: Los Altos Hills\n" +
            "        state:\n" +
            "          type: string\n" +
            "          example: CA\n" +
            "        zip:\n" +
            "          type: string\n" +
            "          example: '94022'";

    OpenAPIV3Parser parser = new OpenAPIV3Parser();

    ParseOptions options = new ParseOptions();
    options.setResolve(true);

    SwaggerParseResult result = parser.readContents(yaml,auths,options);
    OpenAPI openAPI = result.getOpenAPI();
    Schema stateSchemaProperty = (Schema)openAPI.getComponents().getSchemas().get("Address").getProperties().get("state");

    Assert.assertNotNull(stateSchemaProperty.getExample());
    Assert.assertEquals(stateSchemaProperty.getExample(),"CA" );
}
 
Example 9
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testCodegenIssue4555() throws Exception {
    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    String yaml = "openapi: 3.0.0\n" +
            "info:\n" +
            "  title: test\n" +
            "  version: \"0.0.1\"\n" +
            "\n" +
            "paths:\n" +
            "  '/contents/{id}':\n" +
            "    parameters:\n" +
            "      - name: id\n" +
            "        in: path\n" +
            "        description: test\n" +
            "        required: true\n" +
            "        schema:\n" +
            "          type: integer\n" +
            "  get:\n" +
            "    description: test\n" +
            "    responses:\n" +
            "      '200':\n" +
            "        description: OK\n" +
            "        schema: null\n" +
            "        $ref: '#/components/schemas/Content'\n" +
            "components:\n" +
            "  schemas:\n" +
            "    Content:\n" +
            "      type: object\n" +
            "      title: \t\ttest";

    final SwaggerParseResult result = parser.readContents(yaml,null,null);

    // can't parse with tabs!
    assertNull(result.getOpenAPI());
}
 
Example 10
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testEmpty() {
    String json = "{}";

    OpenAPIV3Parser parser = new OpenAPIV3Parser();

    SwaggerParseResult result = parser.readContents(json, null, null);
    List<String> messageList = result.getMessages();
    Set<String> messages = new HashSet<>(messageList);

    assertTrue(messages.contains("attribute openapi is missing"));
}
 
Example 11
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testAdditionalPropertiesBoolean() {
    String yaml =
        "openapi: 3.0.0\n" +
        "info:\n" +
        "  title: Test\n" +
        "  version: 1.0.0\n" +
        "paths:\n" +
        "  \"/store/inventory\":\n" +
        "    post:\n" +
        "      requestBody:\n" +
        "        content:\n" +
        "          application/json:\n" +
        "            schema:\n" +
        "              additionalProperties: true\n" +
        "      responses:\n" +
        "        '200':\n" +
        "          description: successful operation\n" +
        "          content:\n" +
        "            application/json:\n" +
        "              schema:\n" +
        "                additionalProperties: false\n";

    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    SwaggerParseResult result = parser.readContents(yaml, null, null);
    assertEquals(result.getMessages(), emptyList());
    
    OpenAPI openAPI = result.getOpenAPI();

    Schema body = openAPI.getPaths().get("/store/inventory").getPost().getRequestBody().getContent().get("application/json").getSchema();
    assertEquals(body.getAdditionalProperties(), Boolean.TRUE);
    assertEquals(body.getClass(), MapSchema.class);

    Schema response = openAPI.getPaths().get("/store/inventory").getPost().getResponses().get("200").getContent().get("application/json").getSchema();
    assertEquals(response.getAdditionalProperties(), Boolean.FALSE);
    assertEquals(response.getClass(), ObjectSchema.class);
}
 
Example 12
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeserializeWithBooleanEnumDiscriminator() {
    String yaml =
            "openapi: 3.0.0\n" +
                    "components:\n" +
                    "  schemas:\n" +
                    "    Animal:\n" +
                    "      type: object\n" +
                    "      discriminator:\n" +
                    "        propertyName: petType\n" +
                    "      description: |\n" +
                    "        A basic `Animal` object which can extend to other animal types.\n" +
                    "      required:\n" +
                    "        - commonName\n" +
                    "        - petType\n" +
                    "      properties:\n" +
                    "        commonName:\n" +
                    "          description: the household name of the animal\n" +
                    "          type: string\n" +
                    "        petType:\n" +
                    "          enum:\n" +
                    "            - true\n" +
                    "            - false";
    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    SwaggerParseResult result = parser.readContents(yaml, null, null);
    Map<String, Schema> properties = result.getOpenAPI().getComponents().getSchemas().get("Animal").getProperties();
    assertTrue(properties.containsKey("commonName"));
    assertTrue(properties.containsKey("petType"));
    assertEquals(properties.get("petType").getType(), "boolean");
}
 
Example 13
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override
public String getOASDefinitionWithTierContentAwareProperty(String oasDefinition, List<String> contentAwareTiersList,
        String apiLevelTier) throws APIManagementException {
    OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();
    SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(oasDefinition, null, null);
    if (CollectionUtils.isNotEmpty(parseAttemptForV3.getMessages())) {
        log.debug("Errors found when parsing OAS definition");
    }
    OpenAPI swagger = parseAttemptForV3.getOpenAPI();
    // check if API Level tier is content aware. if so, we set a extension as a global property
    if (contentAwareTiersList.contains(apiLevelTier)) {
        swagger.addExtension(APIConstants.SWAGGER_X_THROTTLING_BANDWIDTH, true);
        // no need to check resource levels since both cannot exist at the same time.
        log.debug("API Level policy is content aware..");
        return Json.pretty(swagger);
    }
    // if api level tier exists, skip checking for resource level tiers since both cannot exist at the same time.
    if (apiLevelTier != null) {
        log.debug("API Level policy is not content aware..");
        return oasDefinition;
    } else {
        log.debug("API Level policy does not exist. Checking for resource level");
        for (Map.Entry<String, PathItem> entry : swagger.getPaths().entrySet()) {
            String path = entry.getKey();
            List<Operation> operations = swagger.getPaths().get(path).readOperations();
            for (Operation op : operations) {
                if (contentAwareTiersList
                        .contains(op.getExtensions().get(APIConstants.SWAGGER_X_THROTTLING_TIER))) {
                    if (log.isDebugEnabled()) {
                        log.debug(
                                "API resource Level policy is content aware for operation " + op.getOperationId());
                    }
                    op.addExtension(APIConstants.SWAGGER_X_THROTTLING_BANDWIDTH, true);
                }
            }
        }
        return Json.pretty(swagger);
    }
}
 
Example 14
Source File: SyntaxChecker.java    From servicecomb-toolkit with Apache License 2.0 5 votes vote down vote up
public static List<String> check(String oasSpecContent) {

    ParseOptions parseOptions = new ParseOptions();
    parseOptions.setResolve(false);
    parseOptions.setResolveFully(false);
    parseOptions.setResolveCombinators(false);
    parseOptions.setFlatten(false);

    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    SwaggerParseResult result = parser.readContents(oasSpecContent, null, parseOptions);
    return result.getMessages() == null ? emptyList() : result.getMessages();

  }
 
Example 15
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@Test
public void testOneOfSchema(@Injectable List<AuthorizationValue> auths){
    String yaml = "openapi: '3.0'\n" +
        "components:\n" +
        "  schemas:\n" +
        "    Cat:\n" +
        "      type: object\n" +
        "      # all properties specific to a `Cat`\n" +
        "      properties:\n" +
        "        purring:\n" +
        "          type: string\n" +
        "    Dog:\n" +
        "      type: object\n" +
        "      # all properties specific to a `Dog`\n" +
        "      properties:\n" +
        "        bark:\n" +
        "          type: string\n" +
        "    Pet:\n" +
        "      oneOf: \n" +
        "       - $ref: '#/components/schemas/Cat'\n" +      
        "       - $ref: '#/components/schemas/Dog'\n" +
        "       - type: object\n" +
        "         # neither a `Cat` nor a `Dog`\n" +
        "         properties:\n" +
        "           name:\n" +
        "             type: string\n" ;
  
    OpenAPIV3Parser parser = new OpenAPIV3Parser();
  
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
  
    SwaggerParseResult result = parser.readContents(yaml,auths,options);
    List<String> messageList = result.getMessages();
    Set<String> messages = new HashSet<>(messageList);
  
    Schema petSchema = result.getOpenAPI().getComponents().getSchemas().get("Pet");
    assertTrue(petSchema != null);
    assertTrue(petSchema instanceof ComposedSchema);
    
    ComposedSchema petCompSchema = (ComposedSchema) petSchema;
    List<Schema> oneOfSchemas = petCompSchema.getOneOf();
    assertTrue(oneOfSchemas != null);
    assertEquals(oneOfSchemas.size(), 3);
    
    Schema refCatSchema = oneOfSchemas.get(0);
    assertTrue(refCatSchema != null);
    assertEquals(refCatSchema.get$ref(), "#/components/schemas/Cat");
  
    Schema refDogSchema = oneOfSchemas.get(1);
    assertTrue(refDogSchema != null);
    assertEquals(refDogSchema.get$ref(), "#/components/schemas/Dog");
    
    Schema otherSchema = oneOfSchemas.get(2);
    assertTrue(otherSchema != null);
    Schema nameProp = (Schema) otherSchema.getProperties().get("name");
    assertTrue(nameProp != null);
    assertEquals(nameProp.getType(), "string");
    
}
 
Example 16
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@Test
public void testSettingsAddParametersToEachOperationDisabled() {
    String yaml ="openapi: 3.0.0\n" +
            "servers: []\n" +
            "info:\n" +
            "  title: test spec\n" +
            "  version: '1.0'\n" +
            "paths:\n" +
            "  '/test/{id}':\n" +
            "    parameters:\n" +
            "      - name: id\n" +
            "        in: path\n" +
            "        required: true\n" +
            "        schema:\n" +
            "          type: string\n" +
            "    get:\n" +
            "      description: test get\n" +
            "      parameters:\n" +
            "        - name: page\n" +
            "          in: query\n" +
            "          schema:\n" +
            "            type: string\n" +
            "      responses:\n" +
            "        default:\n" +
            "          description: test response";

    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    SwaggerParseResult result = parser.readContents(yaml,null,null);

    OpenAPI swagger = result.getOpenAPI();

    final OpenAPI resolved = new OpenAPIResolver(swagger, null, null,
            new OpenAPIResolver.Settings().addParametersToEachOperation(false))
            .resolve();


    assertEquals(resolved.getPaths().get("/test/{id}").getParameters().size(), 1);
    PathParameter pp = (PathParameter)resolved.getPaths().get("/test/{id}").getParameters().get(0);
    assertEquals(pp.getName(), "id");

    assertEquals(resolved.getPaths().get("/test/{id}").getGet().getParameters().size(), 1);
    QueryParameter qp = (QueryParameter)resolved.getPaths().get("/test/{id}").getGet().getParameters().get(0);
    assertEquals(qp.getName(), "page");
}
 
Example 17
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@Test
public void testIssue343Parameter() {
    String yaml =
            "openapi: 3.0.0\n" +
                    "servers: []\n" +
                    "info:\n" +
                    "  description: bleh\n" +
                    "  version: 2.0.0\n" +
                    "  title: Test\n" +
                    "paths:\n" +
                    "  /foo:\n" +
                    "    post:\n" +
                    "      parameters:\n" +
                    "        - in: query\n" +
                    "          name: skip\n" +
                    "          schema:\n" +
                    "            type: integer\n" +
                    "            format: int32\n" +
                    "            multipleOf: 3\n" +
                    "      responses:\n" +
                    "        '200':\n" +
                    "          description: OK\n" +
                    "      requestBody:\n" +
                    "        content:\n" +
                    "          application/json:\n" +
                    "            schema:\n" +
                    "              type: object\n" +
                    "              additionalProperties:\n" +
                    "                type: string\n" +
                    "        required: true\n" +
                    "components:\n" +
                    "  schemas:\n" +
                    "    Fun:\n" +
                    "      properties:\n" +
                    "        id:\n" +
                    "          type: integer\n" +
                    "          format: int32\n" +
                    "          multipleOf: 5\n" +
                    "        mySet:\n" +
                    "          type: array\n" +
                    "          uniqueItems: true\n" +
                    "          items:\n" +
                    "            type: string";

    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    SwaggerParseResult result = parser.readContents(yaml, null, null);
    OpenAPI openAPI = result.getOpenAPI();

    QueryParameter qp = (QueryParameter)openAPI.getPaths().get("/foo").getPost().getParameters().get(0);
    assertEquals(new BigDecimal("3"), qp.getSchema().getMultipleOf());

    RequestBody bp =  openAPI.getPaths().get("/foo").getPost().getRequestBody();
    Schema schema = bp.getContent().get("application/json").getSchema();
    assertTrue(schema.getAdditionalProperties() != null);

    IntegerSchema id = (IntegerSchema)openAPI.getComponents().getSchemas().get("Fun").getProperties().get("id");
    assertEquals(id.getMultipleOf(), new BigDecimal("5"));

    ArraySchema ap = (ArraySchema)openAPI.getComponents().getSchemas().get("Fun").getProperties().get("mySet");
    assertTrue(ap.getUniqueItems());
}
 
Example 18
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@Test
public void testNestedDefinitions() {
    String yaml = "openapi: 3.0.0\n" +
            "servers: []\n" +
            "info:\n" +
            "  version: ''\n" +
            "  title: ''\n" +
            "paths: {}\n" +
            "components:\n" +
            "  schemas:\n" +
            "    Person:\n" +
            "      required:\n" +
            "        - id\n" +
            "        - name\n" +
            "      properties:\n" +
            "        id:\n" +
            "          type: integer\n" +
            "          format: int64\n" +
            "        name:\n" +
            "          type: string\n" +
            "        address:\n" +
            "          $ref: '#/components/schemas/Address'\n" +
            "    Address:\n" +
            "      required:\n" +
            "        - zip\n" +
            "      properties:\n" +
            "        street:\n" +
            "          type: string\n" +
            "        zip:\n" +
            "          type: integer\n" +
            "          format: int32\n" +
            "          minimum: 0\n" +
            "          exclusiveMinimum: true\n" +
            "          maximum: 99999\n" +
            "          exclusiveMaximum: true";

    OpenAPIV3Parser parser = new OpenAPIV3Parser();

    SwaggerParseResult result = parser.readContents(yaml, null, null);


    assertTrue(result.getOpenAPI().getComponents().getSchemas().get("Person") instanceof Schema);
    assertTrue(result.getOpenAPI().getComponents().getSchemas().get("Address") instanceof Schema);

    Schema person =  result.getOpenAPI().getComponents().getSchemas().get("Person");
    Schema property = (Schema) person.getProperties().get("address");
    assertTrue(property.get$ref() !=  null);

    Schema zip = (Schema)(result.getOpenAPI().getComponents().getSchemas().get("Address")).getProperties().get("zip");
    assertTrue(zip instanceof IntegerSchema);

    IntegerSchema zipProperty = (IntegerSchema) zip;
    assertEquals(zipProperty.getMinimum(), new BigDecimal("0"));
    assertTrue(zipProperty.getExclusiveMinimum());

    assertEquals(zipProperty.getMaximum(), new BigDecimal("99999"));
    assertTrue(zipProperty.getExclusiveMaximum());
}
 
Example 19
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@Test
public void testPaths() {
    String json = "{\n" +
            "  \"openapi\": \"3.0.0\",\n" +
            "  \"paths\": {\n" +
            "    \"/pet\": {\n" +
            "      \"foo\": \"bar\",\n" +
            "      \"get\": {\n" +
            "        \"security\": [\n" +
            "          {\n" +
            "            \"petstore_auth\": [\n" +
            "              \"write:pets\",\n" +
            "              \"read:pets\"\n" +
            "            ]\n" +
            "          }\n" +
            "        ]\n" +
            "      }\n" +
            "    }\n" +
            "  }\n" +
            "}";
    OpenAPIV3Parser parser = new OpenAPIV3Parser();

    SwaggerParseResult result = parser.readContents(json, null, null);
    List<String> messageList = result.getMessages();
    Set<String> messages = new HashSet<>(messageList);

    assertTrue(messages.contains("attribute paths.'/pet'.foo is unexpected"));
    OpenAPI openAPI = result.getOpenAPI();

    PathItem path = openAPI.getPaths().get("/pet");
    assertNotNull(path);
    Operation operation = path.getGet();
    assertNotNull(operation);
    List<SecurityRequirement> security = operation.getSecurity();

    assertTrue(security.size() == 1);
    Map<String, List<String>> requirement = security.get(0);

    assertTrue(requirement.containsKey("petstore_auth"));
    List<String> scopesList = requirement.get("petstore_auth");

    Set<String> scopes = new HashSet<>(scopesList);
    assertTrue(scopes.contains("read:pets"));
    assertTrue(scopes.contains("write:pets"));
}
 
Example 20
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@Test
public void testArrayItems() {
    String yaml =
        "openapi: 3.0.0\n" +
        "info:\n" +
        "  title: Test\n" +
        "  version: 1.0.0\n" +
        "paths:\n" +
        "  \"/store/inventory\":\n" +
        "    post:\n" +
        "      requestBody:\n" +
        "        content:\n" +
        "          application/json:\n" +
        "            schema:\n" +
        "              type: array\n" +
        "              minItems: 1\n" +
        "      responses:\n" +
        "        '200':\n" +
        "          description: successful operation\n" +
        "          content:\n" +
        "            application/json:\n" +
        "              schema:\n" +
        "                items:\n" +
        "                  type: string"
        ;

    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    SwaggerParseResult result = parser.readContents(yaml, null, null);
    assertEquals(result.getMessages(), Arrays.asList("attribute paths.'/store/inventory'(post).requestBody.content.'application/json'.schema.items is missing"));
    
    OpenAPI openAPI = result.getOpenAPI();

    Schema body = openAPI.getPaths().get("/store/inventory").getPost().getRequestBody().getContent().get("application/json").getSchema();
    assertFalse(body.getClass().equals( ArraySchema.class), "body is an ArraySchema");
    assertEquals(body.getType(), "array");
    assertEquals(body.getMinItems(), Integer.valueOf(1));

    Schema response = openAPI.getPaths().get("/store/inventory").getPost().getResponses().get("200").getContent().get("application/json").getSchema();
    assertTrue(response.getClass().equals( ArraySchema.class), "response is an ArraySchema");
    assertEquals(body.getType(), "array");
}