io.swagger.v3.parser.core.models.SwaggerParseResult Java Examples

The following examples show how to use io.swagger.v3.parser.core.models.SwaggerParseResult. 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: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssue834() {
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    SwaggerParseResult result = new OpenAPIV3Parser().readLocation("issue-834/index.yaml", null, options);
    assertNotNull(result.getOpenAPI());

    Content foo200Content = result.getOpenAPI().getPaths().get("/foo").getGet().getResponses().get("200").getContent();
    assertNotNull(foo200Content);
    String foo200SchemaRef = foo200Content.get("application/json").getSchema().get$ref();
    assertEquals(foo200SchemaRef, "#/components/schemas/schema");

    Content foo300Content = result.getOpenAPI().getPaths().get("/foo").getGet().getResponses().get("300").getContent();
    assertNotNull(foo300Content);
    String foo300SchemaRef = foo300Content.get("application/json").getSchema().get$ref();
    assertEquals(foo300SchemaRef, "#/components/schemas/schema");

    Content bar200Content = result.getOpenAPI().getPaths().get("/bar").getGet().getResponses().get("200").getContent();
    assertNotNull(bar200Content);
    String bar200SchemaRef = bar200Content.get("application/json").getSchema().get$ref();
    assertEquals(bar200SchemaRef, "#/components/schemas/schema");
}
 
Example #2
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testInlineModelResolver(@Injectable final List<AuthorizationValue> auths) throws Exception{

    String pathFile = FileUtils.readFileToString(new File("src/test/resources/flatten.json"));
    pathFile = pathFile.replace("${dynamicPort}", String.valueOf(this.serverPort));
    ParseOptions options = new ParseOptions();
    options.setFlatten(true);

    SwaggerParseResult result = new OpenAPIV3Parser().readContents(pathFile, auths, options);

    Assert.assertNotNull(result);
    OpenAPI openAPI = result.getOpenAPI();
    Assert.assertNotNull(openAPI);
    Schema user = openAPI.getComponents().getSchemas().get("User");

    assertNotNull(user);
    Schema address = (Schema)user.getProperties().get("address");

    assertTrue((address.get$ref()!= null));

    Schema userAddress = openAPI.getComponents().getSchemas().get("User_address");
    assertNotNull(userAddress);
    assertNotNull(userAddress.getProperties().get("city"));
    assertNotNull(userAddress.getProperties().get("street"));
}
 
Example #3
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "data")
public void readExternalDocsObject(JsonNode rootNode) throws Exception {
    final OpenAPIDeserializer deserializer = new OpenAPIDeserializer();
    final SwaggerParseResult result = deserializer.deserialize(rootNode);

    Assert.assertNotNull(result);

    final OpenAPI openAPI = result.getOpenAPI();
    Assert.assertNotNull(openAPI);

    final ExternalDocumentation externalDocumentation = openAPI.getExternalDocs();
    Assert.assertNotNull(externalDocumentation);
    Assert.assertNotNull(externalDocumentation.getUrl());
    Assert.assertEquals(externalDocumentation.getUrl(),"http://swagger.io");

    Assert.assertNotNull(externalDocumentation.getDescription());
    Assert.assertEquals(externalDocumentation.getDescription(),"Find out more about Swagger");

}
 
Example #4
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 #5
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testInlineModelResolverByUrl(){
    String url = "http://localhost:${dynamicPort}/remote/json";
    url = url.replace("${dynamicPort}", String.valueOf(this.serverPort));

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

    SwaggerParseResult result = new OpenAPIV3Parser().readLocation(url,new ArrayList<>(),options);
    Assert.assertNotNull(result);
    OpenAPI openAPI = result.getOpenAPI();
    Assert.assertNotNull(openAPI);
    Schema user = openAPI.getComponents().getSchemas().get("User");

    assertNotNull(user);
    Schema address = (Schema)user.getProperties().get("address");

    assertTrue((address.get$ref()!= null));

    Schema userAddress = openAPI.getComponents().getSchemas().get("User_address");
    assertNotNull(userAddress);
    assertNotNull(userAddress.getProperties().get("city"));
    assertNotNull(userAddress.getProperties().get("street"));
}
 
Example #6
Source File: OpenAPIV3Parser.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
private SwaggerParseResult resolve(SwaggerParseResult result, List<AuthorizationValue> auth, ParseOptions options,
        String location) {
    try {
        if (options != null) {
            if (options.isResolve() || options.isResolveFully()) {
                result.setOpenAPI(new OpenAPIResolver(result.getOpenAPI(), emptyListIfNull(auth),
                        location).resolve());
                if (options.isResolveFully()) {
                    new ResolverFully(options.isResolveCombinators()).resolveFully(result.getOpenAPI());
                }
            }
            if (options.isFlatten()) {
                final InlineModelResolver inlineModelResolver =
                        new InlineModelResolver(options.isFlattenComposedSchemas(),
                                options.isCamelCaseFlattenNaming(), options.isSkipMatches());
                inlineModelResolver.flatten(result.getOpenAPI());
            }
        }
    } catch (Exception e) {
        LOGGER.warn("Exception while resolving:", e);
        result.setMessages(Collections.singletonList(e.getMessage()));
    }
    return result;
}
 
Example #7
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeserializeBinaryString() {
    String yaml = "openapi: 3.0.0\n" +
            "servers: []\n" +
            "info:\n" +
            "  title: foo\n" +
            "  version: ''\n" +
            "paths:\n" +
            "  /test:\n" +
            "    post:\n" +
            "      responses:\n" +
            "        '200':\n" +
            "          description: ok\n" +
            "      requestBody:\n" +
            "        content:\n" +
            "          application/json:\n" +
            "            schema:\n" +
            "              type: string\n" +
            "              format: binary";

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

    final OpenAPI resolved = new OpenAPIResolver(result.getOpenAPI(), null).resolve();
    assertTrue(resolved.getPaths().get("/test").getPost().getRequestBody().getContent().get("application/json").getSchema() instanceof BinarySchema);
}
 
Example #8
Source File: OpenAPIV3Parser.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
private SwaggerParseResult readContents(String swaggerAsString, List<AuthorizationValue> auth, ParseOptions options,
                                        String location) {
    if (swaggerAsString == null || swaggerAsString.trim().isEmpty()) {
        return SwaggerParseResult.ofError("Null or empty definition");
    }

    try {
        final ObjectMapper mapper = getRightMapper(swaggerAsString);
        final JsonNode rootNode = mapper.readTree(swaggerAsString);
        final SwaggerParseResult result = parseJsonNode(location, rootNode);
        return resolve(result, auth, options, location);
    } catch (JsonProcessingException e) {
        LOGGER.warn("Exception while parsing:", e);
        final String message = getParseErrorMessage(e.getOriginalMessage(), location);
        return SwaggerParseResult.ofError(message);
    }
}
 
Example #9
Source File: CheckCompatibilityBase.java    From servicecomb-toolkit with Apache License 2.0 6 votes vote down vote up
private OpenAPI loadOpenApi(String filePath) throws IOException {
  String yaml = loadFileContent(filePath);
  SwaggerParseResult oldParseResult = CompatibilityCheckParser.parseYaml(yaml);
  OpenAPI openAPI = oldParseResult.getOpenAPI();
  if (openAPI == null) {
    StringJoiner errors = new StringJoiner("\n", "Parse errors:", "");
    if (CollectionUtils.isNotEmpty(oldParseResult.getMessages())) {
      for (String message : oldParseResult.getMessages()) {
        errors.add(message);
      }
    }
    throw new RuntimeException(errors.toString());
  }

  return openAPI;
}
 
Example #10
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testParseOptionsSkipMatchesFalse() {
    final String location = "src/test/resources/skipMatches.yaml";

    final ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setFlatten(true);
    options.setSkipMatches(false);

    final OpenAPIV3Parser parserUnderTest = new OpenAPIV3Parser();

    final SwaggerParseResult result = parserUnderTest.readLocation(location, null, options);

    final OpenAPI openAPI = result.getOpenAPI();

    assertNotNull(openAPI);
    assertNotNull(openAPI.getComponents());
    assertNotNull(openAPI.getComponents().getSchemas());
    assertEquals(4, openAPI.getComponents().getSchemas().size());
}
 
Example #11
Source File: OpenAPIParserTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssueRelativeRefs2(){
    String location = "exampleSpecs/specs/my-domain/test-api/v1/test-api-swagger_v1.json";
    ParseOptions po = new ParseOptions();
    po.setResolve(true);
    SwaggerParseResult result = new OpenAPIParser().readLocation(location, null, po);

    assertNotNull(result.getOpenAPI());
    OpenAPI openAPI = result.getOpenAPI();

    Map<String, Schema> schemas = openAPI.getComponents().getSchemas();
    Assert.assertTrue(schemas.get("confirmMessageType_v01").getProperties().get("resources") instanceof ArraySchema);

    ArraySchema arraySchema = (ArraySchema) schemas.get("confirmMessageType_v01").getProperties().get("resources");
    Schema prop = (Schema) arraySchema.getItems().getProperties().get("resourceID");

    assertEquals(prop.get$ref(),"#/components/schemas/simpleIDType_v01");
}
 
Example #12
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testCodegenIssue8601() {
    OpenAPIV3Parser openApiParser = new OpenAPIV3Parser();
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setFlatten(true);
    SwaggerParseResult parseResult = openApiParser.readLocation("codegen-issue-8601.yaml", null, options);

    OpenAPI openAPI = parseResult.getOpenAPI();
    assertNotNull(openAPI.getComponents().getSchemas().get("status"));
    assertNotNull(openAPI.getComponents().getSchemas().get("body"));
    assertNotNull(openAPI.getComponents().getSchemas().get("inline_response_200"));
    assertNotNull(openAPI.getComponents().getSchemas().get("body_1"));
    assertNotNull(openAPI.getComponents().getSchemas().get("Test1"));
    assertNotNull(openAPI.getComponents().getSchemas().get("Test2"));
}
 
Example #13
Source File: OpenAPIStyleValidatorTask.java    From openapi-style-validator with Apache License 2.0 6 votes vote down vote up
@TaskAction
public void execute() {
    if (inputFile == null) {
        throw new GradleException(String.format("The input file is not defined, set the '%s' option", INPUT_FILE));
    }
    getLogger().quiet(String.format("Validating spec: %s", inputFile));

    OpenAPIParser openApiParser = new OpenAPIParser();
    ParseOptions parseOptions = new ParseOptions();
    parseOptions.setResolve(true);

    SwaggerParseResult parserResult = openApiParser.readLocation(inputFile, null, parseOptions);
    io.swagger.v3.oas.models.OpenAPI swaggerOpenAPI = parserResult.getOpenAPI();

    org.eclipse.microprofile.openapi.models.OpenAPI openAPI = SwAdapter.toOpenAPI(swaggerOpenAPI);
    OpenApiSpecStyleValidator openApiSpecStyleValidator = new OpenApiSpecStyleValidator(openAPI);

    ValidatorParameters parameters = createValidatorParameters();
    List<StyleError> result = openApiSpecStyleValidator.validate(parameters);
    if (!result.isEmpty()) {
        getLogger().error("OpenAPI Specification does not meet the requirements. Issues:\n");
        result.stream().map(StyleError::toString).forEach(m -> getLogger().error(String.format("\t%s", m)));
        throw new GradleException("OpenAPI Style validation failed");
    }
}
 
Example #14
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 #15
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testResponses() {
    String yaml = "openapi: 3.0.0\n" +
            "servers: []\n" +
            "info:\n" +
            "  version: ''\n" +
            "  title: ''\n" +
            "paths: {}\n" +
            "components:\n" +
            "  responses:\n" +
            "    foo:\n" +
            "      description: description\n" +
            "      bar: baz\n" +
            "      x-foo: bar";

    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 components.responses.foo.bar is unexpected"));

    assertEquals(result.getOpenAPI().getComponents().getResponses().get("foo").getExtensions().get("x-foo").toString(), "bar");
}
 
Example #16
Source File: FileReferenceTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssue306() {
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    SwaggerParseResult result = new OpenAPIV3Parser().readLocation("./src/test/resources/nested-file-references/issue-306.yaml", null, options);
    assertNotNull(result.getOpenAPI());

    OpenAPI swagger = result.getOpenAPI();

    assertTrue(swagger.getComponents().getSchemas().size() == 5);
    // resolved from `$ref: './book.yaml'`
    assertNotNull(swagger.getComponents().getSchemas().get("Inventory"));
    // resolved from `$ref: 'book.yaml'`
    assertNotNull(swagger.getComponents().getSchemas().get("Orders"));

    // copied from `./book.yaml`
    assertNotNull(swagger.getComponents().getSchemas().get("book"));
}
 
Example #17
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testSampleParser() {
    final String location = "src/test/resources/issue-1211.json";

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

    final OpenAPIV3Parser parser = new OpenAPIV3Parser();
    final SwaggerParseResult result = parser.readLocation(location, null, options);
    System.out.println(result.getMessages());
    OpenAPI openAPI = result.getOpenAPI();

    assertNotNull(result.getOpenAPI());
    assertTrue(result.getMessages().size() > 0);
    assertEquals(result.getMessages().get(0).contains("attribute components.schemas.Pet. writeOnly and readOnly are both present"), true);

}
 
Example #18
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 #19
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "data")
public void readSchemaArray(JsonNode rootNode) throws Exception {
    final OpenAPIDeserializer deserializer = new OpenAPIDeserializer();
    final SwaggerParseResult result = deserializer.deserialize(rootNode);

    Assert.assertNotNull(result);

    final OpenAPI openAPI = result.getOpenAPI();
    Assert.assertNotNull(openAPI);

    final Paths paths = openAPI.getPaths();
    Assert.assertNotNull(paths);
    Assert.assertEquals(paths.size(), 18);

    //parameters operation get
    PathItem petByStatusEndpoint = paths.get("/pet/findByTags");
    Assert.assertNotNull(petByStatusEndpoint.getGet());
    Assert.assertNotNull(petByStatusEndpoint.getGet().getParameters());
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().size(), 1);
    Assert.assertNotNull(petByStatusEndpoint.getGet().getParameters().get(0).getSchema());
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getSchema().getType(), "array");
    Assert.assertEquals(((ArraySchema)(petByStatusEndpoint.getGet().getParameters().get(0).getSchema())).getItems().getType(), "string");
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getName(),"tags");
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getExplode(), Boolean.TRUE);
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getStyle(), StyleEnum.FORM);
}
 
Example #20
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test(description = "it should read a top-level extension per https://github.com/openAPI-api/validator-badge/issues/59")
public void testToplevelExtension() throws Exception {
    String yaml = "openapi: 3.0.0\n" +
            "servers: []\n" +
            "x-foo: woof\n" +
            "info:\n" +
            "  version: 0.0.0\n" +
            "  title: Simple API\n" +
            "paths:\n" +
            "  /:\n" +
            "    get:\n" +
            "      responses:\n" +
            "        '200':\n" +
            "          description: OK";

    OpenAPIV3Parser parser = new OpenAPIV3Parser();

    SwaggerParseResult result = parser.readContents(yaml, null, null);
    assertNotNull(result.getOpenAPI().getExtensions());
}
 
Example #21
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testIssue1147() {
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setFlatten(true);
    SwaggerParseResult parseResult = new OpenAPIV3Parser().readLocation("issue-1147/issue1147.yaml", null, options);
    OpenAPI apispec = parseResult.getOpenAPI();
    assertNotNull(apispec);
    assertEquals(((Schema)apispec.getComponents().getSchemas().get("StringObject").getProperties().get("val")).get$ref(),"#/components/schemas/String");
}
 
Example #22
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testEmptyDefinitions() throws Exception {
    String yaml = "openapi: 3.0.0\n" +
            "servers:\n" +
            "  - url: 'http://abc:5555/mypath'\n" +
            "info:\n" +
            "  version: '1.0'\n" +
            "  title: dd\n" +
            "paths:\n" +
            "  /resource1/Id:\n" +
            "    post:\n" +
            "      description: ''\n" +
            "      operationId: postOp\n" +
            "      responses:\n" +
            "        '200':\n" +
            "          description: Successful\n" +
            "        '401':\n" +
            "          description: Access Denied\n" +
            "      requestBody:\n" +
            "        content:\n" +
            "          application/json:\n" +
            "            schema:\n" +
            "              $ref: '#/components/schemas/mydefinition'\n" +
            "        required: true\n" +
            "components:\n" +
            "  schemas:\n" +
            "    mydefinition: {}";

    OpenAPIV3Parser parser = new OpenAPIV3Parser();

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

    assertNotNull(openAPI.getComponents().getSchemas().get("mydefinition"));

}
 
Example #23
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 #24
Source File: OAS3ParserTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateAPIDefinitionWithExtensions() throws Exception {
    String relativePath = "definitions" + File.separator + "oas3" + File.separator + "oas3Resources.json";
    String oas3Resources = IOUtils.toString(getClass().getClassLoader().getResourceAsStream(relativePath), "UTF-8");
    OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();

    // check remove vendor extensions
    String definition = testGenerateAPIDefinitionWithExtension(oas3Parser, oas3Resources);
    SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(definition, null, null);
    OpenAPI openAPI = parseAttemptForV3.getOpenAPI();
    boolean isExtensionNotFound = openAPI.getExtensions() == null || !openAPI.getExtensions()
            .containsKey(APIConstants.SWAGGER_X_WSO2_SECURITY);
    Assert.assertTrue(isExtensionNotFound);
    Assert.assertEquals(2, openAPI.getPaths().size());

    Iterator<Map.Entry<String, PathItem>> itr = openAPI.getPaths().entrySet().iterator();
    while (itr.hasNext()) {
        Map.Entry<String, PathItem> pathEntry = itr.next();
        PathItem path = pathEntry.getValue();
        for (Operation operation : path.readOperations()) {
            Assert.assertFalse(operation.getExtensions().containsKey(APIConstants.SWAGGER_X_SCOPE));
        }
    }

    // check updated scopes in security definition
    Operation itemGet = openAPI.getPaths().get("/items").getGet();
    Assert.assertTrue(itemGet.getSecurity().get(0).get("default").contains("newScope"));

    // check available scopes in security definition
    SecurityScheme securityScheme = openAPI.getComponents().getSecuritySchemes().get("default");
    OAuthFlow implicityOauth = securityScheme.getFlows().getImplicit();
    Assert.assertTrue(implicityOauth.getScopes().containsKey("newScope"));
    Assert.assertEquals("newScopeDescription", implicityOauth.getScopes().get("newScope"));

    Assert.assertTrue(implicityOauth.getExtensions().containsKey(APIConstants.SWAGGER_X_SCOPES_BINDINGS));
    Map<String, String> scopeBinding =
            (Map<String, String>) implicityOauth.getExtensions().get(APIConstants.SWAGGER_X_SCOPES_BINDINGS);
    Assert.assertTrue(scopeBinding.containsKey("newScope"));
    Assert.assertEquals("admin", scopeBinding.get("newScope"));
}
 
Example #25
Source File: OpenAPIParserTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testIssue895() {
    SwaggerParseResult result = new OpenAPIParser().readLocation("issue895.yaml", null, null);
    assertNotNull(result);
    assertNotNull(result.getOpenAPI());
    assertEquals(result.getMessages().get(0),"attribute info.contact.test");
    assertEquals(result.getMessages().get(1),"attribute info.license.test1");

}
 
Example #26
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testIssue291() {
    String json = "openapi: 3.0.0\n" +
            "servers: []\n" +
            "info:\n" +
            "  title: test spec\n" +
            "  version: '1.0'\n" +
            "paths:\n" +
            "  /test:\n" +
            "    get:\n" +
            "      description: test get\n" +
            "      parameters:\n" +
            "        - $ref: '#/components/parameters/testParam'\n" +
            "      responses:\n" +
            "        default:\n" +
            "          description: test response\n" +
            "components:\n" +
            "  parameters:\n" +
            "    testParam:\n" +
            "      name: test\n" +
            "      in: query\n" +
            "      style: form\n" +
            "      schema:\n" +
            "        type: array\n" +
            "        items:\n" +
            "          type: string";
    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    SwaggerParseResult result = parser.readContents(json, null, null);

    OpenAPI swagger = result.getOpenAPI();
    final OpenAPI resolved = new OpenAPIResolver(swagger, null).resolve();


    Parameter param = resolved.getPaths().get("/test").getGet().getParameters().get(0);
    QueryParameter qp = (QueryParameter) param;
    //assertEquals(qp.getCollectionFormat(), "csv");
}
 
Example #27
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testSecurity() {
    String json = "{\n" +
            "  \"openapi\": \"3.0.0\",\n" +
            "  \"security\": [\n" +
            "    {\n" +
            "      \"petstore_auth\": [\n" +
            "        \"write:pets\",\n" +
            "        \"read:pets\"\n" +
            "      ]\n" +
            "    }\n" +
            "  ]\n" +
            "}";
    OpenAPIV3Parser parser = new OpenAPIV3Parser();

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


    OpenAPI openAPI = result.getOpenAPI();

    assertNotNull(openAPI.getSecurity());
    List<SecurityRequirement> security = openAPI.getSecurity();
    Assert.assertTrue(security.size() == 1);
    Assert.assertTrue(security.get(0).size() == 1);

    List<String> requirement = security.get(0).get("petstore_auth");
    Assert.assertTrue(requirement.size() == 2);

    Set<String> requirements = new HashSet(requirement);
    Assert.assertTrue(requirements.contains("read:pets"));
    Assert.assertTrue(requirements.contains("write:pets"));
}
 
Example #28
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testResolveFully() throws Exception{
    String pathFile = FileUtils.readFileToString(new File("src/test/resources/oas3.yaml.template"));
    pathFile = pathFile.replace("${dynamicPort}", String.valueOf(this.serverPort));
    ParseOptions options = new ParseOptions();
    options.setResolveFully(true);

    SwaggerParseResult result = new OpenAPIV3Parser().readContents(pathFile, new ArrayList<>(), options  );

    Assert.assertNotNull(result);
    Assert.assertNotNull(result.getOpenAPI());
    assertEquals(result.getOpenAPI().getOpenapi(), "3.0.1");
    assertEquals(result.getOpenAPI().getComponents().getSchemas().get("OrderRef").getType(),"object");
}
 
Example #29
Source File: OpenAPIParser.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
public SwaggerParseResult readContents(String swaggerAsString, List<AuthorizationValue> auth, ParseOptions options) {
    SwaggerParseResult output = null;

    for(SwaggerParserExtension extension : OpenAPIV3Parser.getExtensions()) {
        output = extension.readContents(swaggerAsString, auth, options);
        if(output != null && output.getOpenAPI() != null) {
            return output;
        }
    }

    return output;
}
 
Example #30
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testRegressionIssue1236() {
    final ParseOptions options = new ParseOptions();
    options.setResolve(true);

    SwaggerParseResult result = new OpenAPIV3Parser()
            .readLocation("src/test/resources/testRegressionIssue1236.yaml", null, options);
    assertTrue(result.getMessages().size() == 0);

}