Example #1
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));
        }
    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);
    }
Example #3
0
        public override string GenerateCode()
        {
            var s = Name.ToLowerInvariant();

            s = "Cmd" + GenerateCodeHelper.ConvertToPascalCase(s);
            return($"public bool {s} {{ get {{ return _args[\"{Name}\"].IsTrue; }} }}");
        }
        public Task <string> RequiredCode(string channel, string type)
        {
            var provider = GetSecurityCodeProvider(type);

            var record = GetCurrentCode(channel, type);

            if (record == null)
            {
                //不存在,生成
                record                 = new SecurityCodeRecord();
                record.Channel         = channel;
                record.Code            = GenerateCodeHelper.GetRandomDigital(provider.GetLenth());
                record.CodeType        = type;
                record.CreateOn        = DateTime.Now;
                record.ExpireTime      = provider.GetExpireTime();
                record.ServiceProvider = _smsChannel.GetSMSProvider();
                record.IsValid         = false;
                _repository.CreateRecord(record);
                _repository.Flush();
            }
            else
            {
                //存在,更新过期时间
                record.ExpireTime = provider.GetExpireTime();
                _repository.UpdateRecord(record);
                _repository.Flush();
            }

            return(Task.FromResult(record.Code));
        }
        public void ConvertDashesToCamelCase_all_uppercase_letters()
        {
            var input    = "STRING-WITH-DASHES";
            var expected = "STRINGWITHDASHES";
            var actual   = GenerateCodeHelper.ConvertDashesToCamelCase(input);

            Assert.AreEqual(expected, actual);
        }
        public void ConvertDashesToCamelCase_existing_uppercase_letters()
        {
            var input    = "string-With-Dashes";
            var expected = "StringWithDashes";
            var actual   = GenerateCodeHelper.ConvertDashesToCamelCase(input);

            Assert.AreEqual(expected, actual);
        }
        public void ConvertDashesToCamelCase_consecutive_dashes()
        {
            var input    = "string--with----dashes";
            var expected = "StringWithDashes";
            var actual   = GenerateCodeHelper.ConvertDashesToCamelCase(input);

            Assert.AreEqual(expected, actual);
        }
Example #8
0
        public void ConvertToPascalCase_all_uppercase_letters(char sep)
        {
            var input    = "STRING" + sep + "WITH" + sep + "DASHES";
            var expected = "STRINGWITHDASHES";
            var actual   = GenerateCodeHelper.ConvertToPascalCase(input);

            Assert.AreEqual(expected, actual);
        }
Example #9
0
        public void ConvertToPascalCase_existing_uppercase_letters(char sep)
        {
            var input    = "string" + sep + "With" + sep + "Dashes";
            var expected = "StringWithDashes";
            var actual   = GenerateCodeHelper.ConvertToPascalCase(input);

            Assert.AreEqual(expected, actual);
        }
Example #10
0
        public void ConvertToPascalCase_consecutive_dashes(char sep)
        {
            var input    = "string" + sep + sep + "with" + sep + sep + sep + sep + "dashes";
            var expected = "StringWithDashes";
            var actual   = GenerateCodeHelper.ConvertToPascalCase(input);

            Assert.AreEqual(expected, actual);
        }
Example #11
0
        private void btnGenerate_Click(object sender, EventArgs e)
        {
            var generateSettings = new List <GenerateSettings>();

            foreach (var control in pnlTempSettings.Controls)
            {
                var tsControl = control as TempSettingControl;
                if (tsControl != null)
                {
                    var settings = tsControl.GetSettings();
                    if (!settings.IsGenerate)
                    {
                        continue;
                    }

                    if (string.IsNullOrWhiteSpace(settings.TemplateFileName))
                    {
                        throw new Exception("模板文件名为空!");
                    }

                    generateSettings.Add(settings);
                }
            }
            if (generateSettings.Count == 0)
            {
                throw new Exception("你选择了0个生成模板!");
            }

            var modelFileNames = new List <string>();

            foreach (TreeNode node in tvDir.Nodes)
            {
                GetCheckedFiles(node, modelFileNames);
            }
            if (modelFileNames.Count == 0)
            {
                throw new Exception("你选择了0个模型文件!");
            }

            var modelParameters = new List <ModelParameter>();

            foreach (var modelFileName in modelFileNames)
            {
                modelParameters.Add(GenerateCodeHelper.GetModelParameters(modelFileName));
            }

            //foreach (var item in modelParameters)
            //{
            //    textBox1.Text = textBox1.Text + GenerateCodeHelper.GenerateCode(item, generateSettings);
            //}

            foreach (var item in generateSettings)
            {
                textBox1.Text = textBox1.Text + GenerateCodeHelper.GenerateCode(modelParameters, item);
            }
        }
Example #12
0
        public static LogKeyValueItem GenerateGeneratedTests(
            DomainProjectOptions domainProjectOptions,
            SyntaxGeneratorHandler sgHandler)
        {
            if (domainProjectOptions == null)
            {
                throw new ArgumentNullException(nameof(domainProjectOptions));
            }

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

            var area   = sgHandler.FocusOnSegmentName.EnsureFirstCharacterToUpper();
            var nsSrc  = $"{domainProjectOptions.ProjectName}.{NameConstants.Handlers}.{area}";
            var nsTest = $"{domainProjectOptions.ProjectName}.Tests.{NameConstants.Handlers}.{area}.Generated";

            var srcSyntaxNodeRoot           = ReadCsFile(domainProjectOptions, sgHandler.FocusOnSegmentName, sgHandler);
            var usedInterfacesInConstructor = GetUsedInterfacesInConstructor(srcSyntaxNodeRoot);

            var usingStatements = GetUsedUsingStatements(
                srcSyntaxNodeRoot,
                nsSrc,
                usedInterfacesInConstructor.Count > 0);

            var sb = new StringBuilder();

            foreach (var item in usingStatements)
            {
                sb.AppendLine($"using {item};");
            }

            sb.AppendLine();
            GenerateCodeHelper.AppendNamespaceComment(sb, domainProjectOptions.ToolNameAndVersion);
            sb.AppendLine($"namespace {nsTest}");
            sb.AppendLine("{");
            GenerateCodeHelper.AppendGeneratedCodeAttribute(sb, domainProjectOptions.ToolName, domainProjectOptions.ToolVersion);
            sb.AppendLine(4, $"public class {sgHandler.HandlerTypeName}GeneratedTests");
            sb.AppendLine(4, "{");
            AppendInstantiateConstructor(sb, sgHandler, usedInterfacesInConstructor);
            if (sgHandler.HasParametersOrRequestBody)
            {
                sb.AppendLine();
                AppendParameterArgumentNullCheck(sb, sgHandler, usedInterfacesInConstructor);
            }

            sb.AppendLine(4, "}");
            sb.AppendLine("}");

            var pathGenerated = Path.Combine(Path.Combine(domainProjectOptions.PathForTestHandlers !.FullName, area), "Generated");
            var fileGenerated = new FileInfo(Path.Combine(pathGenerated, $"{sgHandler.HandlerTypeName}GeneratedTests.cs"));

            return(TextFileHelper.Save(fileGenerated, sb.ToString()));
        }
Example #13
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, "{");
 }
Example #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, "{");
 }
Example #15
0
    public static void GenerateGeneratedTests(
        ILogger logger,
        DomainProjectOptions domainProjectOptions,
        SyntaxGeneratorHandler sgHandler)
    {
        ArgumentNullException.ThrowIfNull(logger);
        ArgumentNullException.ThrowIfNull(domainProjectOptions);
        ArgumentNullException.ThrowIfNull(sgHandler);

        var area   = sgHandler.FocusOnSegmentName.EnsureFirstCharacterToUpper();
        var nsSrc  = $"{domainProjectOptions.ProjectName}.{NameConstants.Handlers}.{area}";
        var nsTest = $"{domainProjectOptions.ProjectName}.Tests.{NameConstants.Handlers}.{area}.Generated";

        var srcSyntaxNodeRoot           = ReadCsFile(domainProjectOptions, sgHandler.FocusOnSegmentName, sgHandler);
        var usedInterfacesInConstructor = GetUsedInterfacesInConstructor(srcSyntaxNodeRoot);

        var usingStatements = GetUsedUsingStatements(
            srcSyntaxNodeRoot,
            nsSrc,
            usedInterfacesInConstructor.Count > 0);

        var sb = new StringBuilder();

        foreach (var item in usingStatements)
        {
            sb.AppendLine($"using {item};");
        }

        sb.AppendLine();
        GenerateCodeHelper.AppendGeneratedCodeWarningComment(sb, domainProjectOptions.ToolNameAndVersion);
        sb.AppendLine($"namespace {nsTest}");
        sb.AppendLine("{");
        GenerateCodeHelper.AppendGeneratedCodeAttribute(sb, domainProjectOptions.ToolName, domainProjectOptions.ToolVersion);
        sb.AppendLine(4, $"public class {sgHandler.HandlerTypeName}GeneratedTests");
        sb.AppendLine(4, "{");
        AppendInstantiateConstructor(sb, sgHandler, usedInterfacesInConstructor);
        if (sgHandler.HasParametersOrRequestBody)
        {
            sb.AppendLine();
            AppendParameterArgumentNullCheck(sb, sgHandler, usedInterfacesInConstructor);
        }

        sb.AppendLine(4, "}");
        sb.AppendLine("}");

        var pathGenerated = Path.Combine(Path.Combine(domainProjectOptions.PathForTestHandlers !.FullName, area), "Generated");
        var fileGenerated = new FileInfo(Path.Combine(pathGenerated, $"{sgHandler.HandlerTypeName}GeneratedTests.cs"));

        var fileDisplayLocation = fileGenerated.FullName.Replace(domainProjectOptions.PathForTestGenerate !.FullName, "test: ", StringComparison.Ordinal);

        TextFileHelper.Save(logger, fileGenerated, fileDisplayLocation, sb.ToString());
    }
Example #16
0
        public static void TansactionServiceInit()
        {
            //开发时,用于saea.rpc 客户端代码生成
            GenerateCodeHelper.GenerateCode();

            var config = DSConfigBuilder.Read();

            if (config == null)
            {
                config = new DSConfigBuilder().UsePort().SetMaster().Build();
            }

            TransactionServiceManager.Init(config);
        }
    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);
    }
    public static void AppendModel(
        int indentSpaces,
        StringBuilder sb,
        EndpointMethodMetadata endpointMethodMetadata,
        string modelName,
        OpenApiSchema schema,
        TrailingCharType trailingChar,
        int itemNumber,
        int maxItemsForList,
        int depthHierarchy,
        int maxDepthHierarchy,
        KeyValuePair <string, OpenApiSchema>?badPropertySchema,
        bool asJsonBody,
        string?parentModelNameToJsonBody = null)
    {
        ArgumentNullException.ThrowIfNull(sb);
        ArgumentNullException.ThrowIfNull(schema);

        var countString     = 1;
        var renderModelName = OpenApiDocumentSchemaModelNameHelper.EnsureModelNameWithNamespaceIfNeeded(endpointMethodMetadata, modelName);
        var jsonSpaces      = string.Empty.PadLeft(depthHierarchy * 2);

        if (asJsonBody)
        {
            sb.AppendLine(
                indentSpaces,
                string.IsNullOrEmpty(parentModelNameToJsonBody)
                    ? GenerateXunitTestPartsHelper.WrapInStringBuilderAppendLine($"{jsonSpaces}{{")
                    : GenerateXunitTestPartsHelper.WrapInStringBuilderAppendLine($"{jsonSpaces}\\\"{parentModelNameToJsonBody}\\\": {{"));
        }
        else
        {
            sb.AppendLine(renderModelName);
            sb.AppendLine(indentSpaces, "{");
        }

        foreach (var schemaProperty in schema.Properties)
        {
            var trailingCharForProperty = GenerateXunitTestPartsHelper.GetTrailingCharForProperty(asJsonBody, schemaProperty, schema.Properties);
            var useForBadRequest        = badPropertySchema is not null &&
                                          schemaProperty.Key.Equals(badPropertySchema.Value.Key, StringComparison.Ordinal);

            var dataType = schemaProperty.Value.GetDataType();

            var propertyValueGenerated = GenerateXunitTestPartsHelper.PropertyValueGenerator(
                schemaProperty,
                endpointMethodMetadata.ComponentsSchemas,
                useForBadRequest,
                itemNumber,
                customValue: null);

            if ("NEW-INSTANCE-LIST".Equals(propertyValueGenerated, StringComparison.Ordinal))
            {
                AppendDataEqualNewListOfModel(
                    indentSpaces + 4,
                    sb,
                    endpointMethodMetadata,
                    schemaProperty,
                    trailingCharForProperty,
                    maxItemsForList,
                    depthHierarchy + 1,
                    maxDepthHierarchy,
                    badPropertySchema,
                    asJsonBody);
            }
            else if ("NEW-INSTANCE".Equals(propertyValueGenerated, StringComparison.Ordinal))
            {
                AppendModelComplexProperty(
                    indentSpaces,
                    sb,
                    endpointMethodMetadata,
                    schemaProperty,
                    dataType,
                    trailingCharForProperty,
                    itemNumber,
                    maxItemsForList,
                    depthHierarchy + 1,
                    maxDepthHierarchy,
                    badPropertySchema,
                    asJsonBody);
            }
            else
            {
                var countResult = GenerateXunitTestPartsHelper.AppendModelSimpleProperty(
                    indentSpaces,
                    sb,
                    endpointMethodMetadata,
                    schemaProperty,
                    dataType,
                    schema.Required.Contains(schemaProperty.Key),
                    propertyValueGenerated,
                    countString,
                    asJsonBody,
                    depthHierarchy,
                    trailingCharForProperty);

                if (countResult > 1)
                {
                    countString += 1;
                }
            }
        }

        sb.AppendLine(
            indentSpaces,
            asJsonBody
                ? GenerateXunitTestPartsHelper.WrapInStringBuilderAppendLine($"{jsonSpaces}}}{GenerateCodeHelper.GetTrailingChar(trailingChar)}")
                : $"}}{GenerateCodeHelper.GetTrailingChar(trailingChar)}");
    }
Example #19
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();

            sb.AppendLine("using System;");
            sb.AppendLine("using System.CodeDom.Compiler;");
            sb.AppendLine("using System.Collections.Generic;");
            sb.AppendLine("using System.Net;");
            sb.AppendLine("using System.Net.Http;");
            sb.AppendLine("using System.Text;");
            sb.AppendLine("using System.Threading.Tasks;");
            sb.AppendLine("using FluentAssertions;");
            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};");
            sb.AppendLine("using Xunit;");
            sb.AppendLine();
            GenerateCodeHelper.AppendNamespaceComment(sb, hostProjectOptions.ToolNameAndVersion);
            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, "{");
            sb.AppendLine(8, $"public {endpointMethodMetadata.MethodName}Tests(WebApiStartupFactory fixture) : base(fixture) {{ }}");
            foreach (var contractReturnTypeName in endpointMethodMetadata.ContractReturnTypeNames)
            {
                switch (contractReturnTypeName.Item1)
                {
                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;
                }
            }

            sb.AppendLine(4, "}");
            sb.AppendLine("}");

            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()));
        }
    public static int AppendModelSimpleProperty(
        int indentSpaces,
        StringBuilder sb,
        EndpointMethodMetadata endpointMethodMetadata,
        KeyValuePair <string, OpenApiSchema> schemaProperty,
        string dataType,
        bool isRequired,
        string propertyValueGenerated,
        int countString,
        bool asJsonBody,
        int depthHierarchy,
        TrailingCharType trailingChar)
    {
        ArgumentNullException.ThrowIfNull(endpointMethodMetadata);
        ArgumentNullException.ThrowIfNull(propertyValueGenerated);

        var propertyName = schemaProperty.Key.EnsureFirstCharacterToUpper();

        var isHandled = false;

        if (isRequired &&
            OpenApiDataTypeConstants.Array.Equals(dataType, StringComparison.OrdinalIgnoreCase))
        {
            var itemsDataType = schemaProperty.Value.Items.GetDataType();

            if (asJsonBody)
            {
                switch (itemsDataType)
                {
                case OpenApiDataTypeConstants.String:
                    sb.AppendLine(indentSpaces, $"sb.AppendLine(\"  {WrapInQuotes(propertyName)}: [ {WrapInQuotes("Hallo")}, {WrapInQuotes("World")} ]{GenerateCodeHelper.GetTrailingChar(trailingChar)}\");");
                    isHandled = true;
                    break;

                case OpenApiDataTypeConstants.Integer:
                    sb.AppendLine(indentSpaces, $"sb.AppendLine(\"  {WrapInQuotes(propertyName)}: [ 42, 17 ]{GenerateCodeHelper.GetTrailingChar(trailingChar)}\");");
                    isHandled = true;
                    break;

                case OpenApiDataTypeConstants.Boolean:
                    sb.AppendLine(indentSpaces, $"sb.AppendLine(\"  {WrapInQuotes(propertyName)}: [ true, false, true ]{GenerateCodeHelper.GetTrailingChar(trailingChar)}\");");
                    isHandled = true;
                    break;

                case "IFormFile":
                    throw new NotSupportedException("IFormFile is not supported when working with Json.");
                }
            }
            else
            {
                switch (itemsDataType)
                {
                case OpenApiDataTypeConstants.String:
                    sb.AppendLine(indentSpaces + 4, $"{propertyName} = new List<string>() {{ \"Hallo\", \"World\" }},");
                    isHandled = true;
                    break;

                case OpenApiDataTypeConstants.Integer:
                    sb.AppendLine(indentSpaces + 4, $"{propertyName} = new List<int>() {{ 42, 17 }},");
                    isHandled = true;
                    break;

                case OpenApiDataTypeConstants.Boolean:
                    sb.AppendLine(indentSpaces + 4, $"{propertyName} = new List<bool>() {{ true, false, true }},");
                    isHandled = true;
                    break;

                case "IFormFile":
                    sb.AppendLine(indentSpaces + 4, $"{propertyName} = GetTestFiles(),");
                    isHandled = true;
                    break;
                }
            }
        }

        if (isHandled)
        {
            return(countString);
        }

        switch (dataType)
        {
        case "string":
            countString = AppendModelSimplePropertyForString(
                indentSpaces,
                sb,
                propertyName,
                schemaProperty,
                propertyValueGenerated,
                countString,
                asJsonBody,
                depthHierarchy,
                trailingChar);
            break;

        case "DateTimeOffset":
            AppendModelSimplePropertyForDateTimeOffset(
                indentSpaces,
                sb,
                propertyName,
                propertyValueGenerated,
                asJsonBody,
                depthHierarchy,
                trailingChar);
            break;

        case "Guid":
            AppendModelSimplePropertyForGuid(
                indentSpaces,
                sb,
                propertyName,
                propertyValueGenerated,
                asJsonBody,
                depthHierarchy,
                trailingChar);
            break;

        case "Uri":
            AppendModelSimplePropertyForUri(
                indentSpaces,
                sb,
                propertyName,
                propertyValueGenerated,
                asJsonBody,
                depthHierarchy,
                trailingChar);
            break;

        case "IFormFile":
            AppendModelSimplePropertyForIFormFile(
                indentSpaces,
                sb,
                propertyName,
                propertyValueGenerated,
                asJsonBody,
                depthHierarchy,
                trailingChar);
            break;

        default:
            var enumDataType = GetDataTypeIfEnum(schemaProperty, endpointMethodMetadata.ComponentsSchemas);
            if (enumDataType is null)
            {
                AppendModelSimplePropertyDefault(
                    indentSpaces,
                    sb,
                    propertyName,
                    propertyValueGenerated,
                    asJsonBody,
                    depthHierarchy,
                    trailingChar);
            }
            else
            {
                if (propertyValueGenerated.Contains('=', StringComparison.Ordinal))
                {
                    propertyValueGenerated = propertyValueGenerated.Split('=').First().Trim();
                }

                if (asJsonBody)
                {
                    sb.AppendLine(
                        indentSpaces,
                        WrapInStringBuilderAppendLineWithKeyAndValueQuotes(depthHierarchy, propertyName, propertyValueGenerated, trailingChar));
                }
                else
                {
                    sb.AppendLine(
                        indentSpaces + 4,
                        $"{propertyName} = {enumDataType}.{propertyValueGenerated},");
                }
            }

            break;
        }

        return(countString);
    }
Example #21
0
        public void ConvertToPascalCase_single_dashes(char sep)
        {
            var actual = GenerateCodeHelper.ConvertToPascalCase("string" + sep + "with" + sep + "dashes");

            Assert.AreEqual("StringWithDashes", actual);
        }
        public void ConvertDashesToCamelCase_single_dashes()
        {
            var actual = GenerateCodeHelper.ConvertDashesToCamelCase("string-with-dashes");

            Assert.AreEqual("StringWithDashes", actual);
        }
    public static void AppendModelComplexProperty(
        int indentSpaces,
        StringBuilder sb,
        EndpointMethodMetadata endpointMethodMetadata,
        KeyValuePair <string, OpenApiSchema> schemaProperty,
        string dataType,
        TrailingCharType trailingChar,
        int itemNumber,
        int maxItemsForList,
        int depthHierarchy,
        int maxDepthHierarchy,
        KeyValuePair <string, OpenApiSchema>?badPropertySchema,
        bool asJsonBody)
    {
        var propertyName = schemaProperty.Key.EnsureFirstCharacterToUpper();

        if (depthHierarchy > maxDepthHierarchy)
        {
            if (asJsonBody)
            {
                // TODO Missing Json support.
            }
            else
            {
                sb.AppendLine(
                    indentSpaces,
                    $"{propertyName} = null{GenerateCodeHelper.GetTrailingChar(trailingChar)}");
                return;
            }
        }

        if (!asJsonBody)
        {
            indentSpaces += 4;
            GenerateXunitTestPartsHelper.AppendPartDataEqualNew(
                indentSpaces,
                sb,
                propertyName);
        }

        var schemaPropertyValue = schemaProperty.Value;

        if (schemaProperty.Value.Properties.Count == 0 &&
            schemaProperty.Value.OneOf.Count > 0)
        {
            schemaPropertyValue = schemaProperty.Value.OneOf.First();
        }

        var modelName = schemaProperty.Key.EnsureFirstCharacterToUpper();

        AppendModel(
            indentSpaces,
            sb,
            endpointMethodMetadata,
            dataType,
            schemaPropertyValue,
            trailingChar,
            itemNumber,
            maxItemsForList,
            depthHierarchy,
            maxDepthHierarchy,
            badPropertySchema,
            asJsonBody,
            modelName);
    }
    public static void AppendVarDataEqualNewListOfModel(
        int indentSpaces,
        StringBuilder sb,
        EndpointMethodMetadata endpointMethodMetadata,
        KeyValuePair <string, OpenApiSchema> schemaProperty,
        TrailingCharType trailingChar,
        int maxItemsForList,
        int depthHierarchy,
        int maxDepthHierarchy,
        KeyValuePair <string, OpenApiSchema>?badPropertySchema,
        bool asJsonBody)
    {
        ArgumentNullException.ThrowIfNull(sb);

        var modelName       = schemaProperty.Value.GetModelName();
        var renderModelName = OpenApiDocumentSchemaModelNameHelper.EnsureModelNameWithNamespaceIfNeeded(endpointMethodMetadata, modelName);

        if (depthHierarchy > maxDepthHierarchy)
        {
            if (asJsonBody)
            {
                // TODO Missing Json support.
            }
            else
            {
                sb.AppendLine(
                    indentSpaces,
                    $"var {schemaProperty.Key} = new List<{renderModelName}>(){GenerateCodeHelper.GetTrailingChar(trailingChar)}");
                return;
            }
        }

        if (!asJsonBody)
        {
            GenerateXunitTestPartsHelper.AppendPartVarDataEqualNewListOf(
                indentSpaces,
                sb,
                schemaProperty.Key,
                renderModelName);
            sb.AppendLine();
            sb.AppendLine(indentSpaces, "{");
        }

        var modelSchema = endpointMethodMetadata.ComponentsSchemas.GetSchemaByModelName(modelName);

        for (var i = 0; i < maxItemsForList; i++)
        {
            var trailingCharForProperty = GenerateXunitTestPartsHelper.GetTrailingCharForProperty(asJsonBody, i, maxItemsForList);
            var indentSpacesForItem     = indentSpaces + 4;
            if (!asJsonBody)
            {
                indentSpacesForItem = indentSpaces + 4;
                GenerateXunitTestPartsHelper.AppendPartDataNew(indentSpacesForItem, sb);
            }

            AppendModel(
                indentSpacesForItem,
                sb,
                endpointMethodMetadata,
                modelName,
                modelSchema,
                trailingCharForProperty,
                i + 1,
                maxItemsForList,
                depthHierarchy,
                maxDepthHierarchy,
                badPropertySchema,
                asJsonBody);
        }

        if (!asJsonBody)
        {
            sb.AppendLine(
                indentSpaces,
                $"}}{GenerateCodeHelper.GetTrailingChar(trailingChar)}");
        }
    }
        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();

            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};");
            sb.AppendLine();
            GenerateCodeHelper.AppendNamespaceComment(sb, hostProjectOptions.ToolNameAndVersion);
            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, "{");
            sb.AppendLine(8, endpointMethodMetadata.ContractParameterTypeName == null
                ? $"public Task<{endpointMethodMetadata.ContractResultTypeName}> ExecuteAsync(CancellationToken cancellationToken = default)"
                : $"public Task<{endpointMethodMetadata.ContractResultTypeName}> ExecuteAsync({endpointMethodMetadata.ContractParameterTypeName} parameters, CancellationToken cancellationToken = default)");
            sb.AppendLine(8, "{");
            if (endpointMethodMetadata.ContractReturnTypeNames.FirstOrDefault(x => x.Item1 == HttpStatusCode.OK) != null)
            {
                AppendContentForExecuteAsync(sb, endpointMethodMetadata, HttpStatusCode.OK);
            }
            else if (endpointMethodMetadata.ContractReturnTypeNames.FirstOrDefault(x => x.Item1 == HttpStatusCode.Created) != null)
            {
                AppendContentForExecuteAsync(sb, endpointMethodMetadata, HttpStatusCode.Created);
            }
            else
            {
                sb.AppendLine(12, "throw new System.NotImplementedException();");
            }

            sb.AppendLine(8, "}");
            sb.AppendLine(4, "}");
            sb.AppendLine("}");

            var pathA    = Path.Combine(hostProjectOptions.PathForTestGenerate !.FullName, "Endpoints");
            var pathB    = Path.Combine(pathA, endpointMethodMetadata.SegmentName);
            var pathC    = Path.Combine(pathB, "Generated");
            var fileName = $"{endpointMethodMetadata.ContractInterfaceHandlerTypeName.Substring(1)}Stub.cs";
            var file     = new FileInfo(Path.Combine(pathC, fileName));

            return(TextFileHelper.Save(file, sb.ToString()));
        }
    public static void AppendDataEqualNewListOfModel(
        int indentSpaces,
        StringBuilder sb,
        EndpointMethodMetadata endpointMethodMetadata,
        KeyValuePair <string, OpenApiSchema> schemaProperty,
        TrailingCharType trailingChar,
        int maxItemsForList,
        int depthHierarchy,
        int maxDepthHierarchy,
        KeyValuePair <string, OpenApiSchema>?badPropertySchema,
        bool asJsonBody)
    {
        var modelName       = schemaProperty.Value.GetModelName();
        var renderModelName = OpenApiDocumentSchemaModelNameHelper.EnsureModelNameWithNamespaceIfNeeded(endpointMethodMetadata, modelName);
        var propertyName    = schemaProperty.Key.EnsureFirstCharacterToUpper();
        var jsonSpacesCount = (depthHierarchy * 2) + 2;

        if (depthHierarchy > maxDepthHierarchy)
        {
            if (asJsonBody)
            {
                // TODO Missing Json support.
            }
            else
            {
                sb.AppendLine(
                    indentSpaces,
                    $"{propertyName} = new List<{renderModelName}>()" + GenerateCodeHelper.GetTrailingChar(trailingChar));
                return;
            }
        }

        if (asJsonBody)
        {
            var useForBadRequest = badPropertySchema is not null &&
                                   schemaProperty.Key.Equals(badPropertySchema.Value.Key, StringComparison.Ordinal);

            if (useForBadRequest)
            {
                sb.AppendLine(
                    indentSpaces - jsonSpacesCount,
                    GenerateXunitTestPartsHelper.WrapInStringBuilderAppendLineWithKeyQuotes(depthHierarchy - 1, propertyName, "null", trailingChar));
                return;
            }

            sb.AppendLine(
                indentSpaces - jsonSpacesCount,
                GenerateXunitTestPartsHelper.WrapInStringBuilderAppendLineWithKeyQuotes(depthHierarchy - 1, propertyName, "[", TrailingCharType.None));
        }
        else
        {
            GenerateXunitTestPartsHelper.AppendPartDataEqualNewListOf(
                indentSpaces,
                sb,
                propertyName,
                modelName);
            sb.AppendLine();
            sb.AppendLine(indentSpaces, "{");
        }

        var modelSchema         = endpointMethodMetadata.ComponentsSchemas.GetSchemaByModelName(modelName);
        var currentIndentSpaces = asJsonBody
            ? indentSpaces - jsonSpacesCount
            : indentSpaces + 4;

        for (int i = 0; i < maxItemsForList; i++)
        {
            var trailingCharForProperty = GenerateXunitTestPartsHelper.GetTrailingCharForProperty(asJsonBody, i, maxItemsForList);

            if (!asJsonBody)
            {
                GenerateXunitTestPartsHelper.AppendPartDataNew(currentIndentSpaces, sb);
            }

            AppendModel(
                currentIndentSpaces,
                sb,
                endpointMethodMetadata,
                modelName,
                modelSchema,
                trailingCharForProperty,
                i + 1,
                maxItemsForList,
                depthHierarchy,
                maxDepthHierarchy,
                badPropertySchema,
                asJsonBody);
        }

        if (asJsonBody)
        {
            var jsonSpaces = string.Empty.PadLeft((depthHierarchy - 1) * 2);
            sb.AppendLine(
                indentSpaces - jsonSpacesCount,
                GenerateXunitTestPartsHelper.WrapInStringBuilderAppendLine($"{jsonSpaces}  ]{GenerateCodeHelper.GetTrailingChar(trailingChar)}"));
        }
        else
        {
            sb.AppendLine(
                indentSpaces,
                $"}}{GenerateCodeHelper.GetTrailingChar(trailingChar)}");
        }
    }