コード例 #1
0
        public void NameSymbolObjectValueFormDefinitionInfersAddIdentityTrue()
        {
            SimpleConfigModel configModel = SimpleConfigModel.FromJObject(EngineEnvironmentSettings, NameConfigObjectValueFormWithoutIdentityAndAddIdentityUnspecified);

            Assert.True(configModel.Symbols.ContainsKey("name"));

            ISymbolModel symbolInfo = configModel.Symbols["name"];

            Assert.True(symbolInfo is ParameterSymbol);

            ParameterSymbol paramSymbol = symbolInfo as ParameterSymbol;
            IList <string>  configuredValueFormNames = paramSymbol.Forms.GlobalForms.ToList();

            Assert.Equal(4, configuredValueFormNames.Count);
            Assert.Equal(IdentityValueForm.FormName, configuredValueFormNames[0]);
            Assert.Equal("foo", configuredValueFormNames[1]);
            Assert.Equal("bar", configuredValueFormNames[2]);
            Assert.Equal("baz", configuredValueFormNames[3]);
        }
コード例 #2
0
        public void ParameterSymbolWithArrayIdentityValueFormRetainsFormsUnmodified()
        {
            SimpleConfigModel configModel = SimpleConfigModel.FromJObject(EngineEnvironmentSettings, ArrayConfigForSymbolWithValueFormsIncludingIdentity);

            Assert.True(configModel.Symbols.ContainsKey("testSymbol"));

            ISymbolModel symbolInfo = configModel.Symbols["testSymbol"];

            Assert.True(symbolInfo is ParameterSymbol);

            ParameterSymbol paramSymbol = symbolInfo as ParameterSymbol;
            IList <string>  configuredValueFormNames = paramSymbol.Forms.GlobalForms.ToList();

            Assert.Equal(4, configuredValueFormNames.Count);
            Assert.Equal("foo", configuredValueFormNames[0]);
            Assert.Equal("bar", configuredValueFormNames[1]);
            Assert.Equal("baz", configuredValueFormNames[2]);
            Assert.Equal(IdentityValueForm.FormName, configuredValueFormNames[3]);
        }
コード例 #3
0
        public void ObjectConfigNameSymbolWithIdentityFormAndAddIdentityTrueRetainsConfiguredFormsExactly()
        {
            SimpleConfigModel configModel = SimpleConfigModel.FromJObject(EngineEnvironmentSettings, ObjectConfigNameSymbolWithIdentityFormAndAddIdentityTrue);

            Assert.True(configModel.Symbols.ContainsKey("name"));

            ISymbolModel symbolInfo = configModel.Symbols["name"];

            Assert.True(symbolInfo is ParameterSymbol);

            ParameterSymbol nameSymbol = symbolInfo as ParameterSymbol;
            IList <string>  configuredValueFormNames = nameSymbol.Forms.GlobalForms.ToList();

            Assert.Equal(4, configuredValueFormNames.Count);
            Assert.Equal("foo", configuredValueFormNames[0]);
            Assert.Equal("bar", configuredValueFormNames[1]);
            Assert.Equal(IdentityValueForm.FormName, configuredValueFormNames[2]);
            Assert.Equal("baz", configuredValueFormNames[3]);
        }
コード例 #4
0
        public void ArrayConfigNameSymbolWithoutIdentityFormGetsIdentityFormAddedAsFirst()
        {
            SimpleConfigModel configModel = SimpleConfigModel.FromJObject(EngineEnvironmentSettings, ArrayConfigWithNameSymbolAndValueFormsButNotIdentity);

            Assert.True(configModel.Symbols.ContainsKey("name"));

            ISymbolModel symbolInfo = configModel.Symbols["name"];

            Assert.True(symbolInfo is ParameterSymbol);

            ParameterSymbol nameSymbol = symbolInfo as ParameterSymbol;
            IList <string>  configuredValueFormNames = nameSymbol.Forms.GlobalForms.ToList();

            Assert.Equal(4, configuredValueFormNames.Count);
            Assert.Equal(IdentityValueForm.FormName, configuredValueFormNames[0]);
            Assert.Equal("foo", configuredValueFormNames[1]);
            Assert.Equal("bar", configuredValueFormNames[2]);
            Assert.Equal("baz", configuredValueFormNames[3]);
        }
コード例 #5
0
        public void ObjectValueFormDefinitionRespectsAddIdentityTrue()
        {
            SimpleConfigModel configModel = SimpleConfigModel.FromJObject(EngineEnvironmentSettings, ConfigWithObjectValueFormDefinitionAddIdentityTrue);

            Assert.True(configModel.Symbols.ContainsKey("testSymbol"));

            ISymbolModel symbolInfo = configModel.Symbols["testSymbol"];

            Assert.True(symbolInfo is ParameterSymbol);

            ParameterSymbol paramSymbol = symbolInfo as ParameterSymbol;
            IList <string>  configuredValueFormNames = paramSymbol.Forms.GlobalForms.ToList();

            Assert.Equal(4, configuredValueFormNames.Count);
            Assert.Equal(IdentityValueForm.FormName, configuredValueFormNames[0]);
            Assert.Equal("foo", configuredValueFormNames[1]);
            Assert.Equal("bar", configuredValueFormNames[2]);
            Assert.Equal("baz", configuredValueFormNames[3]);
        }
コード例 #6
0
        public void NameSymbolGetsAddedWithDefaultValueForms()
        {
            SimpleConfigModel configModel = SimpleConfigModel.FromJObject(_engineEnvironmentSettings, ArrayConfigForSymbolWithFormsButNotIdentity);

            Assert.True(configModel.Symbols.ContainsKey("name"));

            ISymbolModel symbolInfo = configModel.Symbols["name"];

            Assert.True(symbolInfo is ParameterSymbol);

            ParameterSymbol nameSymbol = symbolInfo as ParameterSymbol;
            IList <string>  configuredValueFormNames = nameSymbol.Forms.GlobalForms.ToList();

            Assert.Equal(5, configuredValueFormNames.Count);
            Assert.Equal(IdentityValueForm.FormName, configuredValueFormNames[0]);
            Assert.Equal(DefaultSafeNameValueFormModel.FormName, configuredValueFormNames[1]);
            Assert.Equal(DefaultLowerSafeNameValueFormModel.FormName, configuredValueFormNames[2]);
            Assert.Equal(DefaultSafeNamespaceValueFormModel.FormName, configuredValueFormNames[3]);
            Assert.Equal(DefaultLowerSafeNamespaceValueFormModel.FormName, configuredValueFormNames[4]);
        }
コード例 #7
0
        public void CanReadFilenameReplacementConfig()
        {
            string                     configContent  = @"
{
  ""identity"": ""test"",
  ""symbols"": {
	""testparam"": {
      ""type"": ""parameter"",
      ""datatype"": ""string"",
	  ""fileRename"": ""testparamfilereplacement""
    },
    ""testgenerated"": {
      ""type"": ""generated"",
      ""generator"": ""casing"",
      ""parameters"": {
        ""source"": ""name"",
        ""toLower"": true
      },
	  ""fileRename"": ""testgeneratedfilereplacement""
    },
    ""testgenerated2"": {
      ""type"": ""generated"",
      ""generator"": ""casing"",
      ""parameters"": {
        ""source"": ""name"",
        ""toLower"": true
      },
	  ""replace"": ""testgeneratedreplacement""
    },
  }
}
";
            SimpleConfigModel          configModel    = SimpleConfigModel.FromJObject(JObject.Parse(configContent));
            IEngineEnvironmentSettings environment    = _environmentSettingsHelper.CreateEnvironment();
            RunnableProjectConfig      runnableConfig =
                new RunnableProjectConfig(environment, A.Fake <IGenerator>(), configModel);

            Assert.Equal(2, runnableConfig.SymbolFilenameReplacements.Count);
            Assert.Equal("testparamfilereplacement", runnableConfig.SymbolFilenameReplacements.Single(x => x.VariableName.Contains("testparam")).OriginalValue.Value);
            Assert.Equal("testgeneratedfilereplacement", runnableConfig.SymbolFilenameReplacements.Single(x => x.VariableName == "testgenerated").OriginalValue.Value);
        }
コード例 #8
0
        public async Task CanProcessDifferentVersions(string configuredVersion, string hostVersion, bool expectedResult)
        {
            var config = new
            {
                identity    = "test",
                constraints = new
                {
                    host = new
                    {
                        type = "host",
                        args = new[]
                        {
                            new
                            {
                                hostName = "host1",
                                version  = configuredVersion
                            }
                        }
                    }
                }
            };

            var configModel = SimpleConfigModel.FromJObject(JObject.FromObject(config));
            IEngineEnvironmentSettings settings = A.Fake <IEngineEnvironmentSettings>();

            A.CallTo(() => settings.Host.HostIdentifier).Returns("host1");
            A.CallTo(() => settings.Host.Version).Returns(hostVersion);
            A.CallTo(() => settings.Components.OfType <ITemplateConstraintFactory>()).Returns(new[] { new HostConstraintFactory() });

            var constraintManager = new TemplateConstraintManager(settings);
            var evaluateResult    = await constraintManager.EvaluateConstraintAsync(configModel.Constraints.Single().Type, configModel.Constraints.Single().Args, default).ConfigureAwait(false);

            if (expectedResult)
            {
                Assert.Equal(TemplateConstraintResult.Status.Allowed, evaluateResult.EvaluationStatus);
            }
            else
            {
                Assert.Equal(TemplateConstraintResult.Status.Restricted, evaluateResult.EvaluationStatus);
            }
        }
コード例 #9
0
        public void TestEvaluateConfig(string predicate, bool expectedResult)
        {
            string variableName             = "myPredicate";
            string evaluator                = "C++";
            EvaluateMacroConfig macroConfig = new EvaluateMacroConfig(variableName, predicate, evaluator);

            IVariableCollection    variables  = new VariableCollection();
            IRunnableProjectConfig config     = new SimpleConfigModel();
            IParameterSet          parameters = new ParameterSet(config);
            ParameterSetter        setter     = MacroTestHelpers.TestParameterSetter(EngineEnvironmentSettings, parameters);

            EvaluateMacro macro = new EvaluateMacro();

            macro.EvaluateConfig(EngineEnvironmentSettings, variables, macroConfig, parameters, setter);
            ITemplateParameter resultParam;

            Assert.True(parameters.TryGetParameterDefinition(variableName, out resultParam));
            bool resultValue = (bool)parameters.ResolvedValues[resultParam];

            Assert.Equal(resultValue, expectedResult);
        }
コード例 #10
0
        public void CheckTemplateRootRelativeToInstallPath(string pathToTemplateJson, bool shouldAllPathsBeValid)
        {
            string sourcePath = FileSystemHelpers.GetNewVirtualizedPath(EngineEnvironmentSettings);
            IDictionary <string, string> templateSourceFiles = new Dictionary <string, string>();

            templateSourceFiles.Add(pathToTemplateJson, BasicTemplateConfig);
            TestTemplateSetup setup = new TestTemplateSetup(EngineEnvironmentSettings, sourcePath, templateSourceFiles);

            setup.WriteSource();

            RunnableProjectGenerator generator = new RunnableProjectGenerator();

            IFile                   templateFile            = setup.FileInfoForSourceFile(pathToTemplateJson);
            JObject                 srcObject               = generator.ReadJObjectFromIFile(templateFile);
            SimpleConfigModel       templateModel           = SimpleConfigModel.FromJObject(templateFile.MountPoint.EnvironmentSettings, srcObject);
            RunnableProjectTemplate runnableProjectTemplate = new RunnableProjectTemplate(srcObject, generator, templateFile, templateModel, null, null);

            bool allPathsAreValid = generator.AreAllTemplatePathsValid(templateModel, runnableProjectTemplate);

            Assert.Equal(shouldAllPathsBeValid, allPathsAreValid);
        }
コード例 #11
0
        public void CanReadFilenameReplacementConfig()
        {
            string configContent = @"
{
  ""symbols"": {
	""testparam"": {
      ""type"": ""parameter"",
      ""datatype"": ""string"",
	  ""fileRename"": ""testparamfilereplacement""
    },
    ""testgenerated"": {
      ""type"": ""generated"",
      ""generator"": ""casing"",
      ""parameters"": {
        ""source"": ""name"",
        ""toLower"": true
      },
	  ""fileRename"": ""testgeneratedfilereplacement""
    },
    ""testgenerated2"": {
      ""type"": ""generated"",
      ""generator"": ""casing"",
      ""parameters"": {
        ""source"": ""name"",
        ""toLower"": true
      },
	  ""replace"": ""testgeneratedreplacement""
    },

  }
}
";
            IEngineEnvironmentSettings environment = TemplateConfigTestHelpers.GetTestEnvironment();
            JObject           configJson           = JObject.Parse(configContent);
            SimpleConfigModel config = SimpleConfigModel.FromJObject(environment, configJson);

            Assert.Equal(2, config.SymbolFilenameReplacements.Count);
            Assert.Equal("testparamfilereplacement", config.SymbolFilenameReplacements.Single(x => x.VariableName.Contains("testparam")).OriginalValue.Value);
            Assert.Equal("testgeneratedfilereplacement", config.SymbolFilenameReplacements.Single(x => x.VariableName == "testgenerated").OriginalValue.Value);
        }
コード例 #12
0
        public void SourceConfigExcludesAreOverriddenByIncludes()
        {
            string            sourceBasePath = FileSystemHelpers.GetNewVirtualizedPath(_engineEnvironmentSettings);
            SimpleConfigModel config         = new SimpleConfigModel()
            {
                Identity = "test",
                Sources  = new List <ExtendedFileSource>()
                {
                    new ExtendedFileSource()
                    {
                        Exclude   = "**/*.config",
                        Modifiers = new List <SourceModifier>()
                        {
                            new SourceModifier()
                            {
                                Include = "core.config"
                            }
                        }
                    }
                }
            };

            IDictionary <string, string> templateSourceFiles = new Dictionary <string, string>();

            // config
            templateSourceFiles.Add(TestFileSystemHelper.DefaultConfigRelativePath, config.ToJObject().ToString());
            // content
            templateSourceFiles.Add("core.config", null);
            templateSourceFiles.Add("full.config", null);
            TestTemplateSetup setup = new TestTemplateSetup(_engineEnvironmentSettings, sourceBasePath, templateSourceFiles, config);

            setup.WriteSource();

            string targetDir = FileSystemHelpers.GetNewVirtualizedPath(_engineEnvironmentSettings);

            setup.InstantiateTemplate(targetDir);

            Assert.True(_engineEnvironmentSettings.Host.FileSystem.FileExists(Path.Combine(targetDir, "core.config")));
            Assert.False(_engineEnvironmentSettings.Host.FileSystem.FileExists(Path.Combine(targetDir, "full.config")));
        }
コード例 #13
0
        public void TestJoinConstantAndReferenceSymbolConfig(string separator)
        {
            string variableName         = "joinedParameter";
            string referenceSymbolName  = "referenceSymbol";
            string referenceSymbolValue = "referenceValue";
            string constantValue        = "constantValue";

            List <KeyValuePair <string, string> > definitions = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("const", constantValue),
                new KeyValuePair <string, string>("ref", referenceSymbolName)
            };

            JoinMacroConfig macroConfig = new JoinMacroConfig(variableName, null, definitions, separator);

            IVariableCollection    variables  = new VariableCollection();
            IRunnableProjectConfig config     = new SimpleConfigModel();
            IParameterSet          parameters = new RunnableProjectGenerator.ParameterSet(config);
            ParameterSetter        setter     = MacroTestHelpers.TestParameterSetter(EngineEnvironmentSettings, parameters);

            Parameter referenceParam = new Parameter
            {
                IsVariable = true,
                Name       = referenceSymbolName
            };

            variables[referenceSymbolName] = referenceSymbolValue;
            setter(referenceParam, referenceSymbolValue);

            JoinMacro macro = new JoinMacro();

            macro.EvaluateConfig(EngineEnvironmentSettings, variables, macroConfig, parameters, setter);

            Assert.True(parameters.TryGetParameterDefinition(variableName, out ITemplateParameter convertedParam));

            string convertedValue = (string)parameters.ResolvedValues[convertedParam];
            string expectedValue  = string.Join(separator, constantValue, referenceSymbolValue);

            Assert.Equal(convertedValue, expectedValue);
        }
コード例 #14
0
        public void UnknownFormNameOnParameterSymbolDoesNotThrow()
        {
            string            templateJson = @"
{
  ""name"": ""TestTemplate"",
  ""identity"": ""TestTemplate"",
  ""symbols"": {
    ""mySymbol"": {
      ""type"": ""parameter"",
      ""replaces"": ""whatever"",
      ""forms"": {
        ""global"": [ ""fakeName"" ],
      }
    }
  }
}
";
            JObject           configObj    = JObject.Parse(templateJson);
            SimpleConfigModel configModel  = SimpleConfigModel.FromJObject(EngineEnvironmentSettings, configObj);
            IGlobalRunConfig  runConfig    = null;

            try
            {
                runConfig = ((IRunnableProjectConfig)configModel).OperationConfig;
            }
            catch
            {
                Assert.True(false, "Should not throw on unknown value form name");
            }

            Assert.NotNull(runConfig);
            Assert.Equal(1, runConfig.Macros.Count(m => m.VariableName.StartsWith("mySymbol")));
            var mySymbolMacro = runConfig.Macros.Single(m => m.VariableName.StartsWith("mySymbol"));

            Assert.True(mySymbolMacro is ProcessValueFormMacroConfig);
            ProcessValueFormMacroConfig identityFormConfig = mySymbolMacro as ProcessValueFormMacroConfig;

            Assert.Equal("identity", identityFormConfig.FormName);
        }
コード例 #15
0
ファイル: ConstraintsTest.cs プロジェクト: dotnet/templating
        public void CannotReadConstraint_WhenTypeIsNotSet()
        {
            var json = new
            {
                identity    = "test",
                constraints = new
                {
                    one = new
                    {
                        args = "arg"
                    }
                }
            };

            List <(LogLevel, string)> loggedMessages = new List <(LogLevel, string)>();
            InMemoryLoggerProvider    loggerProvider = new InMemoryLoggerProvider(loggedMessages);
            var model = SimpleConfigModel.FromJObject(JObject.FromObject(json), loggerProvider.CreateLogger("test"));

            Assert.Empty(model.Constraints);
            Assert.Single(loggedMessages);
            Assert.Equal($"Constraint definition '{JObject.FromObject(new { args = "arg" }).ToString()}' does not contain mandatory property 'type'.", loggedMessages.Single().Item2);
        }
コード例 #16
0
        public void TestConstantConfig()
        {
            string variableName             = "myConstant";
            string value                    = "1048576";
            ConstantMacroConfig macroConfig = new ConstantMacroConfig(null, variableName, value);

            IVariableCollection    variables  = new VariableCollection();
            IRunnableProjectConfig config     = new SimpleConfigModel();
            IParameterSet          parameters = new ParameterSet(config);
            ParameterSetter        setter     = MacroTestHelpers.TestParameterSetter(EngineEnvironmentSettings, parameters);

            ConstantMacro macro = new ConstantMacro();

            macro.EvaluateConfig(EngineEnvironmentSettings, variables, macroConfig, parameters, setter);

            ITemplateParameter constParameter;

            Assert.True(parameters.TryGetParameterDefinition(variableName, out constParameter));
            string constParamValue = (parameters.ResolvedValues[constParameter]).ToString();

            Assert.Equal(constParamValue, value);
        }
コード例 #17
0
        public void CanValidatePostActionWithoutLocalization()
        {
            IEngineEnvironmentSettings environmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true);
            string tempFolder       = _environmentSettingsHelper.CreateTemporaryFolder();
            string localizationFile = string.Format(DefaultLocalizeConfigRelativePath, "de-DE");

            WriteFile(Path.Combine(tempFolder, localizationFile), "{ \"postActions/pa0/description\": \"localizedDescription\" }", environmentSettings);

            using IMountPoint mountPoint = GetMountPointForPath(tempFolder, environmentSettings);

            SimpleConfigModel baseConfig = new SimpleConfigModel()
            {
                Identity         = "Test",
                PostActionModels = new List <PostActionModel>
                {
                    new PostActionModel()
                    {
                        Id          = "",
                        Description = "text",
                        ActionId    = Guid.NewGuid()
                    },
                    new PostActionModel()
                    {
                        Id          = "pa0",
                        Description = "text",
                        ActionId    = Guid.NewGuid()
                    },
                }
            };

            var runnableProjectConfig = new RunnableProjectConfig(environmentSettings, A.Fake <IGenerator>(), baseConfig);
            var localizationModel     = LocalizationModelDeserializer.Deserialize(mountPoint.FileInfo(localizationFile) !);

            Assert.True(runnableProjectConfig.VerifyLocalizationModel(localizationModel));

            runnableProjectConfig.ConfigurationModel.Localize(localizationModel);
            runnableProjectConfig.PostActionModels.Single(model => model.Id == "pa0" && model.Description == "localizedDescription");
            runnableProjectConfig.PostActionModels.Single(model => model.Id != "pa0" && model.Description == "text");
        }
コード例 #18
0
        public void TestRegexMacro()
        {
            string variableName   = "myRegex";
            string sourceVariable = "originalValue";
            IList <KeyValuePair <string, string> > steps = new List <KeyValuePair <string, string> >();

            steps.Add(new KeyValuePair <string, string>("2+", "3"));
            steps.Add(new KeyValuePair <string, string>("13", "Z"));
            RegexMacroConfig macroConfig = new RegexMacroConfig(variableName, sourceVariable, steps);

            IVariableCollection    variables  = new VariableCollection();
            IRunnableProjectConfig config     = new SimpleConfigModel();
            IParameterSet          parameters = new ParameterSet(config);
            ParameterSetter        setter     = MacroTestHelpers.TestParameterSetter(EngineEnvironmentSettings, parameters);

            string sourceValue   = "QQQ121222112";
            string expectedValue = "QQQZZ1Z";

            Parameter sourceParam = new Parameter
            {
                IsVariable = true,
                Name       = sourceVariable
            };

            variables[sourceVariable] = sourceValue;
            setter(sourceParam, sourceValue);

            RegexMacro macro = new RegexMacro();

            macro.EvaluateConfig(EngineEnvironmentSettings, variables, macroConfig, parameters, setter);

            ITemplateParameter newParam;

            Assert.True(parameters.TryGetParameterDefinition(variableName, out newParam));
            string newValue = (string)parameters.ResolvedValues[newParam];

            Assert.Equal(newValue, expectedValue);
        }
コード例 #19
0
ファイル: PostActionTests.cs プロジェクト: dotnet/templating
        public void TestPostActionConditioning(bool condition1, bool condition2, int expectedActionCount, string[] firstResult, string[] secondResult)
        {
            SimpleConfigModel   configModel = SimpleConfigModel.FromJObject(TestTemplateJson);
            IVariableCollection vc          = new VariableCollection
            {
                ["ActionOneCondition"] = condition1,
                ["ActionTwoCondition"] = condition2
            };
            List <IPostAction> postActions = PostAction.ListFromModel(_logger, configModel.PostActionModels, vc);

            Assert.Equal(expectedActionCount, postActions.Count);
            if (firstResult != null && firstResult.Length > 0)
            {
                Assert.True(string.Equals(postActions[0].Description, firstResult[0]), $"expected '{firstResult[0]}', but got {postActions[0].Description}");
                Assert.Equal(firstResult[1], postActions[0].ManualInstructions);
            }

            if (secondResult != null && secondResult.Length > 0)
            {
                Assert.True(string.Equals(postActions[1].Description, secondResult[0]), $"expected '{secondResult[0]}', but got {postActions[1].Description}");
                Assert.Equal(secondResult[1], postActions[1].ManualInstructions);
            }
        }
コード例 #20
0
        public void TestDeferredCaseChangeConfig()
        {
            string variableName = "myString";

            Dictionary <string, JToken> jsonParameters = new Dictionary <string, JToken>();
            string sourceVariable = "sourceString";

            jsonParameters.Add("source", sourceVariable);
            jsonParameters.Add("toLower", false);
            GeneratedSymbolDeferredMacroConfig deferredConfig = new GeneratedSymbolDeferredMacroConfig("CaseChangeMacro", null, variableName, jsonParameters);

            CaseChangeMacro        macro      = new CaseChangeMacro();
            IVariableCollection    variables  = new VariableCollection();
            IRunnableProjectConfig config     = new SimpleConfigModel();
            IParameterSet          parameters = new ParameterSet(config);
            ParameterSetter        setter     = MacroTestHelpers.TestParameterSetter(_engineEnvironmentSettings, parameters);

            string    sourceValue = "Original Value SomethingCamelCase";
            Parameter sourceParam = new Parameter
            {
                IsVariable = true,
                Name       = sourceVariable
            };

            variables[sourceVariable] = sourceValue;
            setter(sourceParam, sourceValue);

            IMacroConfig realConfig = macro.CreateConfig(_engineEnvironmentSettings, deferredConfig);

            macro.EvaluateConfig(_engineEnvironmentSettings, variables, realConfig, parameters, setter);
            ITemplateParameter convertedParam;

            Assert.True(parameters.TryGetParameterDefinition(variableName, out convertedParam));
            string convertedValue = (string)parameters.ResolvedValues[convertedParam];

            Assert.Equal(convertedValue, sourceValue.ToUpper());
        }
コード例 #21
0
        public void TestConstantDeferredConfig()
        {
            string variableName = "myConstant";
            string value        = "1048576";
            Dictionary <string, JToken> jsonParameters = new Dictionary <string, JToken>();

            jsonParameters.Add("value", value);
            GeneratedSymbolDeferredMacroConfig deferredConfig = new GeneratedSymbolDeferredMacroConfig("ConstantMacro", variableName, jsonParameters);

            IVariableCollection    variables  = new VariableCollection();
            IRunnableProjectConfig config     = new SimpleConfigModel();
            IParameterSet          parameters = new ParameterSet(config);
            ParameterSetter        setter     = MacroTestHelpers.TestParameterSetter(EngineEnvironmentSettings, parameters);

            ConstantMacro macro = new ConstantMacro();

            macro.EvaluateDeferredConfig(EngineEnvironmentSettings, variables, deferredConfig, parameters, setter);
            ITemplateParameter constParameter;

            Assert.True(parameters.TryGetParameterDefinition(variableName, out constParameter));
            string constParamValue = (parameters.ResolvedValues[constParameter]).ToString();

            Assert.Equal(constParamValue, value);
        }
コード例 #22
0
ファイル: PostActionTests.cs プロジェクト: dotnet/templating
        public void TestPostActionInstructionsConditioning(bool condition1, bool condition2, int expectedActionCount, string operatingSystemValue, string firstInstruction, string secondInstruction)
        {
            SimpleConfigModel   configModel = SimpleConfigModel.FromJObject(TestTemplateJson);
            IVariableCollection vc          = new VariableCollection
            {
                ["ActionOneCondition"]  = condition1,
                ["ActionTwoCondition"]  = condition2,
                ["OperatingSystemKind"] = operatingSystemValue
            };

            List <IPostAction> postActions = PostAction.ListFromModel(_logger, configModel.PostActionModels, vc);

            Assert.Equal(expectedActionCount, postActions.Count);

            if (!string.IsNullOrEmpty(firstInstruction))
            {
                Assert.Equal(firstInstruction, postActions[0].ManualInstructions);
            }

            if (!string.IsNullOrEmpty(secondInstruction))
            {
                Assert.Equal(secondInstruction, postActions[1].ManualInstructions);
            }
        }
コード例 #23
0
        public async void InstantiateAsync_ParamsProperlyHonored(string?parameterValue, string expectedOutput, bool instantiateShouldFail)
        {
            //
            // Template content preparation
            //

            string sourceSnippet = @"
//#if( ChoiceParam == FirstChoice )
FIRST
//#elseif (ChoiceParam == SecondChoice )
SECOND
//#elseif (ChoiceParam == ThirdChoice )
THIRD
//#else
UNKNOWN
//#endif
";
            IDictionary <string, string?> templateSourceFiles = new Dictionary <string, string?>();

            // template.json
            templateSourceFiles.Add(TestFileSystemHelper.DefaultConfigRelativePath, TemplateConfigQuotelessLiteralsEnabled);

            //content
            templateSourceFiles.Add("sourceFile", sourceSnippet);

            //
            // Dependencies preparation and mounting
            //

            IEngineEnvironmentSettings environment = _engineEnvironmentSettings;
            string sourceBasePath = FileSystemHelpers.GetNewVirtualizedPath(environment);

            TestFileSystemHelper.WriteTemplateSource(environment, sourceBasePath, templateSourceFiles);
            IMountPoint?sourceMountPoint = TestFileSystemHelper.CreateMountPoint(environment, sourceBasePath);
            RunnableProjectGenerator rpg = new RunnableProjectGenerator();
            // cannot use SimpleConfigModel dirrectly - due to missing easy way of creating ParameterSymbols
            SimpleConfigModel configModel = SimpleConfigModel.FromJObject(JObject.Parse(TemplateConfigQuotelessLiteralsEnabled));
            var runnableConfig            = new RunnableProjectConfig(environment, rpg, configModel, sourceMountPoint.FileInfo(TestFileSystemHelper.DefaultConfigRelativePath));

            TemplateCreator creator = new TemplateCreator(_engineEnvironmentSettings);

            string targetDir = FileSystemHelpers.GetNewVirtualizedPath(_engineEnvironmentSettings);

            IReadOnlyDictionary <string, string?> parameters = new Dictionary <string, string?>()
            {
                { "ChoiceParam", parameterValue }
            };

            var res = await creator.InstantiateAsync(
                templateInfo : runnableConfig,
                name : "tst",
                fallbackName : "tst2",
                inputParameters : parameters,
                outputPath : targetDir);

            if (instantiateShouldFail)
            {
                Assert.NotNull(res.ErrorMessage);
                Assert.Null(res.OutputBaseDirectory);
            }
            else
            {
                Assert.Null(res.ErrorMessage);
                Assert.NotNull(res.OutputBaseDirectory);
                string resultContent = _engineEnvironmentSettings.Host.FileSystem
                                       .ReadAllText(Path.Combine(res.OutputBaseDirectory !, "sourceFile")).Trim();
                Assert.Equal(expectedOutput, resultContent);
            }
        }
コード例 #24
0
 public TestTemplateSetup(IEngineEnvironmentSettings environment, string sourceBaseDir, IDictionary <string, string> sourceFiles, SimpleConfigModel configModel)
 {
     _environmentSettings = environment;
     _sourceFiles         = sourceFiles;
     _configModel         = configModel;
     _sourceBaseDir       = sourceBaseDir;
     _configFile          = TestFileSystemHelper.DefaultConfigRelativePath;
 }
コード例 #25
0
        public void CanGenerateFileRenamesForSymbolBasedRenames_Forms()
        {
            //environment
            IEngineEnvironmentSettings environment = _environmentSettingsHelper.CreateEnvironment();

            //simulate template files
            string sourceBasePath = FileSystemHelpers.GetNewVirtualizedPath(environment);
            IDictionary <string, string?> templateSourceFiles = new Dictionary <string, string?>();

            // template.json
            templateSourceFiles.Add(TemplateConfigTestHelpers.DefaultConfigRelativePath, string.Empty);
            // content
            templateSourceFiles.Add("Replace1_file.txt", null);
            templateSourceFiles.Add("replace2_file.txt", null);
            templateSourceFiles.Add("REPLACE3_file.txt", null);
            TestTemplateSetup setup = new TestTemplateSetup(environment, sourceBasePath, templateSourceFiles);

            setup.WriteSource();

            //get target directory
            string targetDir = FileSystemHelpers.GetNewVirtualizedPath(environment);

            //prepare parameters
            ParameterSet parameters    = new ParameterSet(SimpleConfigModel.FromJObject(environment, JObject.Parse("{}")));
            Parameter    nameParameter = new Parameter()
            {
                Name = "name"
            };
            Parameter testParameterIdentity = new Parameter()
            {
                Name = "test{-VALUE-FORMS-}identity"
            };
            Parameter testParameterUC = new Parameter()
            {
                Name = "test{-VALUE-FORMS-}uc"
            };
            Parameter testParameterLC = new Parameter()
            {
                Name = "test{-VALUE-FORMS-}lc"
            };

            parameters.AddParameter(nameParameter);
            parameters.AddParameter(testParameterIdentity);
            parameters.AddParameter(testParameterUC);
            parameters.AddParameter(testParameterLC);
            parameters.ResolvedValues[nameParameter]         = "testName";
            parameters.ResolvedValues[testParameterIdentity] = "TestProject";
            parameters.ResolvedValues[testParameterUC]       = "TESTPROJECT";
            parameters.ResolvedValues[testParameterLC]       = "testproject";

            //prepare renames configuration
            List <IReplacementTokens> symbolBasedRenames = new List <IReplacementTokens>();

            symbolBasedRenames.Add(new ReplacementTokens("test{-VALUE-FORMS-}identity", TokenConfig.FromValue("Replace")));
            symbolBasedRenames.Add(new ReplacementTokens("test{-VALUE-FORMS-}uc", TokenConfig.FromValue("REPLACE")));
            symbolBasedRenames.Add(new ReplacementTokens("test{-VALUE-FORMS-}lc", TokenConfig.FromValue("replace")));

            IReadOnlyDictionary <string, string> allChanges = setup.GetRenames("./", targetDir, parameters, symbolBasedRenames);

            Assert.Equal(3, allChanges.Count);
            Assert.Equal("TestProject1_file.txt", allChanges["Replace1_file.txt"]);
            Assert.Equal("TESTPROJECT3_file.txt", allChanges["REPLACE3_file.txt"]);
            Assert.Equal("testproject2_file.txt", allChanges["replace2_file.txt"]);
        }
コード例 #26
0
        public async void CreateAsyncTest_MultiChoiceParamJoining()
        {
            //
            // Template content preparation
            //

            string templateConfig = @"
{
  ""identity"": ""test.template"",
  ""symbols"": {
    ""Platform"": {
      ""type"": ""parameter"",
      ""description"": ""The target framework for the project."",
      ""datatype"": ""choice"",
      ""allowMultipleValues"": true,
      ""choices"": [
        {
          ""choice"": ""Windows"",
          ""description"": ""Windows Desktop""
        },
        {
          ""choice"": ""WindowsPhone"",
          ""description"": ""Windows Phone""
        },
        {
          ""choice"": ""MacOS"",
          ""description"": ""Macintosh computers""
        },
        {
          ""choice"": ""iOS"",
          ""description"": ""iOS mobile""
        },
        {
          ""choice"": ""android"",
          ""description"": ""android mobile""
        },
        {
          ""choice"": ""nix"",
          ""description"": ""Linux distributions""
        }
      ],
      ""defaultValue"": ""MacOS|iOS""
    },
    ""joinedRename"": {
      ""type"": ""generated"",
      ""generator"": ""join"",
      ""replaces"": ""SupportedPlatforms"",
      ""parameters"": {
        ""symbols"": [
          {
            ""type"": ""ref"",
            ""value"": ""Platform""
          }
        ],
        ""separator"": "", "",
        ""removeEmptyValues"": true,
      }
    }
  }
}
";

            string sourceSnippet = @"
// This file is generated for platfrom: SupportedPlatforms
";

            string expectedSnippet = @"
// This file is generated for platfrom: MacOS, iOS
";

            IDictionary <string, string?> templateSourceFiles = new Dictionary <string, string?>();

            // template.json
            templateSourceFiles.Add(TestFileSystemHelper.DefaultConfigRelativePath, templateConfig);

            //content
            templateSourceFiles.Add("sourcFile", sourceSnippet);

            //
            // Dependencies preparation and mounting
            //

            IEngineEnvironmentSettings environment = _environmentSettingsHelper.CreateEnvironment();
            string sourceBasePath = FileSystemHelpers.GetNewVirtualizedPath(environment);
            string targetDir      = FileSystemHelpers.GetNewVirtualizedPath(environment);

            TestFileSystemHelper.WriteTemplateSource(environment, sourceBasePath, templateSourceFiles);
            IMountPoint?sourceMountPoint            = TestFileSystemHelper.CreateMountPoint(environment, sourceBasePath);
            RunnableProjectGenerator rpg            = new RunnableProjectGenerator();
            SimpleConfigModel        configModel    = SimpleConfigModel.FromJObject(JObject.Parse(templateConfig));
            IRunnableProjectConfig   runnableConfig = new RunnableProjectConfig(environment, rpg, configModel, sourceMountPoint.FileInfo(TestFileSystemHelper.DefaultConfigRelativePath));
            IParameterSet            parameters     = new ParameterSet(runnableConfig);
            ITemplateParameter       choiceParameter;

            Assert.True(parameters.TryGetParameterDefinition("Platform", out choiceParameter), "ChoiceParam expected to be extracted from template config");
            parameters.ResolvedValues[choiceParameter] = new MultiValueParameter(new[] { "MacOS", "iOS" });
            IDirectory sourceDir = sourceMountPoint !.DirectoryInfo("/") !;

            //
            // Running the actual scenario: template files processing and generating output (including macros processing)
            //

            await rpg.CreateAsync(environment, runnableConfig, sourceDir, parameters, targetDir, CancellationToken.None);

            //
            // Veryfying the outputs
            //

            string resultContent = environment.Host.FileSystem.ReadAllText(Path.Combine(targetDir, "sourcFile"));

            Assert.Equal(expectedSnippet, resultContent);
        }
コード例 #27
0
        public async void CreateAsyncTest_GuidsMacroProcessingCaseSensitivity()
        {
            //
            // Template content preparation
            //

            Guid              inputTestGuid         = new Guid("12aa8f4e-a4aa-4ac1-927c-94cb99485ef1");
            string            contentFileNamePrefix = "content - ";
            SimpleConfigModel config = new SimpleConfigModel()
            {
                Identity = "test",
                Guids    = new List <Guid>()
                {
                    inputTestGuid
                }
            };

            IDictionary <string, string?> templateSourceFiles = new Dictionary <string, string?>();

            // template.json
            templateSourceFiles.Add(TestFileSystemHelper.DefaultConfigRelativePath, config.ToJObject().ToString());

            //content
            foreach (string guidFormat in GuidMacroConfig.DefaultFormats.Select(c => c.ToString()))
            {
                templateSourceFiles.Add(contentFileNamePrefix + guidFormat, inputTestGuid.ToString(guidFormat));
            }

            //
            // Dependencies preparation and mounting
            //

            IEngineEnvironmentSettings environment = _environmentSettingsHelper.CreateEnvironment();
            string sourceBasePath        = FileSystemHelpers.GetNewVirtualizedPath(environment);
            string targetDir             = FileSystemHelpers.GetNewVirtualizedPath(environment);
            RunnableProjectGenerator rpg = new RunnableProjectGenerator();

            TestFileSystemHelper.WriteTemplateSource(environment, sourceBasePath, templateSourceFiles);
            IMountPoint?           sourceMountPoint = TestFileSystemHelper.CreateMountPoint(environment, sourceBasePath);
            IRunnableProjectConfig runnableConfig   = new RunnableProjectConfig(environment, rpg, config, sourceMountPoint.FileInfo(TestFileSystemHelper.DefaultConfigRelativePath));
            IParameterSet          parameters       = new ParameterSet(runnableConfig);
            IDirectory             sourceDir        = sourceMountPoint !.DirectoryInfo("/") !;

            //
            // Running the actual scenario: template files processing and generating output (including macros processing)
            //

            await rpg.CreateAsync(environment, runnableConfig, sourceDir, parameters, targetDir, CancellationToken.None);

            //
            // Veryfying the outputs
            //

            Guid expectedResultGuid = Guid.Empty;

            foreach (string guidFormat in GuidMacroConfig.DefaultFormats.Select(c => c.ToString()))
            {
                string resultContent = environment.Host.FileSystem.ReadAllText(Path.Combine(targetDir, contentFileNamePrefix + guidFormat));
                Guid   resultGuid;
                Assert.True(
                    Guid.TryParseExact(resultContent, guidFormat, out resultGuid),
                    $"Expected the result conent ({resultContent}) to be parseable by Guid format '{guidFormat}'");

                if (expectedResultGuid == Guid.Empty)
                {
                    expectedResultGuid = resultGuid;
                }
                else
                {
                    Assert.Equal(expectedResultGuid, resultGuid);
                }
            }
            Assert.NotEqual(inputTestGuid, expectedResultGuid);
        }
コード例 #28
0
        public async void CreateAsyncTest_MultiChoiceParamReplacingAndCondition()
        {
            //
            // Template content preparation
            //

            string templateConfig = @"
{
    ""identity"": ""test.template"",
    ""symbols"": {	
	    ""ChoiceParam"": {
	      ""type"": ""parameter"",
	      ""description"": ""sample switch"",
	      ""datatype"": ""choice"",
          ""allowMultipleValues"": true,
          ""enableQuotelessLiterals"": true,
	      ""choices"": [
		    {
		      ""choice"": ""FirstChoice"",
		      ""description"": ""First Sample Choice""
		    },
		    {
		      ""choice"": ""SecondChoice"",
		      ""description"": ""Second Sample Choice""
		    },
		    {
		      ""choice"": ""ThirdChoice"",
		      ""description"": ""Third Sample Choice""
		    }
	      ],
          ""defaultValue"": ""ThirdChoice"",
          ""replaces"": ""REPLACE_VALUE""
        }
    }
}
";

            string sourceSnippet = @"
MultiChoiceValue: REPLACE_VALUE
//#if( ChoiceParam == FirstChoice )
FIRST
//#endif
//#if (ChoiceParam == SecondChoice )
SECOND
//#endif
//#if (ChoiceParam == ThirdChoice )
THIRD
//#endif
";

            string expectedSnippet = @"
MultiChoiceValue: SecondChoice|ThirdChoice
SECOND
THIRD
";

            IDictionary <string, string?> templateSourceFiles = new Dictionary <string, string?>();

            // template.json
            templateSourceFiles.Add(TestFileSystemHelper.DefaultConfigRelativePath, templateConfig);

            //content
            templateSourceFiles.Add("sourcFile", sourceSnippet);

            //
            // Dependencies preparation and mounting
            //

            IEngineEnvironmentSettings environment = _environmentSettingsHelper.CreateEnvironment();
            string sourceBasePath = FileSystemHelpers.GetNewVirtualizedPath(environment);
            string targetDir      = FileSystemHelpers.GetNewVirtualizedPath(environment);

            TestFileSystemHelper.WriteTemplateSource(environment, sourceBasePath, templateSourceFiles);
            IMountPoint?sourceMountPoint            = TestFileSystemHelper.CreateMountPoint(environment, sourceBasePath);
            RunnableProjectGenerator rpg            = new RunnableProjectGenerator();
            SimpleConfigModel        configModel    = SimpleConfigModel.FromJObject(JObject.Parse(templateConfig));
            IRunnableProjectConfig   runnableConfig = new RunnableProjectConfig(environment, rpg, configModel, sourceMountPoint.FileInfo(TestFileSystemHelper.DefaultConfigRelativePath));
            IParameterSet            parameters     = new ParameterSet(runnableConfig);
            ITemplateParameter       choiceParameter;

            Assert.True(parameters.TryGetParameterDefinition("ChoiceParam", out choiceParameter), "ChoiceParam expected to be extracted from template config");
            parameters.ResolvedValues[choiceParameter] = new MultiValueParameter(new[] { "SecondChoice", "ThirdChoice" });
            IDirectory sourceDir = sourceMountPoint !.DirectoryInfo("/") !;

            //
            // Running the actual scenario: template files processing and generating output (including macros processing)
            //

            await rpg.CreateAsync(environment, runnableConfig, sourceDir, parameters, targetDir, CancellationToken.None);

            //
            // Veryfying the outputs
            //

            string resultContent = environment.Host.FileSystem.ReadAllText(Path.Combine(targetDir, "sourcFile"));

            Assert.Equal(expectedSnippet, resultContent);
        }
コード例 #29
0
        public void PerformTemplateValidation_ChoiceValuesValidation(string paramDefintion, bool isMultichoice, bool expectedToBeValid)
        {
            //
            // Template content preparation
            //

            Guid    inputTestGuid         = new Guid("12aa8f4e-a4aa-4ac1-927c-94cb99485ef1");
            string  contentFileNamePrefix = "content - ";
            JObject choiceParam           = JObject.Parse(paramDefintion);

            choiceParam["AllowMultipleValues"] = isMultichoice;
            SimpleConfigModel config = new SimpleConfigModel()
            {
                Identity      = "test",
                Name          = "name",
                ShortNameList = new [] { "shortName" },
                Symbols       = new Dictionary <string, ISymbolModel>()
                {
                    { "ParamA", new ParameterSymbol(choiceParam, null) }
                }
            };

            IDictionary <string, string?> templateSourceFiles = new Dictionary <string, string?>();

            // template.json
            templateSourceFiles.Add(TestFileSystemHelper.DefaultConfigRelativePath, config.ToJObject().ToString());

            //content
            foreach (string guidFormat in GuidMacroConfig.DefaultFormats.Select(c => c.ToString()))
            {
                templateSourceFiles.Add(contentFileNamePrefix + guidFormat, inputTestGuid.ToString(guidFormat));
            }

            //
            // Dependencies preparation and mounting
            //

            List <(LogLevel, string)>  loggedMessages = new List <(LogLevel, string)>();
            InMemoryLoggerProvider     loggerProvider = new InMemoryLoggerProvider(loggedMessages);
            IEngineEnvironmentSettings environment    = _environmentSettingsHelper.CreateEnvironment(addLoggerProviders: new [] { loggerProvider });
            string sourceBasePath        = FileSystemHelpers.GetNewVirtualizedPath(environment);
            string targetDir             = FileSystemHelpers.GetNewVirtualizedPath(environment);
            RunnableProjectGenerator rpg = new RunnableProjectGenerator();

            TestFileSystemHelper.WriteTemplateSource(environment, sourceBasePath, templateSourceFiles);
            IMountPoint?          sourceMountPoint = TestFileSystemHelper.CreateMountPoint(environment, sourceBasePath);
            RunnableProjectConfig runnableConfig   = new RunnableProjectConfig(environment, rpg, config, sourceMountPoint.FileInfo(TestFileSystemHelper.DefaultConfigRelativePath));

            if (expectedToBeValid)
            {
                runnableConfig.PerformTemplateValidation();
                Assert.Empty(loggedMessages.Where(l => l.Item1 >= LogLevel.Warning));
            }
            else
            {
                var exc = Assert.Throws <TemplateValidationException>(runnableConfig.PerformTemplateValidation);
                Assert.Contains("The template configuration ", exc.Message);
                Assert.Contains(" is not valid.", exc.Message);
                Assert.Single(loggedMessages.Where(l => l.Item1 >= LogLevel.Warning));
                string errorMessage = loggedMessages.First(l => l.Item1 >= LogLevel.Warning).Item2;
                Assert.Contains(
                    "Choice parameter  is invalid. It allows multiple values ('AllowMultipleValues=true'), while some of the configured choices contain separator characters ('|', ','). Invalid choices: {First|Choice}",
                    errorMessage);
            }
        }