Exemple #1
0
        public async Task Evaluate_ArrayOfVersions(IReadOnlyList <string> workloads, bool allowed)
        {
            var config = new
            {
                identity    = "test-constraint-01",
                constraints = new
                {
                    specVersions = new
                    {
                        type = "workload",
                        args = new[] { "workloadA", "workloadB" }
                    }
                }
            };

            var configModel = SimpleConfigModel.FromJObject(JObject.FromObject(config));
            IWorkloadsInfoProvider     workloadInfoProvider = new WorkloadsInfoProviderMock(workloads); //A.Fake<IWorkloadsInfoProvider>();
            IEngineEnvironmentSettings settings             = A.Fake <IEngineEnvironmentSettings>();

            A.CallTo(() => settings.Components.OfType <IWorkloadsInfoProvider>()).Returns(new[] { workloadInfoProvider });
            A.CallTo(() => settings.Components.OfType <ITemplateConstraintFactory>()).Returns(new[] { new WorkloadConstraintFactory() });

            var constraintManager = new TemplateConstraintManager(settings);

            //A.CallTo(() => workloadInfoProvider
            //    .GetInstalledWorkloadsAsync(A<CancellationToken>._))
            //    .Returns(Task.FromResult(workloads.Select(s => new WorkloadInfo(s, $"D:{s}"))));

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

            Assert.Equal(allowed ? TemplateConstraintResult.Status.Allowed : TemplateConstraintResult.Status.Restricted, evaluateResult.EvaluationStatus);
        }
        public void CheckTemplateRootRelativeToInstallPath(string pathToTemplateJson, bool shouldAllPathsBeValid)
        {
            SimpleConfigModel        baseConfig = SimpleConfigModel.FromJObject(JObject.Parse(BasicTemplateConfig));
            RunnableProjectGenerator generator  = new RunnableProjectGenerator();

            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();

            IFile templateFile = setup.FileInfoForSourceFile(pathToTemplateJson);
            RunnableProjectConfig templateModel = new RunnableProjectConfig(_engineEnvironmentSettings, generator, baseConfig, templateFile);

            if (shouldAllPathsBeValid)
            {
                Assert.Empty(templateModel.ValidateTemplateSourcePaths());
            }
            else
            {
                Assert.NotEmpty(templateModel.ValidateTemplateSourcePaths());
            }
        }
Exemple #3
0
        public async void CreateAsyncTest_ConditionWithUnquotedChoiceLiteral(string templateConfig, string expectedResult)
        {
            //
            // 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, 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] = "SecondChoice";
            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")).Trim();

            Assert.Equal(expectedResult, resultContent);
        }
        public async Task Evaluate_AlternativeInstalledVersions(string sdkVersion, IReadOnlyList <string> installedVersions, bool hasAlternativeInstalled)
        {
            var config = new
            {
                identity    = "test-constraint-01",
                constraints = new
                {
                    specVersions = new
                    {
                        type = "sdk-version",
                        args = new[] { "1.2.3-*", "4.5.*" }
                    }
                }
            };

            var configModel = SimpleConfigModel.FromJObject(JObject.FromObject(config));
            ISdkInfoProvider           sdkInfoProvider = new SdkInfoProviderMock(sdkVersion, installedVersions); //A.Fake<ISdkInfoProvider>();
            IEngineEnvironmentSettings settings        = A.Fake <IEngineEnvironmentSettings>();

            A.CallTo(() => settings.Components.OfType <ISdkInfoProvider>()).Returns(new[] { sdkInfoProvider });
            A.CallTo(() => settings.Components.OfType <ITemplateConstraintFactory>()).Returns(new[] { new SdkVersionConstraintFactory() });

            var constraintManager = new TemplateConstraintManager(settings);

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

            Assert.Equal(TemplateConstraintResult.Status.Restricted, evaluateResult.EvaluationStatus);
            Assert.StartsWith(
                hasAlternativeInstalled
                    ? "Sample CTA with alternatives"
                    : "Sample CTA without alternatives",
                evaluateResult.CallToAction);
        }
        public void Evaluate_SingleVersionRange(string sdkVersion, bool allowed)
        {
            var config = new
            {
                identity    = "test-constraint-01",
                constraints = new
                {
                    specVersions = new
                    {
                        type = "sdk-version",
                        args = "(1.2.3-*, 4.5]"
                    }
                }
            };

            var configModel = SimpleConfigModel.FromJObject(JObject.FromObject(config));
            ISdkInfoProvider           sdkInfoProvider = new SdkInfoProviderMock(sdkVersion); //A.Fake<ISdkInfoProvider>();
            IEngineEnvironmentSettings settings        = A.Fake <IEngineEnvironmentSettings>();

            A.CallTo(() => settings.Components.OfType <ISdkInfoProvider>()).Returns(new[] { sdkInfoProvider });
            A.CallTo(() => settings.Components.OfType <ITemplateConstraintFactory>()).Returns(new[] { new SdkVersionConstraintFactory() });

            var constraintManager = new TemplateConstraintManager(settings);

            //Workaround needed
            //A.CallTo(() => sdkInfoProvider.GetVersionAsync(A<CancellationToken>._)).Returns(t);

            var evaluateResult = constraintManager.EvaluateConstraintAsync(configModel.Constraints.Single().Type, configModel.Constraints.Single().Args, default).Result;

            Assert.Equal(allowed ? TemplateConstraintResult.Status.Allowed : TemplateConstraintResult.Status.Restricted, evaluateResult.EvaluationStatus);
        }
        public void CheckTemplateSourcesRelativeToTemplateRootMultipleDirsUnderMountPoint(bool shouldAllPathsBeValid, string source)
        {
            const string pathFromMountPointRootToTemplateRoot = "MountRoot/Stuff/TemplateRoot/";
            string       pathToTemplateConfig = pathFromMountPointRootToTemplateRoot + ".template.config/template.json";

            string sourcePath = FileSystemHelpers.GetNewVirtualizedPath(EngineEnvironmentSettings);
            IDictionary <string, string> templateSourceFiles = new Dictionary <string, string>();

            string templateConfig = String.Format(TemplateConfigWithSourcePlaceholder, source);

            templateSourceFiles.Add(pathToTemplateConfig, templateConfig);

            string sampleContentDir = pathFromMountPointRootToTemplateRoot + "things/stuff/_._";

            templateSourceFiles.Add(sampleContentDir, "");    // directories under the template root - valid source locations.
            templateSourceFiles.Add("ExistingDir/_._", "");
            templateSourceFiles.Add("MountRoot/Subdir/_._", "");
            TestTemplateSetup setup = new TestTemplateSetup(EngineEnvironmentSettings, sourcePath, templateSourceFiles);

            setup.WriteSource();

            RunnableProjectGenerator generator = new RunnableProjectGenerator();

            IFile                   templateFile            = setup.FileInfoForSourceFile(pathToTemplateConfig);
            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);
        }
        public async Task CanReadArrayConfiguration()
        {
            var config = new
            {
                identity    = "test",
                constraints = new
                {
                    winOnly = new
                    {
                        type = "os",
                        args = new[] { "Windows", "Linux" }
                    }
                }
            };

            var configModel       = SimpleConfigModel.FromJObject(JObject.FromObject(config));
            var constraintManager = new TemplateConstraintManager(_sharedSettings);
            var evaluateResult    = await constraintManager.EvaluateConstraintAsync(configModel.Constraints.Single().Type, configModel.Constraints.Single().Args, default).ConfigureAwait(false);

            var pass = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux);

            Assert.Equal(pass, evaluateResult.EvaluationStatus == TemplateConstraintResult.Status.Allowed);

            if (!pass)
            {
                Assert.Equal($"Running template on {RuntimeInformation.OSDescription} is not supported, supported OS is/are: {OSPlatform.Windows}, {OSPlatform.Linux}.", evaluateResult.LocalizedErrorMessage);
            }
            else
            {
                Assert.Null(evaluateResult.LocalizedErrorMessage);
            }
            Assert.Null(evaluateResult.CallToAction);
        }
        public async Task FailsOnWrongConfiguration()
        {
            var config = new
            {
                identity    = "test",
                constraints = new
                {
                    host = new
                    {
                        type = "host",
                        args =
                            new
                        {
                            hostName = "host2",
                            version  = "1.0.0"
                        }
                    }
                }
            };

            var configModel = SimpleConfigModel.FromJObject(JObject.FromObject(config));

            IEngineEnvironmentSettings settings = A.Fake <IEngineEnvironmentSettings>();

            A.CallTo(() => settings.Host.HostIdentifier).Returns("host3");
            A.CallTo(() => settings.Host.Version).Returns("2.0.0");
            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);

            Assert.Equal(TemplateConstraintResult.Status.NotEvaluated, evaluateResult.EvaluationStatus);
            Assert.Equal("'{\"hostName\":\"host2\",\"version\":\"1.0.0\"}' is not a valid JSON array.", evaluateResult.LocalizedErrorMessage);
            Assert.Equal("Check the constraint configuration in template.json.", evaluateResult.CallToAction);
        }
        public void UnknownFormNameForDerivedSymbolValueDoesNotThrow()
        {
            string            templateJson = @"
{
  ""name"": ""TestTemplate"",
  ""identity"": ""TestTemplate"",
  ""symbols"": {
    ""original"": {
      ""type"": ""parameter"",
      ""replaces"": ""whatever"",
    },
    ""myDerivedSym"": {
      ""type"": ""derived"",
      ""valueSource"": ""original"",
      ""valueTransform"": ""fakeForm"",
      ""replaces"": ""something""
    }
  }
}
";
            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);
        }
        public void CheckTemplateSourcesRelativeToTemplateRootMultipleDirsUnderMountPoint(bool shouldAllPathsBeValid, string source)
        {
            string                   templateConfig = string.Format(TemplateConfigWithSourcePlaceholder, source);
            SimpleConfigModel        baseConfig     = SimpleConfigModel.FromJObject(JObject.Parse(templateConfig));
            RunnableProjectGenerator generator      = new RunnableProjectGenerator();

            const string pathFromMountPointRootToTemplateRoot = "MountRoot/Stuff/TemplateRoot/";
            string       pathToTemplateConfig = pathFromMountPointRootToTemplateRoot + ".template.config/template.json";

            string sourcePath = FileSystemHelpers.GetNewVirtualizedPath(_engineEnvironmentSettings);
            IDictionary <string, string> templateSourceFiles = new Dictionary <string, string>();

            templateSourceFiles.Add(pathToTemplateConfig, templateConfig);

            string sampleContentDir = pathFromMountPointRootToTemplateRoot + "things/stuff/_._";

            templateSourceFiles.Add(sampleContentDir, "");    // directories under the template root - valid source locations.
            templateSourceFiles.Add("ExistingDir/_._", "");
            templateSourceFiles.Add("MountRoot/Subdir/_._", "");
            TestTemplateSetup setup = new TestTemplateSetup(_engineEnvironmentSettings, sourcePath, templateSourceFiles);

            setup.WriteSource();

            IFile templateFile = setup.FileInfoForSourceFile(pathToTemplateConfig);
            RunnableProjectConfig templateModel = new RunnableProjectConfig(_engineEnvironmentSettings, generator, baseConfig, templateFile);

            if (shouldAllPathsBeValid)
            {
                Assert.Empty(templateModel.ValidateTemplateSourcePaths());
            }
            else
            {
                Assert.NotEmpty(templateModel.ValidateTemplateSourcePaths());
            }
        }
Exemple #11
0
        public void CanGenerateFileRenamesForSymbolBasedRenames_NonString()
        {
            //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("date_name.txt", null);
            templateSourceFiles.Add("other_name.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 intDateParameter = new Parameter()
            {
                Name = "date"
            };
            Parameter otherParameter = new Parameter()
            {
                Name = "other"
            };

            parameters.AddParameter(nameParameter);
            parameters.AddParameter(intDateParameter);
            parameters.AddParameter(otherParameter);
            parameters.ResolvedValues[nameParameter]    = "testName";
            parameters.ResolvedValues[intDateParameter] = 20210429;
            parameters.ResolvedValues[otherParameter]   = new TestParameterValueClass {
                A = "foo", B = "bar"
            };

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

            symbolBasedRenames.Add(new ReplacementTokens("date", TokenConfig.FromValue("date")));
            symbolBasedRenames.Add(new ReplacementTokens("other", TokenConfig.FromValue("other")));
            symbolBasedRenames.Add(new ReplacementTokens("name", TokenConfig.FromValue("name")));

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

            Assert.Equal(2, allChanges.Count);
            Assert.Equal("20210429_testName.txt", allChanges["date_name.txt"]);
            Assert.Equal("foo-bar_testName.txt", allChanges["other_name.txt"]);
        }
Exemple #12
0
        public void CanGenerateFileRenamesForSymbolBasedRenames_WhenFormsResultInSameValue()
        {
            //environment
            IEngineEnvironmentSettings environment = TemplateConfigTestHelpers.GetTestEnvironment();

            //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);
            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 testParameterLC = new Parameter()
            {
                Name = "test{-VALUE-FORMS-}lc"
            };

            parameters.AddParameter(nameParameter);
            parameters.AddParameter(testParameterIdentity);
            parameters.AddParameter(testParameterLC);
            parameters.ResolvedValues[nameParameter]         = "testName";
            parameters.ResolvedValues[testParameterIdentity] = "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-}lc", TokenConfig.FromValue("replace")));


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

            Assert.Equal(2, allChanges.Count);
            Assert.Equal("testproject1_file.txt", allChanges["replace1_file.txt"]);
            Assert.Equal("testproject2_file.txt", allChanges["replace2_file.txt"]);
        }
Exemple #13
0
        public void CanReadFilenameReplacementConfigWithForms()
        {
            string                     configContent  = @"
{
  ""identity"": ""test"",
  ""symbols"": {
	""testparam"": {
      ""type"": ""parameter"",
      ""datatype"": ""string"",
	  ""fileRename"": ""TestParamFileReplacement"",
      ""forms"": {
        ""global"" : [ ""identity"", ""lc"", ""uc""]
      }
    },
    ""testgenerated"": {
      ""type"": ""generated"",
      ""generator"": ""casing"",
      ""parameters"": {
        ""source"": ""name"",
        ""toLower"": true
      },
	  ""fileRename"": ""testgeneratedfilereplacement""
    },
    ""testgenerated2"": {
      ""type"": ""generated"",
      ""generator"": ""casing"",
      ""parameters"": {
        ""source"": ""name"",
        ""toLower"": true
      },
	  ""replace"": ""testgeneratedreplacement""
    },
  },
  ""forms"": {
    ""lc"": {
        ""identifier"": ""lowercase""
    },
    ""uc"": {
        ""identifier"": ""uppercase""
    }
  }
}";
            SimpleConfigModel          configModel    = SimpleConfigModel.FromJObject(JObject.Parse(configContent));
            IEngineEnvironmentSettings environment    = _environmentSettingsHelper.CreateEnvironment();
            RunnableProjectConfig      runnableConfig =
                new RunnableProjectConfig(environment, A.Fake <IGenerator>(), configModel);

            Assert.Equal(4, runnableConfig.SymbolFilenameReplacements.Count);
            Assert.Equal(3, runnableConfig.SymbolFilenameReplacements.Count(x => x.VariableName.Contains("testparam")));
            Assert.Equal("TestParamFileReplacement", runnableConfig.SymbolFilenameReplacements.Single(x => x.VariableName == "testparam{-VALUE-FORMS-}identity").OriginalValue.Value);
            Assert.Equal("TESTPARAMFILEREPLACEMENT", runnableConfig.SymbolFilenameReplacements.Single(x => x.VariableName == "testparam{-VALUE-FORMS-}uc").OriginalValue.Value);
            Assert.Equal("testparamfilereplacement", runnableConfig.SymbolFilenameReplacements.Single(x => x.VariableName == "testparam{-VALUE-FORMS-}lc").OriginalValue.Value);
            Assert.Equal("testgeneratedfilereplacement", runnableConfig.SymbolFilenameReplacements.Single(x => x.VariableName == "testgenerated").OriginalValue.Value);
        }
        public void ExplicitNameSymbolWithCustomBindingRetainsCustomBinding()
        {
            SimpleConfigModel configModel = SimpleConfigModel.FromJObject(_engineEnvironmentSettings, ConfigWithNameSymbolWithCustomBinding);

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

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

            Assert.True(symbolInfo is ParameterSymbol);

            ParameterSymbol nameSymbol = symbolInfo as ParameterSymbol;

            Assert.Equal("customBinding", symbolInfo.Binding);
        }
        // Note: this does not deal with configs split into multiple files.
        public static IRunnableProjectConfig ConfigFromSource(IEngineEnvironmentSettings environment, IMountPoint mountPoint, string configFile = null)
        {
            if (string.IsNullOrEmpty(configFile))
            {
                configFile = DefaultConfigRelativePath;
            }

            string fullPath      = Path.Combine(mountPoint.Info.Place, configFile);
            string configContent = environment.Host.FileSystem.ReadAllText(fullPath);

            JObject configJson = JObject.Parse(configContent);

            return(SimpleConfigModel.FromJObject(environment, configJson));
        }
        public void ExplicitNameSymbolWithoutBindingGetsDefaultNameBinding()
        {
            SimpleConfigModel configModel = SimpleConfigModel.FromJObject(ConfigWithNameSymbolWithoutBinding);

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

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

            Assert.True(symbolInfo is ParameterSymbol);

            ParameterSymbol nameSymbol = symbolInfo as ParameterSymbol;

            Assert.Equal("name", symbolInfo.Binding);
        }
Exemple #17
0
        public void CanReadConstraintDefinition()
        {
            var json = new
            {
                identity    = "test",
                constraints = new
                {
                    one = new
                    {
                        type = "con1",
                        args = "arg"
                    },
                    two = new
                    {
                        type = "con2",
                        args = new[]
                        {
                            "one", "two", "three"
                        }
                    },
                    three = new
                    {
                        type = "con3",
                        args = new
                        {
                            one = "one",
                            two = "two",
                        }
                    },
                    four = new
                    {
                        type = "con4"
                    },
                }
            };

            var model = SimpleConfigModel.FromJObject(JObject.FromObject(json));

            Assert.Equal(4, model.Constraints.Count);
            Assert.Equal("con1", model.Constraints[0].Type);
            Assert.Equal("con2", model.Constraints[1].Type);
            Assert.Equal("con3", model.Constraints[2].Type);
            Assert.Equal("con4", model.Constraints[3].Type);

            Assert.Equal("\"arg\"", model.Constraints[0].Args);
            Assert.Equal("[\"one\",\"two\",\"three\"]", model.Constraints[1].Args);
            Assert.Equal("{\"one\":\"one\",\"two\":\"two\"}", model.Constraints[2].Args);
            Assert.Null(model.Constraints[3].Args);
        }
Exemple #18
0
        // Note: this does not deal with configs split into multiple files.
        internal static IRunnableProjectConfig ConfigFromSource(IEngineEnvironmentSettings environment, IMountPoint mountPoint, string configFile = null)
        {
            if (string.IsNullOrEmpty(configFile))
            {
                configFile = DefaultConfigRelativePath;
            }

            using Stream stream             = mountPoint.FileInfo(configFile).OpenRead();
            using StreamReader streamReader = new StreamReader(stream);
            string configContent = streamReader.ReadToEnd();

            JObject configJson = JObject.Parse(configContent);

            return(SimpleConfigModel.FromJObject(environment, configJson));
        }
        public void ParameterSymbolWithNoValueFormsGetsIdentityFormAdded()
        {
            SimpleConfigModel configModel = SimpleConfigModel.FromJObject(_engineEnvironmentSettings, ConfigForSymbolWithoutValueForms);

            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(1, configuredValueFormNames.Count);
            Assert.Equal(IdentityValueForm.FormName, configuredValueFormNames[0]);
        }
        public async Task CanProcessDifferentHostNames(string hostName, string fallbackHostNames, string hostVersion, bool expectedResult)
        {
            var config = new
            {
                identity    = "test",
                constraints = new
                {
                    host = new
                    {
                        type = "host",
                        args = new[]
                        {
                            new
                            {
                                hostName = "host1",
                                version  = "[1.0, 2.0]"
                            },
                            new
                            {
                                hostName = "fallback",
                                version  = "[2.0, 3.0]"
                            },
                        }
                    }
                }
            };

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

            A.CallTo(() => settings.Host.HostIdentifier).Returns(hostName);
            A.CallTo(() => settings.Host.Version).Returns(hostVersion);
            A.CallTo(() => settings.Host.FallbackHostTemplateConfigNames).Returns(fallbackHostNames.Split('|'));
            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);
            }
        }
        public void ParameterSymbolWithoutIdentityValueFormGetsIdentityAddedAsFirst()
        {
            SimpleConfigModel configModel = SimpleConfigModel.FromJObject(_engineEnvironmentSettings, ArrayConfigForSymbolWithFormsButNotIdentity);

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

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

            Assert.True(symbolInfo is ParameterSymbol);

            ParameterSymbol paramSymbol = symbolInfo as ParameterSymbol;

            Assert.Single(paramSymbol.Forms.GlobalForms.ToList()
                          .Where(x => string.Equals(x, IdentityValueForm.FormName, StringComparison.OrdinalIgnoreCase))
                          );
            Assert.Equal(0, paramSymbol.Forms.GlobalForms.ToList().IndexOf(IdentityValueForm.FormName));
        }
        public async Task CanReadConfiguration_ExactVersion()
        {
            var config = new
            {
                identity    = "test",
                constraints = new
                {
                    host = new
                    {
                        type = "host",
                        args = new[]
                        {
                            new
                            {
                                hostName = "host1",
                                version  = ""
                            },
                            new
                            {
                                hostName = "host2",
                                version  = "1.0.0"
                            },
                            new
                            {
                                hostName = "host3",
                                version  = "[1.0.0-*]"
                            },
                        }
                    }
                }
            };

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

            A.CallTo(() => settings.Host.HostIdentifier).Returns("host2");
            A.CallTo(() => settings.Host.Version).Returns("2.0.0");
            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);

            Assert.Equal(TemplateConstraintResult.Status.Restricted, evaluateResult.EvaluationStatus);
            Assert.Equal("Running template on host2 (version: 2.0.0) is not supported, supported hosts is/are: host1, host2(1.0.0), host3([1.0.0-*]).", evaluateResult.LocalizedErrorMessage);
            Assert.Null(evaluateResult.CallToAction);
        }
Exemple #23
0
        public async Task Evaluate_MultipleConflictingProviders()
        {
            var config = new
            {
                identity    = "test-constraint-01",
                constraints = new
                {
                    specVersions = new
                    {
                        type = "workload",
                        args = new[] { "workloadA", "workloadB" }
                    }
                }
            };

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

            A.CallTo(() => workloadInfoProviderA
                     .GetInstalledWorkloadsAsync(A <CancellationToken> ._))
            .Returns(Task.FromResult(new[] { "workload", "workloadA" }.Select(s => new WorkloadInfo(s, $"D:{s}"))));

            IWorkloadsInfoProvider workloadInfoProviderB = A.Fake <IWorkloadsInfoProvider>();

            A.CallTo(() => workloadInfoProviderB
                     .GetInstalledWorkloadsAsync(A <CancellationToken> ._))
            .Returns(Task.FromResult(new[] { "workload", "workloadA", "workloadB" }.Select(s => new WorkloadInfo(s, $"D:{s}"))));

            IEngineEnvironmentSettings settings = A.Fake <IEngineEnvironmentSettings>();

            A.CallTo(() => settings.Components.OfType <IWorkloadsInfoProvider>()).Returns(new[] { workloadInfoProviderA, workloadInfoProviderB });
            A.CallTo(() => settings.Components.OfType <ITemplateConstraintFactory>()).Returns(new[] { new WorkloadConstraintFactory() });
            List <(LogLevel, string)> messagesCollection = new();
            ILogger logger = new InMemoryLoggerProvider(messagesCollection).CreateLogger("x");

            A.CallTo(() => settings.Host.Logger).Returns(logger);

            var constraintManager = new TemplateConstraintManager(settings);

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

            Assert.Equal(TemplateConstraintResult.Status.NotEvaluated, evaluateResult.EvaluationStatus);
            Assert.Equal(0, messagesCollection.Count(t => t.Item1 >= LogLevel.Warning));
            Assert.StartsWith("The constraint 'workload' failed to initialize", evaluateResult.LocalizedErrorMessage);
        }
        public async Task CanReadConfiguration_VersionRange()
        {
            var config = new
            {
                identity    = "test",
                constraints = new
                {
                    host = new
                    {
                        type = "host",
                        args = new[]
                        {
                            new
                            {
                                hostName = "host1",
                                version  = ""
                            },
                            new
                            {
                                hostName = "host2",
                                version  = "1.0.0"
                            },
                            new
                            {
                                hostName = "host3",
                                version  = "[1.0.0-*]"
                            },
                        }
                    }
                }
            };

            var configModel = SimpleConfigModel.FromJObject(JObject.FromObject(config));

            IEngineEnvironmentSettings settings = A.Fake <IEngineEnvironmentSettings>();

            A.CallTo(() => settings.Host.HostIdentifier).Returns("host3");
            A.CallTo(() => settings.Host.Version).Returns("2.0.0");
            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);

            Assert.Equal(TemplateConstraintResult.Status.Allowed, evaluateResult.EvaluationStatus);
        }
        public void ObjectValueFormDefinitionRespectsAddIdentityFalse()
        {
            SimpleConfigModel configModel = SimpleConfigModel.FromJObject(_engineEnvironmentSettings, ConfigWithObjectValueFormDefinitionAddIdentityFalse);

            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(3, configuredValueFormNames.Count);
            Assert.Equal("foo", configuredValueFormNames[0]);
            Assert.Equal("bar", configuredValueFormNames[1]);
            Assert.Equal("baz", configuredValueFormNames[2]);
        }
        public void NameSymbolObjectValueFormWithIdentityWithoutAddIdentityRetainsConfiguredForms()
        {
            SimpleConfigModel configModel = SimpleConfigModel.FromJObject(NameConfigObjectValueFormWithIdentityAndAddIdentityUnspecified);

            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("foo", configuredValueFormNames[0]);
            Assert.Equal("bar", configuredValueFormNames[1]);
            Assert.Equal("baz", configuredValueFormNames[2]);
            Assert.Equal(IdentityValueForm.FormName, configuredValueFormNames[3]);
        }
        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]);
        }
        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]);
        }
        public void ParameterSymbolObjectValueFormDefinitionInfersAddIdentityTrue()
        {
            SimpleConfigModel configModel = SimpleConfigModel.FromJObject(_engineEnvironmentSettings, ParameterConfigObjectValueFormWithoutIdentityAndAddIdentityUnspecified);

            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]);
        }
        public void ObjectConfigParameterSymbolWithIdentityFormAndAddIdentityTrueRetainsConfiguredFormsExactly()
        {
            SimpleConfigModel configModel = SimpleConfigModel.FromJObject(_engineEnvironmentSettings, ObjectConfigParameterSymbolWithIdentityFormAndAddIdentityTrue);

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

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

            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]);
        }