org.openapitools.codegen.CodegenOperation Java Examples

The following examples show how to use org.openapitools.codegen.CodegenOperation. 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: InfluxJavaGenerator.java    From influxdb-client-java with MIT License 6 votes vote down vote up
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Schema> definitions, OpenAPI openAPI) {

    CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, openAPI);

    //
    // Set base path
    //
    String url;
    if (operation.getServers() != null) {
        url = operation.getServers().get(0).getUrl();
    } else if (openAPI.getPaths().get(path).getServers() != null) {
        url = openAPI.getPaths().get(path).getServers().get(0).getUrl();
    } else {
        url = openAPI.getServers().get(0).getUrl();
    }

    if (!url.equals("/")) {
        op.path = url + op.path;
    }

    return op;
}
 
Example #2
Source File: JavaVertXWebServerCodegen.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs, List<Object> allModels) {
    Map<String, Object> newObjs = super.postProcessOperationsWithModels(objs, allModels);
    Map<String, Object> operations = (Map<String, Object>) newObjs.get("operations");
    if (operations != null) {
        List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
        for (CodegenOperation operation : ops) {
            operation.httpMethod = operation.httpMethod.toLowerCase(Locale.ROOT);

            if (operation.returnType == null) {
                operation.returnType = "Void";
            }
        }
    }
    return newObjs;
}
 
Example #3
Source File: PhpLumenServerCodegen.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs, List<Object> allModels) {
    @SuppressWarnings("unchecked")
    Map<String, Object> objectMap = (Map<String, Object>) objs.get("operations");
    @SuppressWarnings("unchecked")
    List<CodegenOperation> operations = (List<CodegenOperation>) objectMap.get("operation");

    for (CodegenOperation op : operations) {
        op.httpMethod = op.httpMethod.toLowerCase(Locale.ROOT);
    }

    // sort the endpoints in ascending to avoid the route priority issure. 
    Collections.sort(operations, new Comparator<CodegenOperation>() {
        @Override
        public int compare(CodegenOperation lhs, CodegenOperation rhs) {
            return lhs.path.compareTo(rhs.path);
        }
    });

    escapeMediaType(operations);

    return objs;
}
 
Example #4
Source File: BashTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test(description = "test basic petstore operation with example body")
public void petstoreParameterExampleTest() {

    final OpenAPI openAPI
        = TestUtils.parseFlattenSpec("src/test/resources/2_0/petstore-bash.json");
    final DefaultCodegen codegen = new BashClientCodegen();
    codegen.setOpenAPI(openAPI);
    final Operation addPetOperation
        = openAPI.getPaths().get("/pet").getPost();

    final CodegenOperation op
        = codegen.fromOperation(
            "/pet",
            "POST",
            addPetOperation,
            null);

    Assert.assertEquals(op.bodyParams.size(), 1);

    CodegenParameter p = op.bodyParams.get(0);

    Assert.assertTrue(p.vendorExtensions
                        .containsKey("x-codegen-body-example"));
    Assert.assertEquals(p.description, "Pet object that needs to be added to the store");

}
 
Example #5
Source File: Swift4CodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test(description = "returns Data when response format is binary", enabled = true)
public void binaryDataTest() {
    // TODO update json file

    final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/2_0/binaryDataTest.json");
    final DefaultCodegen codegen = new Swift4Codegen();
    codegen.setOpenAPI(openAPI);
    final String path = "/tests/binaryResponse";
    final Operation p = openAPI.getPaths().get(path).getPost();
    final CodegenOperation op = codegen.fromOperation(path, "post", p, null);

    Assert.assertEquals(op.returnType, "URL");
    Assert.assertEquals(op.bodyParam.dataType, "URL");
    Assert.assertTrue(op.bodyParam.isBinary);
    Assert.assertTrue(op.responses.get(0).isBinary);
}
 
Example #6
Source File: JavaCXFExtServerCodegen.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
private void appendRandomShort(StringBuilder buffer, CodegenOperation op, CodegenVariable var) {
    if (!appendRandomEnum(buffer, op, var)) {
        // NOTE: use int to hold short values, to avoid numeric overflow.
        int min = var == null || var.minimum == null ? Short.MIN_VALUE : Short.parseShort(var.minimum);
        int max = var == null || var.maximum == null ? Short.MAX_VALUE : Short.parseShort(var.maximum);
        int exclusiveMin = var != null && var.exclusiveMinimum ? 1 : 0;
        int inclusiveMax = var == null || !var.exclusiveMaximum ? 1 : 0;
        short randomShort = (short) (min + exclusiveMin
                + ((max + inclusiveMax - min - exclusiveMin) * Math.random()));

        if (loadTestDataFromFile)
            var.addTestData(randomShort);
        else
            buffer.append(String.format(Locale.getDefault(), "(short)%d", randomShort));
    }
}
 
Example #7
Source File: JavaCXFExtServerCodegen.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
private void appendRandomLong(StringBuilder buffer, CodegenOperation op, CodegenVariable var) {
    if (!appendRandomEnum(buffer, op, var)) {
        // NOTE: use BigDecimal to hold long values, to avoid numeric overflow.
        BigDecimal min = new BigDecimal(
                var == null || var.minimum == null ? Long.MIN_VALUE : Long.parseLong(var.minimum));
        BigDecimal max = new BigDecimal(
                var == null || var.maximum == null ? Long.MAX_VALUE : Long.parseLong(var.maximum));
        BigDecimal exclusiveMin = new BigDecimal(var != null && var.exclusiveMinimum ? 1 : 0);
        BigDecimal inclusiveMax = new BigDecimal(var == null || !var.exclusiveMaximum ? 1 : 0);
        long randomLong = min.add(exclusiveMin).add(
                max.add(inclusiveMax).subtract(min).subtract(exclusiveMin).multiply(new BigDecimal(Math.random())))
                .longValue();

        if (loadTestDataFromFile)
            var.addTestData(randomLong);
        else
            buffer.append(randomLong).append('L');
    }
}
 
Example #8
Source File: JavaCXFExtServerCodegen.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
private void appendRandomFloat(StringBuilder buffer, CodegenOperation op, CodegenVariable var) {
    if (!appendRandomEnum(buffer, op, var)) {
        // NOTE: use double to hold float values, to avoid numeric overflow.
        double min = var == null || var.minimum == null ? -Float.MAX_VALUE : Float.parseFloat(var.minimum);
        double max = var == null || var.maximum == null ? Float.MAX_VALUE : Float.parseFloat(var.maximum);
        double exclusiveMin = (double) (var != null && var.exclusiveMinimum ? 1 : 0);
        double inclusiveMax = (double) (var == null || !var.exclusiveMaximum ? 1 : 0);
        float randomFloat = (float) (min + exclusiveMin
                + ((max + inclusiveMax - min - exclusiveMin) * Math.random()));

        if (loadTestDataFromFile)
            var.addTestData(randomFloat);
        else
            buffer.append(String.format(Locale.getDefault(), "%g", randomFloat)).append('F');
    }
}
 
Example #9
Source File: JavaCXFExtServerCodegen.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
private void appendRandomDouble(StringBuilder buffer, CodegenOperation op, CodegenVariable var) {
    if (!appendRandomEnum(buffer, op, var)) {
        // NOTE: use BigDecimal to hold double values, to avoid numeric overflow.
        BigDecimal min = new BigDecimal(
                var == null || var.minimum == null ? Long.MIN_VALUE : Double.parseDouble(var.minimum));
        BigDecimal max = new BigDecimal(
                var == null || var.maximum == null ? Long.MAX_VALUE : Double.parseDouble(var.maximum));
        BigDecimal exclusiveMin = new BigDecimal(var != null && var.exclusiveMinimum ? 1 : 0);
        BigDecimal inclusiveMax = new BigDecimal(var == null || !var.exclusiveMaximum ? 1 : 0);
        BigDecimal randomBigDecimal = min.add(exclusiveMin).add(max.add(inclusiveMax).subtract(min)
                .subtract(exclusiveMin).multiply(new BigDecimal(String.valueOf(Math.random()))));

        if (loadTestDataFromFile)
            var.addTestData(randomBigDecimal);
        else
            buffer.append(randomBigDecimal.toString()).append('D');
    }
}
 
Example #10
Source File: JavaCXFExtServerCodegen.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
private void appendRandomChar(StringBuilder buffer, CodegenOperation op, CodegenVariable var) {
    if (!appendRandomEnum(buffer, op, var)) {
        // TODO: consider whether to broaden the default range.
        // NOTE: char is unsigned, so there's no overflow issue in computing (max - min).
        char min = var == null || var.minimum == null ? 'a' : var.minimum.charAt(0);
        char max = var == null || var.maximum == null ? 'z' : var.maximum.charAt(0);
        char exclusiveMin = (char) (var != null && var.exclusiveMinimum ? 1 : 0);
        char inclusiveMax = (char) (var == null || !var.exclusiveMaximum ? 1 : 0);
        char randomChar = (char) (min + exclusiveMin + ((max + inclusiveMax - min - exclusiveMin) * Math.random()));

        if (loadTestDataFromFile)
            var.addTestData(randomChar);
        else
            buffer.append(String.format(Locale.getDefault(), "'%c'", randomChar));
    }
}
 
Example #11
Source File: PythonClientCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test(description = "test regex patterns")
public void testRegularExpressionOpenAPISchemaVersion3() {
    final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/issue_1517.yaml");
    final PythonClientCodegen codegen = new PythonClientCodegen();
    codegen.setOpenAPI(openAPI);
    final String path = "/ping";
    final Operation p = openAPI.getPaths().get(path).getGet();
    final CodegenOperation op = codegen.fromOperation(path, "get", p, null);
    // pattern_no_forward_slashes '^pattern$'
    Assert.assertEquals(op.allParams.get(0).pattern, "/^pattern$/");
    // pattern_two_slashes '/^pattern$/'
    Assert.assertEquals(op.allParams.get(1).pattern, "/^pattern$/");
    // pattern_dont_escape_backslash '/^pattern\d{3}$/'
    Assert.assertEquals(op.allParams.get(2).pattern, "/^pattern\\d{3}$/");
    // pattern_dont_escape_escaped_forward_slash '/^pattern\/\d{3}$/'
    Assert.assertEquals(op.allParams.get(3).pattern, "/^pattern\\/\\d{3}$/");
    // pattern_escape_unescaped_forward_slash '^pattern/\d{3}$'
    Assert.assertEquals(op.allParams.get(4).pattern, "/^pattern\\/\\d{3}$/");
    // pattern_with_modifiers '/^pattern\d{3}$/i
    Assert.assertEquals(op.allParams.get(5).pattern, "/^pattern\\d{3}$/i");
}
 
Example #12
Source File: Swift5ClientCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test(description = "returns Data when response format is binary", enabled = true)
public void binaryDataTest() {
    // TODO update json file

    final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/2_0/binaryDataTest.json");
    final DefaultCodegen codegen = new Swift5ClientCodegen();
    codegen.setOpenAPI(openAPI);
    final String path = "/tests/binaryResponse";
    final Operation p = openAPI.getPaths().get(path).getPost();
    final CodegenOperation op = codegen.fromOperation(path, "post", p, null);

    Assert.assertEquals(op.returnType, "URL");
    Assert.assertEquals(op.bodyParam.dataType, "URL");
    Assert.assertTrue(op.bodyParam.isBinary);
    Assert.assertTrue(op.responses.get(0).isBinary);
}
 
Example #13
Source File: JavaCXFExtServerCodegen.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
private void appendObjectValue(StringBuilder buffer, String indent, CodegenOperation op, CodegenVariable var,
                               String localVar, Collection<String> localVars, Map<String, CodegenModel> models) {

    if ("Object".equals(var.dataType)) {
        // Jackson can't serialize java.lang.Object, so we'll provide an empty JSON ObjectNode instead.
        if (loadTestDataFromFile)
            var.addTestData(JsonNodeFactory.instance.objectNode());
        else
            buffer.append("JsonNodeFactory.instance.objectNode();");
    } else {
        if (needToImport(var.dataType))
            op.imports.add(var.dataType);
        if (!loadTestDataFromFile)
            buffer.append("new ").append(var.dataType).append("();");
        appendPropertyAssignments(buffer, indent, op, var, localVar, localVars, models);
    }
}
 
Example #14
Source File: JavaCXFExtServerCodegen.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
private void appendPropertyAssignments(StringBuilder buffer, String indent, CodegenOperation op,
                                       CodegenVariable parent, String localVar, Collection<String> localVars, Map<String, CodegenModel> models) {

    CodegenModel cm = models.get(parent.dataType);
    if (cm != null) { // TODO: handle isArrayModel and isMapModel
        for (CodegenProperty cp : cm.allVars) {
            CodegenVariable var = new CodegenVariable(parent, cp, null, models);
            if (var.isContainer || !var.isPrimitiveType) {
                String containerVar = appendLocalVariable(buffer, indent, op, var, localVars, models);
                if (!loadTestDataFromFile) {
                    buffer.append(NL).append(indent).append(localVar).append('.').append(var.setter).append('(')
                            .append(containerVar);
                }
            } else {
                // No need to use a local variable for types which can be initialised with a single expression.
                if (!loadTestDataFromFile)
                    buffer.append(NL).append(indent).append(localVar).append('.').append(var.setter).append('(');
                appendValue(buffer, indent, op, var, localVar, localVars, models);
            }
            if (!loadTestDataFromFile)
                buffer.append(");");
        }
    }
}
 
Example #15
Source File: JavaCXFExtServerCodegen.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Declares and initialises a local variable of the specified type.
 *
 * @param buffer
 * @param indent
 * @param op
 * @param var
 * @param localVars
 * @param models
 *
 * @return <code>localVar</code> with a numeric suffix if necessary to ensure uniqueness.
 */
private String appendLocalVariable(StringBuilder buffer, String indent, CodegenOperation op, CodegenVariable var,
                                   Collection<String> localVars, Map<String, CodegenModel> models) {

    // Ensure that we're using a unique local variable name (to avoid typing and overwriting conflicts).
    String localVar = var.name;
    for (int i = 2; localVars.contains(localVar); i++)
        localVar = var.name + i;
    localVars.add(localVar);

    if (!loadTestDataFromFile)
        buffer.append(NL).append(indent).append(var.dataType).append(' ').append(localVar).append(" = ");
    appendValue(buffer, indent, op, var, localVar, localVars, models);
    if (!loadTestDataFromFile)
        appendSemicolon(buffer);

    return localVar;
}
 
Example #16
Source File: AbstractPhpCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void testEscapeMediaType() throws Exception {
    HashMap<String, String> all = new HashMap<>();
    all.put("mediaType", "*/*");
    HashMap<String, String> applicationJson = new HashMap<>();
    applicationJson.put("mediaType", "application/json");

    CodegenOperation codegenOperation = new CodegenOperation();
    codegenOperation.hasProduces = true;
    codegenOperation.produces = Arrays.asList(all, applicationJson);

    final AbstractPhpCodegen codegen = new P_AbstractPhpCodegen();
    codegen.escapeMediaType(Arrays.asList(codegenOperation));

    Assert.assertEquals(codegenOperation.produces.get(0).get("mediaType"), "*_/_*");
    Assert.assertEquals(codegenOperation.produces.get(1).get("mediaType"), "application/json");
}
 
Example #17
Source File: JavaCXFExtServerCodegen.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
private void appendByteArrayValue(StringBuilder buffer, String indent, CodegenOperation op, CodegenVariable var,
                                  String localVar, Collection<String> localVars, Map<String, CodegenModel> models) {

    if (!loadTestDataFromFile)
        buffer.append('"');
    short min = var == null || var.minimum == null ? Byte.MIN_VALUE : Byte.parseByte(var.minimum);
    short max = var == null || var.maximum == null ? Byte.MAX_VALUE : Byte.parseByte(var.maximum);
    short exclusiveMin = (short) (var != null && var.exclusiveMinimum ? 1 : 0);
    short inclusiveMax = (short) (var == null || !var.exclusiveMaximum ? 1 : 0);
    int itemCount = 0;
    if (var != null) {
        itemCount = Math.max(var.itemCount, var.minItems == null ? 1 : Math.max(1, var.minItems));
    }
    byte[] randomBytes = new byte[itemCount];
    for (int i = 0; i < itemCount; i++)
        randomBytes[i] = (byte) (min + exclusiveMin + ((max + inclusiveMax - min - exclusiveMin) * Math.random()));
    String randomBytesBase64 = Base64.getEncoder().encodeToString(randomBytes);
    if (loadTestDataFromFile && var != null)
        var.addTestData(randomBytesBase64);
    else
        buffer.append('"');
}
 
Example #18
Source File: TeiidCodegen.java    From teiid-spring-boot with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs, List<Object> allModels) {
    super.postProcessOperationsWithModels(objs, allModels);
    Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
    List<CodegenOperation> os = (List<CodegenOperation>) operations.get("operation");
    List<TeiidCodegenOperation> newOs = new ArrayList<>();
    for (CodegenOperation o : os) {
        TeiidCodegenOperation tco = new TeiidCodegenOperation(o);
        if (o.returnType == null || o.returnType.contentEquals("Void")) {
            tco.setHasReturn(false);
            o.returnType = "Void";
        }
        newOs.add(tco);
    }
    operations.put("operation", newOs);
    return objs;
}
 
Example #19
Source File: FsharpGiraffeServerCodegen.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Override
protected void processOperation(CodegenOperation operation) {
    super.processOperation(operation);

    // HACK: Unlikely in the wild, but we need to clean operation paths for MVC Routing
    if (operation.path != null) {
        String original = operation.path;
        operation.path = operation.path.replace("?", "/");
        if (!original.equals(operation.path)) {
            LOGGER.warn("Normalized " + original + " to " + operation.path + ". Please verify generated source.");
        }
    }

    // Converts, for example, PUT to HttpPut for controller attributes
    operation.httpMethod = "Http" + operation.httpMethod.substring(0, 1) + operation.httpMethod.substring(1).toLowerCase(Locale.ROOT);
}
 
Example #20
Source File: TypeScriptAxiosClientCodegen.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs, List<Object> allModels) {
    objs = super.postProcessOperationsWithModels(objs, allModels);
    Map<String, Object> vals = (Map<String, Object>) objs.getOrDefault("operations", new HashMap<>());
    List<CodegenOperation> operations = (List<CodegenOperation>) vals.getOrDefault("operation", new ArrayList<>());
    /*
        Filter all the operations that are multipart/form-data operations and set the vendor extension flag
        'multipartFormData' for the template to work with.
     */
    operations.stream()
            .filter(op -> op.hasConsumes)
            .filter(op -> op.consumes.stream().anyMatch(opc -> opc.values().stream().anyMatch("multipart/form-data"::equals)))
            .forEach(op -> op.vendorExtensions.putIfAbsent("multipartFormData", true));
    return objs;
}
 
Example #21
Source File: PerlClientCodegenTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void testIssue677() {
    final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/issue677.yaml");
    final PerlClientCodegen codegen = new PerlClientCodegen();
    codegen.setOpenAPI(openAPI);

    Operation operation = openAPI.getPaths().get("/issue677").getPost();
    CodegenOperation co = codegen.fromOperation("/issue677", "POST", operation, null);
    Assert.assertNotNull(co);
}
 
Example #22
Source File: JavaJerseyServerCodegenTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private List<CodegenOperation> getOperationsList(Map<String, Object> templateData) {
    Assert.assertTrue(templateData.get("operations") instanceof Map);
    Map<String, Object> operations = (Map<String, Object>) templateData.get("operations");
    Assert.assertTrue(operations.get("operation") instanceof List);
    return (List<CodegenOperation>) operations.get("operation");
}
 
Example #23
Source File: GoServerCodegen.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs, List<Object> allModels) {
    objs = super.postProcessOperationsWithModels(objs, allModels);
    @SuppressWarnings("unchecked")
    Map<String, Object> objectMap = (Map<String, Object>) objs.get("operations");
    @SuppressWarnings("unchecked")
    List<CodegenOperation> operations = (List<CodegenOperation>) objectMap.get("operation");

    List<Map<String, String>> imports = (List<Map<String, String>>) objs.get("imports");
    if (imports == null)
        return objs;

    // override imports to only include packages for interface parameters
    imports.clear();

    boolean addedOptionalImport = false;
    boolean addedTimeImport = false;
    boolean addedOSImport = false;
    boolean addedReflectImport = false;
    for (CodegenOperation operation : operations) {
        for (CodegenParameter param : operation.allParams) {
            // import "os" if the operation uses files
            if (!addedOSImport && "*os.File".equals(param.dataType)) {
                imports.add(createMapping("import", "os"));
                addedOSImport = true;
            }

            // import "time" if the operation has a required time parameter.
            if (param.required) {
                if (!addedTimeImport && "time.Time".equals(param.dataType)) {
                    imports.add(createMapping("import", "time"));
                    addedTimeImport = true;
                }
            }
        }
    }

    return objs;
}
 
Example #24
Source File: JavaCXFClientCodegenTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void responseWithoutContent() throws Exception {
    final Schema listOfPets = new ArraySchema().items(new Schema<>().$ref("#/components/schemas/Pet"));
    Operation operation = new Operation()
            .responses(new ApiResponses()
                    .addApiResponse("200",
                            new ApiResponse().description("Return a list of pets")
                                    .content(new Content().addMediaType("application/json",
                                            new MediaType().schema(listOfPets))))
                    .addApiResponse("400", new ApiResponse().description("Error")));
    OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("Pet", new ObjectSchema());
    final JavaCXFClientCodegen codegen = new JavaCXFClientCodegen();
    final CodegenOperation co = codegen.fromOperation("getAllPets", "GET", operation, null);

    Map<String, Object> objs = new HashMap<>();
    objs.put("operations", Collections.singletonMap("operation", Collections.singletonList(co)));
    objs.put("imports", Collections.emptyList());
    codegen.postProcessOperationsWithModels(objs, Collections.emptyList());

    Assert.assertEquals(co.responses.size(), 2);
    CodegenResponse cr1 = co.responses.get(0);
    Assert.assertEquals(cr1.code, "200");
    Assert.assertEquals(cr1.baseType, "Pet");
    Assert.assertEquals(cr1.dataType, "List<Pet>");
    Assert.assertFalse(cr1.vendorExtensions.containsKey("x-java-is-response-void"));

    CodegenResponse cr2 = co.responses.get(1);
    Assert.assertEquals(cr2.code, "400");
    Assert.assertEquals(cr2.baseType, "Void");
    Assert.assertEquals(cr2.dataType, "void");
    Assert.assertEquals(cr2.vendorExtensions.get("x-java-is-response-void"), Boolean.TRUE);
}
 
Example #25
Source File: BashTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test(description = "test basic petstore operation with Bash extensions")
public void petstoreOperationTest() {

    final OpenAPI openAPI
        = TestUtils.parseFlattenSpec("src/test/resources/2_0/petstore-bash.json");
    final DefaultCodegen codegen = new BashClientCodegen();
    codegen.setOpenAPI(openAPI);
    final Operation findPetsByStatusOperation
        = openAPI.getPaths().get("/pet/findByStatus").getGet();

    final CodegenOperation op
        = codegen.fromOperation(
            "/pet/findByStatus",
            "GET",
            findPetsByStatusOperation,
            null);

    Assert.assertTrue(
        op.vendorExtensions.containsKey("x-code-samples"));

    Assert.assertEquals(
        op.vendorExtensions.get("x-bash-codegen-description"),
        "Multiple status 'values' can be provided with comma separated strings");

    Assert.assertEquals(op.allParams.size(), 1);
    CodegenParameter p = op.allParams.get(0);
    Assert.assertEquals(p.description, "Status values that need to be considered for filter");
}
 
Example #26
Source File: AgServerCodegen.java    From agrest with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
    Map<String, Object> objsResult = super.postProcessOperations(objs);

    Map<String, Object> operations = (Map<String, Object>) objsResult.get("operations");

    if (operations != null && !models.isEmpty()) {
        @SuppressWarnings("unchecked")
        List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
        List<AgCodegenOperation> newOps = new ArrayList<AgCodegenOperation>();
        for (CodegenOperation operation : ops) {
            if (models.get(operation.baseName) == null) {
                continue;
            }

            // Removes container from response
            operation.returnType = operation.baseName;
            AgCodegenOperation newOperation = new AgCodegenOperation(operation);
            // Stores model properties to use them as constraints
            populateModelAttributes(newOperation);
            // Stores model relations to use them as constraints
            for (final CodegenProperty prop : models.get(newOperation.baseName)) {
                if (prop.complexType != null && models.keySet().contains(prop.complexType)) {
                    AgCodegenOperation relation = new AgCodegenOperation();
                    relation.returnType = relation.baseName = prop.complexType;
                    relation.bodyParam = new CodegenParameter();
                    relation.bodyParam.paramName = prop.baseName;

                    populateModelAttributes(relation);
                    populateRelations(newOperation, relation);
                }
            }
            newOps.add(newOperation);
        }
        operations.put("operation", newOps);
    }

    return objsResult;
}
 
Example #27
Source File: TypeScriptAngularClientCodegenTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void testOperationIdParser() {
    OpenAPI openAPI = TestUtils.createOpenAPI();
    Operation operation1 = new Operation().operationId("123_test_@#$%_special_tags").responses(new ApiResponses().addApiResponse("201", new ApiResponse().description("OK")));
    openAPI.path("another-fake/dummy/", new PathItem().get(operation1));
    final TypeScriptAngularClientCodegen codegen = new TypeScriptAngularClientCodegen();
    codegen.setOpenAPI(openAPI);

    CodegenOperation co1 = codegen.fromOperation("/another-fake/dummy/", "get", operation1, null);
    org.testng.Assert.assertEquals(co1.operationId, "_123testSpecialTags");

}
 
Example #28
Source File: Swift4CodegenTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test(description = "returns Date when response format is date", enabled = true)
public void dateTest() {
    final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/2_0/datePropertyTest.json");
    final DefaultCodegen codegen = new Swift4Codegen();
    codegen.setOpenAPI(openAPI);
    final String path = "/tests/dateResponse";
    final Operation p = openAPI.getPaths().get(path).getPost();
    final CodegenOperation op = codegen.fromOperation(path, "post", p, null);

    Assert.assertEquals(op.returnType, "Date");
    Assert.assertEquals(op.bodyParam.dataType, "Date");
}
 
Example #29
Source File: DartDioModelTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test(description = "returns DateTime when using `--model-name-prefix`")
public void dateTest() {
    final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/2_0/datePropertyTest.json");
    final DefaultCodegen codegen = new DartDioClientCodegen();
    codegen.setModelNamePrefix("foo");
    codegen.setOpenAPI(openAPI);

    final String path = "/tests/dateResponse";
    final Operation p = openAPI.getPaths().get(path).getPost();
    final CodegenOperation op = codegen.fromOperation(path, "post", p, null);

    Assert.assertEquals(op.returnType, "DateTime");
    Assert.assertEquals(op.bodyParam.dataType, "DateTime");
}
 
Example #30
Source File: GoClientCodegenTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test(description = "test example value for body parameter")
public void bodyParameterTest() {
    final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml");
    final GoClientCodegen codegen = new GoClientCodegen();
    codegen.setOpenAPI(openAPI);
    final String path = "/fake";
    final Operation p = openAPI.getPaths().get(path).getGet();
    final CodegenOperation op = codegen.fromOperation(path, "post", p, null);
    Assert.assertEquals(op.formParams.size(), 2);
    CodegenParameter bp = op.formParams.get(0);
    Assert.assertFalse(bp.isPrimitiveType);
}