io.swagger.v3.parser.OpenAPIV3Parser Java Examples

The following examples show how to use io.swagger.v3.parser.OpenAPIV3Parser. 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: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssue1161(@Injectable final List<AuthorizationValue> auths) {
    String path = "/issue-1161/swagger.yaml";

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

    OpenAPI openAPI = new OpenAPIV3Parser().readLocation(path, auths, options).getOpenAPI();

    Schema petsSchema = openAPI.getComponents().getSchemas().get("Pets");
    Schema colouringsSchema = openAPI.getComponents().getSchemas().get("Colouring");

    assertNotNull(petsSchema);
    assertNotNull(colouringsSchema);

    assertTrue(petsSchema instanceof ComposedSchema);
    assertTrue(petsSchema.getProperties() != null);
    assertTrue(((ComposedSchema) petsSchema).getOneOf() != null);

    Schema petsColouringProperty = (Schema) petsSchema.getProperties().get("colouring");
    assertTrue(petsColouringProperty.get$ref() == null);
    assertTrue(petsColouringProperty == colouringsSchema);
}
 
Example #2
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 #3
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 #4
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldParseExternalSchemaModelHavingReferenceToItsLocalModel() {
    // given
    String location = "src/test/resources/issue-1040/api.yaml";
    OpenAPIV3Parser tested = new OpenAPIV3Parser();

    // when
    OpenAPI result = tested.read(location);

    // then
    Components components = result.getComponents();
    Schema modelSchema = components.getSchemas().get("Value");

    assertThat(modelSchema, notNullValue());
    assertThat(modelSchema.getProperties().get("id"), instanceOf(Schema.class));
    assertThat(((Schema) modelSchema.getProperties().get("id")).get$ref(), equalTo("#/components/schemas/ValueId"));
}
 
Example #5
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void recursiveIssue984() {
    ParseOptions parseOptions = new ParseOptions();
    parseOptions.setResolve(true);
    parseOptions.setResolveFully(true);
    OpenAPI openAPI = new OpenAPIV3Parser().read("issue-984-simple.yaml", null, parseOptions);
    if (openAPI == null) fail("failed parsing issue-984");
    try {
        Json.pretty(openAPI);
        //System.out.println(Json.pretty(openAPI));
    }
    catch (Exception e) {
        e.printStackTrace();
        fail("Recursive loop found");
    }
}
 
Example #6
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 #7
Source File: OpenAPI3RouterFactory.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new OpenAPI3RouterFactory
 *
 * @param vertx
 * @param url location of your spec. It can be an absolute path, a local path or remote url (with HTTP protocol)
 * @param auth list of authorization values needed to access the remote url. Each item should be json representation
 *             of an {@link AuthorizationValue}
 * @param handler  When specification is loaded, this handler will be called with AsyncResult<OpenAPI3RouterFactory>
 */
static void create(Vertx vertx,
                   String url,
                   List<JsonObject> auth,
                   Handler<AsyncResult<OpenAPI3RouterFactory>> handler) {
  List<AuthorizationValue> authorizationValues = auth.stream()
    .map(obj -> obj.mapTo(AuthorizationValue.class))
    .collect(Collectors.toList());
  vertx.executeBlocking((Promise<OpenAPI3RouterFactory> future) -> {
    SwaggerParseResult swaggerParseResult = new OpenAPIV3Parser().readLocation(url, authorizationValues, OpenApi3Utils.getParseOptions());
    if (swaggerParseResult.getMessages().isEmpty()) {
      future.complete(new OpenAPI3RouterFactoryImpl(vertx, swaggerParseResult.getOpenAPI(), new ResolverCache(swaggerParseResult.getOpenAPI(), null, url)));
    } else {
      if (swaggerParseResult.getMessages().size() == 1 && swaggerParseResult.getMessages().get(0).matches("unable to read location `?\\Q" + url + "\\E`?"))
        future.fail(RouterFactoryException.createSpecNotExistsException(url));
      else
        future.fail(RouterFactoryException.createSpecInvalidException(StringUtils.join(swaggerParseResult.getMessages(), ", ")));
    }
  }, handler);
}
 
Example #8
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 #9
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 #10
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssue1169() {
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    SwaggerParseResult parseResult = new OpenAPIV3Parser().readLocation("issue1169.yaml", null, options);
    assertTrue(parseResult.getMessages().size() == 0);
    OpenAPI apispec = parseResult.getOpenAPI();
    assertNotNull(apispec);
}
 
Example #11
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testRootInfo() {
    String json = "{\n" +
            "\t\"openapi\": \"3.0.0\",\n" +
            "\t\"foo\": \"bar\",\n" +
            "\t\"info\": \"invalid\"\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 foo is unexpected"));
    assertTrue(messages.contains("attribute info is not of type `object`"));
}
 
Example #12
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssue853() {
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setFlatten(true);
    final OpenAPI openAPI = new OpenAPIV3Parser().readLocation("issue-837-853-1131/main.yaml", null, options).getOpenAPI();
    Assert.assertNotNull(openAPI);

    Operation post = openAPI.getPaths().get("/guests").getPost();
    Assert.assertNotNull(post);

    Content content = post.getResponses().get("201").getContent();
    Assert.assertNotNull(content);

    Map<String, Example> examples = content.get("application/json").getExamples();
    Assert.assertEquals(examples.size(), 1);
    assertNotNull(openAPI.getComponents());
    assertNotNull(openAPI.getComponents().getExamples());
    assertNotNull(openAPI.getComponents().getExamples().get("testExample"));
    assertEquals(((LinkedHashMap<String, Object>)openAPI.getComponents().getExamples().get("testExample").getValue()).get("test"),"value");
}
 
Example #13
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 #14
Source File: ExtensionsUtilTest.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
@Test
public void allowBooleanAdditionalProperties(@Injectable final List<AuthorizationValue> auths) {

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

    SwaggerParseResult result = new OpenAPIV3Parser().readLocation("./src/test/swagger/additionalProperties.yaml", auths, options);

    assertNotNull(result);
    assertNotNull(result.getOpenAPI());
    OpenAPI openAPI = result.getOpenAPI();
    Assert.assertEquals(result.getOpenAPI().getOpenapi(), "3.0.0");
    List<String> messages = result.getMessages();

    Assert.assertTrue(openAPI.getComponents().getSchemas().get("someObject").getAdditionalProperties() instanceof Schema);
    Assert.assertTrue(((Schema)(openAPI.getComponents().getSchemas().get("someObject").getProperties().get("innerObject"))).getAdditionalProperties() instanceof Boolean);

}
 
Example #15
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssue837() {
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    final OpenAPI openAPI = new OpenAPIV3Parser().readLocation("issue-837-853-1131/main.yaml", null, options).getOpenAPI();
    Assert.assertNotNull(openAPI);

    Content content = openAPI.getPaths().get("/events").getGet().getResponses().get("200").getContent();
    Assert.assertNotNull(content);

    Map<String, Example> examples = content.get("application/json").getExamples();
    Assert.assertEquals(examples.size(), 3);
    Assert.assertEquals(((ObjectNode) examples.get("plain").getValue()).get("test").asText(), "plain");
    Assert.assertEquals(examples.get("local").get$ref(), "#/components/examples/LocalRef");
    Assert.assertEquals(examples.get("external").get$ref(), "#/components/examples/ExternalRef");
}
 
Example #16
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testAlmostEmpty(@Injectable List<AuthorizationValue> auths) {
    String yaml = "openapi: '3.0.1'\n" +
                  "new: extra";

    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);

    assertTrue(messages.contains("attribute info is missing"));
    assertTrue(messages.contains("attribute paths is missing"));
    assertTrue(messages.contains("attribute new is unexpected"));
}
 
Example #17
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testComposedSchemaAdjacentWithExamples(@Injectable final List<AuthorizationValue> auths) throws Exception {
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setResolveFully(true);
    OpenAPI openAPI = new OpenAPIV3Parser().read("src/test/resources/anyOf_OneOf.yaml", auths, options);

    Assert.assertNotNull(openAPI);

    Assert.assertTrue(openAPI.getComponents().getSchemas().size() == 2);

    Schema schemaPath = openAPI.getPaths().get("/path").getGet().getResponses().get("200").getContent().get("application/json").getSchema();
    Assert.assertTrue(schemaPath instanceof Schema);
    Assert.assertTrue(schemaPath.getProperties().size() == 5);
    Assert.assertTrue(schemaPath.getExample() instanceof HashSet);
    Set<Object> examples = (HashSet) schemaPath.getExample();
    Assert.assertTrue(examples.size() == 2);
}
 
Example #18
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 #19
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testIssue1309() {
    OpenAPIV3Parser openApiParser = new OpenAPIV3Parser();
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    SwaggerParseResult parseResult = openApiParser.readLocation("issue-1309.yaml", null, options);
    OpenAPI openAPI = parseResult.getOpenAPI();
    assertNotNull(openAPI);
    assertEquals(parseResult.getMessages().get(0),"attribute components.schemas.customer-not-found.examples is unexpected");
}
 
Example #20
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeserializeWithEnumDiscriminator() {
    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" +
                    "          description: |\n" +
                    "            The discriminator for the animal type.  It _must_\n" +
                    "            match one of the concrete schemas by name (i.e. `Cat`)\n" +
                    "            for proper deserialization\n" +
                    "          enum:\n" +
                    "            - cat\n" +
                    "            - dog";

    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(), "string");
}
 
Example #21
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void recursiveResolving() {
    ParseOptions parseOptions = new ParseOptions();
    parseOptions.setResolveFully(true);
    OpenAPI openAPI = new OpenAPIV3Parser().read("recursive.yaml", null, parseOptions);
    Assert.assertNotNull(openAPI.getPaths().get("/myPath").getGet().getResponses().get("200").getContent().get("application/json").getSchema().getProperties().get("myProp"));
    try {
        Json.mapper().writeValueAsString(openAPI);
    }
    catch (Exception e) {
        fail("Recursive loop found");
    }

}
 
Example #22
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testDiscriminatorSingleFileNoMapping() throws Exception {
    OpenAPI openAPI = new OpenAPIV3Parser().read("./discriminator-mapping-resolution/single-file-no-mapping.yaml");
    Assert.assertNotNull(openAPI);
    Schema cat = openAPI.getComponents().getSchemas().get("Cat");
    Assert.assertNotNull(cat);
}
 
Example #23
Source File: OAS3ParserTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateAPIDefinition() throws Exception {
    String relativePath = "definitions" + File.separator + "oas3" + File.separator + "oas3Resources.json";
    String oas2Resources = IOUtils.toString(getClass().getClassLoader().getResourceAsStream(relativePath), "UTF-8");

    OASParserEvaluator evaluator = (definition -> {
        OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();
        SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(definition, null, null);
        OpenAPI openAPI = parseAttemptForV3.getOpenAPI();
        Assert.assertNotNull(openAPI);
        Assert.assertEquals(1, openAPI.getPaths().size());
        Assert.assertFalse(openAPI.getPaths().containsKey("/noresource/{resid}"));
    });
    testGenerateAPIDefinition2(oas3Parser, oas2Resources, evaluator);
}
 
Example #24
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 #25
Source File: ResponseExamplesTest.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
@Test
public void testRandomRequestedJsonExample(@Injectable final List<io.swagger.v3.parser.core.models.AuthorizationValue> auths) throws Exception {
    Configuration config = new Configuration();
    List<String> exampleProcessor = new ArrayList<>();
    exampleProcessor.add("random");
    config.setExampleProcessors(exampleProcessor);
    ParseOptions options = new ParseOptions();
    options.setResolveFully(true);

    OpenAPI openAPI = new OpenAPIV3Parser().readLocation( "src/test/swagger/oas3.yaml",auths, options).getOpenAPI();
    Operation operation = openAPI.getPaths().get( "/mockResponses/objectMultipleExamples").getGet();

    OpenAPIOperationController controller = new OpenAPIOperationController(
            config, "/mockResponses/objectMultipleExamples", "GET",operation,"", openAPI.getComponents().getSchemas() );

    ContainerRequestContext requestContext = mock(ContainerRequestContext.class);
    UriInfo uriInfo = mock( UriInfo.class );

    stub( uriInfo.getPath()).toReturn( "/mockResponses/objectMultipleExamples");
    stub( uriInfo.getQueryParameters()).toReturn( new MultivaluedHashMap<String, String>());
    stub( uriInfo.getPathParameters()).toReturn( new MultivaluedHashMap<String, String>());


    stub( requestContext.getHeaders()).toReturn( new MultivaluedHashMap<String, String>());
    requestContext.getHeaders().add("Accept","application/json");
    stub( requestContext.getUriInfo()).toReturn( uriInfo );

    Response response = controller.apply( requestContext );

    assertEquals( 200, response.getStatus() );
    assertEquals( "json", response.getMediaType().getSubtype() );

    assertNotNull( response.getEntity());

}
 
Example #26
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void allOfExampleGeneration(@Injectable final List<AuthorizationValue> auths) throws JsonProcessingException {
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setResolveFully(true);
    OpenAPI openAPI = new OpenAPIV3Parser().read("src/test/resources/simpleAllOf.yaml", null, options);

    Assert.assertNotNull(openAPI);
    Object withoutExample = openAPI.getPaths().get("/foo").getGet().getResponses().get("200").getContent().get("application/json").getSchema().getExample();
    Assert.assertNull(withoutExample);

    Object withExample = openAPI.getPaths().get("/bar").getGet().getResponses().get("200").getContent().get("application/json").getSchema().getExample();
    Assert.assertEquals("{\"someProperty\":\"ABC\",\"someOtherProperty\":42}", Json.mapper().writeValueAsString(withExample));
}
 
Example #27
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Get parsed OpenAPI object
 *
 * @param oasDefinition OAS definition
 * @return OpenAPI
 */
OpenAPI getOpenAPI(String oasDefinition) {
    OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();
    SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(oasDefinition, null, null);
    if (CollectionUtils.isNotEmpty(parseAttemptForV3.getMessages())) {
        log.debug("Errors found when parsing OAS definition");
    }
    return parseAttemptForV3.getOpenAPI();
}
 
Example #28
Source File: ResponseExamplesTest.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
@Test
public void testResponseJsonExample(@Injectable final List<io.swagger.v3.parser.core.models.AuthorizationValue> auths) throws Exception {
    Configuration config = new Configuration();
    List<String> exampleProcessor = new ArrayList<>();
    exampleProcessor.add("sequence");
    config.setExampleProcessors(exampleProcessor);
    ParseOptions options = new ParseOptions();
    options.setResolve(true);

    OpenAPI openAPI = new OpenAPIV3Parser().readLocation( "src/test/swagger/oas3.yaml",auths, options).getOpenAPI();
    Operation operation = openAPI.getPaths().get( "/mockResponses/responseWithExamples").getGet();

   OpenAPIOperationController controller = new OpenAPIOperationController(
        config, "/mockResponses/responseWithExamples", "GET", operation,"" ,openAPI.getComponents().getSchemas() );

    ContainerRequestContext requestContext = mock(ContainerRequestContext.class);
    UriInfo uriInfo = mock( UriInfo.class );

    stub( uriInfo.getPath()).toReturn( "/mockResponses/responseWithExamples");
    stub( uriInfo.getQueryParameters()).toReturn( new MultivaluedHashMap<String, String>());
    stub( uriInfo.getPathParameters()).toReturn( new MultivaluedHashMap<String, String>());

    stub( requestContext.getAcceptableMediaTypes()).toReturn(Arrays.asList(MediaType.APPLICATION_JSON_TYPE));
    stub( requestContext.getHeaders()).toReturn( new MultivaluedHashMap<String, String>());
    stub( requestContext.getUriInfo()).toReturn( uriInfo );

    Response response = controller.apply( requestContext );

    assertEquals( 200, response.getStatus() );
    assertEquals(  Json.mapper().writeValueAsString(response.getEntity()), "{\"value\":{\"test\":\"jsonvalue\"}}");
}
 
Example #29
Source File: ExampleBuilderTest.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
@Test
public void testSwos126() throws Exception {

    String spec = "openapi: 3.0.0\n" +
            "info:\n" +
            "  title: ExampleBuilder and date-time examples\n" +
            "  version: 0.0.0\n" +
            "paths: {}\n" +
            "\n" +
            "components:\n" +
            "  schemas:\n" +
            "    MyModel:\n" +
            "      type: object\n" +
            "      properties:\n" +
            "        date:\n" +
            "          type: string\n" +
            "          format: date\n" +
            "          example: '2019-08-05'\n" +
            "        dateTime:\n" +
            "          type: string\n" +
            "          format: date-time\n" +
            "          example: '2019-08-05T12:34:56Z'";
    String schemaName = "MyModel";
    // Load OAS3 definition
    OpenAPI openapi = new OpenAPIV3Parser().readContents(spec).getOpenAPI();

    // Create an Example object for the MyModel model
    Map<String, Schema> allSchemas = openapi.getComponents().getSchemas();
    Schema schema = allSchemas.get(schemaName);
    Example example = ExampleBuilder.fromSchema(schema, allSchemas, ExampleBuilder.RequestType.READ);

    // Configure JSON example serializer
    SimpleModule simpleModule = new SimpleModule().addSerializer(new JsonNodeExampleSerializer());
    Json.mapper().registerModule(simpleModule);

    // Convert the Example object to a JSON string
    String jsonExample = Json.pretty(example);
    assertTrue(jsonExample.contains("\"date\" : \"2019-08-05\""));
    assertTrue(jsonExample.contains("\"dateTime\" : \"2019-08-05T12:34:56Z\""));
}
 
Example #30
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");
}