private static string RenderRelativeRefsForQueryHelper(
        EndpointMethodMetadata endpointMethodMetadata,
        List <OpenApiParameter>?queryParameters,
        bool useForBadRequest)
    {
        var route = endpointMethodMetadata.Route;

        if (endpointMethodMetadata.ContractParameter is null)
        {
            return(route);
        }

        var routeParameters = endpointMethodMetadata.GetRouteParameters();
        var relativeRefPath = RenderRelativeRefPath(route, routeParameters, routeParameters, endpointMethodMetadata.ComponentsSchemas, useForBadRequest: false);

        if (queryParameters is null ||
            queryParameters.Count == 0)
        {
            return(relativeRefPath);
        }

        var relativeRefQuery = RenderRelativeRefQuery(queryParameters, endpointMethodMetadata.ComponentsSchemas, useForBadRequest);

        return($"{relativeRefPath}{relativeRefQuery}");
    }
    public static void Generate(
        ILogger logger,
        HostProjectOptions hostProjectOptions,
        EndpointMethodMetadata endpointMethodMetadata)
    {
        ArgumentNullException.ThrowIfNull(logger);
        ArgumentNullException.ThrowIfNull(hostProjectOptions);
        ArgumentNullException.ThrowIfNull(endpointMethodMetadata);

        var sb = new StringBuilder();

        AppendUsingStatements(sb, hostProjectOptions, endpointMethodMetadata);
        sb.AppendLine();
        GenerateCodeHelper.AppendGeneratedCodeWarningComment(sb, hostProjectOptions.ToolNameAndVersion);
        AppendNamespaceAndClassStart(sb, hostProjectOptions, endpointMethodMetadata);
        AppendConstructor(sb, endpointMethodMetadata);
        AppendTestMethod(sb, endpointMethodMetadata);

        if (endpointMethodMetadata.IsContractParameterRequestBodyUsedAsMultipartFormData())
        {
            AppendGetMultipartFormDataContentRequestMethod(sb, endpointMethodMetadata, endpointMethodMetadata.IsContractParameterRequestBodyUsedAsMultipartFormDataAndHasInlineSchemaFile());
        }
        else if (endpointMethodMetadata.IsContractParameterRequestBodyUsedAsMultipartOctetStreamData())
        {
            AppendGetSingleFormDataContentRequestMethod(sb, endpointMethodMetadata);
        }

        AppendNamespaceAndClassEnd(sb);
        SaveFile(logger, sb, hostProjectOptions, endpointMethodMetadata);
    }
Exemple #3
0
        private static List <string> RenderRelativeRefsForQuery(EndpointMethodMetadata endpointMethodMetadata, bool useForBadRequest = false)
        {
            var renderRelativeRefs = new List <string>();

            var queryRequiredParameters = endpointMethodMetadata.GetQueryRequiredParameters();

            if (queryRequiredParameters.Count == 0)
            {
                if (!useForBadRequest)
                {
                    // Create without queryParameters
                    renderRelativeRefs.Add(RenderRelativeRefsForQueryHelper(endpointMethodMetadata, null, useForBadRequest));
                }
            }
            else
            {
                var queryParameters = endpointMethodMetadata.GetQueryParameters();
                var combinationOfQueryParameters = ParameterCombinationHelper.GetCombination(queryParameters, useForBadRequest);
                foreach (var parameters in combinationOfQueryParameters)
                {
                    renderRelativeRefs.Add(RenderRelativeRefsForQueryHelper(endpointMethodMetadata, parameters, useForBadRequest));
                }
            }

            return(renderRelativeRefs);
        }
Exemple #4
0
        public static LogKeyValueItem Generate(
            HostProjectOptions hostProjectOptions,
            EndpointMethodMetadata endpointMethodMetadata)
        {
            if (hostProjectOptions == null)
            {
                throw new ArgumentNullException(nameof(hostProjectOptions));
            }

            if (endpointMethodMetadata == null)
            {
                throw new ArgumentNullException(nameof(endpointMethodMetadata));
            }

            var sb = new StringBuilder();

            AppendUsingStatements(sb, hostProjectOptions, endpointMethodMetadata);
            sb.AppendLine();
            GenerateCodeHelper.AppendNamespaceComment(sb, hostProjectOptions.ToolNameAndVersion);
            AppendNamespaceAndClassStart(sb, hostProjectOptions, endpointMethodMetadata);
            AppendConstructor(sb, endpointMethodMetadata);
            AppendTestMethod(sb, endpointMethodMetadata);
            AppendNamespaceAndClassEnd(sb);
            return(SaveFile(sb, hostProjectOptions, endpointMethodMetadata));
        }
Exemple #5
0
        private static string RenderRelativeRefsForPathHelper(EndpointMethodMetadata endpointMethodMetadata, List <OpenApiParameter> allRouteParameters, List <OpenApiParameter> badRouteParameters, bool useForBadRequest)
        {
            var route = endpointMethodMetadata.Route;

            if (endpointMethodMetadata.ContractParameter == null)
            {
                return(route);
            }

            string relativeRefPath = RenderRelativeRefPath(route, allRouteParameters, badRouteParameters, endpointMethodMetadata.ComponentsSchemas, useForBadRequest);

            if (allRouteParameters.Count == 0)
            {
                return(relativeRefPath);
            }

            var queryRequiredParameters = endpointMethodMetadata.GetQueryRequiredParameters();

            if (queryRequiredParameters.Count == 0)
            {
                return(relativeRefPath);
            }

            string relativeRefQuery = RenderRelativeRefQuery(queryRequiredParameters, endpointMethodMetadata.ComponentsSchemas, false);

            return($"{relativeRefPath}{relativeRefQuery}");
        }
        public List <EndpointMethodMetadata> GetMetadataForMethods()
        {
            var list = new List <EndpointMethodMetadata>();
            var hasSharedResponseContract = HasSharedResponseContract();

            foreach (var(key, value) in ApiProjectOptions.Document.GetPathsByBasePathSegmentName(FocusOnSegmentName))
            {
                var generatorParameters = new SyntaxGeneratorContractParameters(ApiProjectOptions, FocusOnSegmentName);
                var generatedParameters = generatorParameters.GenerateSyntaxTrees();

                foreach (var apiOperation in value.Operations)
                {
                    var httpAttributeRoutePart = GetHttpAttributeRoutePart(key);
                    var routePart = string.IsNullOrEmpty(httpAttributeRoutePart)
                        ? $"/{GetRouteSegment()}"
                        : $"/{GetRouteSegment()}/{httpAttributeRoutePart}";
                    var operationName = apiOperation.Value.GetOperationName();

                    string?contractParameterTypeName = null;
                    if (apiOperation.Value.HasParametersOrRequestBody() || value.HasParameters())
                    {
                        contractParameterTypeName = operationName + NameConstants.ContractParameters;
                    }

                    var sgContractParameter = generatedParameters.FirstOrDefault(x => x.ApiOperation.GetOperationName() == operationName);

                    var responseTypeNames = GetResponseTypeNames(apiOperation.Value.Responses, FocusOnSegmentName, operationName);

                    if (contractParameterTypeName != null &&
                        responseTypeNames.FirstOrDefault(x => x.Item1 == HttpStatusCode.BadRequest) == null)
                    {
                        responseTypeNames.Add(
                            new Tuple <HttpStatusCode, string>(
                                HttpStatusCode.BadRequest,
                                "Validation"));
                    }

                    var responseTypeNamesAndItemSchema = GetResponseTypeNamesAndItemSchema(responseTypeNames);

                    var endpointMethodMetadata = new EndpointMethodMetadata(
                        ApiProjectOptions.ApiOptions.Generator.UseNullableReferenceTypes,
                        ApiProjectOptions.ProjectName,
                        FocusOnSegmentName,
                        $"/api/{ApiProjectOptions.ApiVersion}{routePart}",
                        apiOperation.Key,
                        operationName,
                        hasSharedResponseContract,
                        "I" + operationName + NameConstants.ContractHandler,
                        contractParameterTypeName,
                        operationName + NameConstants.ContractResult,
                        responseTypeNamesAndItemSchema,
                        sgContractParameter,
                        ApiProjectOptions.Document.Components.Schemas);

                    list.Add(endpointMethodMetadata);
                }
            }

            return(list);
        }
    private static void AppendTestMethod(
        StringBuilder sb,
        EndpointMethodMetadata endpointMethodMetadata)
    {
        foreach (var contractReturnTypeName in endpointMethodMetadata.ContractReturnTypeNames)
        {
            switch (contractReturnTypeName.StatusCode)
            {
            case HttpStatusCode.OK:
                AppendTest200Ok(sb, endpointMethodMetadata, contractReturnTypeName);
                break;

            case HttpStatusCode.Created:
                AppendTest201Created(sb, endpointMethodMetadata, contractReturnTypeName);
                break;

            case HttpStatusCode.BadRequest:
                AppendTest400BadRequestInPath(sb, endpointMethodMetadata, contractReturnTypeName);
                AppendTest400BadRequestInHeader(sb, endpointMethodMetadata, contractReturnTypeName);
                AppendTest400BadRequestInQuery(sb, endpointMethodMetadata, contractReturnTypeName);
                AppendTest400BadRequestInBody(sb, endpointMethodMetadata, contractReturnTypeName);
                break;
            }
        }
    }
    private static string RenderRelativeRef(
        EndpointMethodMetadata endpointMethodMetadata)
    {
        var queryParameters = endpointMethodMetadata.GetQueryParameters();

        return(RenderRelativeRefsForQueryHelper(endpointMethodMetadata, queryParameters, useForBadRequest: false));
    }
 private static void AppendMethodExecuteAsyncStart(
     StringBuilder sb,
     EndpointMethodMetadata endpointMethodMetadata)
 {
     sb.AppendLine(8, endpointMethodMetadata.ContractParameterTypeName is null
         ? $"public Task<{endpointMethodMetadata.ContractResultTypeName}> ExecuteAsync(CancellationToken cancellationToken = default)"
         : $"public Task<{endpointMethodMetadata.ContractResultTypeName}> ExecuteAsync({endpointMethodMetadata.ContractParameterTypeName} parameters, CancellationToken cancellationToken = default)");
     sb.AppendLine(8, "{");
 }
Exemple #10
0
 private static void AppendUsingStatements(
     StringBuilder sb,
     HostProjectOptions hostProjectOptions,
     EndpointMethodMetadata endpointMethodMetadata)
 {
     foreach (var statement in GetUsingStatements(hostProjectOptions, endpointMethodMetadata))
     {
         sb.AppendLine($"using {statement};");
     }
 }
Exemple #11
0
 private static void AppendNamespaceAndClassStart(
     StringBuilder sb,
     HostProjectOptions hostProjectOptions,
     EndpointMethodMetadata endpointMethodMetadata)
 {
     sb.AppendLine($"namespace {hostProjectOptions.ProjectName}.Tests.Endpoints.{endpointMethodMetadata.SegmentName}.Generated");
     sb.AppendLine("{");
     GenerateCodeHelper.AppendGeneratedCodeAttribute(sb, hostProjectOptions.ToolName, hostProjectOptions.ToolVersion);
     sb.AppendLine(4, $"public class {endpointMethodMetadata.MethodName}HandlerStub : {endpointMethodMetadata.ContractInterfaceHandlerTypeName}");
     sb.AppendLine(4, "{");
 }
        public static string EnsureModelNameWithNamespaceIfNeeded(EndpointMethodMetadata endpointMethodMetadata, string modelName)
        {
            if (endpointMethodMetadata == null)
            {
                throw new ArgumentNullException(nameof(endpointMethodMetadata));
            }

            return(EnsureModelNameWithNamespaceIfNeeded(
                       endpointMethodMetadata.ProjectName,
                       endpointMethodMetadata.SegmentName,
                       modelName));
        }
    public static string EnsureModelNameWithNamespaceIfNeeded(
        EndpointMethodMetadata endpointMethodMetadata,
        string modelName)
    {
        ArgumentNullException.ThrowIfNull(endpointMethodMetadata);

        return(EnsureModelNameWithNamespaceIfNeeded(
                   endpointMethodMetadata.ProjectName,
                   endpointMethodMetadata.SegmentName,
                   modelName,
                   endpointMethodMetadata.IsSharedModel(modelName)));
    }
Exemple #14
0
 private static void AppendNamespaceAndClassStart(
     StringBuilder sb,
     HostProjectOptions hostProjectOptions,
     EndpointMethodMetadata endpointMethodMetadata)
 {
     sb.AppendLine($"namespace {hostProjectOptions.ProjectName}.Tests.Endpoints.{endpointMethodMetadata.SegmentName}.Generated");
     sb.AppendLine("{");
     GenerateCodeHelper.AppendGeneratedCodeAttribute(sb, hostProjectOptions.ToolName, hostProjectOptions.ToolVersion);
     sb.AppendLine(4, "[Collection(\"Sequential-Endpoints\")]");
     sb.AppendLine(4, $"public class {endpointMethodMetadata.MethodName}Tests : WebApiControllerBaseTest");
     sb.AppendLine(4, "{");
 }
        public static void AppendNewModelOrListOfModel(
            int indentSpaces,
            StringBuilder sb,
            EndpointMethodMetadata endpointMethodMetadata,
            OpenApiSchema schema,
            HttpStatusCode httpStatusCode,
            string variableName = "data")
        {
            if (sb == null)
            {
                throw new ArgumentNullException(nameof(sb));
            }

            if (endpointMethodMetadata == null)
            {
                throw new ArgumentNullException(nameof(endpointMethodMetadata));
            }

            if (schema == null)
            {
                throw new ArgumentNullException(nameof(schema));
            }

            var contractReturnTypeName = endpointMethodMetadata.ContractReturnTypeNames.First(x => x.Item1 == httpStatusCode);

            if (!string.IsNullOrEmpty(contractReturnTypeName.Item2) && (
                    contractReturnTypeName.Item2.StartsWith(Microsoft.OpenApi.Models.NameConstants.Pagination, StringComparison.Ordinal) ||
                    contractReturnTypeName.Item2.StartsWith(Microsoft.OpenApi.Models.NameConstants.List, StringComparison.Ordinal)))
            {
                if (contractReturnTypeName.Item2.StartsWith(Microsoft.OpenApi.Models.NameConstants.Pagination, StringComparison.Ordinal))
                {
                    var listDataType = contractReturnTypeName.Item2.Replace(Microsoft.OpenApi.Models.NameConstants.Pagination, Microsoft.OpenApi.Models.NameConstants.List, StringComparison.Ordinal);
                    sb.AppendLine(indentSpaces, $"var {variableName} = new {listDataType}");
                }
                else
                {
                    sb.AppendLine(indentSpaces, $"var {variableName} = new {contractReturnTypeName.Item2}");
                }

                sb.AppendLine(indentSpaces, "{");
                for (int i = 0; i < 3; i++)
                {
                    AppendNewModel(indentSpaces + 4, sb, endpointMethodMetadata.ComponentsSchemas, schema, null, i + 1, null);
                }

                sb.AppendLine(indentSpaces, "};");
            }
            else
            {
                AppendNewModel(indentSpaces, sb, endpointMethodMetadata.ComponentsSchemas, schema, null, 0, variableName);
            }
        }
Exemple #16
0
        private static LogKeyValueItem SaveFile(
            StringBuilder sb,
            HostProjectOptions hostProjectOptions,
            EndpointMethodMetadata endpointMethodMetadata)
        {
            var pathA    = Path.Combine(hostProjectOptions.PathForTestGenerate !.FullName, "Endpoints");
            var pathB    = Path.Combine(pathA, endpointMethodMetadata.SegmentName);
            var pathC    = Path.Combine(pathB, "Generated");
            var fileName = $"{endpointMethodMetadata.MethodName}Tests.cs";
            var file     = new FileInfo(Path.Combine(pathC, fileName));

            return(TextFileHelper.Save(file, sb.ToString()));
        }
Exemple #17
0
        private static void AppendTextContent(
            StringBuilder sb,
            EndpointMethodMetadata endpointMethodMetadata,
            HttpStatusCode testExpectedHttpStatusCode,
            Tuple <HttpStatusCode, string, OpenApiSchema> contractReturnTypeName)
        {
            sb.AppendLine(8, "{");
            if (endpointMethodMetadata.HasContractParameterRequestBody())
            {
                sb.AppendLine(12, "// Arrange");
                var headerParameters = endpointMethodMetadata.GetHeaderParameters();
                if (headerParameters.Count > 0)
                {
                    foreach (var headerParameter in headerParameters)
                    {
                        string propertyValueGenerated = PropertyValueGenerator(headerParameter, endpointMethodMetadata.ComponentsSchemas, false, null);
                        sb.AppendLine(
                            12,
                            $"HttpClient.DefaultRequestHeaders.Add(\"{headerParameter.Name}\", \"{propertyValueGenerated}\");");
                    }

                    sb.AppendLine();
                }

                AppendNewRequestModel(12, sb, endpointMethodMetadata, contractReturnTypeName.Item1);
                sb.AppendLine();
                AppendActHttpClientOperation(12, sb, endpointMethodMetadata.HttpOperation, true);
            }
            else
            {
                AppendActHttpClientOperation(12, sb, endpointMethodMetadata.HttpOperation);
            }

            sb.AppendLine();
            sb.AppendLine(12, "// Assert");
            sb.AppendLine(12, "response.Should().NotBeNull();");
            sb.AppendLine(12, $"response.StatusCode.Should().Be(HttpStatusCode.{testExpectedHttpStatusCode});");

            if (testExpectedHttpStatusCode == HttpStatusCode.OK &&
                !string.IsNullOrEmpty(contractReturnTypeName.Item2) &&
                contractReturnTypeName.Item3 != null && !contractReturnTypeName.Item3.IsSimpleDataType())
            {
                var modelName = OpenApiDocumentSchemaModelNameHelper.EnsureModelNameWithNamespaceIfNeeded(endpointMethodMetadata, contractReturnTypeName.Item2);

                sb.AppendLine();
                sb.AppendLine(12, $"var responseData = await response.DeserializeAsync<{modelName}>(JsonSerializerOptions);");
                sb.AppendLine(12, "responseData.Should().NotBeNull();");
            }

            sb.AppendLine(8, "}");
        }
    private static void AppendTest400BadRequestInHeader(
        StringBuilder sb,
        EndpointMethodMetadata endpointMethodMetadata,
        ResponseTypeNameAndItemSchema contractReturnTypeName)
    {
        var headerRequiredParameters = endpointMethodMetadata.GetHeaderRequiredParameters();
        var testForParameters        = headerRequiredParameters
                                       .Where(x => x.Schema.GetDataType() != OpenApiDataTypeConstants.String)
                                       .ToList();

        if (headerRequiredParameters.Count == 0)
        {
            return;
        }

        var relativeRef = RenderRelativeRef(endpointMethodMetadata);

        foreach (var testForParameter in testForParameters)
        {
            sb.AppendLine();
            sb.AppendLine(8, "[Theory]");
            sb.AppendLine(8, $"[InlineData(\"{relativeRef}\")]");
            sb.AppendLine(8, $"public async Task {endpointMethodMetadata.MethodName}_BadRequest_InHeader_{testForParameter.Name.EnsureFirstCharacterToUpper()}(string relativeRef)");
            sb.AppendLine(8, "{");
            sb.AppendLine(12, "// Arrange");
            if (headerRequiredParameters.Count > 0)
            {
                foreach (var headerParameter in headerRequiredParameters)
                {
                    var useInvalidData         = headerParameter.Name == testForParameter.Name;
                    var propertyValueGenerated = PropertyValueGenerator(headerParameter, endpointMethodMetadata.ComponentsSchemas, useInvalidData, customValue: null);
                    sb.AppendLine(
                        12,
                        $"HttpClient.DefaultRequestHeaders.Add(\"{headerParameter.Name}\", \"{propertyValueGenerated}\");");
                }

                sb.AppendLine();
            }

            AppendNewRequestModel(12, sb, endpointMethodMetadata, contractReturnTypeName.StatusCode);
            sb.AppendLine();
            AppendActHttpClientOperation(12, sb, endpointMethodMetadata.HttpOperation, useData: true);
            sb.AppendLine();
            sb.AppendLine(12, "// Assert");
            sb.AppendLine(12, "response.Should().NotBeNull();");
            sb.AppendLine(12, $"response.StatusCode.Should().Be(HttpStatusCode.{HttpStatusCode.BadRequest});");
            sb.AppendLine(8, "}");
        }
    }
    private static void SaveFile(
        ILogger logger,
        StringBuilder sb,
        HostProjectOptions hostProjectOptions,
        EndpointMethodMetadata endpointMethodMetadata)
    {
        var pathA    = Path.Combine(hostProjectOptions.PathForTestGenerate !.FullName, "Endpoints");
        var pathB    = Path.Combine(pathA, endpointMethodMetadata.SegmentName);
        var pathC    = Path.Combine(pathB, "Generated");
        var fileName = $"{endpointMethodMetadata.MethodName}Tests.cs";
        var file     = new FileInfo(Path.Combine(pathC, fileName));

        var fileDisplayLocation = file.FullName.Replace(hostProjectOptions.PathForTestGenerate.FullName, "test: ", StringComparison.Ordinal);

        TextFileHelper.Save(logger, file, fileDisplayLocation, sb.ToString());
    }
Exemple #20
0
        private static void AppendNewRequestModel(
            int indentSpaces,
            StringBuilder sb,
            EndpointMethodMetadata endpointMethodMetadata,
            HttpStatusCode httpStatusCode,
            string variableName = "data")
        {
            var schema = endpointMethodMetadata.ContractParameter?.ApiOperation.RequestBody?.Content.GetSchema();

            if (schema == null)
            {
                return;
            }

            GenerateXunitTestHelper.AppendNewModelOrListOfModel(indentSpaces, sb, endpointMethodMetadata, schema, httpStatusCode, variableName);
        }
 private static void AppendMethodExecuteAsyncContent(
     StringBuilder sb,
     EndpointMethodMetadata endpointMethodMetadata)
 {
     if (endpointMethodMetadata.ContractReturnTypeNames.Find(x => x.StatusCode == HttpStatusCode.OK) is not null)
     {
         AppendContentForExecuteAsynchronous(sb, endpointMethodMetadata, HttpStatusCode.OK);
     }
     else if (endpointMethodMetadata.ContractReturnTypeNames.Find(x => x.StatusCode == HttpStatusCode.Created) is not null)
     {
         AppendContentForExecuteAsynchronous(sb, endpointMethodMetadata, HttpStatusCode.Created);
     }
     else
     {
         sb.AppendLine(12, "throw new System.NotImplementedException();");
     }
 }
Exemple #22
0
        private static void AppendUsingStatements(
            StringBuilder sb,
            HostProjectOptions hostProjectOptions,
            EndpointMethodMetadata endpointMethodMetadata)
        {
            sb.AppendLine("using System;");
            sb.AppendLine("using System.CodeDom.Compiler;");
            sb.AppendLine("using System.Collections.Generic;");
            sb.AppendLine("using System.Threading;");
            sb.AppendLine("using System.Threading.Tasks;");
            if (endpointMethodMetadata.IsPaginationUsed())
            {
                sb.AppendLine("using Atc.Rest.Results;");
            }

            sb.AppendLine($"using {hostProjectOptions.ProjectName}.Generated.Contracts;");
            sb.AppendLine($"using {hostProjectOptions.ProjectName}.Generated.Contracts.{endpointMethodMetadata.SegmentName};");
        }
Exemple #23
0
        private static void AppendTest200Ok(StringBuilder sb, EndpointMethodMetadata endpointMethodMetadata, Tuple <HttpStatusCode, string, OpenApiSchema> contractReturnTypeName)
        {
            var renderRelativeRefs = RenderRelativeRefsForQuery(endpointMethodMetadata);

            if (renderRelativeRefs.Count == 0)
            {
                return;
            }

            sb.AppendLine();
            sb.AppendLine(8, "[Theory]");
            foreach (var renderRelativeRef in renderRelativeRefs)
            {
                sb.AppendLine(8, $"[InlineData(\"{renderRelativeRef}\")]");
            }

            sb.AppendLine(8, $"public async Task {endpointMethodMetadata.MethodName}_Ok(string relativeRef)");
            AppendTextContent(sb, endpointMethodMetadata, HttpStatusCode.OK, contractReturnTypeName);
        }
Exemple #24
0
        private static List <string> RenderRelativeRefsForBadRequestInPath(EndpointMethodMetadata endpointMethodMetadata, bool useForBadRequest = false)
        {
            var renderRelativeRefs = new List <string>();

            var allRouteParameters        = endpointMethodMetadata.GetRouteParameters();
            var badRequestRouteParameters = FindBadRequestRouteParameters(allRouteParameters);

            if (badRequestRouteParameters.Count <= 0)
            {
                return(renderRelativeRefs);
            }

            var combinationOfRouteParameters = ParameterCombinationHelper.GetCombination(badRequestRouteParameters, useForBadRequest);

            foreach (var parameters in combinationOfRouteParameters)
            {
                renderRelativeRefs.Add(RenderRelativeRefsForPathHelper(endpointMethodMetadata, allRouteParameters, parameters, useForBadRequest));
            }

            return(renderRelativeRefs);
        }
Exemple #25
0
        private static void AppendNewRequestModel(
            int indentSpaces,
            StringBuilder sb,
            EndpointMethodMetadata endpointMethodMetadata,
            HttpStatusCode httpStatusCode)
        {
            var schema = endpointMethodMetadata.ContractParameter?.ApiOperation.RequestBody?.Content.GetSchema();

            if (schema == null)
            {
                return;
            }

            GenerateXunitTestHelper.AppendVarDataModelOrListOfModel(
                indentSpaces,
                sb,
                endpointMethodMetadata,
                schema,
                httpStatusCode,
                SchemaMapLocatedAreaType.RequestBody);
        }
    private static void AppendGetSingleFormDataContentRequestMethod(
        StringBuilder sb,
        EndpointMethodMetadata endpointMethodMetadata)
    {
        var modelName = $"{endpointMethodMetadata.MethodName}{NameConstants.Request}";

        sb.AppendLine();
        sb.AppendLine(8, $"private async Task<MultipartFormDataContent> GetMultipartFormDataContentFrom{modelName}(IFormFile request)");
        sb.AppendLine(8, "{");
        sb.AppendLine(12, "var formDataContent = new MultipartFormDataContent();");

        sb.AppendLine(12, "if (request is not null)");
        sb.AppendLine(12, "{");
        sb.AppendLine(16, "var bytesContent = new ByteArrayContent(await request.GetBytes());");
        sb.AppendLine(16, "formDataContent.Add(bytesContent, \"Request\", request.FileName);");
        sb.AppendLine(12, "}");
        sb.AppendLine();

        sb.AppendLine(12, "return formDataContent;");
        sb.AppendLine(8, "}");
    }
    public static void Generate(
        ILogger logger,
        HostProjectOptions hostProjectOptions,
        EndpointMethodMetadata endpointMethodMetadata)
    {
        ArgumentNullException.ThrowIfNull(logger);
        ArgumentNullException.ThrowIfNull(hostProjectOptions);
        ArgumentNullException.ThrowIfNull(endpointMethodMetadata);

        var sb = new StringBuilder();

        AppendUsingStatements(sb, hostProjectOptions, endpointMethodMetadata);
        sb.AppendLine();
        GenerateCodeHelper.AppendGeneratedCodeWarningComment(sb, hostProjectOptions.ToolNameAndVersion);
        AppendNamespaceAndClassStart(sb, hostProjectOptions, endpointMethodMetadata);
        AppendMethodExecuteAsyncStart(sb, endpointMethodMetadata);
        AppendMethodExecuteAsyncContent(sb, endpointMethodMetadata);
        AppendMethodExecuteAsyncEnd(sb);
        AppendNamespaceAndClassEnd(sb);
        SaveFile(logger, sb, hostProjectOptions, endpointMethodMetadata);
    }
    private static void AppendTest400BadRequestInQuery(
        StringBuilder sb,
        EndpointMethodMetadata endpointMethodMetadata,
        ResponseTypeNameAndItemSchema contractReturnTypeName)
    {
        var renderRelativeRefs = RenderRelativeRefsForQuery(endpointMethodMetadata, useForBadRequest: true);

        if (renderRelativeRefs.Count == 0)
        {
            return;
        }

        sb.AppendLine();
        sb.AppendLine(8, "[Theory]");
        foreach (var renderRelativeRef in renderRelativeRefs)
        {
            sb.AppendLine(8, $"[InlineData(\"{renderRelativeRef}\")]");
        }

        sb.AppendLine(8, $"public async Task {endpointMethodMetadata.MethodName}_BadRequest_InQuery(string relativeRef)");
        AppendTextContent(sb, endpointMethodMetadata, HttpStatusCode.BadRequest, contractReturnTypeName);
    }
Exemple #29
0
        private static List <string> RenderRelativeRefsForPath(EndpointMethodMetadata endpointMethodMetadata, bool useForBadRequest = false)
        {
            var renderRelativeRefs = new List <string>();

            var routeParameters = endpointMethodMetadata.GetRouteParameters()
                                  .Where(x => x.Schema.GetDataType() != OpenApiDataTypeConstants.String)
                                  .ToList();

            if (routeParameters.Count <= 0)
            {
                return(renderRelativeRefs);
            }

            var combinationOfRouteParameters = ParameterCombinationHelper.GetCombination(routeParameters, useForBadRequest);

            foreach (var parameters in combinationOfRouteParameters)
            {
                renderRelativeRefs.Add(RenderRelativeRefsForPathHelper(endpointMethodMetadata, routeParameters, parameters, useForBadRequest));
            }

            return(renderRelativeRefs);
        }
        public static void AppendNewModelOrListOfModelForBadRequest(
            int indentSpaces,
            StringBuilder sb,
            EndpointMethodMetadata endpointMethodMetadata,
            OpenApiSchema schema,
            HttpStatusCode httpStatusCode,
            KeyValuePair <string, OpenApiSchema> badPropertySchema,
            string variableName = "data")
        {
            if (sb == null)
            {
                throw new ArgumentNullException(nameof(sb));
            }

            if (endpointMethodMetadata == null)
            {
                throw new ArgumentNullException(nameof(endpointMethodMetadata));
            }

            if (schema == null)
            {
                throw new ArgumentNullException(nameof(schema));
            }

            var contractReturnTypeName = endpointMethodMetadata.ContractReturnTypeNames.First(x => x.Item1 == httpStatusCode);

            if (!string.IsNullOrEmpty(contractReturnTypeName.Item2) && (
                    contractReturnTypeName.Item2.StartsWith(Microsoft.OpenApi.Models.NameConstants.Pagination, StringComparison.Ordinal) ||
                    contractReturnTypeName.Item2.StartsWith(Microsoft.OpenApi.Models.NameConstants.List, StringComparison.Ordinal)))
            {
                // TO-DO: Imp this.
            }
            else
            {
                AppendNewModelAsJson(indentSpaces, sb, endpointMethodMetadata.ComponentsSchemas, schema, badPropertySchema.Key, 0, variableName);
            }
        }