io.swagger.v3.oas.models.OpenAPI Java Examples

The following examples show how to use io.swagger.v3.oas.models.OpenAPI. 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: TestUtils.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
public static OpenAPI createOpenAPI() {
    OpenAPI openAPI = new OpenAPI();
    openAPI.setComponents(new Components());
    openAPI.setPaths(new Paths());

    final Info info = new Info();
    info.setDescription("API under test");
    info.setVersion("1.0.7");
    info.setTitle("My title");
    openAPI.setInfo(info);

    final Server server = new Server();
    server.setUrl("https://localhost:9999/root");
    openAPI.setServers(Collections.singletonList(server));
    return openAPI;
}
 
Example #2
Source File: OperationTagsReferenceValidatorTest.java    From servicecomb-toolkit with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidate() {
  OpenAPI openAPI = loadRelative("petstore-operation-tags-reference.yaml");
  OasSpecValidator oasSpecValidator =
      oasSpecValidatorFactory.create(
          singleOption(OperationTagsReferenceValidator.CONFIG_KEY, "true")
      );

  List<OasViolation> violations = oasSpecValidator.validate(createContext(openAPI), openAPI);
  assertThat(violations).containsExactly(
      createViolation(OperationTagsReferenceValidator.ERROR,
      "paths", PATHS,
      "/pets", PATH_ITEM,
      "get", OPERATION,
      "tags[0]", null));
}
 
Example #3
Source File: InlineModelResolverTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void resolveInlineArrayRequestBody() {
    OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/3_0/inline_model_resolver.yaml");
    new InlineModelResolver().flatten(openAPI);

    MediaType mediaType = openAPI
            .getPaths()
            .get("/resolve_inline_array_request_body")
            .getPost()
            .getRequestBody()
            .getContent()
            .get("application/json");

    assertTrue(mediaType.getSchema() instanceof ArraySchema);

    ArraySchema requestBody = (ArraySchema) mediaType.getSchema();
    assertNotNull(requestBody.getItems().get$ref());
    assertEquals("#/components/schemas/InlineObject", requestBody.getItems().get$ref());

    Schema items = ModelUtils.getReferencedSchema(openAPI, ((ArraySchema) mediaType.getSchema()).getItems());
    assertTrue(items.getProperties().get("street") instanceof StringSchema);
    assertTrue(items.getProperties().get("city") instanceof StringSchema);
}
 
Example #4
Source File: SpringCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
private Map<String, File> generateFiles(SpringCodegen codegen, String filePath) throws IOException {
    final File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
    output.deleteOnExit();
    final String outputPath = output.getAbsolutePath().replace('\\', '/');

    codegen.setOutputDir(output.getAbsolutePath());
    codegen.additionalProperties().put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true");

    final ClientOptInput input = new ClientOptInput();
    final OpenAPI openAPI = new OpenAPIParser().readLocation(filePath, null, new ParseOptions()).getOpenAPI();
    input.openAPI(openAPI);
    input.config(codegen);

    final DefaultGenerator generator = new DefaultGenerator();
    List<File> files = generator.opts(input).generate();

    return files.stream().collect(Collectors.toMap(e -> e.getName().replace(outputPath, ""), i -> i));
}
 
Example #5
Source File: JavascriptClosureAngularClientCodegen.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Override
public void preprocessOpenAPI(OpenAPI openAPI) {
    super.preprocessOpenAPI(openAPI);

    if (useEs6) {
        embeddedTemplateDir = templateDir = "Javascript-Closure-Angular/es6";
        apiPackage = "resources";
        apiTemplateFiles.put("api.mustache", ".js");
        supportingFiles.add(new SupportingFile("module.mustache", "", "module.js"));
    } else {
        modelTemplateFiles.put("model.mustache", ".js");
        apiTemplateFiles.put("api.mustache", ".js");
        embeddedTemplateDir = templateDir = "Javascript-Closure-Angular";
        apiPackage = "API.Client";
        modelPackage = "API.Client";
    }
}
 
Example #6
Source File: EncodingAddNotAllowedDiffValidatorTest.java    From servicecomb-toolkit with Apache License 2.0 6 votes vote down vote up
@Test
public void validate() {
  OpenAPI leftOpenAPI = loadRelative("petstore-encoding-add-a.yaml");
  OpenAPI rightOpenAPI = loadRelative("petstore-encoding-add-b.yaml");
  List<OasDiffViolation> violations = oasSpecDiffValidator
    .validate(createContext(leftOpenAPI, rightOpenAPI), leftOpenAPI, rightOpenAPI);

  assertThat(violations)
    .containsExactlyInAnyOrder(
      createViolationRight(
        DiffViolationMessages.OP_ADD_FORBIDDEN,
        new Object[] {
          "paths", PATHS,
          "/pets", PATH_ITEM,
          "post", OPERATION,
          "requestBody", REQUEST_BODY,
          "content.'application/x-www-form-urlencoded'", MEDIA_TYPE,
          "encoding.'bar'", ENCODING
        }
      )
    );

}
 
Example #7
Source File: PhpModelTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test(description = "convert a model with complex list property")
public void complexListProperty() {
    final Schema model = new Schema()
            .description("a sample model")
            .addProperties("children", new ArraySchema()
                    .items(new Schema().$ref("#/definitions/Children")));
    final DefaultCodegen codegen = new PhpClientCodegen();
    OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
    codegen.setOpenAPI(openAPI);
    final CodegenModel cm = codegen.fromModel("sample", model);

    Assert.assertEquals(cm.name, "sample");
    Assert.assertEquals(cm.classname, "Sample");
    Assert.assertEquals(cm.description, "a sample model");
    Assert.assertEquals(cm.vars.size(), 1);

    final CodegenProperty property1 = cm.vars.get(0);
    Assert.assertEquals(property1.baseName, "children");
    Assert.assertEquals(property1.dataType, "\\OpenAPI\\Client\\Model\\Children[]");
    Assert.assertEquals(property1.name, "children");
    Assert.assertEquals(property1.baseType, "array");
    Assert.assertEquals(property1.containerType, "array");
    Assert.assertFalse(property1.required);
    Assert.assertTrue(property1.isContainer);
}
 
Example #8
Source File: PlantumlDocumentationCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void listFieldTest() {
    final Schema model = new Schema()
            .description("a sample model")
            .addProperties("tags", new ArraySchema().items(new StringSchema()));
    OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
    plantumlDocumentationCodegen.setOpenAPI(openAPI);
    final CodegenModel cm = plantumlDocumentationCodegen.fromModel("sample", model);

    Map<String, Object> objs = createObjectsMapFor(cm);

    plantumlDocumentationCodegen.postProcessSupportingFileData(objs);

    List<Object> entityList = getList(objs, "entities");

    Map<String, Object> sampleEntity = getEntityFromList("Sample", entityList);
    Map<String, Object> tagsField = getFieldFromEntity("tags", sampleEntity);
    Assert.assertEquals((String)tagsField.get("dataType"), "List<String>");
}
 
Example #9
Source File: ParameterDescriptionRequiredValidatorTest.java    From servicecomb-toolkit with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidate() {
  OpenAPI openAPI = loadRelative("petstore-parameter-desc-none.yaml");
  OasSpecValidator oasSpecValidator =
      oasSpecValidatorFactory.create(
          singleOption(ParameterDescriptionRequiredValidator.CONFIG_KEY, "true")
      );

  List<OasViolation> violations = oasSpecValidator.validate(createContext(openAPI), openAPI);
  assertThat(violations).containsExactlyInAnyOrder(
    createViolation(
      ViolationMessages.REQUIRED,
      "paths", PATHS,
      "/pets/{petId}", PATH_ITEM,
      "get", OPERATION,
      "parameters[0]", PARAMETER,
      "description", null
    ),
    createViolation(
      ViolationMessages.REQUIRED,
      "components", COMPONENTS,
      "parameters.'Bar'", PARAMETER,
      "description", null
    )
  );
}
 
Example #10
Source File: KotlinSpringServerCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test(description = "test embedded enum array")
public void embeddedEnumArrayTest() throws Exception {
    String baseModelPackage = "zz";
    File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); //may be move to /build
    OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/issue______kotlinArrayEnumEmbedded.yaml");
    KotlinSpringServerCodegen codegen = new KotlinSpringServerCodegen();
    codegen.setOutputDir(output.getAbsolutePath());
    codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, baseModelPackage + ".yyyy.model.xxxx");
    ClientOptInput input = new ClientOptInput();
    input.openAPI(openAPI);
    input.config(codegen);
    DefaultGenerator generator = new DefaultGenerator();
    generator.opts(input).generate();
    File resultSourcePath = new File(output, "src/main/kotlin");
    File outputModel = Files.createTempDirectory("test").toFile().getCanonicalFile();
    FileUtils.copyDirectory(new File(resultSourcePath, baseModelPackage), new File(outputModel, baseModelPackage));
    //no exception
    ClassLoader cl = KotlinTestUtils.buildModule(Collections.singletonList(outputModel.getAbsolutePath()), Thread.currentThread().getContextClassLoader());
}
 
Example #11
Source File: RubyClientCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test(description = "test allOf (OAS3)")
public void allOfTestLegacy() {
    final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/allOf.yaml");
    final RubyClientCodegen codegen = new RubyClientCodegen();
    // codegen.discriminatorExplicitMappingVerbose == false by default
    codegen.setModuleName("OnlinePetstore");

    final Schema schema = openAPI.getComponents().getSchemas().get("Person");
    codegen.setOpenAPI(openAPI);
    CodegenModel person = codegen.fromModel("Person", schema);
    Assert.assertNotNull(person);

    CodegenDiscriminator codegenDiscriminator = person.getDiscriminator();
    Set<CodegenDiscriminator.MappedModel> mappedModels = new LinkedHashSet<CodegenDiscriminator.MappedModel>();
    mappedModels.add(new CodegenDiscriminator.MappedModel("a", "Adult"));
    mappedModels.add(new CodegenDiscriminator.MappedModel("c", "Child"));
    Assert.assertEquals(codegenDiscriminator.getMappedModels(), mappedModels);
}
 
Example #12
Source File: VaadinConnectTsGenerator.java    From flow with Apache License 2.0 6 votes vote down vote up
@Override
public CodegenOperation fromOperation(String path, String httpMethod,
        Operation operation, Map<String, Schema> schemas, OpenAPI openAPI) {
    if (!"POST".equalsIgnoreCase(httpMethod)) {
        throw getGeneratorException(
                "Code generator only supports POST requests.");
    }
    Matcher matcher = PATH_REGEX.matcher(path);
    if (!matcher.matches()) {
        throw getGeneratorException(
                "Path must be in form of \"/<EndpointName>/<MethodName>\".");
    }
    CodegenOperation codegenOperation = super.fromOperation(path,
            httpMethod, operation, schemas, openAPI);
    String endpointName = matcher.group(1);
    String methodName = matcher.group(2);
    codegenOperation.getVendorExtensions()
            .put(EXTENSION_VAADIN_CONNECT_METHOD_NAME, methodName);
    codegenOperation.getVendorExtensions()
            .put(EXTENSION_VAADIN_CONNECT_SERVICE_NAME, endpointName);
    validateOperationTags(path, httpMethod, operation);
    return codegenOperation;
}
 
Example #13
Source File: EncodingHeadersKeysCaseValidatorTest.java    From servicecomb-toolkit with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidate2() {
  OpenAPI openAPI = loadRelative("petstore-encoding-headers-key-case-2.yaml");
  OasSpecValidator oasSpecValidator = oasSpecValidator();

  List<OasViolation> violations = oasSpecValidator.validate(createContext(openAPI), openAPI);
  assertThat(violations).containsExactlyInAnyOrder(
      createViolation(
          EncodingHeadersKeysCaseValidator.ERROR + "upper-hyphen-case",
          "paths", PATHS,
          "/pets", PATH_ITEM,
          "post", OPERATION,
          "responses", RESPONSES,
          "default", RESPONSE,
          "content.'application/json'", MEDIA_TYPE,
          "encoding.'foo'", ENCODING,
          "headers.'foo-bar'", null
      )
  );
}
 
Example #14
Source File: ModelUtils.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
private static void visitParameters(OpenAPI openAPI, List<Parameter> parameters, OpenAPISchemaVisitor visitor,
                                    List<String> visitedSchemas) {
    if (parameters != null) {
        for (Parameter p : parameters) {
            Parameter parameter = getReferencedParameter(openAPI, p);
            if (parameter != null) {
                if (parameter.getSchema() != null) {
                    visitSchema(openAPI, parameter.getSchema(), null, visitedSchemas, visitor);
                }
                visitContent(openAPI, parameter.getContent(), visitor, visitedSchemas);
            } else {
                once(LOGGER).warn("Unreferenced parameter(s) found.");
            }
        }
    }
}
 
Example #15
Source File: CsharpModelEnumTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test(description = "use default suffixes for enums")
public void useDefaultEnumSuffixes() {
    final AspNetCoreServerCodegen codegen = new AspNetCoreServerCodegen();

    OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/petstore.yaml");
    codegen.setOpenAPI(openAPI);

    final Schema petSchema = openAPI.getComponents().getSchemas().get("Pet");
    final CodegenModel cm = codegen.fromModel("Pet", petSchema);
    final CodegenProperty statusProperty = cm.vars.get(5);
    Assert.assertEquals(statusProperty.name, "Status");
    Assert.assertTrue(statusProperty.isEnum);
    Assert.assertEquals(statusProperty.datatypeWithEnum, "StatusEnum");

    Assert.assertEquals(codegen.toEnumVarName("Aaaa", ""), "AaaaEnum");
}
 
Example #16
Source File: InputModeller.java    From tcases with MIT License 6 votes vote down vote up
/**
 * Returns the variable definition(s) for headers in the given response.
 */
private Optional<IVarDef> responseHeadersVar( OpenAPI api, String status, ApiResponse response)
  {
  return
    resultFor( "headers",
      () -> {
      List<String> headerNames =
        Optional.ofNullable( response.getHeaders())
        .map( headers -> headers.keySet().stream().filter( name -> !name.equals( "Content-Type")).collect( toList()))
        .orElse( emptyList());

      return
        Optional.ofNullable( headerNames.isEmpty()? null : headerNames)
        .map( names -> {
          return
            VarSetBuilder.with( "Headers")
            .members(
              names.stream()
              .map( name -> responseHeaderVar( api, status, name, resolveHeader( api, response.getHeaders().get( name)))))
            .build();
          });
      });
  }
 
Example #17
Source File: OpenApiUtils.java    From tcases with MIT License 6 votes vote down vote up
/**
 * Returns the given schema after resolving schemas referenced by any "allOf", "anyOf", or "oneOf" members.
 */
public static ComposedSchema resolveSchemaMembers( OpenAPI api, ComposedSchema composed)
  {
  // Resolve "allOf" schemas
  composed.setAllOf(
    Optional.ofNullable( composed.getAllOf()).orElse( emptyList())
    .stream()
    .map( member -> resolveSchema( api, member))
    .collect( toList()));
    
  // Resolve "anyOf" schemas
  composed.setAnyOf(
    Optional.ofNullable( composed.getAnyOf()).orElse( emptyList())
    .stream()
    .map( member -> resolveSchema( api, member))
    .collect( toList()));
    
  // Resolve "oneOf" schemas
  composed.setOneOf(
    Optional.ofNullable( composed.getOneOf()).orElse( emptyList())
    .stream()
    .map( member -> resolveSchema( api, member))
    .collect( toList()));

  return composed;
  }
 
Example #18
Source File: SchemaPropertiesKeysCaseValidatorTest.java    From servicecomb-toolkit with Apache License 2.0 6 votes vote down vote up
@Test
public void testResponse2() {
  OpenAPI openAPI = loadRelative("petstore-schema-p-keys-lower-camel-case-resp-2.yaml");
  OasSpecValidator oasSpecValidator = createOasSpecValidator();
  List<OasViolation> violations = oasSpecValidator.validate(createContext(openAPI), openAPI);
  assertThat(violations).containsExactlyInAnyOrder(
    createViolation(
      SchemaPropertiesKeysCaseValidator.ERROR + "lower-camel-case",
      "components", COMPONENTS,
      "responses.'Foo'", RESPONSE,
      "content.'application/json'", MEDIA_TYPE,
      "schema", SCHEMA,
      "properties.'Foo'", null
    )
  );
}
 
Example #19
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 #20
Source File: OpenAPICodegenUtils.java    From product-microgateway with Apache License 2.0 6 votes vote down vote up
/**
 * Get http, https and mutualSSL from API Definition x-wso2-transport and x-wso2-mutual-ssl extensions.
 *
 * @param api       Extended api
 * @param openAPI   API definition
 */
private static void populateTransportSecurity(ExtendedAPI api, OpenAPI openAPI) throws CLIRuntimeException {
    List<String> transports = new ArrayList<>();
    String mutualSSL = null;
    Map<String, Object> apiDefExtensions = openAPI.getExtensions();
    if (apiDefExtensions.containsKey(OpenAPIConstants.MUTUAL_SSL)) {
        if (logger.isDebugEnabled()) {
            logger.debug(OpenAPIConstants.MUTUAL_SSL + " extension found in the API Definition");
        }
        mutualSSL = validateMutualSSL(apiDefExtensions.get(OpenAPIConstants.MUTUAL_SSL), openAPI);
        api.setMutualSSL(mutualSSL);
    }
    if (apiDefExtensions.containsKey(OpenAPIConstants.TRANSPORT_SECURITY)) {
        if (logger.isDebugEnabled()) {
            logger.debug(OpenAPIConstants.TRANSPORT_SECURITY + " extension found in the API Definition");
        }
        transports = validateTransports(apiDefExtensions.get(OpenAPIConstants.TRANSPORT_SECURITY), mutualSSL,
                openAPI);
    }
    if (transports.isEmpty()) {
        transports = Arrays.asList(OpenAPIConstants.TRANSPORT_HTTP, OpenAPIConstants.TRANSPORT_HTTPS);
    }
    api.setTransport(transports);
}
 
Example #21
Source File: OpenAPICodegenUtils.java    From product-microgateway with Apache License 2.0 6 votes vote down vote up
/**
 * Convert the v2 or v3 open API definition in yaml or json format into json format of the respective format.
 * v2/YAML -> v2/JSON
 * v3/YAML -> v3/JSON
 *
 * @param openAPIContent open API as a string content
 * @return openAPI definition as a JSON String
 */
public static String getOpenAPIAsJson(OpenAPI openAPI, String openAPIContent, Path openAPIPath) {
    String jsonOpenAPI = Json.pretty(openAPI);
    String openAPIVersion;
    Path fileName = openAPIPath.getFileName();

    if (fileName == null) {
        throw new CLIRuntimeException("Error: Couldn't resolve OpenAPI file name.");
    } else if (fileName.toString().endsWith("json")) {
        openAPIVersion = findSwaggerVersion(openAPIContent, false);
    } else {
        openAPIVersion = findSwaggerVersion(jsonOpenAPI, false);
    }

    switch (openAPIVersion) {
        case "2":
            Swagger swagger = new SwaggerParser().parse(openAPIContent);
            return Json.pretty(swagger);
        case "3":
            return jsonOpenAPI;

        default:
            throw new CLIRuntimeException("Error: Swagger version is not identified");
    }
}
 
Example #22
Source File: OperationDeleteNotAllowedDiffValidatorTest.java    From servicecomb-toolkit with Apache License 2.0 6 votes vote down vote up
@Test
public void validate() {
  OpenAPI leftOpenAPI = loadRelative("petstore-operation-delete-a.yaml");
  OpenAPI rightOpenAPI = loadRelative("petstore-operation-delete-b.yaml");
  List<OasDiffViolation> violations = oasSpecDiffValidator
    .validate(createContext(leftOpenAPI, rightOpenAPI), leftOpenAPI, rightOpenAPI);

  assertThat(violations)
    .containsExactlyInAnyOrder(
      createViolationLeft(
        DiffViolationMessages.OP_DEL_FORBIDDEN,
        new Object[] {
          "paths", PATHS,
          "/pets", PATH_ITEM,
          "post", OPERATION
        }
      )
    );

}
 
Example #23
Source File: OpenAPICodegenUtils.java    From product-microgateway with Apache License 2.0 6 votes vote down vote up
/**
 * store the security schemas of type "basic" and "apikey".
 *
 * @param openAPI {@link OpenAPI} object
 */
public static void setSecuritySchemaList(OpenAPI openAPI) {
    //Since the security schema list needs to instantiated per each API
    basicSecuritySchemaList = new ArrayList<>();
    apiKeySecuritySchemaMap = new HashMap();
    if (openAPI.getComponents() == null || openAPI.getComponents().getSecuritySchemes() == null) {
        return;
    }
    openAPI.getComponents().getSecuritySchemes().forEach((key, val) -> {
        if (val.getType() == SecurityScheme.Type.HTTP &&
                val.getScheme().toLowerCase(Locale.getDefault()).equals("basic")) {
            basicSecuritySchemaList.add(key);
        } else if (val.getType() == SecurityScheme.Type.APIKEY) {
            APIKey apiKey = new APIKey(val.getIn(), val.getName());
            apiKeySecuritySchemaMap.put(key, apiKey);
        }
    });
}
 
Example #24
Source File: OpenAPIParserTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssueRelativeRefs1(){
    String location = "specs2/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("test-api-schema_v01").getProperties().get("testingApi") instanceof ArraySchema);

    ArraySchema arraySchema = (ArraySchema) schemas.get("test-api-schema_v01").getProperties().get("testingApi");
    Schema prop = (Schema) arraySchema.getItems().getProperties().get("itemID");

    assertEquals(prop.get$ref(),"#/components/schemas/simpleIDType_v01");
}
 
Example #25
Source File: ResolverCache.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
public ResolverCache(OpenAPI openApi, List<AuthorizationValue> auths, String parentFileLocation) {
    this.openApi = openApi;
    this.auths = auths;
    this.rootPath = parentFileLocation;

    if(parentFileLocation != null) {
        if(parentFileLocation.startsWith("http")) {
            parentDirectory = null;
        } else {
            parentDirectory = PathUtils.getParentDirectoryOfFile(parentFileLocation);
        }
    } else {
        File file = new File(".");
        parentDirectory = file.toPath();
    }

}
 
Example #26
Source File: JavaModelTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test(description = "translate an invalid param name")
public void invalidParamNameTest() {
    final Schema schema = new Schema()
            .description("a model with a 2nd char upper-case property names")
            .addProperties("_", new StringSchema());
    final DefaultCodegen codegen = new JavaClientCodegen();
    OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", schema);
    codegen.setOpenAPI(openAPI);
    final CodegenModel cm = codegen.fromModel("sample", schema);

    Assert.assertEquals(cm.name, "sample");
    Assert.assertEquals(cm.classname, "Sample");
    Assert.assertEquals(cm.vars.size(), 1);

    final CodegenProperty property = cm.vars.get(0);
    Assert.assertEquals(property.baseName, "_");
    Assert.assertEquals(property.getter, "getU");
    Assert.assertEquals(property.setter, "setU");
    Assert.assertEquals(property.dataType, "String");
    Assert.assertEquals(property.name, "u");
    Assert.assertEquals(property.defaultValue, null);
    Assert.assertEquals(property.baseType, "String");
    Assert.assertFalse(property.hasMore);
    Assert.assertFalse(property.isContainer);
}
 
Example #27
Source File: InputModeller.java    From tcases with MIT License 6 votes vote down vote up
/**
 * Returns the variable definitions for the given response definitions.
 */
private Stream<IVarDef> responseVars( OpenAPI api, ApiResponses responses)
  {
  return
    responses.keySet().stream()
    .map( status -> {
      return
        resultFor( status,
          () ->  {
          ApiResponse response = resolveResponse( api, responses.get( status));
          String statusValueName = status.equals( "default")? "Other" : status;
          return
            VarSetBuilder.with( statusValueName)
            .when( has( statusCodeProperty( statusValueName)))
            .type( "response")
            .members( iterableOf( responseHeadersVar( api, status, response)))
            .members( responseContentVar( api, status, response))
            .build();
          });
      });
  }
 
Example #28
Source File: DefaultCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void testDiscriminator() {
    final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml");
    DefaultCodegen codegen = new DefaultCodegen();

    Schema animal = openAPI.getComponents().getSchemas().get("Animal");
    codegen.setOpenAPI(openAPI);
    CodegenModel animalModel = codegen.fromModel("Animal", animal);
    CodegenDiscriminator discriminator = animalModel.getDiscriminator();
    CodegenDiscriminator test = new CodegenDiscriminator();
    test.setPropertyName("className");
    test.setPropertyBaseName("className");
    test.getMappedModels().add(new CodegenDiscriminator.MappedModel("Dog", "Dog"));
    test.getMappedModels().add(new CodegenDiscriminator.MappedModel("Cat", "Cat"));
    test.getMappedModels().add(new CodegenDiscriminator.MappedModel("BigCat", "BigCat"));
    Assert.assertEquals(discriminator, test);
}
 
Example #29
Source File: V2ConverterTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test(description = "Nice to have: Convert x-nullable to nullable")
public void testIssue35() throws Exception {
    OpenAPI oas = getConvertedOpenAPIFromJsonFile(ISSUE_35_JSON);
    Operation getOperation = oas.getPaths().get(FOO_PATH).getGet();
    assertNotNull(getOperation);
    List<Parameter> parameters = getOperation.getParameters();
    assertNotNull(parameters);
    assertEquals(parameters.get(0).getSchema().getNullable(), Boolean.TRUE);
    assertEquals(parameters.get(1).getSchema().getNullable(), Boolean.FALSE);
    assertEquals(parameters.get(2).getSchema().getNullable(), Boolean.TRUE);
    assertEquals(getOperation.getResponses().get("200").getContent().get("*/*").getSchema().getNullable(),
            Boolean.TRUE);
    Schema user = oas.getComponents().getSchemas().get(USER_MODEL);
    assertNotNull(user);
    assertEquals(user.getNullable(), Boolean.TRUE);
    assertEquals(((Schema) user.getProperties().get(ID)).getNullable(), Boolean.TRUE);
}
 
Example #30
Source File: PhpModelTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test(description = "convert a model with list property")
public void listPropertyTest() {
    final Schema model = new Schema()
            .description("a sample model")
            .addProperties("id", new IntegerSchema())
            .addProperties("urls", new ArraySchema()
                    .items(new StringSchema()))
            .addRequiredItem("id");
    final DefaultCodegen codegen = new PhpClientCodegen();
    OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
    codegen.setOpenAPI(openAPI);
    final CodegenModel cm = codegen.fromModel("sample", model);

    Assert.assertEquals(cm.name, "sample");
    Assert.assertEquals(cm.classname, "Sample");
    Assert.assertEquals(cm.description, "a sample model");
    Assert.assertEquals(cm.vars.size(), 2);

    final CodegenProperty property1 = cm.vars.get(0);
    Assert.assertEquals(property1.baseName, "id");
    Assert.assertEquals(property1.dataType, "int");
    Assert.assertEquals(property1.name, "id");
    Assert.assertEquals(property1.defaultValue, null);
    Assert.assertEquals(property1.baseType, "int");
    Assert.assertTrue(property1.hasMore);
    Assert.assertTrue(property1.required);
    Assert.assertTrue(property1.isPrimitiveType);
    Assert.assertFalse(property1.isContainer);

    final CodegenProperty property2 = cm.vars.get(1);
    Assert.assertEquals(property2.baseName, "urls");
    Assert.assertEquals(property2.dataType, "string[]");
    Assert.assertEquals(property2.name, "urls");
    Assert.assertEquals(property2.baseType, "array");
    Assert.assertFalse(property2.hasMore);
    Assert.assertEquals(property2.containerType, "array");
    Assert.assertFalse(property2.required);
    Assert.assertTrue(property2.isPrimitiveType);
    Assert.assertTrue(property2.isContainer);
}