diff --git a/eng/Packages.props b/eng/Packages.props index 6f62f23d4dfb..b7bb286c4347 100644 --- a/eng/Packages.props +++ b/eng/Packages.props @@ -7,6 +7,7 @@ + diff --git a/eng/Signing.props b/eng/Signing.props index fa6b2f9fd55c..ca1613286414 100644 --- a/eng/Signing.props +++ b/eng/Signing.props @@ -94,6 +94,7 @@ + diff --git a/eng/dependabot/Packages.props b/eng/dependabot/Packages.props index e5a597a4eea3..bd9b09009f44 100644 --- a/eng/dependabot/Packages.props +++ b/eng/dependabot/Packages.props @@ -8,6 +8,7 @@ + diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/AliasAssignmentTests.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/AliasAssignmentTests.cs index 00b23735bb85..786a78525ae4 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/AliasAssignmentTests.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/AliasAssignmentTests.cs @@ -13,6 +13,7 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests { + [TestClass] public class AliasAssignmentTests { private static HashSet InitiallyTakenAliases @@ -46,7 +47,7 @@ private static HashSet InitiallyTakenAliases } // also asserts that "--param:" is used if is taken - [Fact(DisplayName = nameof(LongNameOverrideTakesPrecendence))] + [TestMethod] public void LongNameOverrideTakesPrecendence() { IReadOnlyList paramList = new List() @@ -61,10 +62,10 @@ public void LongNameOverrideTakesPrecendence() Assert.Contains("-f", result["foo"].Aliases); Assert.Contains("--foo", result["bar"].Aliases); Assert.Contains("-fo", result["bar"].Aliases); // the short name is based on the long name override if it exists - Assert.DoesNotContain(result, r => r.Value.Errors.Any()); + Assert.IsFalse(result.Any(r => r.Value.Errors.Any())); } - [Fact(DisplayName = nameof(ShortNameOverrideTakesPrecedence))] + [TestMethod] public void ShortNameOverrideTakesPrecedence() { IReadOnlyList paramList = new List() @@ -79,10 +80,10 @@ public void ShortNameOverrideTakesPrecedence() Assert.Contains("-fo", result["foo"].Aliases); Assert.Contains("--bar", result["bar"].Aliases); Assert.Contains("-f", result["bar"].Aliases); - Assert.DoesNotContain(result, r => r.Value.Errors.Any()); + Assert.IsFalse(result.Any(r => r.Value.Errors.Any())); } - [Fact(DisplayName = nameof(ShortNameExcludedWithEmptyStringOverride))] + [TestMethod] public void ShortNameExcludedWithEmptyStringOverride() { IReadOnlyList paramList = new List() @@ -96,11 +97,11 @@ public void ShortNameExcludedWithEmptyStringOverride() Assert.Contains("--foo", result["foo"].Aliases); Assert.Contains("-f", result["foo"].Aliases); Assert.Contains("--bar", result["bar"].Aliases); - Assert.Single(result["bar"].Aliases); - Assert.DoesNotContain(result, r => r.Value.Errors.Any()); + Assert.HasCount(1, result["bar"].Aliases); + Assert.IsFalse(result.Any(r => r.Value.Errors.Any())); } - [Fact(DisplayName = nameof(ParameterNameCannotContainColon))] + [TestMethod] public void ParameterNameCannotContainColon() { IReadOnlyList paramList = new List() @@ -109,12 +110,12 @@ public void ParameterNameCannotContainColon() }; var result = AliasAssignmentCoordinator.AssignAliasesForParameter(paramList, InitiallyTakenAliases).ToDictionary(r => r.Parameter.Name, r => r); - Assert.Empty(result["foo:bar"].Aliases); - Assert.Single(result["foo:bar"].Errors); + Assert.IsFalse(result["foo:bar"].Aliases.Any()); + Assert.HasCount(1, result["foo:bar"].Errors); Assert.Contains("Parameter name 'foo:bar' contains colon, which is forbidden.", result["foo:bar"].Errors); } - [Fact(DisplayName = nameof(ShortNameGetPrependedPColonIfNeeded))] + [TestMethod] public void ShortNameGetPrependedPColonIfNeeded() { IReadOnlyList paramList = new List() @@ -129,10 +130,10 @@ public void ShortNameGetPrependedPColonIfNeeded() Assert.Contains("-f", result["bar"].Aliases); Assert.Contains("--f", result["f"].Aliases); Assert.Contains("-p:f", result["f"].Aliases); - Assert.DoesNotContain(result, r => r.Value.Errors.Any()); + Assert.IsFalse(result.Any(r => r.Value.Errors.Any())); } - [Fact] + [TestMethod] public void ShortNameGenerationShouldNotProduceDuplicates() { List paramList = new(); @@ -147,7 +148,7 @@ public void ShortNameGenerationShouldNotProduceDuplicates() .BeFalse("Duplicate option aliases should not be generated."); } - [Fact] + [TestMethod] public void ShortNameSkippedAfter4Reps() { List paramList = new(); @@ -169,7 +170,7 @@ public void ShortNameSkippedAfter4Reps() } // This reflects the MVC 2.0 tempalte as of May 24, 2017 - [Fact(DisplayName = nameof(CheckAliasAssignmentsMvc20))] + [TestMethod] public void CheckAliasAssignmentsMvc20() { IReadOnlyList paramList = new List() @@ -201,7 +202,7 @@ public void CheckAliasAssignmentsMvc20() Assert.Contains("-au", result["auth"].Aliases); Assert.Contains("--auth", result["auth"].Aliases); - Assert.Single(result["AAdB2CInstance"].Aliases); + Assert.HasCount(1, result["AAdB2CInstance"].Aliases); Assert.Contains("--aad-b2c-instance", result["AAdB2CInstance"].Aliases); Assert.Contains("-ssp", result["SignUpSignInPolicyId"].Aliases); Assert.Contains("--susi-policy-id", result["SignUpSignInPolicyId"].Aliases); @@ -209,15 +210,15 @@ public void CheckAliasAssignmentsMvc20() Assert.Contains("--reset-password-policy-id", result["ResetPasswordPolicyId"].Aliases); Assert.Contains("-ep", result["EditProfilePolicyId"].Aliases); Assert.Contains("--edit-profile-policy-id", result["EditProfilePolicyId"].Aliases); - Assert.Single(result["AADInstance"].Aliases); + Assert.HasCount(1, result["AADInstance"].Aliases); Assert.Contains("--aad-instance", result["AADInstance"].Aliases); - Assert.Single(result["ClientId"].Aliases); + Assert.HasCount(1, result["ClientId"].Aliases); Assert.Contains("--client-id", result["ClientId"].Aliases); - Assert.Single(result["Domain"].Aliases); + Assert.HasCount(1, result["Domain"].Aliases); Assert.Contains("--domain", result["Domain"].Aliases); - Assert.Single(result["TenantId"].Aliases); + Assert.HasCount(1, result["TenantId"].Aliases); Assert.Contains("--tenant-id", result["TenantId"].Aliases); - Assert.Single(result["CallbackPath"].Aliases); + Assert.HasCount(1, result["CallbackPath"].Aliases); Assert.Contains("--callback-path", result["CallbackPath"].Aliases); Assert.Contains("-r", result["OrgReadAccess"].Aliases); Assert.Contains("--org-read-access", result["OrgReadAccess"].Aliases); @@ -233,21 +234,21 @@ public void CheckAliasAssignmentsMvc20() Assert.Contains("--IISExpressPort", result["IISExpressPort"].Aliases); Assert.Contains("-uld", result["UseLocalDB"].Aliases); Assert.Contains("--use-local-db", result["UseLocalDB"].Aliases); - Assert.Single(result["TargetFrameworkOverride"].Aliases); + Assert.HasCount(1, result["TargetFrameworkOverride"].Aliases); Assert.Contains("--target-framework-override", result["TargetFrameworkOverride"].Aliases); Assert.Contains("-f", result["Framework"].Aliases); Assert.Contains("--framework", result["Framework"].Aliases); Assert.Contains("-nt", result["NoTools"].Aliases); Assert.Contains("--no-tools", result["NoTools"].Aliases); - Assert.Single(result["skipRestore"].Aliases); + Assert.HasCount(1, result["skipRestore"].Aliases); Assert.Contains("--no-restore", result["skipRestore"].Aliases); - Assert.DoesNotContain(result, r => r.Value.Errors.Any()); + Assert.IsFalse(result.Any(r => r.Value.Errors.Any())); } - [Theory] - [InlineData("package", "--param:package")] - [InlineData("u", "-p:u")] - [InlineData("notreserved", "--notreserved")] + [TestMethod] + [DataRow("package", "--param:package")] + [DataRow("u", "-p:u")] + [DataRow("notreserved", "--notreserved")] public void CanAssignAliasForParameterWithReservedAlias(string parameterName, string expectedContainedAlias) { string command = "foo"; @@ -266,13 +267,13 @@ public void CanAssignAliasForParameterWithReservedAlias(string parameterName, st .FromTemplateList(CliTemplateInfo.FromTemplateInfo(templates, A.Fake())) .Single(); var templateCommands = InstantiateCommand.GetTemplateCommand(args, settings, A.Fake(), templateGroup); - Assert.Single(templateCommands); + Assert.HasCount(1, templateCommands); var templateOption = templateCommands.Single().TemplateOptions[parameterName]; Assert.Contains(expectedContainedAlias, templateOption.Aliases); } - [Theory] - [MemberData(nameof(GetTemplateData))] + [TestMethod] + [DynamicData(nameof(GetTemplateData))] public void CanOverrideAliasesForParameterWithHostData(string hostJsonData, string expectedJsonResult) { var hostData = new HostSpecificTemplateData(string.IsNullOrEmpty(hostJsonData) ? null : JsonNode.Parse(hostJsonData)?.AsObject()); @@ -294,7 +295,7 @@ public void CanOverrideAliasesForParameterWithHostData(string hostJsonData, stri ParseResult parseResult = myCommand.Parse(" new foo"); InstantiateCommandArgs args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); var templateCommands = InstantiateCommand.GetTemplateCommand(args, settings, templatePackageManager, templateGroup); - Assert.Single(templateCommands); + Assert.HasCount(1, templateCommands); foreach (var expectedResult in expectedResults) { var expectedArr = expectedResult.Value!.AsArray(); @@ -302,17 +303,17 @@ public void CanOverrideAliasesForParameterWithHostData(string hostJsonData, stri var expectedShortAlias = expectedArr[1]?.GetValue(); var expectedIsHidden = expectedArr[2]?.GetValue() ?? false; var templateOptions = templateCommands.Single().TemplateOptions; - Assert.NotNull(templateOptions); + Assert.IsNotNull(templateOptions); Assert.Contains(expectedResult.Key, templateOptions.Keys); var templateOption = templateOptions[expectedResult.Key]; - Assert.NotNull(templateOption); - Assert.True(templateOption.Aliases.Count > 0); + Assert.IsNotNull(templateOption); + Assert.IsTrue(templateOption.Aliases.Count > 0); var longAlias = templateOption.Aliases.ElementAt(0); var shortAlias = templateOption.Aliases.Count > 1 ? templateOption.Aliases.ElementAt(1) : null; var isHidden = templateOption.Option.Hidden; - Assert.Equal(expectedLongAlias, longAlias); - Assert.Equal(expectedShortAlias, shortAlias); - Assert.Equal(expectedIsHidden, isHidden); + Assert.AreEqual(expectedLongAlias, longAlias); + Assert.AreEqual(expectedShortAlias, shortAlias); + Assert.AreEqual(expectedIsHidden, isHidden); } } diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/AllComponents.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/AllComponents.cs index f9a7ac710bf8..61a69bac0f4d 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/AllComponents.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/AllComponents.cs @@ -1,13 +1,14 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.TemplateEngine.TestHelper; namespace Microsoft.TemplateEngine.Cli.UnitTests { + [TestClass] public class AllComponents { - [Fact] + [TestMethod] public void TestAllComponents() { var assemblyCatalog = new AssemblyComponentCatalog(new[] { typeof(Components).Assembly }); @@ -15,7 +16,7 @@ public void TestAllComponents() var expectedTypeNames = assemblyCatalog.Select(pair => pair.Item1.FullName + ";" + pair.Item2.GetType().FullName).OrderBy(name => name); var actualTypeNames = Components.AllComponents.Select(t => t.Type.FullName + ";" + t.Instance.GetType().FullName).OrderBy(name => name); - Assert.Equal(expectedTypeNames, actualTypeNames); + Assert.AreSequenceEqual(expectedTypeNames, actualTypeNames); } } } diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/BaseTest.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/BaseTest.cs index 316b2c11e55f..440fc415ec7f 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/BaseTest.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/BaseTest.cs @@ -3,7 +3,7 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests { - public abstract class BaseTest + public abstract class BaseTest : VerifyBase { /// /// Gets a path to the folder with dotnet new test assets. diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/GlobalUsings.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/GlobalUsings.cs new file mode 100644 index 000000000000..08ace8decf52 --- /dev/null +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/GlobalUsings.cs @@ -0,0 +1,24 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +// Microsoft.TemplateEngine.TestHelper still references xunit.v3.extensibility.core +// (it is consumed by other in-tree xUnit projects and is not part of this migration). +// EnvironmentSettingsHelper's constructor takes an Xunit.Sdk.IMessageSink. We surface +// it here with a short alias so the tests below can construct a no-op sink without +// pulling in xUnit's global usings (which would conflict with MSTest's Assert). +global using IMessageSink = Xunit.Sdk.IMessageSink; +global using IMessageSinkMessage = Xunit.Sdk.IMessageSinkMessage; + +// Verify.MSTest's VerifyBase is used by snapshot test classes (HelpTests, +// TabCompletionTests via BaseTest). +global using VerifyMSTest; + +// The xUnit-only Directory.Build.targets adds these as global usings for VSTest +// projects. MSTest.Sdk projects do not get them automatically. +global using Microsoft.NET.TestFramework; +global using Microsoft.NET.TestFramework.Utilities; + +// Some test methods (e.g. in InstantiateTests) take parameters of internal types +// from Microsoft.TemplateEngine.Cli. Discover them via DiscoverInternals to keep +// the existing method accessibility. +[assembly: Microsoft.VisualStudio.TestTools.UnitTesting.DiscoverInternals] diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/HostDataLoaderTests.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/HostDataLoaderTests.cs index 4403ed4e04a2..0728c31fd50d 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/HostDataLoaderTests.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/HostDataLoaderTests.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using FakeItEasy; @@ -11,22 +11,38 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests { - public class HostDataLoaderTests : IClassFixture + [TestClass] + public class HostDataLoaderTests { - private readonly EnvironmentSettingsHelper _environmentSettingsHelper; + // MSTest has no IClassFixture equivalent; a lazily-initialized static helper + // mirrors the per-class lifetime that xUnit's IClassFixture provides. + private static readonly Lazy s_environmentSettingsHelper = + new(() => new EnvironmentSettingsHelper(NullMessageSink.Instance)); - public HostDataLoaderTests(EnvironmentSettingsHelper environmentSettingsHelper) + private EnvironmentSettingsHelper _environmentSettingsHelper = null!; + + [TestInitialize] + public void TestInitialize() { - _environmentSettingsHelper = environmentSettingsHelper; + _environmentSettingsHelper = s_environmentSettingsHelper.Value; + } + + [ClassCleanup] + public static void ClassCleanup() + { + if (s_environmentSettingsHelper.IsValueCreated) + { + s_environmentSettingsHelper.Value.Dispose(); + } } - [Fact] + [TestMethod] public void CanLoadHostDataFile() { IEngineEnvironmentSettings engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true); HostSpecificDataLoader hostSpecificDataLoader = new(engineEnvironmentSettings); - Assert.True(engineEnvironmentSettings.TryGetMountPoint(Directory.GetCurrentDirectory(), out IMountPoint? mountPoint)); - Assert.NotNull(mountPoint); + Assert.IsTrue(engineEnvironmentSettings.TryGetMountPoint(Directory.GetCurrentDirectory(), out IMountPoint? mountPoint)); + Assert.IsNotNull(mountPoint); IFile? dataFile = mountPoint!.FileInfo("/Resources/dotnetcli.host.json"); ITemplateInfo template = A.Fake(); @@ -34,31 +50,31 @@ public void CanLoadHostDataFile() A.CallTo(() => template.HostConfigPlace).Returns("/Resources/dotnetcli.host.json"); HostSpecificTemplateData data = hostSpecificDataLoader.ReadHostSpecificTemplateData(template); - Assert.NotNull(data); + Assert.IsNotNull(data); - Assert.False(data.IsHidden); - Assert.Equal(2, data.UsageExamples?.Count); - Assert.NotNull(data.UsageExamples); + Assert.IsFalse(data.IsHidden); + Assert.AreEqual(2, data.UsageExamples?.Count); + Assert.IsNotNull(data.UsageExamples); Assert.Contains("--framework netcoreapp3.1 --langVersion '9.0'", data.UsageExamples); - Assert.Equal(4, data.SymbolInfo?.Count); + Assert.AreEqual(4, data.SymbolInfo?.Count); Assert.Contains("TargetFrameworkOverride", data.HiddenParameterNames); Assert.Contains("Framework", data.ParametersToAlwaysShow); - Assert.True(data.LongNameOverrides.ContainsKey("skipRestore")); - Assert.Equal("no-restore", data.LongNameOverrides["skipRestore"]); - Assert.True(data.ShortNameOverrides.ContainsKey("skipRestore")); - Assert.Equal("", data.ShortNameOverrides["skipRestore"]); - Assert.Equal("no-restore", data.DisplayNameForParameter("skipRestore")); + Assert.IsTrue(data.LongNameOverrides.ContainsKey("skipRestore")); + Assert.AreEqual("no-restore", data.LongNameOverrides["skipRestore"]); + Assert.IsTrue(data.ShortNameOverrides.ContainsKey("skipRestore")); + Assert.AreEqual("", data.ShortNameOverrides["skipRestore"]); + Assert.AreEqual("no-restore", data.DisplayNameForParameter("skipRestore")); } - [Fact] + [TestMethod] public void CanReadHostDataFromITemplateInfo() { IEngineEnvironmentSettings engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true); HostSpecificDataLoader hostSpecificDataLoader = new(engineEnvironmentSettings); - Assert.True(engineEnvironmentSettings.TryGetMountPoint(Directory.GetCurrentDirectory(), out IMountPoint? mountPoint)); - Assert.NotNull(mountPoint); + Assert.IsTrue(engineEnvironmentSettings.TryGetMountPoint(Directory.GetCurrentDirectory(), out IMountPoint? mountPoint)); + Assert.IsNotNull(mountPoint); IFile? dataFile = mountPoint!.FileInfo("/Resources/dotnetcli.host.json"); - Assert.NotNull(dataFile); + Assert.IsNotNull(dataFile); using Stream s = dataFile.OpenRead(); using TextReader tr = new StreamReader(s, Encoding.UTF8, true); @@ -67,23 +83,23 @@ public void CanReadHostDataFromITemplateInfo() A.CallTo(() => ((ITemplateInfoHostJsonCache)template).HostData).Returns(json); HostSpecificTemplateData data = hostSpecificDataLoader.ReadHostSpecificTemplateData(template); - Assert.NotNull(data); + Assert.IsNotNull(data); - Assert.False(data.IsHidden); - Assert.Equal(2, data.UsageExamples?.Count); - Assert.NotNull(data.UsageExamples); + Assert.IsFalse(data.IsHidden); + Assert.AreEqual(2, data.UsageExamples?.Count); + Assert.IsNotNull(data.UsageExamples); Assert.Contains("--framework netcoreapp3.1 --langVersion '9.0'", data.UsageExamples); - Assert.Equal(4, data.SymbolInfo?.Count); + Assert.AreEqual(4, data.SymbolInfo?.Count); Assert.Contains("TargetFrameworkOverride", data.HiddenParameterNames); Assert.Contains("Framework", data.ParametersToAlwaysShow); - Assert.True(data.LongNameOverrides.ContainsKey("skipRestore")); - Assert.Equal("no-restore", data.LongNameOverrides["skipRestore"]); - Assert.True(data.ShortNameOverrides.ContainsKey("skipRestore")); - Assert.Equal("", data.ShortNameOverrides["skipRestore"]); - Assert.Equal("no-restore", data.DisplayNameForParameter("skipRestore")); + Assert.IsTrue(data.LongNameOverrides.ContainsKey("skipRestore")); + Assert.AreEqual("no-restore", data.LongNameOverrides["skipRestore"]); + Assert.IsTrue(data.ShortNameOverrides.ContainsKey("skipRestore")); + Assert.AreEqual("", data.ShortNameOverrides["skipRestore"]); + Assert.AreEqual("no-restore", data.DisplayNameForParameter("skipRestore")); } - [Fact] + [TestMethod] public void ReturnDefaultForInvalidEntry() { IEngineEnvironmentSettings engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true); @@ -93,11 +109,11 @@ public void ReturnDefaultForInvalidEntry() A.CallTo(() => ((ITemplateInfoHostJsonCache)template).HostData).Returns(null); HostSpecificTemplateData data = hostSpecificDataLoader.ReadHostSpecificTemplateData(template); - Assert.NotNull(data); - Assert.Equal(HostSpecificTemplateData.Default, data); + Assert.IsNotNull(data); + Assert.AreEqual(HostSpecificTemplateData.Default, data); } - [Fact] + [TestMethod] public void ReturnDefaultForInvalidFile() { IEngineEnvironmentSettings engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true); @@ -108,11 +124,11 @@ public void ReturnDefaultForInvalidFile() A.CallTo(() => template.HostConfigPlace).Returns("unknown"); HostSpecificTemplateData data = hostSpecificDataLoader.ReadHostSpecificTemplateData(template); - Assert.NotNull(data); - Assert.Equal(HostSpecificTemplateData.Default, data); + Assert.IsNotNull(data); + Assert.AreEqual(HostSpecificTemplateData.Default, data); } - [Fact] + [TestMethod] public void CanSerializeData() { var usageExamples = new[] { "example1" }; @@ -147,15 +163,15 @@ public void CanSerializeData() var data = new HostSpecificTemplateData(symbolInfo, usageExamples, isHidden: true); var serialized = JsonSerializer.SerializeToNode(data)!.AsObject(); - Assert.NotNull(serialized); - Assert.Equal(3, serialized.Count); + Assert.IsNotNull(serialized); + Assert.AreEqual(3, serialized.Count); Assert.Contains("UsageExamples", serialized.Select(p => p.Key)); Assert.Contains("SymbolInfo", serialized.Select(p => p.Key)); Assert.Contains("IsHidden", serialized.Select(p => p.Key)); } - [Fact] + [TestMethod] public void CanSerializeData_SkipsEmpty() { var usageExamples = Array.Empty(); @@ -190,18 +206,18 @@ public void CanSerializeData_SkipsEmpty() var data = new HostSpecificTemplateData(symbolInfo, usageExamples, isHidden: false); var serialized = JsonSerializer.SerializeToNode(data)!.AsObject(); - Assert.NotNull(serialized); - Assert.Single(serialized); + Assert.IsNotNull(serialized); + Assert.HasCount(1, serialized); Assert.Contains("SymbolInfo", serialized.Select(p => p.Key)); var symbolInfoObj = serialized["SymbolInfo"]!.AsObject(); - Assert.NotNull(symbolInfoObj); + Assert.IsNotNull(symbolInfoObj); //empty values should stay when deserializing symbol info - Assert.Equal(3, symbolInfoObj["param1"]!.AsObject().Count); - Assert.Equal("", symbolInfoObj["param2"]!["longName"]!.GetValue()); - Assert.Equal(3, symbolInfoObj["param2"]!.AsObject().Count); - Assert.Single(symbolInfoObj["param3"]!.AsObject()); + Assert.AreEqual(3, symbolInfoObj["param1"]!.AsObject().Count); + Assert.AreEqual("", symbolInfoObj["param2"]!["longName"]!.GetValue()); + Assert.AreEqual(3, symbolInfoObj["param2"]!.AsObject().Count); + Assert.HasCount(1, symbolInfoObj["param3"]!.AsObject()); Assert.DoesNotContain("IsHidden", serialized.Select(p => p.Key)); Assert.DoesNotContain("UsageExamples", serialized.Select(p => p.Key)); diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/JExtensionsTests.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/JExtensionsTests.cs index 9dc32256cfd2..e3e8801a59d4 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/JExtensionsTests.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/JExtensionsTests.cs @@ -7,9 +7,10 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests; +[TestClass] public class JExtensionsTests { - [Fact] + [TestMethod] public void ToInt32ParsesStringPropertyValues() { JsonObject json = JsonNode.Parse(""" diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/Microsoft.TemplateEngine.Cli.UnitTests.csproj b/test/Microsoft.TemplateEngine.Cli.UnitTests/Microsoft.TemplateEngine.Cli.UnitTests.csproj index 386ce0a9a8d9..1188c6ada429 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/Microsoft.TemplateEngine.Cli.UnitTests.csproj +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/Microsoft.TemplateEngine.Cli.UnitTests.csproj @@ -1,10 +1,9 @@ - + $(SdkTargetFramework) - Exe + true enable MicrosoftAspNetCore - true true @@ -16,7 +15,7 @@ - + diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/NullMessageSink.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/NullMessageSink.cs new file mode 100644 index 000000000000..802db3a1334a --- /dev/null +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/NullMessageSink.cs @@ -0,0 +1,20 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace Microsoft.TemplateEngine.Cli.UnitTests; + +/// +/// A no-op used to satisfy +/// 's constructor +/// in an MSTest context (no xUnit runner is present to provide one). +/// +internal sealed class NullMessageSink : IMessageSink +{ + public static readonly IMessageSink Instance = new NullMessageSink(); + + private NullMessageSink() + { + } + + public bool OnMessage(IMessageSinkMessage message) => true; +} diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/HelpTests.Resolution.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/HelpTests.Resolution.cs index d77739fb14bc..6b8a71cbd606 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/HelpTests.Resolution.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/HelpTests.Resolution.cs @@ -13,7 +13,7 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests.ParserTests { public partial class HelpTests { - [Fact] + [TestMethod] public void UniqueNameMatchesCorrectly() { IReadOnlyList templatesToSearch = new List() @@ -29,13 +29,13 @@ public void UniqueNameMatchesCorrectly() ParseResult parseResult = myCommand.Parse($" new console2"); var args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); IEnumerable matchingTemplates = InstantiateCommand.GetMatchingTemplates(args, settings, A.Fake(), templateGroup); - Assert.Single(matchingTemplates); + Assert.HasCount(1, matchingTemplates); BufferedReporter reporter = new(); - Assert.True(InstantiateCommand.VerifyMatchingTemplates(settings, matchingTemplates, reporter, out _)); - Assert.Empty(reporter.Lines); + Assert.IsTrue(InstantiateCommand.VerifyMatchingTemplates(settings, matchingTemplates, reporter, out _)); + Assert.IsFalse(reporter.Lines.Any()); } - [Fact] + [TestMethod] public Task FailedToResolveTemplate_WhenMultipleLanguagesAreFound() { IReadOnlyList templatesToSearch = new List() @@ -54,14 +54,14 @@ public Task FailedToResolveTemplate_WhenMultipleLanguagesAreFound() ParseResult parseResult = myCommand.Parse($" new console"); var args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); IEnumerable matchingTemplates = InstantiateCommand.GetMatchingTemplates(args, settings, A.Fake(), templateGroup); - Assert.Equal(3, matchingTemplates.Count()); + Assert.HasCount(3, matchingTemplates); StringWriter output = new(); BufferedReporter reporter = new(); - Assert.False(InstantiateCommand.VerifyMatchingTemplates(settings, matchingTemplates, reporter, out _)); + Assert.IsFalse(InstantiateCommand.VerifyMatchingTemplates(settings, matchingTemplates, reporter, out _)); return Verify(string.Join(Environment.NewLine, reporter.Lines)); } - [Fact] + [TestMethod] public void DefaultLanguageDisambiguates() { List templatesToSearch = new() @@ -84,15 +84,15 @@ public void DefaultLanguageDisambiguates() ParseResult parseResult = myCommand.Parse($" new console"); var args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); IEnumerable matchingTemplates = InstantiateCommand.GetMatchingTemplates(args, settings, A.Fake(), templateGroup); - Assert.Equal(2, matchingTemplates.Count()); + Assert.HasCount(2, matchingTemplates); BufferedReporter reporter = new(); - Assert.True(InstantiateCommand.VerifyMatchingTemplates(settings, matchingTemplates, reporter, out IEnumerable? filtered)); - Assert.Equal(1, filtered?.Count()); - Assert.Equal("Console.App.L1", filtered?.Single().Template.Identity); - Assert.Empty(reporter.Lines); + Assert.IsTrue(InstantiateCommand.VerifyMatchingTemplates(settings, matchingTemplates, reporter, out IEnumerable? filtered)); + Assert.HasCount(1, filtered!); + Assert.AreEqual("Console.App.L1", filtered?.Single().Template.Identity); + Assert.IsFalse(reporter.Lines.Any()); } - [Fact] + [TestMethod] public void InputLanguageIsPreferredOverDefault() { List templatesToSearch = new() @@ -114,15 +114,15 @@ public void InputLanguageIsPreferredOverDefault() ParseResult parseResult = myCommand.Parse($"new console --language L2"); var args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); IEnumerable matchingTemplates = InstantiateCommand.GetMatchingTemplates(args, settings, A.Fake(), templateGroup); - Assert.Single(matchingTemplates); + Assert.HasCount(1, matchingTemplates); BufferedReporter reporter = new(); - Assert.True(InstantiateCommand.VerifyMatchingTemplates(settings, matchingTemplates, reporter, out IEnumerable? filtered)); - Assert.Equal(1, filtered?.Count()); - Assert.Equal("Console.App.L2", filtered?.Single().Template.Identity); - Assert.Empty(reporter.Lines); + Assert.IsTrue(InstantiateCommand.VerifyMatchingTemplates(settings, matchingTemplates, reporter, out IEnumerable? filtered)); + Assert.HasCount(1, filtered!); + Assert.AreEqual("Console.App.L2", filtered?.Single().Template.Identity); + Assert.IsFalse(reporter.Lines.Any()); } - [Fact] + [TestMethod] public void TemplatesAreSameLanguage() { List templatesToSearch = new() @@ -140,14 +140,14 @@ public void TemplatesAreSameLanguage() ParseResult parseResult = myCommand.Parse($"new console"); var args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); IEnumerable matchingTemplates = InstantiateCommand.GetMatchingTemplates(args, settings, A.Fake(), templateGroup); - Assert.Equal(3, matchingTemplates.Count()); + Assert.HasCount(3, matchingTemplates); BufferedReporter reporter = new(); - Assert.True(InstantiateCommand.VerifyMatchingTemplates(settings, matchingTemplates, reporter, out IEnumerable? filtered)); - Assert.Equal(3, filtered?.Count()); - Assert.Empty(reporter.Lines); + Assert.IsTrue(InstantiateCommand.VerifyMatchingTemplates(settings, matchingTemplates, reporter, out IEnumerable? filtered)); + Assert.HasCount(3, filtered!); + Assert.IsFalse(reporter.Lines.Any()); } - [Fact] + [TestMethod] public void HasLanguageMismatch() { List templatesToSearch = new() @@ -167,10 +167,10 @@ public void HasLanguageMismatch() ParseResult parseResult = myCommand.Parse($"new console --language L2"); var args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); IEnumerable matchingTemplates = InstantiateCommand.GetMatchingTemplates(args, settings, A.Fake(), templateGroup); - Assert.Empty(matchingTemplates); + Assert.IsFalse(matchingTemplates.Any()); } - [Fact] + [TestMethod] public void HasTypeMismatch() { List templatesToSearch = new() @@ -190,10 +190,10 @@ public void HasTypeMismatch() ParseResult parseResult = myCommand.Parse($"new console --type item"); var args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); IEnumerable matchingTemplates = InstantiateCommand.GetMatchingTemplates(args, settings, A.Fake(), templateGroup); - Assert.Empty(matchingTemplates); + Assert.IsFalse(matchingTemplates.Any()); } - [Fact] + [TestMethod] public void HasBaselineMismatch() { List templatesToSearch = new() @@ -213,10 +213,10 @@ public void HasBaselineMismatch() ParseResult parseResult = myCommand.Parse($"new console --baseline core"); var args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); IEnumerable matchingTemplates = InstantiateCommand.GetMatchingTemplates(args, settings, A.Fake(), templateGroup); - Assert.Empty(matchingTemplates); + Assert.IsFalse(matchingTemplates.Any()); } - [Fact] + [TestMethod] public void HasMultipleMismatches() { List templatesToSearch = new() @@ -236,10 +236,10 @@ public void HasMultipleMismatches() ParseResult parseResult = myCommand.Parse($"new console --language L2 --type item --baseline core"); var args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); IEnumerable matchingTemplates = InstantiateCommand.GetMatchingTemplates(args, settings, A.Fake(), templateGroup); - Assert.Empty(matchingTemplates); + Assert.IsFalse(matchingTemplates.Any()); } - [Fact] + [TestMethod] public void HasTypeMismatch_HasGroupLanguageMatch() { List templatesToSearch = new() @@ -264,10 +264,10 @@ public void HasTypeMismatch_HasGroupLanguageMatch() ParseResult parseResult = myCommand.Parse($"new console --language L2 --type item"); var args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); IEnumerable matchingTemplates = InstantiateCommand.GetMatchingTemplates(args, settings, A.Fake(), templateGroup); - Assert.Empty(matchingTemplates); + Assert.IsFalse(matchingTemplates.Any()); } - [Fact] + [TestMethod] public void OtherParameterMatch_Text() { List templatesToSearch = new() @@ -299,10 +299,10 @@ public void OtherParameterMatch_Text() ParseResult parseResult = myCommand.Parse($"new console --langVersion ver"); var args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); IEnumerable matchingTemplates = InstantiateCommand.GetMatchingTemplates(args, settings, A.Fake(), templateGroup); - Assert.Single(matchingTemplates); + Assert.HasCount(1, matchingTemplates); } - [Fact] + [TestMethod] public void OtherParameterMatch_Choice() { List templatesToSearch = new() @@ -334,11 +334,11 @@ public void OtherParameterMatch_Choice() ParseResult parseResult = myCommand.Parse($"new console --framework netcoreapp1.0"); var args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); IEnumerable matchingTemplates = InstantiateCommand.GetMatchingTemplates(args, settings, A.Fake(), templateGroup); - Assert.Single(matchingTemplates); + Assert.HasCount(1, matchingTemplates); } - [Fact] + [TestMethod] public void OtherParameterDoesNotExist() { List templatesToSearch = new() @@ -370,7 +370,7 @@ public void OtherParameterDoesNotExist() ParseResult parseResult = myCommand.Parse($"new console --do-not-exist"); var args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); IEnumerable matchingTemplates = InstantiateCommand.GetMatchingTemplates(args, settings, A.Fake(), templateGroup); - Assert.Empty(matchingTemplates); + Assert.IsFalse(matchingTemplates.Any()); } } } diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/HelpTests.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/HelpTests.cs index ca297a70b6a3..b41149119844 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/HelpTests.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/HelpTests.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.CommandLine; @@ -12,33 +12,34 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests.ParserTests { - public partial class HelpTests + [TestClass] + public partial class HelpTests : VerifyBase { - [Theory] + [TestMethod] #pragma warning disable SA1117 // Parameters should be on same line or separate lines - [InlineData("Template Name", "Language", "Me", "Template Description", + [DataRow("Template Name", "Language", "Me", "Template Description", @"Template Name (Language) Author: Me Description: Template Description ")] - [InlineData("Template Name", null, "Me", "Template Description", + [DataRow("Template Name", null, "Me", "Template Description", @"Template Name Author: Me Description: Template Description ")] - [InlineData("Template Name", "Language", null, "Template Description", + [DataRow("Template Name", "Language", null, "Template Description", @"Template Name (Language) Description: Template Description ")] - [InlineData("Template Name", "Language", "Me", null, + [DataRow("Template Name", "Language", "Me", null, @"Template Name (Language) Author: Me ")] - [InlineData("Template Name", null, null, null, + [DataRow("Template Name", null, null, null, @"Template Name ")] @@ -60,10 +61,10 @@ public void CanShowTemplateDescription(string name, string? language, string? au CliTemplateInfo cliTemplateInfo = new(templateInfo, HostSpecificTemplateData.Default); StringWriter sw = new(); InstantiateCommand.ShowTemplateDetailHeaders(cliTemplateInfo, sw); - Assert.Equal(expected, sw.ToString()); + Assert.AreEqual(expected, sw.ToString()); } - [Fact] + [TestMethod] public void CanShowUsage() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(); @@ -73,10 +74,10 @@ public void CanShowUsage() HelpContext helpContext = new(new HelpBuilder(), myCommand, sw); InstantiateCommand.ShowUsage(myCommand, new[] { "short-name" }, helpContext); - Assert.Equal($"Usage:{Environment.NewLine} new short-name [options] [template options]{Environment.NewLine}{Environment.NewLine}", sw.ToString()); + Assert.AreEqual($"Usage:{Environment.NewLine} new short-name [options] [template options]{Environment.NewLine}{Environment.NewLine}", sw.ToString()); } - [Fact] + [TestMethod] public void CanShowUsage_ForMultipleShortNames() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(); @@ -86,10 +87,10 @@ public void CanShowUsage_ForMultipleShortNames() HelpContext helpContext = new(new HelpBuilder(), myCommand, sw); InstantiateCommand.ShowUsage(myCommand, new[] { "short-name1", "short-name2" }, helpContext); - Assert.Equal($"Usage:{Environment.NewLine} new short-name1 [options] [template options]{Environment.NewLine} new short-name2 [options] [template options]{Environment.NewLine}{Environment.NewLine}", sw.ToString()); + Assert.AreEqual($"Usage:{Environment.NewLine} new short-name1 [options] [template options]{Environment.NewLine} new short-name2 [options] [template options]{Environment.NewLine}{Environment.NewLine}", sw.ToString()); } - [Fact] + [TestMethod] public Task CanShowCommandOptions_Basic() { var template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group"); @@ -112,7 +113,7 @@ public Task CanShowCommandOptions_Basic() return Verify(sw.ToString()); } - [Fact] + [TestMethod] public Task CanShowCommandOptions_Language() { MockTemplateInfo template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group").WithTag("language", "MyLang"); @@ -135,7 +136,7 @@ public Task CanShowCommandOptions_Language() return Verify(sw.ToString()); } - [Fact] + [TestMethod] public Task CanShowCommandOptions_Type() { MockTemplateInfo template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group").WithTag("type", "MyType"); @@ -158,7 +159,7 @@ public Task CanShowCommandOptions_Type() return Verify(sw.ToString()); } - [Fact] + [TestMethod] public void CanShowCommandOptions_NoOptions() { MockTemplateInfo template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group").WithTag("type", "MyType"); @@ -178,10 +179,10 @@ public void CanShowCommandOptions_NoOptions() HelpContext helpContext = new(new HelpBuilder(), myCommand, sw); InstantiateCommand.ShowTemplateSpecificOptions(new[] { templateCommand }, helpContext); - Assert.Equal($"Template options:{Environment.NewLine} (No options){Environment.NewLine}", sw.ToString()); + Assert.AreEqual($"Template options:{Environment.NewLine} (No options){Environment.NewLine}", sw.ToString()); } - [Fact] + [TestMethod] public Task CanShowTemplateOptions_SingleTemplate_Choice() { MockTemplateInfo template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group") @@ -205,7 +206,7 @@ public Task CanShowTemplateOptions_SingleTemplate_Choice() return Verify(sw.ToString()); } - [Fact] + [TestMethod] public Task CanShowTemplateOptions_MultipleTemplate_CombinedChoice() { MockTemplateInfo template1 = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group", precedence: 0) @@ -232,7 +233,7 @@ public Task CanShowTemplateOptions_MultipleTemplate_CombinedChoice() return Verify(sw.ToString()); } - [Fact] + [TestMethod] public Task CanShowTemplateOptions_SingleTemplate_NonChoice() { MockTemplateInfo template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group") @@ -256,7 +257,7 @@ public Task CanShowTemplateOptions_SingleTemplate_NonChoice() return Verify(sw.ToString()); } - [Fact] + [TestMethod] public Task CanShowTemplateOptions_MultipleTemplate_MultipleParams() { MockTemplateInfo template1 = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group", precedence: 0) @@ -285,7 +286,7 @@ public Task CanShowTemplateOptions_MultipleTemplate_MultipleParams() return Verify(sw.ToString()); } - [Fact] + [TestMethod] public Task CanShowTemplateOptions_SingleTemplate_Choice_Required() { MockTemplateInfo template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group") @@ -309,7 +310,7 @@ public Task CanShowTemplateOptions_SingleTemplate_Choice_Required() return Verify(sw.ToString()); } - [Fact] + [TestMethod] public void CanShowTemplateOptions_RequiredIsNotShownWhenDefaultValueIsGiven() { MockTemplateInfo template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group") @@ -333,7 +334,7 @@ public void CanShowTemplateOptions_RequiredIsNotShownWhenDefaultValueIsGiven() Assert.DoesNotContain("(REQUIRED)", sw.ToString()); } - [Fact] + [TestMethod] public Task CanShowHintsForOtherTemplates() { MockTemplateInfo template1 = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group").WithTag("language", "Lang1").WithTag("type", "project"); @@ -355,7 +356,7 @@ public Task CanShowHintsForOtherTemplates() return Verify(sw.ToString()); } - [Fact] + [TestMethod] public Task CanShowTemplateOptions_SingleTemplate_Choice_ShortenedUsage_FirstTwoValuesFit() { MockTemplateInfo template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group") @@ -379,7 +380,7 @@ public Task CanShowTemplateOptions_SingleTemplate_Choice_ShortenedUsage_FirstTwo return Verify(sw.ToString()); } - [Fact] + [TestMethod] public Task CanShowTemplateOptions_SingleTemplate_Choice_ShortenedUsage() { MockTemplateInfo template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group") @@ -403,7 +404,7 @@ public Task CanShowTemplateOptions_SingleTemplate_Choice_ShortenedUsage() return Verify(sw.ToString()); } - [Fact] + [TestMethod] public Task DoesNotCombineParametersWhenAliasesAreDifferent() { MockTemplateInfo template1 = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group") @@ -446,7 +447,7 @@ public Task DoesNotCombineParametersWhenAliasesAreDifferent() return Verify(sw.ToString()); } - [Fact] + [TestMethod] public Task CanShowTemplateOptions_RequiredParam() { MockTemplateInfo template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group") diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/InstallTests.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/InstallTests.cs index 268f682babdb..72fd3aec3545 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/InstallTests.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/InstallTests.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.CommandLine; @@ -7,11 +7,12 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests.ParserTests { + [TestClass] public class InstallTests : BaseTest { - [Theory] - [InlineData("--add-source")] - [InlineData("--nuget-source")] + [TestMethod] + [DataRow("--add-source")] + [DataRow("--nuget-source")] public void Install_CanParseAddSourceOption(string optionName) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -20,14 +21,14 @@ public void Install_CanParseAddSourceOption(string optionName) ParseResult parseResult = myCommand.Parse($"new install source {optionName} my-custom-source"); InstallCommandArgs args = new((InstallCommand)parseResult.CommandResult.Command, parseResult); - Assert.NotNull(args.AdditionalSources); - Assert.Single(args.AdditionalSources); + Assert.IsNotNull(args.AdditionalSources); + Assert.HasCount(1, args.AdditionalSources); Assert.Contains("my-custom-source", args.AdditionalSources); - Assert.Single(args.TemplatePackages); + Assert.HasCount(1, args.TemplatePackages); Assert.Contains("source", args.TemplatePackages); } - [Fact] + [TestMethod] public void Install_Error_NoArguments() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -35,13 +36,13 @@ public void Install_Error_NoArguments() ParseResult parseResult = myCommand.Parse($"new install"); - Assert.True(parseResult.Errors.Any()); - Assert.Contains(parseResult.Errors, error => error.Message.Contains("Required argument") && error.Message.Contains("missing")); + Assert.IsTrue(parseResult.Errors.Any()); + Assert.IsTrue(parseResult.Errors.Any(error => error.Message.Contains("Required argument") && error.Message.Contains("missing"))); Assert.Throws(() => new InstallCommandArgs((InstallCommand)parseResult.CommandResult.Command, parseResult)); } - [Fact] + [TestMethod] public void Install_Legacy_Error_NoArguments() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -49,15 +50,15 @@ public void Install_Legacy_Error_NoArguments() ParseResult parseResult = myCommand.Parse($"new --install --interactive"); - Assert.True(parseResult.Errors.Any()); - Assert.Contains(parseResult.Errors, error => error.Message.Contains("Required argument") && error.Message.Contains("missing")); + Assert.IsTrue(parseResult.Errors.Any()); + Assert.IsTrue(parseResult.Errors.Any(error => error.Message.Contains("Required argument") && error.Message.Contains("missing"))); Assert.Throws(() => new InstallCommandArgs((LegacyInstallCommand)parseResult.CommandResult.Command, parseResult)); } - [Theory] - [InlineData("new install source --add-source my-custom-source1 my-custom-source2")] - [InlineData("new install source --add-source my-custom-source1 --add-source my-custom-source2")] + [TestMethod] + [DataRow("new install source --add-source my-custom-source1 my-custom-source2")] + [DataRow("new install source --add-source my-custom-source1 --add-source my-custom-source2")] public void Install_CanParseAddSourceOption_MultipleEntries(string testCase) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -65,15 +66,15 @@ public void Install_CanParseAddSourceOption_MultipleEntries(string testCase) ParseResult parseResult = myCommand.Parse(testCase); InstallCommandArgs args = new((InstallCommand)parseResult.CommandResult.Command, parseResult); - Assert.NotNull(args.AdditionalSources); - Assert.Equal(2, args.AdditionalSources.Count); + Assert.IsNotNull(args.AdditionalSources); + Assert.AreEqual(2, args.AdditionalSources.Count); Assert.Contains("my-custom-source1", args.AdditionalSources); Assert.Contains("my-custom-source2", args.AdditionalSources); - Assert.Single(args.TemplatePackages); + Assert.HasCount(1, args.TemplatePackages); Assert.Contains("source", args.TemplatePackages); } - [Fact] + [TestMethod] public void Install_CanParseInteractiveOption() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -82,19 +83,19 @@ public void Install_CanParseInteractiveOption() ParseResult parseResult = myCommand.Parse($"new install source --interactive"); InstallCommandArgs args = new((InstallCommand)parseResult.CommandResult.Command, parseResult); - Assert.True(args.Interactive); - Assert.Single(args.TemplatePackages); + Assert.IsTrue(args.Interactive); + Assert.HasCount(1, args.TemplatePackages); Assert.Contains("source", args.TemplatePackages); parseResult = myCommand.Parse($"new install source"); args = new InstallCommandArgs((InstallCommand)parseResult.CommandResult.Command, parseResult); - Assert.False(args.Interactive); - Assert.Single(args.TemplatePackages); + Assert.IsFalse(args.Interactive); + Assert.HasCount(1, args.TemplatePackages); Assert.Contains("source", args.TemplatePackages); } - [Fact] + [TestMethod] public void Install_CanParseForceOption() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -103,19 +104,19 @@ public void Install_CanParseForceOption() ParseResult parseResult = myCommand.Parse($"new install source --force"); InstallCommandArgs args = new((InstallCommand)parseResult.CommandResult.Command, parseResult); - Assert.True(args.Force); - Assert.Single(args.TemplatePackages); + Assert.IsTrue(args.Force); + Assert.HasCount(1, args.TemplatePackages); Assert.Contains("source", args.TemplatePackages); parseResult = myCommand.Parse($"new install source"); args = new InstallCommandArgs((InstallCommand)parseResult.CommandResult.Command, parseResult); - Assert.False(args.Force); - Assert.Single(args.TemplatePackages); + Assert.IsFalse(args.Force); + Assert.HasCount(1, args.TemplatePackages); Assert.Contains("source", args.TemplatePackages); } - [Fact] + [TestMethod] public void Install_CanParseMultipleArgs() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -124,15 +125,15 @@ public void Install_CanParseMultipleArgs() ParseResult parseResult = myCommand.Parse($"new install source1 source2"); InstallCommandArgs args = new((InstallCommand)parseResult.CommandResult.Command, parseResult); - Assert.Equal(2, args.TemplatePackages.Count); + Assert.AreEqual(2, args.TemplatePackages.Count); Assert.Contains("source1", args.TemplatePackages); Assert.Contains("source2", args.TemplatePackages); } - [Theory] - [InlineData("new --install source --add-source my-custom-source")] - [InlineData("new --install source --nuget-source my-custom-source")] - [InlineData("new --nuget-source my-custom-source --install source")] + [TestMethod] + [DataRow("new --install source --add-source my-custom-source")] + [DataRow("new --install source --nuget-source my-custom-source")] + [DataRow("new --nuget-source my-custom-source --install source")] public void Install_Legacy_CanParseAddSourceOption(string testCase) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -141,16 +142,16 @@ public void Install_Legacy_CanParseAddSourceOption(string testCase) ParseResult parseResult = myCommand.Parse(testCase); InstallCommandArgs args = new((LegacyInstallCommand)parseResult.CommandResult.Command, parseResult); - Assert.NotNull(args.AdditionalSources); - Assert.Single(args.AdditionalSources); + Assert.IsNotNull(args.AdditionalSources); + Assert.HasCount(1, args.AdditionalSources); Assert.Contains("my-custom-source", args.AdditionalSources); - Assert.Single(args.TemplatePackages); + Assert.HasCount(1, args.TemplatePackages); Assert.Contains("source", args.TemplatePackages); } - [Theory] - [InlineData("new --install source --interactive")] - [InlineData("new --interactive --install source")] + [TestMethod] + [DataRow("new --install source --interactive")] + [DataRow("new --interactive --install source")] public void Install_Legacy_CanParseInteractiveOption(string testCase) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -159,14 +160,14 @@ public void Install_Legacy_CanParseInteractiveOption(string testCase) ParseResult parseResult = myCommand.Parse(testCase); InstallCommandArgs args = new((LegacyInstallCommand)parseResult.CommandResult.Command, parseResult); - Assert.True(args.Interactive); - Assert.Single(args.TemplatePackages); + Assert.IsTrue(args.Interactive); + Assert.HasCount(1, args.TemplatePackages); Assert.Contains("source", args.TemplatePackages); } - [Theory] - [InlineData("new --install source1 --install source2")] - [InlineData("new --install source1 source2")] + [TestMethod] + [DataRow("new --install source1 --install source2")] + [DataRow("new --install source1 source2")] public void Install_Legacy_CanParseMultipleArgs(string testCase) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -175,15 +176,15 @@ public void Install_Legacy_CanParseMultipleArgs(string testCase) ParseResult parseResult = myCommand.Parse(testCase); InstallCommandArgs args = new((LegacyInstallCommand)parseResult.CommandResult.Command, parseResult); - Assert.Equal(2, args.TemplatePackages.Count); + Assert.AreEqual(2, args.TemplatePackages.Count); Assert.Contains("source1", args.TemplatePackages); Assert.Contains("source2", args.TemplatePackages); } - [Theory] - [InlineData("new --install source --add-source my-custom-source1 --add-source my-custom-source2")] - [InlineData("new --add-source my-custom-source1 --add-source my-custom-source2 --install source")] - [InlineData("new --add-source my-custom-source1 --install source --add-source my-custom-source2")] + [TestMethod] + [DataRow("new --install source --add-source my-custom-source1 --add-source my-custom-source2")] + [DataRow("new --add-source my-custom-source1 --add-source my-custom-source2 --install source")] + [DataRow("new --add-source my-custom-source1 --install source --add-source my-custom-source2")] public void Install_Legacy_CanParseAddSourceOption_MultipleEntries(string testCase) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -191,21 +192,21 @@ public void Install_Legacy_CanParseAddSourceOption_MultipleEntries(string testCa ParseResult parseResult = myCommand.Parse(testCase); InstallCommandArgs args = new((LegacyInstallCommand)parseResult.CommandResult.Command, parseResult); - Assert.NotNull(args.AdditionalSources); - Assert.Equal(2, args.AdditionalSources.Count); + Assert.IsNotNull(args.AdditionalSources); + Assert.AreEqual(2, args.AdditionalSources.Count); Assert.Contains("my-custom-source1", args.AdditionalSources); Assert.Contains("my-custom-source2", args.AdditionalSources); - Assert.Single(args.TemplatePackages); + Assert.HasCount(1, args.TemplatePackages); Assert.Contains("source", args.TemplatePackages); } - [Theory] - [InlineData("new --add-source my-custom-source install source", "'--add-source','my-custom-source'")] - [InlineData("new --interactive install source", "'--interactive'")] - [InlineData("new --language F# --install source", "'--language','F#'")] - [InlineData("new --language F# install source", "'--language','F#'")] - [InlineData("new source1 source2 source3 --install source", "'source1'|'source2','source3'")] - [InlineData("new source1 --install source", "'source1'")] + [TestMethod] + [DataRow("new --add-source my-custom-source install source", "'--add-source','my-custom-source'")] + [DataRow("new --interactive install source", "'--interactive'")] + [DataRow("new --language F# --install source", "'--language','F#'")] + [DataRow("new --language F# install source", "'--language','F#'")] + [DataRow("new source1 source2 source3 --install source", "'source1'|'source2','source3'")] + [DataRow("new source1 --install source", "'source1'")] public void Install_CanReturnParseError(string command, string expectedInvalidTokens) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -216,15 +217,15 @@ public void Install_CanReturnParseError(string command, string expectedInvalidTo string[] expectedInvalidTokenSets = expectedInvalidTokens.Split("|"); - Assert.NotEmpty(parseResult.Errors); - Assert.Equal(expectedInvalidTokenSets.Length, parseResult.Errors.Count); + Assert.IsTrue(parseResult.Errors.Any()); + Assert.AreEqual(expectedInvalidTokenSets.Length, parseResult.Errors.Count); foreach (string tokenSet in expectedInvalidTokenSets) { - Assert.True(errorMessages.Contains($"Unrecognized command or argument(s): {tokenSet}.") || errorMessages.Contains($"Unrecognized command or argument {tokenSet}.")); + Assert.IsTrue(errorMessages.Contains($"Unrecognized command or argument(s): {tokenSet}.") || errorMessages.Contains($"Unrecognized command or argument {tokenSet}.")); } } - [Fact] + [TestMethod] public void CommandExampleCanShowParentCommandsBeyondNew() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -235,7 +236,7 @@ public void CommandExampleCanShowParentCommandsBeyondNew() }; ParseResult parseResult = rootCommand.Parse("dotnet new install source"); - Assert.Equal("dotnet new install my-source", Example.For(parseResult).WithSubcommand().WithArguments("my-source")); + Assert.AreEqual("dotnet new install my-source", Example.For(parseResult).WithSubcommand().WithArguments("my-source")); } } } diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/InstantiateTests.NoMatchHandling.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/InstantiateTests.NoMatchHandling.cs index 753ea92bb18d..16493e1edeb7 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/InstantiateTests.NoMatchHandling.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/InstantiateTests.NoMatchHandling.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.CommandLine; @@ -280,8 +280,8 @@ public static IEnumerable GetInvalidParametersTestData() }; } - [Theory] - [MemberData(nameof(GetInvalidParametersTestData))] + [TestMethod] + [DynamicData(nameof(GetInvalidParametersTestData))] // invalid params: // [0] name / value - Kind // [1] canonical @@ -302,11 +302,11 @@ internal void CanEvaluateInvalidParameters(string command, MockTemplateInfo[] te ParseResult parseResult = myCommand.Parse($" new {command}"); var args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); HashSet templateCommands = InstantiateCommand.GetTemplateCommand(args, settings, A.Fake(), templateGroup); - Assert.Empty(templateCommands); + Assert.IsFalse(templateCommands.Any()); List templateMatchInfos = InstantiateCommand.CollectTemplateMatchInfo(args, settings, templatePackageManager, templateGroup); List invalidOptions = InstantiateCommand.GetInvalidOptions(templateMatchInfos); - Assert.Equal(expectedInvalidParams.Length, invalidOptions.Count); + Assert.AreEqual(expectedInvalidParams.Length, invalidOptions.Count); foreach (string?[] invalidParam in expectedInvalidParams) { @@ -325,11 +325,11 @@ internal void CanEvaluateInvalidParameters(string command, MockTemplateInfo[] te InvalidTemplateOptionResult actualParam = invalidOptions.Single(param => param.InputFormat == expectedInputFormat); - Assert.Equal(expectedErrorKind, actualParam.ErrorKind); - Assert.Equal(expectedCanonicalName, actualParam.TemplateOption?.TemplateParameter.Name); - Assert.Equal(expectedInputFormat, actualParam.InputFormat); - Assert.Equal(expectedSpecifiedValue, actualParam.SpecifiedValue); - Assert.Equal(expectedErrorMessage, actualParam.ErrorMessage); + Assert.AreEqual(expectedErrorKind, actualParam.ErrorKind); + Assert.AreEqual(expectedCanonicalName, actualParam.TemplateOption?.TemplateParameter.Name); + Assert.AreEqual(expectedInputFormat, actualParam.InputFormat); + Assert.AreEqual(expectedSpecifiedValue, actualParam.SpecifiedValue); + Assert.AreEqual(expectedErrorMessage, actualParam.ErrorMessage); } } } diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/InstantiateTests.Subcommand.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/InstantiateTests.Subcommand.cs index 8cd1443b7fcd..479713710a6a 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/InstantiateTests.Subcommand.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/InstantiateTests.Subcommand.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.CommandLine; @@ -14,22 +14,22 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests.ParserTests { public partial class InstantiateTests { - [Fact] - public void Create_CanParseTemplateWithOptions() + [TestMethod] + internal void Create_CanParseTemplateWithOptions() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); var myCommand = CliTestHostFactory.CreateNewCommand(host); ParseResult parseResult = myCommand.Parse("new create console --framework net5.0"); InstantiateCommandArgs args = new((InstantiateCommand)parseResult.CommandResult.Command, parseResult); - Assert.Equal("console", args.ShortName); - Assert.Equal(2, args.RemainingArguments.Length); + Assert.AreEqual("console", args.ShortName); + Assert.AreEqual(2, args.RemainingArguments.Length); Assert.Contains("--framework", args.RemainingArguments); Assert.Contains("net5.0", args.RemainingArguments); } - [Theory] - [MemberData(nameof(CanEvaluateTemplateToRunData))] + [TestMethod] + [DynamicData(nameof(CanEvaluateTemplateToRunData))] internal void Create_CanEvaluateTemplateToRun(string command, string templateSet, string? defaultLanguage, string? expectedIdentitiesStr) { TemplateGroup templateGroup = TemplateGroup.FromTemplateList( @@ -52,16 +52,16 @@ internal void Create_CanEvaluateTemplateToRun(string command, string templateSet var instantiateCommand = (InstantiateCommand)parseResult.CommandResult.Command; var args = new InstantiateCommandArgs(instantiateCommand, parseResult); HashSet templateCommands = InstantiateCommand.GetTemplateCommand(args, settings, A.Fake(), templateGroup); - Assert.Equal(expectedIdentities.Length, templateCommands.Count); - Assert.Equal(expectedIdentities.OrderBy(s => s), templateCommands.Select(templateCommand => templateCommand.Template.Identity).OrderBy(s => s)); + Assert.AreEqual(expectedIdentities.Length, templateCommands.Count); + Assert.AreSequenceEqual(expectedIdentities.OrderBy(s => s), templateCommands.Select(templateCommand => templateCommand.Template.Identity).OrderBy(s => s)); } - [Theory] - [InlineData("new create foo --name name", "name")] - [InlineData("new create foo -n name", "name")] - [InlineData("new create foo", null)] - [InlineData("new create --name name foo ", "name")] - [InlineData("new create -n name foo", "name")] + [TestMethod] + [DataRow("new create foo --name name", "name")] + [DataRow("new create foo -n name", "name")] + [DataRow("new create foo", null)] + [DataRow("new create --name name foo ", "name")] + [DataRow("new create -n name foo", "name")] internal void Create_CanParseNameOption(string command, string? expectedValue) { var template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group"); @@ -87,17 +87,17 @@ internal void Create_CanParseNameOption(string command, string? expectedValue) ParseResult templateParseResult = parser.Parse(args.TokensToInvoke ?? Array.Empty(), ParserFactory.ParserConfiguration); var templateArgs = new TemplateCommandArgs(templateCommand, instantiateCommand, templateParseResult); - Assert.Equal(expectedValue, templateArgs.Name); + Assert.AreEqual(expectedValue, templateArgs.Name); } - [Theory] - [InlineData("new --name name create foo", "Unrecognized command or argument(s): '--name','name'.")] - [InlineData("--name name new create foo", "Unrecognized command or argument '--name'.|Unrecognized command or argument 'name'.")] - [InlineData("new --output name create foo", "Unrecognized command or argument(s): '--output','name'.")] - [InlineData("new --project name create foo", "Unrecognized command or argument(s): '--project','name'.")] - [InlineData("new --force create foo", "Unrecognized command or argument(s): '--force'.")] - [InlineData("new --dry-run create foo", "Unrecognized command or argument(s): '--dry-run'.")] - [InlineData("new --no-update-check create foo", "Unrecognized command or argument(s): '--no-update-check'.")] + [TestMethod] + [DataRow("new --name name create foo", "Unrecognized command or argument(s): '--name','name'.")] + [DataRow("--name name new create foo", "Unrecognized command or argument '--name'.|Unrecognized command or argument 'name'.")] + [DataRow("new --output name create foo", "Unrecognized command or argument(s): '--output','name'.")] + [DataRow("new --project name create foo", "Unrecognized command or argument(s): '--project','name'.")] + [DataRow("new --force create foo", "Unrecognized command or argument(s): '--force'.")] + [DataRow("new --dry-run create foo", "Unrecognized command or argument(s): '--dry-run'.")] + [DataRow("new --no-update-check create foo", "Unrecognized command or argument(s): '--no-update-check'.")] internal void Create_CanValidateOptionUsage_InNewCommand(string command, string? expectedErrors) { string[] expectedErrorsParsed = expectedErrors?.Split("|") ?? Array.Empty(); @@ -120,8 +120,8 @@ internal void Create_CanValidateOptionUsage_InNewCommand(string command, string? parseResult.Errors.Select(e => e.Message).Should().BeEquivalentTo(expectedErrorsParsed); } - [Theory] - [MemberData(nameof(CanParseTemplateOptionsData))] + [TestMethod] + [DynamicData(nameof(CanParseTemplateOptionsData))] internal void Create_CanParseTemplateOptions(string command, string parameterName, string parameterType, string? defaultValue, string? defaultIfNoOptionValue, string? expectedValue) { //unique case for dotnet new create @@ -152,17 +152,17 @@ internal void Create_CanParseTemplateOptions(string command, string parameterNam if (string.IsNullOrWhiteSpace(expectedValue)) { - Assert.False(templateArgs.TemplateParameters.ContainsKey(parameterName)); + Assert.IsFalse(templateArgs.TemplateParameters.ContainsKey(parameterName)); } else { - Assert.True(templateArgs.TemplateParameters.ContainsKey(parameterName)); - Assert.Equal(expectedValue, templateArgs.TemplateParameters[parameterName]); + Assert.IsTrue(templateArgs.TemplateParameters.ContainsKey(parameterName)); + Assert.AreEqual(expectedValue, templateArgs.TemplateParameters[parameterName]); } } - [Theory] - [MemberData(nameof(CanParseChoiceTemplateOptionsData))] + [TestMethod] + [DynamicData(nameof(CanParseChoiceTemplateOptionsData))] internal void Create_CanParseChoiceTemplateOptions(string command, string parameterName, string parameterValues, string? defaultIfNoOptionValue, string? expectedValue) { MockTemplateInfo template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group") @@ -187,17 +187,17 @@ internal void Create_CanParseChoiceTemplateOptions(string command, string parame if (string.IsNullOrWhiteSpace(expectedValue)) { - Assert.False(templateArgs.TemplateParameters.ContainsKey(parameterName)); + Assert.IsFalse(templateArgs.TemplateParameters.ContainsKey(parameterName)); } else { - Assert.True(templateArgs.TemplateParameters.ContainsKey(parameterName)); - Assert.Equal(expectedValue, templateArgs.TemplateParameters[parameterName]); + Assert.IsTrue(templateArgs.TemplateParameters.ContainsKey(parameterName)); + Assert.AreEqual(expectedValue, templateArgs.TemplateParameters[parameterName]); } } - [Theory] - [MemberData(nameof(CanDetectParseErrorsTemplateOptionsData))] + [TestMethod] + [DynamicData(nameof(CanDetectParseErrorsTemplateOptionsData))] internal void Create_CanDetectParseErrorsTemplateOptions( string command, string parameterName, @@ -226,12 +226,12 @@ internal void Create_CanDetectParseErrorsTemplateOptions( TemplateCommand templateCommand = new(instantiateCommand, settings, packageManager, templateGroup, templateGroup.Templates.Single()); Command parser = ParserFactory.CreateParser(templateCommand); ParseResult templateParseResult = parser.Parse(args.RemainingArguments ?? Array.Empty(), ParserFactory.ParserConfiguration); - Assert.True(templateParseResult.Errors.Any()); - Assert.Equal(expectedError, templateParseResult.Errors.Single().Message); + Assert.IsTrue(templateParseResult.Errors.Any()); + Assert.AreEqual(expectedError, templateParseResult.Errors.Single().Message); } - [Theory] - [MemberData(nameof(CanDetectParseErrorsChoiceTemplateOptionsData))] + [TestMethod] + [DynamicData(nameof(CanDetectParseErrorsChoiceTemplateOptionsData))] internal void Create_CanDetectParseErrorsChoiceTemplateOptions( string command, string parameterName, @@ -260,13 +260,13 @@ internal void Create_CanDetectParseErrorsChoiceTemplateOptions( TemplateCommand templateCommand = new(instantiateCommand, settings, packageManager, templateGroup, templateGroup.Templates.Single()); Command parser = ParserFactory.CreateParser(templateCommand); ParseResult templateParseResult = parser.Parse(args.RemainingArguments ?? Array.Empty(), ParserFactory.ParserConfiguration); - Assert.True(templateParseResult.Errors.Any()); - Assert.Equal(expectedError, templateParseResult.Errors.Single().Message); + Assert.IsTrue(templateParseResult.Errors.Any()); + Assert.AreEqual(expectedError, templateParseResult.Errors.Single().Message); } - [Theory] - [InlineData("create", "createTemplate")] - [InlineData("list", "listTemplate")] + [TestMethod] + [DataRow("create", "createTemplate")] + [DataRow("list", "listTemplate")] internal void Create_CanEvaluateTemplateWithSubcommandShortName(string command, string? expectedIdentitiesStr) { MockTemplateInfo template = new(command, identity: $"{command}Template"); @@ -284,8 +284,8 @@ internal void Create_CanEvaluateTemplateWithSubcommandShortName(string command, var instantiateCommand = (InstantiateCommand)parseResult.CommandResult.Command; var args = new InstantiateCommandArgs(instantiateCommand, parseResult); HashSet templateCommands = InstantiateCommand.GetTemplateCommand(args, settings, A.Fake(), templateGroup); - Assert.Equal(expectedIdentities.Length, templateCommands.Count); - Assert.Equal(expectedIdentities.OrderBy(s => s), templateCommands.Select(templateCommand => templateCommand.Template.Identity).OrderBy(s => s)); + Assert.AreEqual(expectedIdentities.Length, templateCommands.Count); + Assert.AreSequenceEqual(expectedIdentities.OrderBy(s => s), templateCommands.Select(templateCommand => templateCommand.Template.Identity).OrderBy(s => s)); } } } diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/InstantiateTests.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/InstantiateTests.cs index d337e62efc5d..712359745fc7 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/InstantiateTests.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/InstantiateTests.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.CommandLine; @@ -13,9 +13,10 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests.ParserTests { + [TestClass] public partial class InstantiateTests : BaseTest { - [Fact] + [TestMethod] public void Instantiate_CanParseTemplateWithOptions() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -23,7 +24,7 @@ public void Instantiate_CanParseTemplateWithOptions() ParseResult parseResult = myCommand.Parse("new console --framework net5.0"); InstantiateCommandArgs args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); - Assert.Equal("console", args.ShortName); + Assert.AreEqual("console", args.ShortName); Assert.Contains("--framework", args.RemainingArguments); Assert.Contains("net5.0", args.RemainingArguments); } @@ -204,8 +205,8 @@ public void Instantiate_CanParseTemplateWithOptions() new[] { "foo --framework netcoreapp2.0", "2TemplatesWithDifferentChoiceOptions", null, null }, }; - [Theory] - [MemberData(nameof(CanEvaluateTemplateToRunData))] + [TestMethod] + [DynamicData(nameof(CanEvaluateTemplateToRunData))] internal void CanEvaluateTemplateToRun(string command, string templateSet, string? defaultLanguage, string? expectedIdentitiesStr) { TemplateGroup templateGroup = TemplateGroup.FromTemplateList( @@ -227,16 +228,16 @@ internal void CanEvaluateTemplateToRun(string command, string templateSet, strin ParseResult parseResult = myCommand.Parse($" new {command}"); InstantiateCommandArgs args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); HashSet templateCommands = InstantiateCommand.GetTemplateCommand(args, settings, A.Fake(), templateGroup); - Assert.Equal(expectedIdentities.Length, templateCommands.Count); - Assert.Equal(expectedIdentities.OrderBy(s => s), templateCommands.Select(templateCommand => templateCommand.Template.Identity).OrderBy(s => s)); + Assert.AreEqual(expectedIdentities.Length, templateCommands.Count); + Assert.AreSequenceEqual(expectedIdentities.OrderBy(s => s), templateCommands.Select(templateCommand => templateCommand.Template.Identity).OrderBy(s => s)); } - [Theory] - [InlineData("new foo --name name", "name")] - [InlineData("new foo -n name", "name")] - [InlineData("new foo", null)] - [InlineData("new --name name foo ", "name")] - [InlineData("new -n name foo", "name")] + [TestMethod] + [DataRow("new foo --name name", "name")] + [DataRow("new foo -n name", "name")] + [DataRow("new foo", null)] + [DataRow("new --name name foo ", "name")] + [DataRow("new -n name foo", "name")] internal void CanParseNameOption(string command, string? expectedValue) { MockTemplateInfo template = new("foo", identity: "foo.1", groupIdentity: "foo.group"); @@ -259,7 +260,7 @@ internal void CanParseNameOption(string command, string? expectedValue) ParseResult templateParseResult = parser.Parse(args.TokensToInvoke ?? Array.Empty(), ParserFactory.ParserConfiguration); var templateArgs = new TemplateCommandArgs(templateCommand, myCommand, templateParseResult); - Assert.Equal(expectedValue, templateArgs.Name); + Assert.AreEqual(expectedValue, templateArgs.Name); } public static IEnumerable CanParseTemplateOptionsData => @@ -301,8 +302,8 @@ internal void CanParseNameOption(string command, string? expectedValue) new[] { "foo --hex", "hex", "hex", null, "0xABCD", "0xABCD" }, }; - [Theory] - [MemberData(nameof(CanParseTemplateOptionsData))] + [TestMethod] + [DynamicData(nameof(CanParseTemplateOptionsData))] internal void CanParseTemplateOptions(string command, string parameterName, string parameterType, string? defaultValue, string? defaultIfNoOptionValue, string? expectedValue) { MockTemplateInfo template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group") @@ -327,12 +328,12 @@ internal void CanParseTemplateOptions(string command, string parameterName, stri if (string.IsNullOrWhiteSpace(expectedValue)) { - Assert.False(templateArgs.TemplateParameters.ContainsKey(parameterName)); + Assert.IsFalse(templateArgs.TemplateParameters.ContainsKey(parameterName)); } else { - Assert.True(templateArgs.TemplateParameters.ContainsKey(parameterName)); - Assert.Equal(expectedValue, templateArgs.TemplateParameters[parameterName]); + Assert.IsTrue(templateArgs.TemplateParameters.ContainsKey(parameterName)); + Assert.AreEqual(expectedValue, templateArgs.TemplateParameters[parameterName]); } } @@ -345,8 +346,8 @@ internal void CanParseTemplateOptions(string command, string parameterName, stri new[] { "foo --framework ", "framework", "net5.0|net6.0", "net6.0", "net6.0" }, }; - [Theory] - [MemberData(nameof(CanParseChoiceTemplateOptionsData))] + [TestMethod] + [DynamicData(nameof(CanParseChoiceTemplateOptionsData))] internal void CanParseChoiceTemplateOptions(string command, string parameterName, string parameterValues, string? defaultIfNoOptionValue, string? expectedValue) { MockTemplateInfo template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group") @@ -370,12 +371,12 @@ internal void CanParseChoiceTemplateOptions(string command, string parameterName if (string.IsNullOrWhiteSpace(expectedValue)) { - Assert.False(templateArgs.TemplateParameters.ContainsKey(parameterName)); + Assert.IsFalse(templateArgs.TemplateParameters.ContainsKey(parameterName)); } else { - Assert.True(templateArgs.TemplateParameters.ContainsKey(parameterName)); - Assert.Equal(expectedValue, templateArgs.TemplateParameters[parameterName]); + Assert.IsTrue(templateArgs.TemplateParameters.ContainsKey(parameterName)); + Assert.AreEqual(expectedValue, templateArgs.TemplateParameters[parameterName]); } } @@ -389,8 +390,8 @@ internal void CanParseChoiceTemplateOptions(string command, string parameterName new[] { "foo --framework ", "framework", "net5.0|net6.0|net7.0", "net5.0|net6.0", "net5.0|net6.0" }, }; - [Theory] - [MemberData(nameof(CanParseMultiChoiceTemplateOptionsData))] + [TestMethod] + [DynamicData(nameof(CanParseMultiChoiceTemplateOptionsData))] internal void CanParseMultiChoiceTemplateOptions(string command, string parameterName, string parameterValues, string? defaultIfNoOptionValue, string? expectedValue) { MockTemplateInfo template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group") @@ -414,12 +415,12 @@ internal void CanParseMultiChoiceTemplateOptions(string command, string paramete if (string.IsNullOrWhiteSpace(expectedValue)) { - Assert.False(templateArgs.TemplateParameters.ContainsKey(parameterName)); + Assert.IsFalse(templateArgs.TemplateParameters.ContainsKey(parameterName)); } else { - Assert.True(templateArgs.TemplateParameters.ContainsKey(parameterName)); - Assert.Equal(expectedValue, templateArgs.TemplateParameters[parameterName]); + Assert.IsTrue(templateArgs.TemplateParameters.ContainsKey(parameterName)); + Assert.AreEqual(expectedValue, templateArgs.TemplateParameters[parameterName]); } } @@ -452,8 +453,8 @@ internal void CanParseMultiChoiceTemplateOptions(string command, string paramete }; - [Theory] - [MemberData(nameof(CanDetectParseErrorsTemplateOptionsData))] + [TestMethod] + [DynamicData(nameof(CanDetectParseErrorsTemplateOptionsData))] internal void CanDetectParseErrorsTemplateOptions( string command, string parameterName, @@ -481,8 +482,8 @@ internal void CanDetectParseErrorsTemplateOptions( TemplateCommand templateCommand = new(myCommand, settings, packageManager, templateGroup, templateGroup.Templates.Single()); Command parser = ParserFactory.CreateParser(templateCommand); ParseResult templateParseResult = parser.Parse(args.RemainingArguments ?? Array.Empty()); - Assert.True(templateParseResult.Errors.Any()); - Assert.Equal(expectedError, templateParseResult.Errors.Single().Message); + Assert.IsTrue(templateParseResult.Errors.Any()); + Assert.AreEqual(expectedError, templateParseResult.Errors.Single().Message); } public static IEnumerable CanDetectParseErrorsChoiceTemplateOptionsData => @@ -496,8 +497,8 @@ internal void CanDetectParseErrorsTemplateOptions( new object?[] { "foo --framework", "framework", "net5.0|net6.0", true, null, "netcoreapp2.1", $"Cannot parse default if option without value 'netcoreapp2.1' for option '--framework' as expected type 'choice': value 'netcoreapp2.1' is not allowed, allowed values are: 'net5.0','net6.0'." } }; - [Theory] - [MemberData(nameof(CanDetectParseErrorsChoiceTemplateOptionsData))] + [TestMethod] + [DynamicData(nameof(CanDetectParseErrorsChoiceTemplateOptionsData))] internal void CanDetectParseErrorsChoiceTemplateOptions( string command, string parameterName, @@ -526,12 +527,12 @@ internal void CanDetectParseErrorsChoiceTemplateOptions( TemplateCommand templateCommand = new(myCommand, settings, packageManager, templateGroup, templateGroup.Templates.Single()); Command templateCommandParser = ParserFactory.CreateParser(templateCommand); ParseResult templateParseResult = templateCommandParser.Parse(args.RemainingArguments ?? Array.Empty(), ParserFactory.ParserConfiguration); - Assert.True(templateParseResult.Errors.Any()); - Assert.Equal(expectedError, templateParseResult.Errors.Single().Message); + Assert.IsTrue(templateParseResult.Errors.Any()); + Assert.AreEqual(expectedError, templateParseResult.Errors.Single().Message); } - [Fact] - internal void DoNotAddAllowScriptOptionForTemplate() + [TestMethod] + public void DoNotAddAllowScriptOptionForTemplate() { var template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group"); @@ -552,17 +553,17 @@ internal void DoNotAddAllowScriptOptionForTemplate() ParseResult templateParseResult = parser.Parse(args.RemainingArguments ?? Array.Empty()); TemplateCommandArgs templateArgs = new(templateCommand, myCommand, templateParseResult); - Assert.Null(templateArgs.AllowScripts); + Assert.IsNull(templateArgs.AllowScripts); } - [Theory] - [InlineData("foo", AllowRunScripts.Prompt)] - [InlineData("foo --allow-scripts prompt", AllowRunScripts.Prompt)] - [InlineData("foo --allow-scripts Prompt", AllowRunScripts.Prompt)] - [InlineData("foo --allow-scripts yes", AllowRunScripts.Yes)] - [InlineData("foo --allow-scripts Yes", AllowRunScripts.Yes)] - [InlineData("foo --allow-scripts no", AllowRunScripts.No)] - [InlineData("foo --allow-scripts NO", AllowRunScripts.No)] + [TestMethod] + [DataRow("foo", AllowRunScripts.Prompt)] + [DataRow("foo --allow-scripts prompt", AllowRunScripts.Prompt)] + [DataRow("foo --allow-scripts Prompt", AllowRunScripts.Prompt)] + [DataRow("foo --allow-scripts yes", AllowRunScripts.Yes)] + [DataRow("foo --allow-scripts Yes", AllowRunScripts.Yes)] + [DataRow("foo --allow-scripts no", AllowRunScripts.No)] + [DataRow("foo --allow-scripts NO", AllowRunScripts.No)] internal void CanParseAllowScriptsOption(string command, AllowRunScripts? result) { MockTemplateInfo template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group") @@ -585,17 +586,17 @@ internal void CanParseAllowScriptsOption(string command, AllowRunScripts? result ParseResult templateParseResult = parser.Parse(args.RemainingArguments ?? Array.Empty()); TemplateCommandArgs templateArgs = new(templateCommand, myCommand, templateParseResult); - Assert.Equal(result, templateArgs.AllowScripts); + Assert.AreEqual(result, templateArgs.AllowScripts); } #region MultiShortNameResolutionTests - [Theory] - [InlineData("aaa")] - [InlineData("bbb")] - [InlineData("ccc")] - [InlineData("ddd")] - [InlineData("eee")] - [InlineData("fff")] + [TestMethod] + [DataRow("aaa")] + [DataRow("bbb")] + [DataRow("ccc")] + [DataRow("ddd")] + [DataRow("eee")] + [DataRow("fff")] public void AllTemplatesInGroupUseAllShortNamesForResolution(string shortName) { TemplateGroup templateGroup = TemplateGroup.FromTemplateList( @@ -613,17 +614,17 @@ public void AllTemplatesInGroupUseAllShortNamesForResolution(string shortName) ParseResult parseResult = myCommand.Parse($"new {shortName}"); InstantiateCommandArgs args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); HashSet templateCommands = InstantiateCommand.GetTemplateCommand(args, settings, A.Fake(), templateGroup); - Assert.Single(templateCommands); - Assert.Equal("MultiName.Test.High.CSharp", templateCommands.Single().Template.Identity); + Assert.HasCount(1, templateCommands); + Assert.AreEqual("MultiName.Test.High.CSharp", templateCommands.Single().Template.Identity); } - [Theory] - [InlineData("aaa")] - [InlineData("bbb")] - [InlineData("ccc")] - [InlineData("ddd")] - [InlineData("eee")] - [InlineData("fff")] + [TestMethod] + [DataRow("aaa")] + [DataRow("bbb")] + [DataRow("ccc")] + [DataRow("ddd")] + [DataRow("eee")] + [DataRow("fff")] public void ExplicitLanguageChoiceIsHonoredWithMultipleShortNames(string shortName) { TemplateGroup templateGroup = TemplateGroup.FromTemplateList( @@ -642,18 +643,18 @@ public void ExplicitLanguageChoiceIsHonoredWithMultipleShortNames(string shortNa ParseResult parseResult = myCommand.Parse(command); InstantiateCommandArgs args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); HashSet templateCommands = InstantiateCommand.GetTemplateCommand(args, settings, A.Fake(), templateGroup); - Assert.Single(templateCommands); - Assert.Equal("Multiname.Test.Only.FSharp", templateCommands.Single().Template.Identity); + Assert.HasCount(1, templateCommands); + Assert.AreEqual("Multiname.Test.Only.FSharp", templateCommands.Single().Template.Identity); } - [Theory] - [InlineData("aaa", "W", "MultiName.Test.High.CSharp")] // uses a short name from the expected invokable template - [InlineData("fff", "W", "MultiName.Test.High.CSharp")] // uses a short name from a different template in the group - [InlineData("ccc", "X", "MultiName.Test.Low.CSharp")] // uses a short name from the expected invokable template - [InlineData("fff", "X", "MultiName.Test.Low.CSharp")] // uses a short name from a different template in the group - [InlineData("fff", "Y", "Multiname.Test.Only.FSharp")] // uses a short name from the expected invokable template - [InlineData("eee", "Y", "Multiname.Test.Only.FSharp")] // uses a short name from a different template in the group + [TestMethod] + [DataRow("aaa", "W", "MultiName.Test.High.CSharp")] // uses a short name from the expected invokable template + [DataRow("fff", "W", "MultiName.Test.High.CSharp")] // uses a short name from a different template in the group + [DataRow("ccc", "X", "MultiName.Test.Low.CSharp")] // uses a short name from the expected invokable template + [DataRow("fff", "X", "MultiName.Test.Low.CSharp")] // uses a short name from a different template in the group + [DataRow("fff", "Y", "Multiname.Test.Only.FSharp")] // uses a short name from the expected invokable template + [DataRow("eee", "Y", "Multiname.Test.Only.FSharp")] // uses a short name from a different template in the group public void ChoiceValueDisambiguatesMatchesWithMultipleShortNames(string name, string fooChoice, string expectedIdentity) { TemplateGroup templateGroup = TemplateGroup.FromTemplateList( @@ -673,17 +674,17 @@ public void ChoiceValueDisambiguatesMatchesWithMultipleShortNames(string name, s ParseResult parseResult = myCommand.Parse($" new {command}"); InstantiateCommandArgs args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); HashSet templateCommands = InstantiateCommand.GetTemplateCommand(args, settings, A.Fake(), templateGroup); - Assert.Single(templateCommands); - Assert.Equal(expectedIdentity, templateCommands.Single().Template.Identity); + Assert.HasCount(1, templateCommands); + Assert.AreEqual(expectedIdentity, templateCommands.Single().Template.Identity); } - [Theory] - [InlineData("aaa", "HighC", "someValue", "MultiName.Test.High.CSharp")] // uses a short name from the expected invokable template - [InlineData("fff", "HighC", "someValue", "MultiName.Test.High.CSharp")] // uses a short name from a different template in the group - [InlineData("ccc", "LowC", "someValue", "MultiName.Test.Low.CSharp")] // uses a short name from the expected invokable template - [InlineData("fff", "LowC", "someValue", "MultiName.Test.Low.CSharp")] // uses a short name from a different template in the group - [InlineData("fff", "OnlyF", "someValue", "Multiname.Test.Only.FSharp")] // uses a short name from the expected invokable template - [InlineData("eee", "OnlyF", "someValue", "Multiname.Test.Only.FSharp")] // uses a short name from a different template in the group + [TestMethod] + [DataRow("aaa", "HighC", "someValue", "MultiName.Test.High.CSharp")] // uses a short name from the expected invokable template + [DataRow("fff", "HighC", "someValue", "MultiName.Test.High.CSharp")] // uses a short name from a different template in the group + [DataRow("ccc", "LowC", "someValue", "MultiName.Test.Low.CSharp")] // uses a short name from the expected invokable template + [DataRow("fff", "LowC", "someValue", "MultiName.Test.Low.CSharp")] // uses a short name from a different template in the group + [DataRow("fff", "OnlyF", "someValue", "Multiname.Test.Only.FSharp")] // uses a short name from the expected invokable template + [DataRow("eee", "OnlyF", "someValue", "Multiname.Test.Only.FSharp")] // uses a short name from a different template in the group public void ParameterExistenceDisambiguatesMatchesWithMultipleShortNames(string name, string paramName, string paramValue, string expectedIdentity) { TemplateGroup templateGroup = TemplateGroup.FromTemplateList( @@ -703,18 +704,18 @@ public void ParameterExistenceDisambiguatesMatchesWithMultipleShortNames(string ParseResult parseResult = myCommand.Parse($" new {command}"); InstantiateCommandArgs args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); HashSet templateCommands = InstantiateCommand.GetTemplateCommand(args, settings, A.Fake(), templateGroup); - Assert.Single(templateCommands); - Assert.Equal(expectedIdentity, templateCommands.Single().Template.Identity); + Assert.HasCount(1, templateCommands); + Assert.AreEqual(expectedIdentity, templateCommands.Single().Template.Identity); } #endregion - [Theory] - [InlineData("new foo --dry-run", "dry-run")] - [InlineData("new --dry-run foo", "dry-run")] - [InlineData("new foo --force", "force")] - [InlineData("new --force foo", "force")] - [InlineData("new foo --no-update-check", "no-update-check")] - [InlineData("new --no-update-check foo", "no-update-check")] + [TestMethod] + [DataRow("new foo --dry-run", "dry-run")] + [DataRow("new --dry-run foo", "dry-run")] + [DataRow("new foo --force", "force")] + [DataRow("new --force foo", "force")] + [DataRow("new foo --no-update-check", "no-update-check")] + [DataRow("new --no-update-check foo", "no-update-check")] internal void CanParseFlagsOption(string command, string action) { Func expectedAction = action switch @@ -749,10 +750,10 @@ internal void CanParseFlagsOption(string command, string action) ParseResult templateParseResult = parser.Parse(args.TokensToInvoke ?? Array.Empty()); var templateArgs = new TemplateCommandArgs(templateCommand, myCommand, templateParseResult); - Assert.True(expectedAction(templateArgs)); + Assert.IsTrue(expectedAction(templateArgs)); } - [Fact] + [TestMethod] internal void CanParse_WithoutRequiredParameter() { MockTemplateInfo template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group") @@ -771,7 +772,7 @@ internal void CanParse_WithoutRequiredParameter() ParseResult parseResult = rootCommand.Parse("new foo"); InstantiateCommandArgs args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); HashSet templateCommands = InstantiateCommand.GetTemplateCommand(args, settings, A.Fake(), templateGroup); - Assert.Single(templateCommands); + Assert.HasCount(1, templateCommands); } } } diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/ListTests.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/ListTests.cs index 4d904734b2be..3e1882c97aa2 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/ListTests.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/ListTests.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.CommandLine; @@ -7,6 +7,7 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests.ParserTests { + [TestClass] public class ListTests : BaseTest { private static readonly Dictionary _stringToFilterDefMap = new() @@ -18,61 +19,61 @@ public class ListTests : BaseTest { "baseline", FilterOptionDefinition.BaselineFilter }, }; - [Theory] - [InlineData("new list source --author filter-value", "author")] - [InlineData("new --list source --author filter-value", "author")] - [InlineData("new source --author filter-value --list", "author")] - [InlineData("new source --list --author filter-value ", "author")] - [InlineData("new --author filter-value --list source", "author")] - [InlineData("new list source --language filter-value", "language")] - [InlineData("new --list source --language filter-value", "language")] - [InlineData("new source --language filter-value --list", "language")] - [InlineData("new source --list --language filter-value ", "language")] - [InlineData("new --language filter-value --list source", "language")] - [InlineData("new list source -lang filter-value", "language")] - [InlineData("new --list source -lang filter-value", "language")] - [InlineData("new source -lang filter-value --list", "language")] - [InlineData("new source --list -lang filter-value ", "language")] - [InlineData("new -lang filter-value --list source", "language")] - [InlineData("new list source --tag filter-value", "tag")] - [InlineData("new --list source --tag filter-value", "tag")] - [InlineData("new source --tag filter-value --list", "tag")] - [InlineData("new source --list --tag filter-value ", "tag")] - [InlineData("new --tag filter-value --list source", "tag")] - [InlineData("new list source --type filter-value", "type")] - [InlineData("new --list source --type filter-value", "type")] - [InlineData("new source --type filter-value --list", "type")] - [InlineData("new source --list --type filter-value ", "type")] - [InlineData("new --type filter-value --list source", "type")] - [InlineData("new list source --baseline filter-value", "baseline")] - [InlineData("new --list source --baseline filter-value", "baseline")] - [InlineData("new source --baseline filter-value --list", "baseline")] - [InlineData("new source --list --baseline filter-value ", "baseline")] - [InlineData("new --baseline filter-value --list source", "baseline")] - [InlineData("new -l source --author filter-value", "author")] - [InlineData("new source --author filter-value -l", "author")] - [InlineData("new source -l --author filter-value ", "author")] - [InlineData("new --author filter-value -l source", "author")] - [InlineData("new -l source --language filter-value", "language")] - [InlineData("new source --language filter-value -l", "language")] - [InlineData("new source -l --language filter-value ", "language")] - [InlineData("new --language filter-value -l source", "language")] - [InlineData("new -l source -lang filter-value", "language")] - [InlineData("new source -lang filter-value -l", "language")] - [InlineData("new source -l -lang filter-value ", "language")] - [InlineData("new -lang filter-value -l source", "language")] - [InlineData("new -l source --tag filter-value", "tag")] - [InlineData("new source --tag filter-value -l", "tag")] - [InlineData("new source -l --tag filter-value ", "tag")] - [InlineData("new --tag filter-value -l source", "tag")] - [InlineData("new -l source --type filter-value", "type")] - [InlineData("new source --type filter-value -l", "type")] - [InlineData("new source -l --type filter-value ", "type")] - [InlineData("new --type filter-value -l source", "type")] - [InlineData("new -l source --baseline filter-value", "baseline")] - [InlineData("new source --baseline filter-value -l", "baseline")] - [InlineData("new source -l --baseline filter-value ", "baseline")] - [InlineData("new --baseline filter-value -l source", "baseline")] + [TestMethod] + [DataRow("new list source --author filter-value", "author")] + [DataRow("new --list source --author filter-value", "author")] + [DataRow("new source --author filter-value --list", "author")] + [DataRow("new source --list --author filter-value ", "author")] + [DataRow("new --author filter-value --list source", "author")] + [DataRow("new list source --language filter-value", "language")] + [DataRow("new --list source --language filter-value", "language")] + [DataRow("new source --language filter-value --list", "language")] + [DataRow("new source --list --language filter-value ", "language")] + [DataRow("new --language filter-value --list source", "language")] + [DataRow("new list source -lang filter-value", "language")] + [DataRow("new --list source -lang filter-value", "language")] + [DataRow("new source -lang filter-value --list", "language")] + [DataRow("new source --list -lang filter-value ", "language")] + [DataRow("new -lang filter-value --list source", "language")] + [DataRow("new list source --tag filter-value", "tag")] + [DataRow("new --list source --tag filter-value", "tag")] + [DataRow("new source --tag filter-value --list", "tag")] + [DataRow("new source --list --tag filter-value ", "tag")] + [DataRow("new --tag filter-value --list source", "tag")] + [DataRow("new list source --type filter-value", "type")] + [DataRow("new --list source --type filter-value", "type")] + [DataRow("new source --type filter-value --list", "type")] + [DataRow("new source --list --type filter-value ", "type")] + [DataRow("new --type filter-value --list source", "type")] + [DataRow("new list source --baseline filter-value", "baseline")] + [DataRow("new --list source --baseline filter-value", "baseline")] + [DataRow("new source --baseline filter-value --list", "baseline")] + [DataRow("new source --list --baseline filter-value ", "baseline")] + [DataRow("new --baseline filter-value --list source", "baseline")] + [DataRow("new -l source --author filter-value", "author")] + [DataRow("new source --author filter-value -l", "author")] + [DataRow("new source -l --author filter-value ", "author")] + [DataRow("new --author filter-value -l source", "author")] + [DataRow("new -l source --language filter-value", "language")] + [DataRow("new source --language filter-value -l", "language")] + [DataRow("new source -l --language filter-value ", "language")] + [DataRow("new --language filter-value -l source", "language")] + [DataRow("new -l source -lang filter-value", "language")] + [DataRow("new source -lang filter-value -l", "language")] + [DataRow("new source -l -lang filter-value ", "language")] + [DataRow("new -lang filter-value -l source", "language")] + [DataRow("new -l source --tag filter-value", "tag")] + [DataRow("new source --tag filter-value -l", "tag")] + [DataRow("new source -l --tag filter-value ", "tag")] + [DataRow("new --tag filter-value -l source", "tag")] + [DataRow("new -l source --type filter-value", "type")] + [DataRow("new source --type filter-value -l", "type")] + [DataRow("new source -l --type filter-value ", "type")] + [DataRow("new --type filter-value -l source", "type")] + [DataRow("new -l source --baseline filter-value", "baseline")] + [DataRow("new source --baseline filter-value -l", "baseline")] + [DataRow("new source -l --baseline filter-value ", "baseline")] + [DataRow("new --baseline filter-value -l source", "baseline")] public void List_CanParseFilterOption(string command, string expectedFilter) { FilterOptionDefinition expectedDef = _stringToFilterDefMap[expectedFilter]; @@ -83,37 +84,37 @@ public void List_CanParseFilterOption(string command, string expectedFilter) ParseResult parseResult = myCommand.Parse(command); ListCommandArgs args = new((BaseListCommand)parseResult.CommandResult.Command, parseResult); - Assert.Single(args.AppliedFilters); + Assert.HasCount(1, args.AppliedFilters); Assert.Contains("filter-value", args.GetFilterValue(expectedDef)); - Assert.Equal("source", args.ListNameCriteria); + Assert.AreEqual("source", args.ListNameCriteria); } - [Theory] - [InlineData("new list --author filter-value", "author")] - [InlineData("new --list --author filter-value", "author")] - [InlineData("new --author filter-value --list", "author")] - [InlineData("new list --language filter-value", "language")] - [InlineData("new --list --language filter-value", "language")] - [InlineData("new --language filter-value --list", "language")] - [InlineData("new list --tag filter-value", "tag")] - [InlineData("new --list --tag filter-value", "tag")] - [InlineData("new --tag filter-value --list", "tag")] - [InlineData("new list --type filter-value", "type")] - [InlineData("new --list --type filter-value", "type")] - [InlineData("new --type filter-value --list", "type")] - [InlineData("new list --baseline filter-value", "baseline")] - [InlineData("new --list --baseline filter-value", "baseline")] - [InlineData("new --baseline filter-value --list", "baseline")] - [InlineData("new -l --author filter-value", "author")] - [InlineData("new --author filter-value -l", "author")] - [InlineData("new -l --language filter-value", "language")] - [InlineData("new --language filter-value -l", "language")] - [InlineData("new -l --tag filter-value", "tag")] - [InlineData("new --tag filter-value -l", "tag")] - [InlineData("new -l --type filter-value", "type")] - [InlineData("new --type filter-value -l", "type")] - [InlineData("new -l --baseline filter-value", "baseline")] - [InlineData("new --baseline filter-value -l", "baseline")] + [TestMethod] + [DataRow("new list --author filter-value", "author")] + [DataRow("new --list --author filter-value", "author")] + [DataRow("new --author filter-value --list", "author")] + [DataRow("new list --language filter-value", "language")] + [DataRow("new --list --language filter-value", "language")] + [DataRow("new --language filter-value --list", "language")] + [DataRow("new list --tag filter-value", "tag")] + [DataRow("new --list --tag filter-value", "tag")] + [DataRow("new --tag filter-value --list", "tag")] + [DataRow("new list --type filter-value", "type")] + [DataRow("new --list --type filter-value", "type")] + [DataRow("new --type filter-value --list", "type")] + [DataRow("new list --baseline filter-value", "baseline")] + [DataRow("new --list --baseline filter-value", "baseline")] + [DataRow("new --baseline filter-value --list", "baseline")] + [DataRow("new -l --author filter-value", "author")] + [DataRow("new --author filter-value -l", "author")] + [DataRow("new -l --language filter-value", "language")] + [DataRow("new --language filter-value -l", "language")] + [DataRow("new -l --tag filter-value", "tag")] + [DataRow("new --tag filter-value -l", "tag")] + [DataRow("new -l --type filter-value", "type")] + [DataRow("new --type filter-value -l", "type")] + [DataRow("new -l --baseline filter-value", "baseline")] + [DataRow("new --baseline filter-value -l", "baseline")] public void List_CanParseFilterOptionWithoutMainCriteria(string command, string expectedFilter) { FilterOptionDefinition expectedDef = _stringToFilterDefMap[expectedFilter]; @@ -124,14 +125,14 @@ public void List_CanParseFilterOptionWithoutMainCriteria(string command, string ParseResult parseResult = myCommand.Parse(command); ListCommandArgs args = new((BaseListCommand)parseResult.CommandResult.Command, parseResult); - Assert.Single(args.AppliedFilters); + Assert.HasCount(1, args.AppliedFilters); Assert.Contains("filter-value", args.GetFilterValue(expectedDef)); - Assert.Null(args.ListNameCriteria); + Assert.IsNull(args.ListNameCriteria); } - [Theory] - [InlineData("new --list cr1 cr2")] - [InlineData("new list cr1 cr2")] + [TestMethod] + [DataRow("new --list cr1 cr2")] + [DataRow("new list cr1 cr2")] public void List_CannotParseMultipleArgs(string command) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -139,11 +140,11 @@ public void List_CannotParseMultipleArgs(string command) ParseResult parseResult = myCommand.Parse(command); - Assert.NotEmpty(parseResult.Errors); - Assert.Equal("Unrecognized command or argument 'cr2'.", parseResult.Errors[0].Message); + Assert.IsTrue(parseResult.Errors.Any()); + Assert.AreEqual("Unrecognized command or argument 'cr2'.", parseResult.Errors[0].Message); } - [Fact] + [TestMethod] public void List_CannotParseArgsAtNewLevel() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -151,16 +152,16 @@ public void List_CannotParseArgsAtNewLevel() ParseResult parseResult = myCommand.Parse("new smth list"); - Assert.NotEmpty(parseResult.Errors); - Assert.Equal("Unrecognized command or argument(s): 'smth'.", parseResult.Errors[0].Message); + Assert.IsTrue(parseResult.Errors.Any()); + Assert.AreEqual("Unrecognized command or argument(s): 'smth'.", parseResult.Errors[0].Message); } - [Theory] - [InlineData("new --author filter-value list source", "--author")] - [InlineData("new --type filter-value list source", "--type")] - [InlineData("new --tag filter-value list source", "--tag")] - [InlineData("new --language filter-value list source", "--language")] - [InlineData("new -lang filter-value list source", "-lang")] + [TestMethod] + [DataRow("new --author filter-value list source", "--author")] + [DataRow("new --type filter-value list source", "--type")] + [DataRow("new --tag filter-value list source", "--tag")] + [DataRow("new --language filter-value list source", "--language")] + [DataRow("new -lang filter-value list source", "-lang")] public void List_CannotParseOptionsAtNewLevel(string command, string expectedFilter) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -168,11 +169,11 @@ public void List_CannotParseOptionsAtNewLevel(string command, string expectedFil ParseResult parseResult = myCommand.Parse(command); - Assert.NotEmpty(parseResult.Errors); - Assert.Equal($"Unrecognized command or argument(s): '{expectedFilter}','filter-value'.", parseResult.Errors[0].Message); + Assert.IsTrue(parseResult.Errors.Any()); + Assert.AreEqual($"Unrecognized command or argument(s): '{expectedFilter}','filter-value'.", parseResult.Errors[0].Message); } - [Fact] + [TestMethod] public void List_Legacy_CannotParseArgsAtBothLevels() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -180,14 +181,14 @@ public void List_Legacy_CannotParseArgsAtBothLevels() ParseResult parseResult = myCommand.Parse("new smth --list smth-else"); - Assert.NotEmpty(parseResult.Errors); - Assert.Equal("Unrecognized command or argument(s): 'smth'.", parseResult.Errors[0].Message); + Assert.IsTrue(parseResult.Errors.Any()); + Assert.AreEqual("Unrecognized command or argument(s): 'smth'.", parseResult.Errors[0].Message); } - [Theory] - [InlineData("new --list --columns-all")] - [InlineData("new --columns-all --list")] - [InlineData("new list --columns-all")] + [TestMethod] + [DataRow("new --list --columns-all")] + [DataRow("new --columns-all --list")] + [DataRow("new list --columns-all")] public void List_CanParseColumnsAll(string command) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -197,17 +198,17 @@ public void List_CanParseColumnsAll(string command) ListCommandArgs args = new((BaseListCommand)parseResult.CommandResult.Command, parseResult); - Assert.True(args.DisplayAllColumns); + Assert.IsTrue(args.DisplayAllColumns); } - [Theory] - [InlineData("new list --columns author type", new[] { "author", "type" })] - [InlineData("new list --columns author --columns type", new[] { "author", "type" })] + [TestMethod] + [DataRow("new list --columns author type", new[] { "author", "type" })] + [DataRow("new list --columns author --columns type", new[] { "author", "type" })] //https://github.com/dotnet/command-line-api/issues/1503 - //[InlineData("new list --columns author,type", new[] { "author", "type" })] - //[InlineData("new list --columns author, type --columns tag", new[] { "author", "type", "tag" })] - [InlineData("new --list --columns author --columns type", new[] { "author", "type" })] - //[InlineData("new --list --columns author,type", new[] { "author", "type" })] + //[DataRow("new list --columns author,type", new[] { "author", "type" })] + //[DataRow("new list --columns author, type --columns tag", new[] { "author", "type", "tag" })] + [DataRow("new --list --columns author --columns type", new[] { "author", "type" })] + //[DataRow("new --list --columns author,type", new[] { "author", "type" })] public void List_CanParseColumns(string command, string[] expectedColumns) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -217,19 +218,19 @@ public void List_CanParseColumns(string command, string[] expectedColumns) ListCommandArgs args = new((BaseListCommand)parseResult.CommandResult.Command, parseResult); - Assert.False(args.DisplayAllColumns); - Assert.NotNull(args.ColumnsToDisplay); - Assert.NotEmpty(args.ColumnsToDisplay); - Assert.Equal(expectedColumns.Length, args.ColumnsToDisplay.Count); + Assert.IsFalse(args.DisplayAllColumns); + Assert.IsNotNull(args.ColumnsToDisplay); + Assert.IsTrue(args.ColumnsToDisplay.Any()); + Assert.AreEqual(expectedColumns.Length, args.ColumnsToDisplay.Count); foreach (string column in expectedColumns) { Assert.Contains(column, args.ColumnsToDisplay!); } } - [Theory] - [InlineData("new --list --columns c1 --columns c2")] - [InlineData("new list --columns c1 c2")] + [TestMethod] + [DataRow("new --list --columns c1 --columns c2")] + [DataRow("new list --columns c1 c2")] public void List_CannotParseUnknownColumns(string command) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -237,15 +238,15 @@ public void List_CannotParseUnknownColumns(string command) ParseResult parseResult = myCommand.Parse(command); - Assert.NotEmpty(parseResult.Errors); + Assert.IsTrue(parseResult.Errors.Any()); Assert.Contains("Argument 'c1' not recognized. Must be one of:", parseResult.Errors[0].Message); } - [Theory] - [InlineData("new --interactive list source", "'--interactive'")] - [InlineData("new --interactive --list source", "'--interactive'")] - [InlineData("new foo bar --list source", "'foo'|'bar'")] - [InlineData("new foo bar list source", "'foo'|'bar'")] + [TestMethod] + [DataRow("new --interactive list source", "'--interactive'")] + [DataRow("new --interactive --list source", "'--interactive'")] + [DataRow("new foo bar --list source", "'foo'|'bar'")] + [DataRow("new foo bar list source", "'foo'|'bar'")] public void List_HandleParseErrors(string command, string expectedInvalidTokens) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -256,15 +257,15 @@ public void List_HandleParseErrors(string command, string expectedInvalidTokens) string[] expectedInvalidTokenSets = expectedInvalidTokens.Split("|"); - Assert.NotEmpty(parseResult.Errors); - Assert.Equal(expectedInvalidTokenSets.Length, parseResult.Errors.Count); + Assert.IsTrue(parseResult.Errors.Any()); + Assert.AreEqual(expectedInvalidTokenSets.Length, parseResult.Errors.Count); foreach (string tokenSet in expectedInvalidTokenSets) { - Assert.True(errorMessages.Contains($"Unrecognized command or argument(s): {tokenSet}.") || errorMessages.Contains($"Unrecognized command or argument {tokenSet}.")); + Assert.IsTrue(errorMessages.Contains($"Unrecognized command or argument(s): {tokenSet}.") || errorMessages.Contains($"Unrecognized command or argument {tokenSet}.")); } } - [Fact] + [TestMethod] public void CommandExampleCanShowParentCommandsBeyondNew() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -275,7 +276,7 @@ public void CommandExampleCanShowParentCommandsBeyondNew() }; ParseResult parseResult = rootCommand.Parse("dotnet new list"); - Assert.Equal("dotnet new list", Example.For(parseResult).WithSubcommand()); + Assert.AreEqual("dotnet new list", Example.For(parseResult).WithSubcommand()); } } } diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/MiscTests.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/MiscTests.cs index a549f43e2c11..72bc51110f14 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/MiscTests.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/MiscTests.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.CommandLine; @@ -10,12 +10,13 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests.ParserTests { + [TestClass] public class MiscTests : BaseTest { /// /// This test checks if help aliases are in sync with System.CommandLine. /// - [Fact] + [TestMethod] public void KnownHelpAliasesAreCorrect() { var result = new RootCommand().Parse(Constants.KnownHelpAliases[0]); @@ -29,39 +30,39 @@ public void KnownHelpAliasesAreCorrect() var aliases = new[] { helpOption.Name }.Concat(helpOption.Aliases); - Assert.Equal(aliases.OrderBy(a => a), TemplateCommand.KnownHelpAliases.OrderBy(a => a)); + Assert.AreSequenceEqual(aliases.OrderBy(a => a), TemplateCommand.KnownHelpAliases.OrderBy(a => a)); } /// /// This test check if default completion item comparer compares the instances using labels only. /// - [Fact] + [TestMethod] public void CompletionItemCompareIsAsExpected() { - Assert.Equal( + Assert.AreEqual( new CompletionItem("my-label", kind: "Value", sortText: "sort-text", insertText: "insert-text", documentation: "doc", detail: "det"), new CompletionItem("my-label", kind: "Value", sortText: "sort-text", insertText: "insert-text", documentation: "doc", detail: "det")); - Assert.Equal( + Assert.AreEqual( new CompletionItem("my-label", kind: "Value", sortText: "sort-text1", insertText: "insert-text1", documentation: "doc1", detail: "det1"), new CompletionItem("my-label", kind: "Value", sortText: "sort-text2", insertText: "insert-text2", documentation: "doc2", detail: "det2")); - Assert.NotEqual( + Assert.AreNotEqual( new CompletionItem("my-label", kind: "Value", sortText: "sort-text1", insertText: "insert-text1", documentation: "doc1", detail: "det1"), new CompletionItem("my-label", kind: "Argument", sortText: "sort-text2", insertText: "insert-text2", documentation: "doc2", detail: "det2")); } - [Theory] - [InlineData("new --debug:attach", "--debug:attach")] - [InlineData("new --debug:attach console", "--debug:attach")] - [InlineData("new --debug:reinit", "--debug:reinit")] - [InlineData("new --debug:ephemeral-hive", "--debug:ephemeral-hive")] - [InlineData("new --debug:virtual-hive", "--debug:ephemeral-hive")] - [InlineData("new --debug:rebuildcache", "--debug:rebuild-cache")] - [InlineData("new --debug:rebuild-cache", "--debug:rebuild-cache")] - [InlineData("new --debug:show-config", "--debug:show-config")] - [InlineData("new --debug:showconfig", "--debug:show-config")] + [TestMethod] + [DataRow("new --debug:attach", "--debug:attach")] + [DataRow("new --debug:attach console", "--debug:attach")] + [DataRow("new --debug:reinit", "--debug:reinit")] + [DataRow("new --debug:ephemeral-hive", "--debug:ephemeral-hive")] + [DataRow("new --debug:virtual-hive", "--debug:ephemeral-hive")] + [DataRow("new --debug:rebuildcache", "--debug:rebuild-cache")] + [DataRow("new --debug:rebuild-cache", "--debug:rebuild-cache")] + [DataRow("new --debug:show-config", "--debug:show-config")] + [DataRow("new --debug:showconfig", "--debug:show-config")] public void DebugFlagCanBeParsedOnNewLevel(string command, string option) { @@ -79,19 +80,19 @@ public void DebugFlagCanBeParsedOnNewLevel(string command, string option) ParseResult parseResult = ParserFactory.CreateParser(myCommand).Parse(command); NewCommandArgs args = new(myCommand, parseResult); - Assert.True(optionsMap[option](args)); + Assert.IsTrue(optionsMap[option](args)); } - [Theory] - [InlineData("new install source --debug:attach", "--debug:attach")] - [InlineData("new install source --debug:attach --add-source s1", "--debug:attach")] - [InlineData("new install --debug:reinit source", "--debug:reinit")] - [InlineData("new install source --debug:ephemeral-hive", "--debug:ephemeral-hive")] - [InlineData("new install source --debug:virtual-hive", "--debug:ephemeral-hive")] - [InlineData("new install source --debug:rebuildcache", "--debug:rebuild-cache")] - [InlineData("new install source --debug:rebuild-cache", "--debug:rebuild-cache")] - [InlineData("new install source --debug:show-config", "--debug:show-config")] - [InlineData("new install source --debug:showconfig", "--debug:show-config")] + [TestMethod] + [DataRow("new install source --debug:attach", "--debug:attach")] + [DataRow("new install source --debug:attach --add-source s1", "--debug:attach")] + [DataRow("new install --debug:reinit source", "--debug:reinit")] + [DataRow("new install source --debug:ephemeral-hive", "--debug:ephemeral-hive")] + [DataRow("new install source --debug:virtual-hive", "--debug:ephemeral-hive")] + [DataRow("new install source --debug:rebuildcache", "--debug:rebuild-cache")] + [DataRow("new install source --debug:rebuild-cache", "--debug:rebuild-cache")] + [DataRow("new install source --debug:show-config", "--debug:show-config")] + [DataRow("new install source --debug:showconfig", "--debug:show-config")] public void DebugFlagCanBeParsedOnSubcommandLevel(string command, string option) { @@ -109,19 +110,19 @@ public void DebugFlagCanBeParsedOnSubcommandLevel(string command, string option) ParseResult parseResult = ParserFactory.CreateParser(myCommand).Parse(command); InstallCommandArgs args = new((InstallCommand)parseResult.CommandResult.Command, parseResult); - Assert.True(optionsMap[option](args)); + Assert.IsTrue(optionsMap[option](args)); } - [Theory] - [InlineData("new console --framework net5.0 --flag --debug:attach", "--debug:attach")] - [InlineData("new console --framework net5.0 --debug:attach --flag", "--debug:attach")] - [InlineData("new console --debug:reinit --framework net5.0 --flag", "--debug:reinit")] - [InlineData("new console --framework net5.0 --debug:ephemeral-hive --flag", "--debug:ephemeral-hive")] - [InlineData("new console --framework net5.0 --debug:virtual-hive --flag", "--debug:ephemeral-hive")] - [InlineData("new console --framework net5.0 --debug:rebuildcache --flag", "--debug:rebuild-cache")] - [InlineData("new console --framework net5.0 --debug:rebuild-cache --flag", "--debug:rebuild-cache")] - [InlineData("new console --framework net5.0 --debug:show-config --flag", "--debug:show-config")] - [InlineData("new console --framework net5.0 --debug:showconfig --flag", "--debug:show-config")] + [TestMethod] + [DataRow("new console --framework net5.0 --flag --debug:attach", "--debug:attach")] + [DataRow("new console --framework net5.0 --debug:attach --flag", "--debug:attach")] + [DataRow("new console --debug:reinit --framework net5.0 --flag", "--debug:reinit")] + [DataRow("new console --framework net5.0 --debug:ephemeral-hive --flag", "--debug:ephemeral-hive")] + [DataRow("new console --framework net5.0 --debug:virtual-hive --flag", "--debug:ephemeral-hive")] + [DataRow("new console --framework net5.0 --debug:rebuildcache --flag", "--debug:rebuild-cache")] + [DataRow("new console --framework net5.0 --debug:rebuild-cache --flag", "--debug:rebuild-cache")] + [DataRow("new console --framework net5.0 --debug:show-config --flag", "--debug:show-config")] + [DataRow("new console --framework net5.0 --debug:showconfig --flag", "--debug:show-config")] public void DebugFlagCanBeParsedOnTemplateSubcommandLevel(string command, string option) { @@ -139,12 +140,12 @@ public void DebugFlagCanBeParsedOnTemplateSubcommandLevel(string command, string ParseResult parseResult = myCommand.Parse(command); InstantiateCommandArgs args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); - Assert.True(optionsMap[option](args)); - Assert.Equal("console", args.ShortName); - Assert.Equal(new[] { "--framework", "net5.0", "--flag" }, args.RemainingArguments); + Assert.IsTrue(optionsMap[option](args)); + Assert.AreEqual("console", args.ShortName); + Assert.AreSequenceEqual(new[] { "--framework", "net5.0", "--flag" }, args.RemainingArguments); } - [Fact] + [TestMethod] public void ManuallyAddedOptionIsPreservedOnTemplateSubcommandLevel() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -159,19 +160,19 @@ public void ManuallyAddedOptionIsPreservedOnTemplateSubcommandLevel() ParseResult parseResult = myCommand.Parse("new console --newOption val"); InstantiateCommandArgs args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); - Assert.NotNull(args.ParseResult); - Assert.Equal("console", args.ShortName); - Assert.Empty(args.RemainingArguments); - Assert.Equal("val", args.ParseResult.GetValue(customOption)); + Assert.IsNotNull(args.ParseResult); + Assert.AreEqual("console", args.ShortName); + Assert.IsFalse(args.RemainingArguments.Any()); + Assert.AreEqual("val", args.ParseResult.GetValue(customOption)); } - [Theory] - [InlineData("new --output test console", "test")] - [InlineData("new console --output test", "test")] - [InlineData("new -o test console", "test")] - [InlineData("new console -o test", "test")] - [InlineData("new console --framework net6.0 --output test", "test")] - [InlineData("--output test new console", null)] + [TestMethod] + [DataRow("new --output test console", "test")] + [DataRow("new console --output test", "test")] + [DataRow("new -o test console", "test")] + [DataRow("new console -o test", "test")] + [DataRow("new console --framework net6.0 --output test", "test")] + [DataRow("--output test new console", null)] public void CanParseOutputOption(string command, string? expected) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -183,14 +184,14 @@ public void CanParseOutputOption(string command, string? expected) ParseResult parseResult = rootCommand.Parse(command); - Assert.Equal(expected, parseResult.GetValue(myCommand.Definition.InstantiateOptions.OutputOption)?.Name); + Assert.AreEqual(expected, parseResult.GetValue(myCommand.Definition.InstantiateOptions.OutputOption)?.Name); } - [Theory] - [InlineData("new --project $filePath console", "$filePath")] - [InlineData("new console --project $filePath", "$filePath")] - [InlineData("new console --framework net6.0 --project $filePath", "$filePath")] - [InlineData("--project $filePath new console", null)] + [TestMethod] + [DataRow("new --project $filePath console", "$filePath")] + [DataRow("new console --project $filePath", "$filePath")] + [DataRow("new console --framework net6.0 --project $filePath", "$filePath")] + [DataRow("--project $filePath new console", null)] public void CanParseProjectOption(string command, string? expected) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -206,7 +207,7 @@ public void CanParseProjectOption(string command, string? expected) expected = expected?.Replace("$filePath", Path.GetFileName(existingFilePath)); ParseResult parseResult = rootCommand.Parse(command); - Assert.Equal(expected, parseResult.GetValue(myCommand.Definition.InstantiateOptions.ProjectOption)?.Name); + Assert.AreEqual(expected, parseResult.GetValue(myCommand.Definition.InstantiateOptions.ProjectOption)?.Name); } } } diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/SearchTests.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/SearchTests.cs index d7954d5b6163..6cba9e4a90f8 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/SearchTests.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/SearchTests.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.CommandLine; @@ -7,6 +7,7 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests.ParserTests { + [TestClass] public class SearchTests : BaseTest { private static Dictionary _stringToFilterDefMap = new() @@ -19,42 +20,42 @@ public class SearchTests : BaseTest { "baseline", FilterOptionDefinition.BaselineFilter }, }; - [Theory] - [InlineData("new search source --author filter-value", "author")] - [InlineData("new --search source --author filter-value", "author")] - [InlineData("new source --author filter-value --search", "author")] - [InlineData("new source --search --author filter-value ", "author")] - [InlineData("new --author filter-value --search source", "author")] - [InlineData("new search source --package filter-value", "package")] - [InlineData("new --search source --package filter-value", "package")] - [InlineData("new source --package filter-value --search", "package")] - [InlineData("new source --search --package filter-value ", "package")] - [InlineData("new --package filter-value --search source", "package")] - [InlineData("new search source --language filter-value", "language")] - [InlineData("new --search source --language filter-value", "language")] - [InlineData("new source --language filter-value --search", "language")] - [InlineData("new source --search --language filter-value ", "language")] - [InlineData("new --language filter-value --search source", "language")] - [InlineData("new search source -lang filter-value", "language")] - [InlineData("new --search source -lang filter-value", "language")] - [InlineData("new source -lang filter-value --search", "language")] - [InlineData("new source --search -lang filter-value ", "language")] - [InlineData("new -lang filter-value --search source", "language")] - [InlineData("new search source --tag filter-value", "tag")] - [InlineData("new --search source --tag filter-value", "tag")] - [InlineData("new source --tag filter-value --search", "tag")] - [InlineData("new source --search --tag filter-value ", "tag")] - [InlineData("new --tag filter-value --search source", "tag")] - [InlineData("new search source --type filter-value", "type")] - [InlineData("new --search source --type filter-value", "type")] - [InlineData("new source --type filter-value --search", "type")] - [InlineData("new source --search --type filter-value ", "type")] - [InlineData("new --type filter-value --search source", "type")] - [InlineData("new search source --baseline filter-value", "baseline")] - [InlineData("new --search source --baseline filter-value", "baseline")] - [InlineData("new source --baseline filter-value --search", "baseline")] - [InlineData("new source --search --baseline filter-value ", "baseline")] - [InlineData("new --baseline filter-value --search source", "baseline")] + [TestMethod] + [DataRow("new search source --author filter-value", "author")] + [DataRow("new --search source --author filter-value", "author")] + [DataRow("new source --author filter-value --search", "author")] + [DataRow("new source --search --author filter-value ", "author")] + [DataRow("new --author filter-value --search source", "author")] + [DataRow("new search source --package filter-value", "package")] + [DataRow("new --search source --package filter-value", "package")] + [DataRow("new source --package filter-value --search", "package")] + [DataRow("new source --search --package filter-value ", "package")] + [DataRow("new --package filter-value --search source", "package")] + [DataRow("new search source --language filter-value", "language")] + [DataRow("new --search source --language filter-value", "language")] + [DataRow("new source --language filter-value --search", "language")] + [DataRow("new source --search --language filter-value ", "language")] + [DataRow("new --language filter-value --search source", "language")] + [DataRow("new search source -lang filter-value", "language")] + [DataRow("new --search source -lang filter-value", "language")] + [DataRow("new source -lang filter-value --search", "language")] + [DataRow("new source --search -lang filter-value ", "language")] + [DataRow("new -lang filter-value --search source", "language")] + [DataRow("new search source --tag filter-value", "tag")] + [DataRow("new --search source --tag filter-value", "tag")] + [DataRow("new source --tag filter-value --search", "tag")] + [DataRow("new source --search --tag filter-value ", "tag")] + [DataRow("new --tag filter-value --search source", "tag")] + [DataRow("new search source --type filter-value", "type")] + [DataRow("new --search source --type filter-value", "type")] + [DataRow("new source --type filter-value --search", "type")] + [DataRow("new source --search --type filter-value ", "type")] + [DataRow("new --type filter-value --search source", "type")] + [DataRow("new search source --baseline filter-value", "baseline")] + [DataRow("new --search source --baseline filter-value", "baseline")] + [DataRow("new source --baseline filter-value --search", "baseline")] + [DataRow("new source --search --baseline filter-value ", "baseline")] + [DataRow("new --baseline filter-value --search source", "baseline")] public void Search_CanParseFilterOption(string command, string expectedFilter) { FilterOptionDefinition expectedDef = _stringToFilterDefMap[expectedFilter]; @@ -65,30 +66,30 @@ public void Search_CanParseFilterOption(string command, string expectedFilter) ParseResult parseResult = myCommand.Parse(command); SearchCommandArgs args = new((BaseSearchCommand)parseResult.CommandResult.Command, parseResult); - Assert.Single(args.AppliedFilters); + Assert.HasCount(1, args.AppliedFilters); Assert.Contains("filter-value", args.GetFilterValue(expectedDef)); - Assert.Equal("source", args.SearchNameCriteria); + Assert.AreEqual("source", args.SearchNameCriteria); } - [Theory] - [InlineData("new search --author filter-value", "author")] - [InlineData("new --search --author filter-value", "author")] - [InlineData("new --author filter-value --search", "author")] - [InlineData("new search --package filter-value", "package")] - [InlineData("new --search --package filter-value", "package")] - [InlineData("new --package filter-value --search", "package")] - [InlineData("new search --language filter-value", "language")] - [InlineData("new --search --language filter-value", "language")] - [InlineData("new --language filter-value --search", "language")] - [InlineData("new search --tag filter-value", "tag")] - [InlineData("new --search --tag filter-value", "tag")] - [InlineData("new --tag filter-value --search", "tag")] - [InlineData("new search --type filter-value", "type")] - [InlineData("new --search --type filter-value", "type")] - [InlineData("new --type filter-value --search", "type")] - [InlineData("new search --baseline filter-value", "baseline")] - [InlineData("new --search --baseline filter-value", "baseline")] - [InlineData("new --baseline filter-value --search", "baseline")] + [TestMethod] + [DataRow("new search --author filter-value", "author")] + [DataRow("new --search --author filter-value", "author")] + [DataRow("new --author filter-value --search", "author")] + [DataRow("new search --package filter-value", "package")] + [DataRow("new --search --package filter-value", "package")] + [DataRow("new --package filter-value --search", "package")] + [DataRow("new search --language filter-value", "language")] + [DataRow("new --search --language filter-value", "language")] + [DataRow("new --language filter-value --search", "language")] + [DataRow("new search --tag filter-value", "tag")] + [DataRow("new --search --tag filter-value", "tag")] + [DataRow("new --tag filter-value --search", "tag")] + [DataRow("new search --type filter-value", "type")] + [DataRow("new --search --type filter-value", "type")] + [DataRow("new --type filter-value --search", "type")] + [DataRow("new search --baseline filter-value", "baseline")] + [DataRow("new --search --baseline filter-value", "baseline")] + [DataRow("new --baseline filter-value --search", "baseline")] public void Search_CanParseFilterOptionWithoutMainCriteria(string command, string expectedFilter) { FilterOptionDefinition expectedDef = _stringToFilterDefMap[expectedFilter]; @@ -99,14 +100,14 @@ public void Search_CanParseFilterOptionWithoutMainCriteria(string command, strin ParseResult parseResult = myCommand.Parse(command); SearchCommandArgs args = new((BaseSearchCommand)parseResult.CommandResult.Command, parseResult); - Assert.Single(args.AppliedFilters); + Assert.HasCount(1, args.AppliedFilters); Assert.Contains("filter-value", args.GetFilterValue(expectedDef)); - Assert.Null(args.SearchNameCriteria); + Assert.IsNull(args.SearchNameCriteria); } - [Theory] - [InlineData("new --search cr1 cr2")] - [InlineData("new search cr1 cr2")] + [TestMethod] + [DataRow("new --search cr1 cr2")] + [DataRow("new search cr1 cr2")] public void Search_CannotParseMultipleArgs(string command) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -114,28 +115,28 @@ public void Search_CannotParseMultipleArgs(string command) ParseResult parseResult = myCommand.Parse(command); - Assert.NotEmpty(parseResult.Errors); - Assert.Equal("Unrecognized command or argument 'cr2'.", parseResult.Errors[0].Message); + Assert.IsTrue(parseResult.Errors.Any()); + Assert.AreEqual("Unrecognized command or argument 'cr2'.", parseResult.Errors[0].Message); } - [Fact] + [TestMethod] public void Search_CannotParseArgsAtNewLevel() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); var myCommand = CliTestHostFactory.CreateNewCommand(host); ParseResult parseResult = myCommand.Parse("new smth search"); - Assert.NotEmpty(parseResult.Errors); - Assert.Equal("Unrecognized command or argument(s): 'smth'.", parseResult.Errors[0].Message); + Assert.IsTrue(parseResult.Errors.Any()); + Assert.AreEqual("Unrecognized command or argument(s): 'smth'.", parseResult.Errors[0].Message); } - [Theory] - [InlineData("new --author filter-value search source", "--author")] - [InlineData("new --package filter-value search source", "--package")] - [InlineData("new --type filter-value search source", "--type")] - [InlineData("new --tag filter-value search source", "--tag")] - [InlineData("new --language filter-value search source", "--language")] - [InlineData("new -lang filter-value search source", "-lang")] + [TestMethod] + [DataRow("new --author filter-value search source", "--author")] + [DataRow("new --package filter-value search source", "--package")] + [DataRow("new --type filter-value search source", "--type")] + [DataRow("new --tag filter-value search source", "--tag")] + [DataRow("new --language filter-value search source", "--language")] + [DataRow("new -lang filter-value search source", "-lang")] public void Search_CannotParseOptionsAtNewLevel(string command, string expectedFilter) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -143,11 +144,11 @@ public void Search_CannotParseOptionsAtNewLevel(string command, string expectedF ParseResult parseResult = myCommand.Parse(command); - Assert.NotEmpty(parseResult.Errors); - Assert.Equal($"Unrecognized command or argument(s): '{expectedFilter}','filter-value'.", parseResult.Errors[0].Message); + Assert.IsTrue(parseResult.Errors.Any()); + Assert.AreEqual($"Unrecognized command or argument(s): '{expectedFilter}','filter-value'.", parseResult.Errors[0].Message); } - [Fact] + [TestMethod] public void Search_Legacy_CannotParseArgsAtBothLevels() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -155,15 +156,15 @@ public void Search_Legacy_CannotParseArgsAtBothLevels() ParseResult parseResult = myCommand.Parse("new smth --search smth-else"); - Assert.NotEmpty(parseResult.Errors); - Assert.Equal("Unrecognized command or argument(s): 'smth'.", parseResult.Errors[0].Message); + Assert.IsTrue(parseResult.Errors.Any()); + Assert.AreEqual("Unrecognized command or argument(s): 'smth'.", parseResult.Errors[0].Message); } - [Theory] - [InlineData("new --interactive search source", "'--interactive'")] - [InlineData("new --interactive --search source", "'--interactive'")] - [InlineData("new foo bar --search source", "'foo'|'bar'")] - [InlineData("new foo bar search source", "'foo'|'bar'")] + [TestMethod] + [DataRow("new --interactive search source", "'--interactive'")] + [DataRow("new --interactive --search source", "'--interactive'")] + [DataRow("new foo bar --search source", "'foo'|'bar'")] + [DataRow("new foo bar search source", "'foo'|'bar'")] public void Search_HandleParseErrors(string command, string expectedInvalidTokens) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -174,18 +175,18 @@ public void Search_HandleParseErrors(string command, string expectedInvalidToken string[] expectedInvalidTokenSets = expectedInvalidTokens.Split("|"); - Assert.NotEmpty(parseResult.Errors); - Assert.Equal(expectedInvalidTokenSets.Length, parseResult.Errors.Count); + Assert.IsTrue(parseResult.Errors.Any()); + Assert.AreEqual(expectedInvalidTokenSets.Length, parseResult.Errors.Count); foreach (string tokenSet in expectedInvalidTokenSets) { - Assert.True(errorMessages.Contains($"Unrecognized command or argument(s): {tokenSet}.") || errorMessages.Contains($"Unrecognized command or argument {tokenSet}.")); + Assert.IsTrue(errorMessages.Contains($"Unrecognized command or argument(s): {tokenSet}.") || errorMessages.Contains($"Unrecognized command or argument {tokenSet}.")); } } - [Theory] - [InlineData("new --search --columns-all")] - [InlineData("new --columns-all --search")] - [InlineData("new search --columns-all")] + [TestMethod] + [DataRow("new --search --columns-all")] + [DataRow("new --columns-all --search")] + [DataRow("new search --columns-all")] public void Search_CanParseColumnsAll(string command) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -195,17 +196,17 @@ public void Search_CanParseColumnsAll(string command) SearchCommandArgs args = new((BaseSearchCommand)parseResult.CommandResult.Command, parseResult); - Assert.True(args.DisplayAllColumns); + Assert.IsTrue(args.DisplayAllColumns); } - [Theory] + [TestMethod] //https://github.com/dotnet/command-line-api/issues/1503 - [InlineData("new search --columns author type", new[] { "author", "type" })] - [InlineData("new search --columns author --columns type", new[] { "author", "type" })] - //[InlineData("new search --columns author,type", new[] { "author", "type" })] - //[InlineData("new search --columns author, type --columns tag", new[] { "author", "type", "tag" })] - [InlineData("new --search --columns author --columns type", new[] { "author", "type" })] - //[InlineData("new --search --columns author,type", new[] { "author", "type" })] + [DataRow("new search --columns author type", new[] { "author", "type" })] + [DataRow("new search --columns author --columns type", new[] { "author", "type" })] + //[DataRow("new search --columns author,type", new[] { "author", "type" })] + //[DataRow("new search --columns author, type --columns tag", new[] { "author", "type", "tag" })] + [DataRow("new --search --columns author --columns type", new[] { "author", "type" })] + //[DataRow("new --search --columns author,type", new[] { "author", "type" })] public void Search_CanParseColumns(string command, string[] expectedColumns) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -215,19 +216,19 @@ public void Search_CanParseColumns(string command, string[] expectedColumns) SearchCommandArgs args = new((BaseSearchCommand)parseResult.CommandResult.Command, parseResult); - Assert.NotNull(args.ColumnsToDisplay); - Assert.False(args.DisplayAllColumns); - Assert.NotEmpty(args.ColumnsToDisplay); - Assert.Equal(expectedColumns.Length, args.ColumnsToDisplay.Count); + Assert.IsNotNull(args.ColumnsToDisplay); + Assert.IsFalse(args.DisplayAllColumns); + Assert.IsTrue(args.ColumnsToDisplay.Any()); + Assert.AreEqual(expectedColumns.Length, args.ColumnsToDisplay.Count); foreach (string column in expectedColumns) { Assert.Contains(column, args.ColumnsToDisplay!); } } - [Theory] - [InlineData("new --search --columns c1 --columns c2")] - [InlineData("new search --columns c1 c2")] + [TestMethod] + [DataRow("new --search --columns c1 --columns c2")] + [DataRow("new search --columns c1 c2")] public void Search_CannotParseUnknownColumns(string command) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -235,11 +236,11 @@ public void Search_CannotParseUnknownColumns(string command) ParseResult parseResult = myCommand.Parse(command); - Assert.NotEmpty(parseResult.Errors); + Assert.IsTrue(parseResult.Errors.Any()); Assert.Contains("Argument 'c1' not recognized. Must be one of:", parseResult.Errors[0].Message); } - [Fact] + [TestMethod] public void CommandExampleCanShowParentCommandsBeyondNew() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -250,10 +251,10 @@ public void CommandExampleCanShowParentCommandsBeyondNew() }; ParseResult parseResult = rootCommand.Parse("dotnet new search template"); - Assert.Equal("dotnet new search my-template", Example.For(parseResult).WithSubcommand().WithArguments("my-template")); + Assert.AreEqual("dotnet new search my-template", Example.For(parseResult).WithSubcommand().WithArguments("my-template")); } - [Fact] + [TestMethod] public void CommandExampleShowsMandatoryArg() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -264,10 +265,10 @@ public void CommandExampleShowsMandatoryArg() }; ParseResult parseResult = rootCommand.Parse("dotnet new search template"); - Assert.Equal("dotnet new search []", Example.For(parseResult).WithSubcommand().WithArgument(c => c.Definition.NameArgument)); + Assert.AreEqual("dotnet new search []", Example.For(parseResult).WithSubcommand().WithArgument(c => c.Definition.NameArgument)); } - [Fact] + [TestMethod] public void CommandExampleShowsOptionalArgWhenOptionsAreGiven() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -278,7 +279,7 @@ public void CommandExampleShowsOptionalArgWhenOptionsAreGiven() }; ParseResult parseResult = rootCommand.Parse("dotnet new search template"); - Assert.Equal("dotnet new search [] --author Microsoft", + Assert.AreEqual("dotnet new search [] --author Microsoft", Example.For(parseResult) .WithSubcommand() .WithArgument(c => c.Definition.NameArgument) diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/TabCompletionTests.Approval.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/TabCompletionTests.Approval.cs index 065096acb1cb..268b19962387 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/TabCompletionTests.Approval.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/TabCompletionTests.Approval.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.CommandLine; @@ -9,7 +9,7 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests.ParserTests { public partial class TabCompletionTests : BaseTest { - [Fact] + [TestMethod] public Task RootCommand_GetAllSuggestions() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -21,7 +21,7 @@ public Task RootCommand_GetAllSuggestions() return Verify(result); } - [Fact] + [TestMethod] public Task RootCommand_GetStartsWtihSuggestions() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -33,7 +33,7 @@ public Task RootCommand_GetStartsWtihSuggestions() return Verify(result); } - [Fact] + [TestMethod] public Task Install_GetAllSuggestions() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -45,7 +45,7 @@ public Task Install_GetAllSuggestions() return Verify(result); } - [Fact] + [TestMethod] public Task Uninstall_GetAllSuggestions() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -57,7 +57,7 @@ public Task Uninstall_GetAllSuggestions() return Verify(result); } - [Fact] + [TestMethod] public Task Update_GetAllSuggestions() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -69,7 +69,7 @@ public Task Update_GetAllSuggestions() return Verify(result); } - [Fact] + [TestMethod] public Task List_GetAllSuggestions() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -81,7 +81,7 @@ public Task List_GetAllSuggestions() return Verify(result); } - [Fact] + [TestMethod] public Task Search_GetAllSuggestions() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -93,7 +93,7 @@ public Task Search_GetAllSuggestions() return Verify(result); } - [Fact] + [TestMethod] public Task Create_GetAllSuggestions() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -105,7 +105,7 @@ public Task Create_GetAllSuggestions() return Verify(result); } - [Fact] + [TestMethod] public Task TemplateCommand_GetAllSuggestions() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -117,7 +117,7 @@ public Task TemplateCommand_GetAllSuggestions() return Verify(result); } - [Fact] + [TestMethod] public Task DetailsCommand_GetAllSuggestions() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/TabCompletionTests.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/TabCompletionTests.cs index 744c9ebb90a8..7ade45535b54 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/TabCompletionTests.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/TabCompletionTests.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.CommandLine; @@ -14,9 +14,10 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests.ParserTests { + [TestClass] public partial class TabCompletionTests { - [Fact] + [TestMethod] public void Instantiate_CanSuggestTemplateOption_StartsWith() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -25,13 +26,14 @@ public void Instantiate_CanSuggestTemplateOption_StartsWith() ParseResult parseResult = myCommand.Parse($"new console --framework {ToolsetInfo.CurrentTargetFramework} --l"); string[] suggestions = parseResult.GetCompletions().Select(l => l.Label).ToArray(); - Assert.Equal(2, suggestions.Length); + Assert.AreEqual(2, suggestions.Length); Assert.Contains("--langVersion", suggestions); Assert.Contains("--language", suggestions); } #pragma warning disable xUnit1004 // Test methods should not be skipped - [Fact(Skip = "doesn't work at the moment; it matches with legacy --language option which cannot be completed; to discuss how to avoid that")] + [TestMethod] + [Ignore("doesn't work at the moment; it matches with legacy --language option which cannot be completed; to discuss how to avoid that")] #pragma warning restore xUnit1004 // Test methods should not be skipped public void Instantiate_CanSuggestLanguages() { @@ -41,14 +43,15 @@ public void Instantiate_CanSuggestLanguages() ParseResult parseResult = myCommand.Parse("new console --language "); string[] suggestions = parseResult.GetCompletions().Select(l => l.Label).ToArray(); - Assert.Equal(3, suggestions.Length); + Assert.AreEqual(3, suggestions.Length); Assert.Contains("C#", suggestions); Assert.Contains("F#", suggestions); Assert.Contains("VB", suggestions); } #pragma warning disable xUnit1004 // Test methods should not be skipped - [Fact(Skip = "not valid behavior for parser, should suggest --nuget-source")] + [TestMethod] + [Ignore("not valid behavior for parser, should suggest --nuget-source")] #pragma warning restore xUnit1004 // Test methods should not be skipped public void Install_GetSuggestionsAfterInteractive() { @@ -58,11 +61,11 @@ public void Install_GetSuggestionsAfterInteractive() ParseResult parseResult = myCommand.Parse("new install --interactive "); string[] result = parseResult.GetCompletions().Select(l => l.Label).ToArray(); - Assert.Equal(2, result.Length); + Assert.AreEqual(2, result.Length); Assert.Contains("--nuget-source", result); } - [Fact] + [TestMethod] public void Install_GetSuggestionsAfterOptionWithoutArg() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -71,11 +74,12 @@ public void Install_GetSuggestionsAfterOptionWithoutArg() ParseResult parseResult = myCommand.Parse("new install --nuget-source "); CompletionItem[] result = parseResult.GetCompletions().ToArray(); - Assert.Empty(result); + Assert.IsFalse(result.Any()); } #pragma warning disable xUnit1004 // Test methods should not be skipped - [Fact(Skip = "not valid behavior for parser, should suggest --interactive")] + [TestMethod] + [Ignore("not valid behavior for parser, should suggest --interactive")] #pragma warning restore xUnit1004 // Test methods should not be skipped public void Install_GetSuggestionsAfterOptionWithArg() { @@ -85,11 +89,11 @@ public void Install_GetSuggestionsAfterOptionWithArg() ParseResult parseResult = myCommand.Parse("new install --nuget-source me"); string[] result = parseResult.GetCompletions().Select(l => l.Label).ToArray(); - Assert.Single(result); + Assert.HasCount(1, result); Assert.Contains("--interactive", result); } - [Fact] + [TestMethod] public void Instantiate_CanSuggestTemplate_StartsWith() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -98,11 +102,11 @@ public void Instantiate_CanSuggestTemplate_StartsWith() ParseResult parseResult = myCommand.Parse("new co"); string[] suggestions = parseResult.GetCompletions().Select(l => l.Label).ToArray(); - Assert.Single(suggestions); - Assert.Equal("console", suggestions.Single()); + Assert.HasCount(1, suggestions); + Assert.AreEqual("console", suggestions.Single()); } - [Fact] + [TestMethod] public void CanCompleteChoice_FromSingleTemplate() { MockTemplateInfo template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group") @@ -118,19 +122,19 @@ public void CanCompleteChoice_FromSingleTemplate() var myCommand = CliTestHostFactory.CreateNewCommand(host); ParseResult parseResult = myCommand.Parse($" new foo --testChoice "); var completionContext = parseResult.GetCompletionContext() as TextCompletionContext; - Assert.NotNull(completionContext); + Assert.IsNotNull(completionContext); InstantiateCommandArgs args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); IEnumerable result = InstantiateCommand.GetTemplateCompletions(args, templateGroups, settings, packageManager, completionContext!).Select(l => l.Label); - Assert.Equal(new[] { "val1", "val2", "val3" }, result); + Assert.AreSequenceEqual(new[] { "val1", "val2", "val3" }, result); } - [Theory] - [InlineData(" new foo --testChoice val2 --testChoice va", new[] { "val1", "val2", "val3" })] - [InlineData(" new foo --testC", new[] { "--testChoice" })] - // [InlineData(" new foo --testChoice val2 --testC", new[] { "--testChoice" }, + [TestMethod] + [DataRow(" new foo --testChoice val2 --testChoice va", new[] { "val1", "val2", "val3" })] + [DataRow(" new foo --testC", new[] { "--testChoice" })] + // [DataRow(" new foo --testChoice val2 --testC", new[] { "--testChoice" }, // Skip = "Multiple arity option completion does not work. https://github.com/dotnet/command-line-api/issues/1727")] public void CanCompleteChoice_MultichoiceTabCompletion(string command, string[] suggestions) { @@ -147,16 +151,16 @@ public void CanCompleteChoice_MultichoiceTabCompletion(string command, string[] var myCommand = CliTestHostFactory.CreateNewCommand(host); ParseResult parseResult = myCommand.Parse(command); var completionContext = parseResult.GetCompletionContext() as TextCompletionContext; - Assert.NotNull(completionContext); + Assert.IsNotNull(completionContext); InstantiateCommandArgs args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); IEnumerable result = InstantiateCommand.GetTemplateCompletions(args, templateGroups, settings, packageManager, completionContext!).Select(l => l.Label); - Assert.Equal(suggestions, result); + Assert.AreSequenceEqual(suggestions, result); } - [Fact] + [TestMethod] public void CanCompleteChoice_FromSingleTemplate_StartsWith() { MockTemplateInfo template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group") @@ -172,15 +176,15 @@ public void CanCompleteChoice_FromSingleTemplate_StartsWith() var myCommand = CliTestHostFactory.CreateNewCommand(host); ParseResult parseResult = myCommand.Parse($" new foo --testChoice v"); var completionContext = parseResult.GetCompletionContext() as TextCompletionContext; - Assert.NotNull(completionContext); + Assert.IsNotNull(completionContext); InstantiateCommandArgs args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); IEnumerable result = InstantiateCommand.GetTemplateCompletions(args, templateGroups, settings, packageManager, completionContext!).Select(l => l.Label); - Assert.Equal(new[] { "val1", "val2" }, result); + Assert.AreSequenceEqual(new[] { "val1", "val2" }, result); } - [Fact] + [TestMethod] public void CanCompleteChoice_FromSingleTemplate_InTheMiddle() { MockTemplateInfo template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group") @@ -197,15 +201,15 @@ public void CanCompleteChoice_FromSingleTemplate_InTheMiddle() ParseResult parseResult = myCommand.Parse($" new foo --testChoice v --name test"); InstantiateCommandArgs args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); var completionContext = parseResult.GetCompletionContext() as TextCompletionContext; - Assert.NotNull(completionContext); + Assert.IsNotNull(completionContext); completionContext = completionContext!.AtCursorPosition(23); IEnumerable result = InstantiateCommand.GetTemplateCompletions(args, templateGroups, settings, packageManager, completionContext!).Select(l => l.Label); - Assert.Equal(new[] { "val1", "val2" }, result); + Assert.AreSequenceEqual(new[] { "val1", "val2" }, result); } - [Fact] + [TestMethod] public void CanCompleteChoice_FromMultipleTemplates() { MockTemplateInfo template1 = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group") @@ -225,14 +229,14 @@ public void CanCompleteChoice_FromMultipleTemplates() ParseResult parseResult = myCommand.Parse($" new foo --testChoice "); InstantiateCommandArgs args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); var completionContext = parseResult.GetCompletionContext() as TextCompletionContext; - Assert.NotNull(completionContext); + Assert.IsNotNull(completionContext); IEnumerable result = InstantiateCommand.GetTemplateCompletions(args, templateGroups, settings, packageManager, completionContext!).Select(l => l.Label); - Assert.Equal(new[] { "val1", "val2", "val3" }, result); + Assert.AreSequenceEqual(new[] { "val1", "val2", "val3" }, result); } - [Fact] + [TestMethod] public void CanCompleteChoice_FromMultipleTemplates_StartsWith() { MockTemplateInfo template1 = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group") @@ -252,14 +256,14 @@ public void CanCompleteChoice_FromMultipleTemplates_StartsWith() ParseResult parseResult = myCommand.Parse($" new foo --testChoice v"); InstantiateCommandArgs args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); var completionContext = parseResult.GetCompletionContext() as TextCompletionContext; - Assert.NotNull(completionContext); + Assert.IsNotNull(completionContext); IEnumerable result = InstantiateCommand.GetTemplateCompletions(args, templateGroups, settings, packageManager, completionContext!).Select(l => l.Label); - Assert.Equal(new[] { "val1", "val2" }, result); + Assert.AreSequenceEqual(new[] { "val1", "val2" }, result); } - [Fact] + [TestMethod] public void CanCompleteParameters_FromMultipleTemplates() { MockTemplateInfo template1 = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group") @@ -281,7 +285,7 @@ public void CanCompleteParameters_FromMultipleTemplates() ParseResult parseResult = myCommand.Parse($" new foo "); InstantiateCommandArgs args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); var completionContext = parseResult.GetCompletionContext() as TextCompletionContext; - Assert.NotNull(completionContext); + Assert.IsNotNull(completionContext); IEnumerable result = InstantiateCommand.GetTemplateCompletions(args, templateGroups, settings, packageManager, completionContext!).Select(l => l.Label); @@ -300,7 +304,7 @@ public void CanCompleteParameters_FromMultipleTemplates() Assert.DoesNotContain("--baseline", result); } - [Fact] + [TestMethod] public void CanCompleteParameters_StartsWith_FromMultipleTemplates() { MockTemplateInfo template1 = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group") @@ -322,7 +326,7 @@ public void CanCompleteParameters_StartsWith_FromMultipleTemplates() ParseResult parseResult = myCommand.Parse($" new foo --t"); InstantiateCommandArgs args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); var completionContext = parseResult.GetCompletionContext() as TextCompletionContext; - Assert.NotNull(completionContext); + Assert.IsNotNull(completionContext); IEnumerable result = InstantiateCommand.GetTemplateCompletions(args, templateGroups, settings, packageManager, completionContext!).Select(l => l.Label); @@ -342,7 +346,8 @@ public void CanCompleteParameters_StartsWith_FromMultipleTemplates() } #pragma warning disable xUnit1004 // Test methods should not be skipped - [Fact(Skip = "https://github.com/dotnet/templating/issues/4387")] + [TestMethod] + [Ignore("https://github.com/dotnet/templating/issues/4387")] #pragma warning restore xUnit1004 // Test methods should not be skipped public void CanCompleteParameters_StartsWith_AfterOption() { @@ -365,7 +370,7 @@ public void CanCompleteParameters_StartsWith_AfterOption() ParseResult parseResult = myCommand.Parse($" new foo --foo val1 --bar val2 --t"); InstantiateCommandArgs args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); var completionContext = parseResult.GetCompletionContext() as TextCompletionContext; - Assert.NotNull(completionContext); + Assert.IsNotNull(completionContext); IEnumerable result = InstantiateCommand.GetTemplateCompletions(args, templateGroups, settings, packageManager, completionContext!).Select(l => l.Label); @@ -384,9 +389,9 @@ public void CanCompleteParameters_StartsWith_AfterOption() Assert.DoesNotContain("--baseline", result); } - [Theory] - [InlineData("-lang")] - [InlineData("--language")] + [TestMethod] + [DataRow("-lang")] + [DataRow("--language")] public void CanCompleteLanguages(string optionName) { MockTemplateInfo template1 = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group") @@ -406,14 +411,14 @@ public void CanCompleteLanguages(string optionName) ParseResult parseResult = myCommand.Parse($" new foo {optionName} "); InstantiateCommandArgs args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); var completionContext = parseResult.GetCompletionContext() as TextCompletionContext; - Assert.NotNull(completionContext); + Assert.IsNotNull(completionContext); IEnumerable result = InstantiateCommand.GetTemplateCompletions(args, templateGroups, settings, packageManager, completionContext!).Select(l => l.Label); - Assert.Equal(new[] { "C#", "F#" }, result); + Assert.AreSequenceEqual(new[] { "C#", "F#" }, result); } - [Fact] + [TestMethod] public void CanCompleteTypes() { MockTemplateInfo template1 = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group") @@ -433,17 +438,21 @@ public void CanCompleteTypes() ParseResult parseResult = myCommand.Parse($" new foo --type "); InstantiateCommandArgs args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); var completionContext = parseResult.GetCompletionContext() as TextCompletionContext; - Assert.NotNull(completionContext); + Assert.IsNotNull(completionContext); IEnumerable result = InstantiateCommand.GetTemplateCompletions(args, templateGroups, settings, packageManager, completionContext!).Select(l => l.Label); - Assert.Equal(new[] { "project", "solution" }, result); + Assert.AreSequenceEqual(new[] { "project", "solution" }, result); } - [Fact] - [SkipOnPlatform(TestPlatforms.Linux, "https://github.com/dotnet/sdk/issues/46212")] + [TestMethod] public void CanIgnoreTemplateGroupsWithConstraints() { + if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Linux)) + { + Assert.Inconclusive("Skipped on Linux: https://github.com/dotnet/sdk/issues/46212"); + } + MockTemplateInfo template1 = new MockTemplateInfo("foo1", identity: "foo.1") .WithConstraints(new TemplateConstraintInfo("test", "yes")); @@ -464,14 +473,14 @@ public void CanIgnoreTemplateGroupsWithConstraints() ParseResult parseResult = myCommand.Parse($" new fo"); InstantiateCommandArgs args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); var completionContext = parseResult.GetCompletionContext() as TextCompletionContext; - Assert.NotNull(completionContext); + Assert.IsNotNull(completionContext); IEnumerable result = InstantiateCommand.GetTemplateNameCompletions(args.ShortName, templateGroups, settings).Select(l => l.Label); - Assert.Equal(new[] { "foo1" }, result); + Assert.AreSequenceEqual(new[] { "foo1" }, result); } - [Fact] + [TestMethod] public void CanIgnoreTemplateGroupsWithConstraints_IgnoresLongEvaluationTemplateGroups() { MockTemplateInfo template1 = new MockTemplateInfo("foo1", identity: "foo.1") @@ -494,14 +503,14 @@ public void CanIgnoreTemplateGroupsWithConstraints_IgnoresLongEvaluationTemplate ParseResult parseResult = myCommand.Parse($" new fo"); InstantiateCommandArgs args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); var completionContext = parseResult.GetCompletionContext() as TextCompletionContext; - Assert.NotNull(completionContext); + Assert.IsNotNull(completionContext); IEnumerable result = InstantiateCommand.GetTemplateNameCompletions(args.ShortName, templateGroups, settings).Select(l => l.Label); - Assert.Empty(result); + Assert.IsFalse(result.Any()); } - [Fact] + [TestMethod] public void CanIgnoreTemplatesInGroupWithConstraints() { MockTemplateInfo template1 = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "group") @@ -527,7 +536,7 @@ public void CanIgnoreTemplatesInGroupWithConstraints() ParseResult parseResult = myCommand.Parse($" new foo "); InstantiateCommandArgs args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); var completionContext = parseResult.GetCompletionContext() as TextCompletionContext; - Assert.NotNull(completionContext); + Assert.IsNotNull(completionContext); IEnumerable result = InstantiateCommand.GetTemplateCompletions(args, templateGroups, settings, packageManager, completionContext!).Select(l => l.Label); @@ -536,7 +545,7 @@ public void CanIgnoreTemplatesInGroupWithConstraints() Assert.DoesNotContain("--c", result); } - [Fact] + [TestMethod] public void IncludesTemplatesInGroupWithLongEvaluatedConstraints() { MockTemplateInfo template1 = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "group") @@ -562,7 +571,7 @@ public void IncludesTemplatesInGroupWithLongEvaluatedConstraints() ParseResult parseResult = myCommand.Parse($" new foo "); InstantiateCommandArgs args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); var completionContext = parseResult.GetCompletionContext() as TextCompletionContext; - Assert.NotNull(completionContext); + Assert.IsNotNull(completionContext); IEnumerable result = InstantiateCommand.GetTemplateCompletions(args, templateGroups, settings, packageManager, completionContext!).Select(l => l.Label); @@ -571,7 +580,7 @@ public void IncludesTemplatesInGroupWithLongEvaluatedConstraints() Assert.Contains("--c", result); } - [Fact] + [TestMethod] public void WillNotEvaluateConstraints_WhenAtLeastOneTemplateInGroupDoesNotHaveConstraints() { MockTemplateInfo template1 = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "group") @@ -596,11 +605,11 @@ public void WillNotEvaluateConstraints_WhenAtLeastOneTemplateInGroupDoesNotHaveC ParseResult parseResult = myCommand.Parse($" new fo"); InstantiateCommandArgs args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); var completionContext = parseResult.GetCompletionContext() as TextCompletionContext; - Assert.NotNull(completionContext); + Assert.IsNotNull(completionContext); IEnumerable result = InstantiateCommand.GetTemplateNameCompletions(args.ShortName, templateGroups, settings).Select(l => l.Label); - Assert.Equal(new[] { "foo" }, result); + Assert.AreSequenceEqual(new[] { "foo" }, result); } } } diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/TemplateCommandTests.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/TemplateCommandTests.cs index 328eefd374f5..e197233d52dc 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/TemplateCommandTests.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/TemplateCommandTests.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.CommandLine; @@ -13,9 +13,12 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests.ParserTests { - public class TemplateCommandTests + [TestClass] + public class TemplateCommandTests : VerifyBase { - [Fact] + public new TestContext TestContext { get; set; } = null!; + + [TestMethod] public Task CannotCreateCommandForInvalidParameter() { MockTemplateInfo template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group") @@ -53,8 +56,8 @@ public Task CannotCreateCommandForInvalidParameter() } catch (InvalidTemplateParametersException e) { - Assert.Equal(2, e.ParameterErrors.Count); - Assert.Equal(templateGroup.Templates.Single(), e.Template); + Assert.AreEqual(2, e.ParameterErrors.Count); + Assert.AreEqual(templateGroup.Templates.Single(), e.Template); return Verify(e.Message); } @@ -64,7 +67,7 @@ public Task CannotCreateCommandForInvalidParameter() } - [Fact] + [TestMethod] public async Task Constraints_WhenTheTemplateIsAllowed() { MockTemplateInfo template = new MockTemplateInfo(shortName: "test", identity: "testId1").WithConstraints(new TemplateConstraintInfo("test", "yes")); @@ -74,10 +77,10 @@ public async Task Constraints_WhenTheTemplateIsAllowed() var templateConstraintManager = new TemplateConstraintManager(settings); - Assert.Empty(await TemplateCommand.ValidateConstraintsAsync(templateConstraintManager, template, TestContext.Current.CancellationToken)); + Assert.IsFalse((await TemplateCommand.ValidateConstraintsAsync(templateConstraintManager, template, TestContext.CancellationTokenSource.Token)).Any()); } - [Fact] + [TestMethod] public async Task Constraints_WhenTheTemplateIsRestricted() { MockTemplateInfo template = new MockTemplateInfo(shortName: "test").WithConstraints(new TemplateConstraintInfo("test", "no")); @@ -87,10 +90,10 @@ public async Task Constraints_WhenTheTemplateIsRestricted() var templateConstraintManager = new TemplateConstraintManager(settings); - Assert.NotEmpty(await TemplateCommand.ValidateConstraintsAsync(templateConstraintManager, template, TestContext.Current.CancellationToken)); + Assert.IsTrue((await TemplateCommand.ValidateConstraintsAsync(templateConstraintManager, template, TestContext.CancellationTokenSource.Token)).Any()); } - [Fact] + [TestMethod] public async Task Constraints_WhenTheConstraintCannotBeEvaluated() { MockTemplateInfo template = new MockTemplateInfo(shortName: "test").WithConstraints(new TemplateConstraintInfo("test", "bad-arg")); @@ -99,7 +102,7 @@ public async Task Constraints_WhenTheConstraintCannotBeEvaluated() var templateConstraintManager = new TemplateConstraintManager(settings); - Assert.NotEmpty(await TemplateCommand.ValidateConstraintsAsync(templateConstraintManager, template, TestContext.Current.CancellationToken)); + Assert.IsTrue((await TemplateCommand.ValidateConstraintsAsync(templateConstraintManager, template, TestContext.CancellationTokenSource.Token)).Any()); } } diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/UninstallTests.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/UninstallTests.cs index ee99a381db02..c1bb1579ffb2 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/UninstallTests.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/UninstallTests.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.CommandLine; @@ -7,12 +7,13 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests.ParserTests { + [TestClass] public class UninstallTests : BaseTest { - [Theory] - [InlineData("--uninstall")] - [InlineData("-u")] - [InlineData("uninstall")] + [TestMethod] + [DataRow("--uninstall")] + [DataRow("-u")] + [DataRow("uninstall")] public void Uninstall_NoArguments(string commandName) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -21,14 +22,14 @@ public void Uninstall_NoArguments(string commandName) ParseResult parseResult = myCommand.Parse($"new {commandName}"); UninstallCommandArgs args = new((BaseUninstallCommand)parseResult.CommandResult.Command, parseResult); - Assert.Empty(parseResult.Errors); - Assert.Empty(args.TemplatePackages); + Assert.IsFalse(parseResult.Errors.Any()); + Assert.IsFalse(args.TemplatePackages.Any()); } - [Theory] - [InlineData("--uninstall")] - [InlineData("-u")] - [InlineData("uninstall")] + [TestMethod] + [DataRow("--uninstall")] + [DataRow("-u")] + [DataRow("uninstall")] public void Uninstall_WithArgument(string commandName) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -37,15 +38,15 @@ public void Uninstall_WithArgument(string commandName) ParseResult parseResult = myCommand.Parse($"new {commandName} source"); UninstallCommandArgs args = new((BaseUninstallCommand)parseResult.CommandResult.Command, parseResult); - Assert.Empty(parseResult.Errors); - Assert.Single(args.TemplatePackages); + Assert.IsFalse(parseResult.Errors.Any()); + Assert.HasCount(1, args.TemplatePackages); Assert.Contains("source", args.TemplatePackages); } - [Theory] - [InlineData("new --uninstall source1 --uninstall source2")] - [InlineData("new --uninstall source1 -u source2")] - [InlineData("new uninstall source1 source2")] + [TestMethod] + [DataRow("new --uninstall source1 --uninstall source2")] + [DataRow("new --uninstall source1 -u source2")] + [DataRow("new uninstall source1 source2")] public void Uninstall_WithMultipleArgument(string command) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -54,19 +55,19 @@ public void Uninstall_WithMultipleArgument(string command) ParseResult parseResult = myCommand.Parse(command); UninstallCommandArgs args = new((BaseUninstallCommand)parseResult.CommandResult.Command, parseResult); - Assert.Empty(parseResult.Errors); - Assert.Equal(2, args.TemplatePackages.Count); + Assert.IsFalse(parseResult.Errors.Any()); + Assert.AreEqual(2, args.TemplatePackages.Count); Assert.Contains("source1", args.TemplatePackages); Assert.Contains("source2", args.TemplatePackages); } - [Theory] - [InlineData("new --add-source my-custom-source uninstall source", "'--add-source','my-custom-source'")] - [InlineData("new --interactive uninstall source", "'--interactive'")] - [InlineData("new --language F# --uninstall source", "'--language','F#'")] - [InlineData("new --language F# uninstall source", "'--language','F#'")] - [InlineData("new source1 source2 source3 --uninstall source", "'source1'|'source2','source3'")] - [InlineData("new source1 --uninstall source", "'source1'")] + [TestMethod] + [DataRow("new --add-source my-custom-source uninstall source", "'--add-source','my-custom-source'")] + [DataRow("new --interactive uninstall source", "'--interactive'")] + [DataRow("new --language F# --uninstall source", "'--language','F#'")] + [DataRow("new --language F# uninstall source", "'--language','F#'")] + [DataRow("new source1 source2 source3 --uninstall source", "'source1'|'source2','source3'")] + [DataRow("new source1 --uninstall source", "'source1'")] public void Uninstall_CanReturnParseError(string command, string expectedInvalidTokens) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -77,15 +78,15 @@ public void Uninstall_CanReturnParseError(string command, string expectedInvalid string[] expectedInvalidTokenSets = expectedInvalidTokens.Split("|"); - Assert.NotEmpty(parseResult.Errors); - Assert.Equal(expectedInvalidTokenSets.Length, parseResult.Errors.Count); + Assert.IsTrue(parseResult.Errors.Any()); + Assert.AreEqual(expectedInvalidTokenSets.Length, parseResult.Errors.Count); foreach (string tokenSet in expectedInvalidTokenSets) { - Assert.True(errorMessages.Contains($"Unrecognized command or argument(s): {tokenSet}.") || errorMessages.Contains($"Unrecognized command or argument {tokenSet}.")); + Assert.IsTrue(errorMessages.Contains($"Unrecognized command or argument(s): {tokenSet}.") || errorMessages.Contains($"Unrecognized command or argument {tokenSet}.")); } } - [Fact] + [TestMethod] public void CommandExampleCanShowParentCommandsBeyondNew() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -96,7 +97,7 @@ public void CommandExampleCanShowParentCommandsBeyondNew() }; ParseResult parseResult = rootCommand.Parse("dotnet new uninstall source"); - Assert.Equal("dotnet new uninstall my-source", Example.For(parseResult).WithSubcommand().WithArguments("my-source")); + Assert.AreEqual("dotnet new uninstall my-source", Example.For(parseResult).WithSubcommand().WithArguments("my-source")); } } } diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/UpdateTests.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/UpdateTests.cs index 7c0a28b24e60..c8d5ea0bb82b 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/UpdateTests.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/ParserTests/UpdateTests.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.CommandLine; @@ -7,11 +7,12 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests.ParserTests { + [TestClass] public class UpdateTests : BaseTest { - [Theory] - [InlineData("--add-source")] - [InlineData("--nuget-source")] + [TestMethod] + [DataRow("--add-source")] + [DataRow("--nuget-source")] public void Update_CanParseAddSourceOption(string optionName) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -20,15 +21,15 @@ public void Update_CanParseAddSourceOption(string optionName) ParseResult parseResult = myCommand.Parse($"new update {optionName} my-custom-source"); UpdateCommandArgs args = new(parseResult); - Assert.NotNull(args.AdditionalSources); - Assert.Single(args.AdditionalSources); + Assert.IsNotNull(args.AdditionalSources); + Assert.HasCount(1, args.AdditionalSources); Assert.Contains("my-custom-source", args.AdditionalSources); } - [Theory] - [InlineData("--update-apply")] - [InlineData("--update-check")] - [InlineData("update")] + [TestMethod] + [DataRow("--update-apply")] + [DataRow("--update-check")] + [DataRow("update")] public void Update_Error_WhenArguments(string commandName) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -36,13 +37,13 @@ public void Update_Error_WhenArguments(string commandName) ParseResult parseResult = myCommand.Parse($"new {commandName} source"); - Assert.True(parseResult.Errors.Any()); - Assert.Contains(parseResult.Errors, error => error.Message.Contains("Unrecognized command or argument 'source'")); + Assert.IsTrue(parseResult.Errors.Any()); + Assert.IsTrue(parseResult.Errors.Any(error => error.Message.Contains("Unrecognized command or argument 'source'"))); } - [Theory] - [InlineData("new update --add-source my-custom-source1 my-custom-source2")] - [InlineData("new update --check-only --add-source my-custom-source1 --add-source my-custom-source2")] + [TestMethod] + [DataRow("new update --add-source my-custom-source1 my-custom-source2")] + [DataRow("new update --check-only --add-source my-custom-source1 --add-source my-custom-source2")] public void Update_CanParseAddSourceOption_MultipleEntries(string testCase) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -50,13 +51,13 @@ public void Update_CanParseAddSourceOption_MultipleEntries(string testCase) ParseResult parseResult = myCommand.Parse(testCase); UpdateCommandArgs args = new(parseResult); - Assert.NotNull(args.AdditionalSources); - Assert.Equal(2, args.AdditionalSources.Count); + Assert.IsNotNull(args.AdditionalSources); + Assert.AreEqual(2, args.AdditionalSources.Count); Assert.Contains("my-custom-source1", args.AdditionalSources); Assert.Contains("my-custom-source2", args.AdditionalSources); } - [Fact] + [TestMethod] public void Update_CanParseInteractiveOption() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -65,17 +66,17 @@ public void Update_CanParseInteractiveOption() ParseResult parseResult = myCommand.Parse($"new update --interactive"); UpdateCommandArgs args = new(parseResult); - Assert.True(args.Interactive); + Assert.IsTrue(args.Interactive); parseResult = myCommand.Parse($"new update"); args = new UpdateCommandArgs(parseResult); - Assert.False(args.Interactive); + Assert.IsFalse(args.Interactive); } - [Theory] - [InlineData("--check-only")] - [InlineData("--dry-run")] + [TestMethod] + [DataRow("--check-only")] + [DataRow("--dry-run")] public void Update_CanParseCheckOnlyOption(string optionAlias) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -84,15 +85,15 @@ public void Update_CanParseCheckOnlyOption(string optionAlias) ParseResult parseResult = myCommand.Parse($"new update {optionAlias}"); UpdateCommandArgs args = new(parseResult); - Assert.True(args.CheckOnly); + Assert.IsTrue(args.CheckOnly); parseResult = myCommand.Parse($"new update"); args = new UpdateCommandArgs(parseResult); - Assert.False(args.CheckOnly); + Assert.IsFalse(args.CheckOnly); } - [Fact] + [TestMethod] public void Update_Legacy_CanParseCheckOnlyOption() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -101,18 +102,18 @@ public void Update_Legacy_CanParseCheckOnlyOption() ParseResult parseResult = myCommand.Parse($"new --update-check"); UpdateCommandArgs args = new(parseResult); - Assert.True(args.CheckOnly); + Assert.IsTrue(args.CheckOnly); parseResult = myCommand.Parse($"new --update-apply"); args = new UpdateCommandArgs(parseResult); - Assert.False(args.CheckOnly); + Assert.IsFalse(args.CheckOnly); } - [Theory] - [InlineData("new --update-check --add-source my-custom-source")] - [InlineData("new --update-apply --nuget-source my-custom-source")] - [InlineData("new --nuget-source my-custom-source --update-apply")] + [TestMethod] + [DataRow("new --update-check --add-source my-custom-source")] + [DataRow("new --update-apply --nuget-source my-custom-source")] + [DataRow("new --nuget-source my-custom-source --update-apply")] public void Update_Legacy_CanParseAddSourceOption(string testCase) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -121,14 +122,14 @@ public void Update_Legacy_CanParseAddSourceOption(string testCase) ParseResult parseResult = myCommand.Parse(testCase); UpdateCommandArgs args = new(parseResult); - Assert.NotNull(args.AdditionalSources); - Assert.Single(args.AdditionalSources); + Assert.IsNotNull(args.AdditionalSources); + Assert.HasCount(1, args.AdditionalSources); Assert.Contains("my-custom-source", args.AdditionalSources); } - [Theory] - [InlineData("new --update-check source --interactive")] - [InlineData("new --interactive --update-apply source")] + [TestMethod] + [DataRow("new --update-check source --interactive")] + [DataRow("new --interactive --update-apply source")] public void Update_Legacy_CanParseInteractiveOption(string testCase) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -137,13 +138,13 @@ public void Update_Legacy_CanParseInteractiveOption(string testCase) ParseResult parseResult = myCommand.Parse(testCase); UpdateCommandArgs args = new(parseResult); - Assert.True(args.Interactive); + Assert.IsTrue(args.Interactive); } - [Theory] - [InlineData("new --update-check --add-source my-custom-source1 --add-source my-custom-source2")] - [InlineData("new --add-source my-custom-source1 --add-source my-custom-source2 --update-apply source")] - [InlineData("new --add-source my-custom-source1 --update-apply --add-source my-custom-source2")] + [TestMethod] + [DataRow("new --update-check --add-source my-custom-source1 --add-source my-custom-source2")] + [DataRow("new --add-source my-custom-source1 --add-source my-custom-source2 --update-apply source")] + [DataRow("new --add-source my-custom-source1 --update-apply --add-source my-custom-source2")] public void Update_Legacy_CanParseAddSourceOption_MultipleEntries(string testCase) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -151,20 +152,20 @@ public void Update_Legacy_CanParseAddSourceOption_MultipleEntries(string testCas ParseResult parseResult = myCommand.Parse(testCase); UpdateCommandArgs args = new(parseResult); - Assert.NotNull(args.AdditionalSources); - Assert.Equal(2, args.AdditionalSources.Count); + Assert.IsNotNull(args.AdditionalSources); + Assert.AreEqual(2, args.AdditionalSources.Count); Assert.Contains("my-custom-source1", args.AdditionalSources); Assert.Contains("my-custom-source2", args.AdditionalSources); } - [Theory] - [InlineData("new --add-source my-custom-source update source", "'--add-source','my-custom-source'|'source'")] - [InlineData("new --interactive update source", "'--interactive'|'source'")] - [InlineData("new --language F# --update-check", "'--language','F#'")] - [InlineData("new --language F# --update-apply", "'--language','F#'")] - [InlineData("new --language F# update", "'--language','F#'")] - [InlineData("new source1 source2 source3 --update-apply source", "'source1'|'source'|'source2','source3'")] - [InlineData("new source1 --update-apply source", "'source1'|'source'")] + [TestMethod] + [DataRow("new --add-source my-custom-source update source", "'--add-source','my-custom-source'|'source'")] + [DataRow("new --interactive update source", "'--interactive'|'source'")] + [DataRow("new --language F# --update-check", "'--language','F#'")] + [DataRow("new --language F# --update-apply", "'--language','F#'")] + [DataRow("new --language F# update", "'--language','F#'")] + [DataRow("new source1 source2 source3 --update-apply source", "'source1'|'source'|'source2','source3'")] + [DataRow("new source1 --update-apply source", "'source1'|'source'")] public void Update_CanReturnParseError(string command, string expectedInvalidTokens) { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -175,15 +176,15 @@ public void Update_CanReturnParseError(string command, string expectedInvalidTok string[] expectedInvalidTokenSets = expectedInvalidTokens.Split("|"); - Assert.NotEmpty(parseResult.Errors); - Assert.Equal(expectedInvalidTokenSets.Length, parseResult.Errors.Count); + Assert.IsTrue(parseResult.Errors.Any()); + Assert.AreEqual(expectedInvalidTokenSets.Length, parseResult.Errors.Count); foreach (string tokenSet in expectedInvalidTokenSets) { - Assert.True(errorMessages.Contains($"Unrecognized command or argument(s): {tokenSet}.") || errorMessages.Contains($"Unrecognized command or argument {tokenSet}.")); + Assert.IsTrue(errorMessages.Contains($"Unrecognized command or argument(s): {tokenSet}.") || errorMessages.Contains($"Unrecognized command or argument {tokenSet}.")); } } - [Fact] + [TestMethod] public void CommandExampleCanShowParentCommandsBeyondNew() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(RepoTemplatePackages)); @@ -194,7 +195,7 @@ public void CommandExampleCanShowParentCommandsBeyondNew() }; ParseResult parseResult = rootCommand.Parse("dotnet new update"); - Assert.Equal("dotnet new update", Example.For(parseResult).WithSubcommand()); + Assert.AreEqual("dotnet new update", Example.For(parseResult).WithSubcommand()); } } } diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/PostActionDispatcherTests.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/PostActionDispatcherTests.cs index 9b6a640cba46..fcd26be5543c 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/PostActionDispatcherTests.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/PostActionDispatcherTests.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.CompilerServices; @@ -10,16 +10,32 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests { - public class PostActionDispatcherTests : IClassFixture + [TestClass] + public class PostActionDispatcherTests { - private readonly EnvironmentSettingsHelper _environmentSettingsHelper; + // MSTest has no IClassFixture equivalent; a lazily-initialized static helper + // mirrors the per-class lifetime that xUnit's IClassFixture provides. + private static readonly Lazy s_environmentSettingsHelper = + new(() => new EnvironmentSettingsHelper(NullMessageSink.Instance)); - public PostActionDispatcherTests(EnvironmentSettingsHelper environmentSettingsHelper) + private EnvironmentSettingsHelper _environmentSettingsHelper = null!; + + [TestInitialize] + public void TestInitialize() + { + _environmentSettingsHelper = s_environmentSettingsHelper.Value; + } + + [ClassCleanup] + public static void ClassCleanup() { - _environmentSettingsHelper = environmentSettingsHelper; + if (s_environmentSettingsHelper.IsValueCreated) + { + s_environmentSettingsHelper.Value.Dispose(); + } } - [Fact] + [TestMethod] public void CanProcessSuccessPostAction() { var engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true); @@ -41,16 +57,16 @@ public void CanProcessSuccessPostAction() () => string.Empty); var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Prompt); - Assert.Equal(PostActionExecutionStatus.Success, result); - Assert.Single(postActionProcessor.Calls); - Assert.Equal(engineEnvironmentSettings, postActionProcessor.Calls.Single().EngineEnvironmentSettings); - Assert.Equal(postAction, postActionProcessor.Calls.Single().PostAction); - Assert.Equal(creationEffects, postActionProcessor.Calls.Single().CreationEffects); - Assert.Equal(creationResult, postActionProcessor.Calls.Single().CreationResult); - Assert.Equal("TestPath", postActionProcessor.Calls.Single().OutputPath); + Assert.AreEqual(PostActionExecutionStatus.Success, result); + Assert.HasCount(1, postActionProcessor.Calls); + Assert.AreEqual(engineEnvironmentSettings, postActionProcessor.Calls.Single().EngineEnvironmentSettings); + Assert.AreEqual(postAction, postActionProcessor.Calls.Single().PostAction); + Assert.AreEqual(creationEffects, postActionProcessor.Calls.Single().CreationEffects); + Assert.AreEqual(creationResult, postActionProcessor.Calls.Single().CreationResult); + Assert.AreEqual("TestPath", postActionProcessor.Calls.Single().OutputPath); } - [Fact] + [TestMethod] public void CanDryRunSuccessPostAction() { var engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true); @@ -72,11 +88,11 @@ public void CanDryRunSuccessPostAction() () => string.Empty); var result = dispatcher.Process(templateCreationResult, isDryRun: true, AllowRunScripts.Prompt); - Assert.Equal(PostActionExecutionStatus.Success, result); - Assert.Empty(postActionProcessor.Calls); + Assert.AreEqual(PostActionExecutionStatus.Success, result); + Assert.IsFalse(postActionProcessor.Calls.Any()); } - [Fact] + [TestMethod] public void CanProcessFailedPostAction() { var engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true); @@ -98,15 +114,15 @@ public void CanProcessFailedPostAction() () => string.Empty); var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Prompt); - Assert.Equal(PostActionExecutionStatus.Failure, result); - Assert.Equal(engineEnvironmentSettings, postActionProcessor.Calls.Single().EngineEnvironmentSettings); - Assert.Equal(postAction, postActionProcessor.Calls.Single().PostAction); - Assert.Equal(creationEffects, postActionProcessor.Calls.Single().CreationEffects); - Assert.Equal(creationResult, postActionProcessor.Calls.Single().CreationResult); - Assert.Equal("TestPath", postActionProcessor.Calls.Single().OutputPath); + Assert.AreEqual(PostActionExecutionStatus.Failure, result); + Assert.AreEqual(engineEnvironmentSettings, postActionProcessor.Calls.Single().EngineEnvironmentSettings); + Assert.AreEqual(postAction, postActionProcessor.Calls.Single().PostAction); + Assert.AreEqual(creationEffects, postActionProcessor.Calls.Single().CreationEffects); + Assert.AreEqual(creationResult, postActionProcessor.Calls.Single().CreationResult); + Assert.AreEqual("TestPath", postActionProcessor.Calls.Single().OutputPath); } - [Fact] + [TestMethod] public void CanDryRunFailedPostAction() { var engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true); @@ -129,11 +145,11 @@ public void CanDryRunFailedPostAction() () => string.Empty); var result = dispatcher.Process(templateCreationResult, isDryRun: true, AllowRunScripts.Prompt); - Assert.Equal(PostActionExecutionStatus.Success, result); - Assert.Empty(postActionProcessor.Calls); + Assert.AreEqual(PostActionExecutionStatus.Success, result); + Assert.IsFalse(postActionProcessor.Calls.Any()); } - [Fact] + [TestMethod] public void CanProcessUnknownPostAction() { var engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true); @@ -159,11 +175,11 @@ public void CanProcessUnknownPostAction() () => string.Empty); var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Prompt); - Assert.Equal(PostActionExecutionStatus.Failure, result); - Assert.Empty(postActionProcessor.Calls); + Assert.AreEqual(PostActionExecutionStatus.Failure, result); + Assert.IsFalse(postActionProcessor.Calls.Any()); } - [Fact] + [TestMethod] public void CanProcessPostActionThrowingException() { var engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true); @@ -185,10 +201,10 @@ public void CanProcessPostActionThrowingException() () => string.Empty); var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Yes); - Assert.Equal(PostActionExecutionStatus.Failure, result); + Assert.AreEqual(PostActionExecutionStatus.Failure, result); } - [Fact] + [TestMethod] public void CanContinueOnErrorWhenConfigured() { var engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true); @@ -228,16 +244,16 @@ public void CanContinueOnErrorWhenConfigured() var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Yes); // in case continue on error is true, success status is returned on failure - Assert.Equal(PostActionExecutionStatus.Success, result); + Assert.AreEqual(PostActionExecutionStatus.Success, result); //2 post actions were executed - Assert.Single(trueProcessor.Calls); - Assert.Single(falseProcessor.Calls); - Assert.Equal(postAction1, falseProcessor.Calls[0].PostAction); - Assert.Equal(postAction2, trueProcessor.Calls[0].PostAction); + Assert.HasCount(1, trueProcessor.Calls); + Assert.HasCount(1, falseProcessor.Calls); + Assert.AreEqual(postAction1, falseProcessor.Calls[0].PostAction); + Assert.AreEqual(postAction2, trueProcessor.Calls[0].PostAction); } - [Fact] + [TestMethod] public void CannotContinueOnErrorWhenNotConfigured() { var engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true); @@ -274,15 +290,15 @@ public void CannotContinueOnErrorWhenNotConfigured() () => string.Empty); var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Yes); - Assert.Equal(PostActionExecutionStatus.Failure, result); + Assert.AreEqual(PostActionExecutionStatus.Failure, result); //only first post action was executed - Assert.Empty(trueProcessor.Calls); - Assert.Single(falseProcessor.Calls); - Assert.Equal(postAction1, falseProcessor.Calls[0].PostAction); + Assert.IsFalse(trueProcessor.Calls.Any()); + Assert.HasCount(1, falseProcessor.Calls); + Assert.AreEqual(postAction1, falseProcessor.Calls[0].PostAction); } - [Fact] + [TestMethod] public void CanProcessRunScriptPostAction_WhenRunScriptAllowed() { var engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true); @@ -311,10 +327,10 @@ public void CanProcessRunScriptPostAction_WhenRunScriptAllowed() var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Yes); //expect failure as post action fails - Assert.Equal(PostActionExecutionStatus.Failure, result); + Assert.AreEqual(PostActionExecutionStatus.Failure, result); } - [Fact] + [TestMethod] public void CanProcessRunScriptPostAction_WhenRunScriptNotAllowed() { var engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true); @@ -342,10 +358,10 @@ public void CanProcessRunScriptPostAction_WhenRunScriptNotAllowed() () => string.Empty); var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.No); - Assert.Equal(PostActionExecutionStatus.Cancelled, result); + Assert.AreEqual(PostActionExecutionStatus.Cancelled, result); } - [Fact] + [TestMethod] public void CanProcessRunScriptPostAction_WhenRunScriptPrompt_Yes() { var engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true); @@ -375,10 +391,10 @@ public void CanProcessRunScriptPostAction_WhenRunScriptPrompt_Yes() var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Prompt); //expect failure as post action fails - Assert.Equal(PostActionExecutionStatus.Failure, result); + Assert.AreEqual(PostActionExecutionStatus.Failure, result); } - [Fact] + [TestMethod] public void CanProcessRunScriptPostAction_WhenRunScriptPrompt_No() { var engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true); @@ -406,10 +422,10 @@ public void CanProcessRunScriptPostAction_WhenRunScriptPrompt_No() () => "N"); // the user forbids to run post action var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Prompt); - Assert.Equal(PostActionExecutionStatus.Cancelled, result); + Assert.AreEqual(PostActionExecutionStatus.Cancelled, result); } - [Fact] + [TestMethod] public void CanProcessRunScriptPostAction_DryRun() { var engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true); @@ -438,14 +454,14 @@ public void CanProcessRunScriptPostAction_DryRun() //run script setting doesn't matter for dry run var result = dispatcher.Process(templateCreationResult, isDryRun: true, AllowRunScripts.Prompt); - Assert.Equal(PostActionExecutionStatus.Success, result); + Assert.AreEqual(PostActionExecutionStatus.Success, result); result = dispatcher.Process(templateCreationResult, isDryRun: true, AllowRunScripts.Yes); - Assert.Equal(PostActionExecutionStatus.Success, result); + Assert.AreEqual(PostActionExecutionStatus.Success, result); result = dispatcher.Process(templateCreationResult, isDryRun: true, AllowRunScripts.No); - Assert.Equal(PostActionExecutionStatus.Success, result); + Assert.AreEqual(PostActionExecutionStatus.Success, result); } - [Fact] + [TestMethod] public void CanProcessRunScriptPostActionAndFailedPostAction_WhenRunScriptPrompt_No() { var engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true); @@ -483,12 +499,12 @@ public void CanProcessRunScriptPostActionAndFailedPostAction_WhenRunScriptPrompt () => "N"); // the user forbids to run post action var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Prompt); - Assert.Equal(PostActionExecutionStatus.Cancelled, result); - Assert.Single(postActionProcessor.Calls); - Assert.Equal(postAction2, postActionProcessor.Calls.Single().PostAction); + Assert.AreEqual(PostActionExecutionStatus.Cancelled, result); + Assert.HasCount(1, postActionProcessor.Calls); + Assert.AreEqual(postAction2, postActionProcessor.Calls.Single().PostAction); } - [Fact] + [TestMethod] public void CanProcessRunScriptPostActionAndSuccessPostAction_WhenRunScriptPrompt_No() { var engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true); @@ -526,10 +542,10 @@ public void CanProcessRunScriptPostActionAndSuccessPostAction_WhenRunScriptPromp () => "N"); // the user forbids to run post action var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Prompt); - Assert.Equal(PostActionExecutionStatus.Cancelled, result); - Assert.NotEqual(PostActionExecutionStatus.Failure, result); - Assert.Single(postActionProcessor.Calls); - Assert.Equal(postAction2, postActionProcessor.Calls.Single().PostAction); + Assert.AreEqual(PostActionExecutionStatus.Cancelled, result); + Assert.AreNotEqual(PostActionExecutionStatus.Failure, result); + Assert.HasCount(1, postActionProcessor.Calls); + Assert.AreEqual(postAction2, postActionProcessor.Calls.Single().PostAction); } private class CaptureMePostAction : IPostActionProcessor diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/PostActionTests/AddJsonPropertyPostActionTests.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/PostActionTests/AddJsonPropertyPostActionTests.cs index 23c68bc3ed60..d289b3b8facd 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/PostActionTests/AddJsonPropertyPostActionTests.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/PostActionTests/AddJsonPropertyPostActionTests.cs @@ -13,16 +13,34 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests.PostActionTests { - public class AddJsonPropertyPostActionTests : IClassFixture + [TestClass] + public class AddJsonPropertyPostActionTests { - private readonly IEngineEnvironmentSettings _engineEnvironmentSettings; + // MSTest has no IClassFixture equivalent; a lazily-initialized static helper + // mirrors the per-class lifetime that xUnit's IClassFixture provides. + private static readonly Lazy s_environmentSettingsHelper = + new(() => new EnvironmentSettingsHelper(NullMessageSink.Instance)); - public AddJsonPropertyPostActionTests(EnvironmentSettingsHelper environmentSettingsHelper) + private IEngineEnvironmentSettings _engineEnvironmentSettings = null!; + + [TestInitialize] + public void TestInitialize() + { + _engineEnvironmentSettings = s_environmentSettingsHelper.Value.CreateEnvironment( + hostIdentifier: GetType().Name, + virtualize: true); + } + + [ClassCleanup] + public static void ClassCleanup() { - _engineEnvironmentSettings = environmentSettingsHelper.CreateEnvironment(hostIdentifier: GetType().Name, virtualize: true); + if (s_environmentSettingsHelper.IsValueCreated) + { + s_environmentSettingsHelper.Value.Dispose(); + } } - [Fact] + [TestMethod] public void FailsWhenParentPropertyPathIsInvalid() { string targetBasePath = _engineEnvironmentSettings.GetTempVirtualizedPath(); @@ -59,11 +77,11 @@ public void FailsWhenParentPropertyPathIsInvalid() new MockCreationResult(), targetBasePath); - Assert.False(result); + Assert.IsFalse(result); mockReporter.Verify(r => r.WriteLine(string.Format(LocalizableStrings.PostAction_ModifyJson_Error_ParentPropertyPathInvalid, parentPropertyPath)), Times.Once); } - [Fact] + [TestMethod] public void FailsWhenPropertyPathCasingIsNotCorrect() { string targetBasePath = _engineEnvironmentSettings.GetTempVirtualizedPath(); @@ -93,13 +111,13 @@ public void FailsWhenPropertyPathCasingIsNotCorrect() new MockCreationResult(), targetBasePath); - Assert.False(result); + Assert.IsFalse(result); - Assert.Equal(originalJsonContent, _engineEnvironmentSettings.Host.FileSystem.ReadAllText(jsonFilePath)); + Assert.AreEqual(originalJsonContent, _engineEnvironmentSettings.Host.FileSystem.ReadAllText(jsonFilePath)); } - [Theory] - [MemberData(nameof(ModifyJsonPostActionTestCase>.InvalidConfigurationTestCases), MemberType = typeof(ModifyJsonPostActionTestCase>))] + [TestMethod] + [DynamicData(nameof(ModifyJsonPostActionTestCase>.InvalidConfigurationTestCases), typeof(ModifyJsonPostActionTestCase>))] public void FailsWhenMandatoryArgumentsNotConfigured(ModifyJsonPostActionTestCase> testCase) { string targetBasePath = _engineEnvironmentSettings.GetTempVirtualizedPath(); @@ -128,20 +146,20 @@ public void FailsWhenMandatoryArgumentsNotConfigured(ModifyJsonPostActionTestCas new MockCreationResult(), targetBasePath); - Assert.False(result); + Assert.IsFalse(result); testCase.AssertionCallback(mockReporter); } - [Theory] - [MemberData(nameof(ModifyJsonPostActionTestCase<(JsonNode, bool)>.SuccessTestCases), MemberType = typeof(ModifyJsonPostActionTestCase<(JsonNode, bool)>))] + [TestMethod] + [DynamicData(nameof(ModifyJsonPostActionTestCase<(JsonNode, bool)>.SuccessTestCases), typeof(ModifyJsonPostActionTestCase<(JsonNode, bool)>))] public void CanSuccessfullyModifyJsonFile(ModifyJsonPostActionTestCase<(JsonNode, bool)> testCase) { string targetBasePath = _engineEnvironmentSettings.GetTempVirtualizedPath(); string? jsonFileName = testCase.PostActionArgs["jsonFileName"]; - Assert.NotNull(jsonFileName); + Assert.IsNotNull(jsonFileName); string jsonFilePath = CreateJsonFile(targetBasePath, jsonFileName, testCase.OriginalJsonContent); @@ -160,17 +178,17 @@ public void CanSuccessfullyModifyJsonFile(ModifyJsonPostActionTestCase<(JsonNode new MockCreationResult(), targetBasePath); - Assert.True(result); + Assert.IsTrue(result); JsonNode? modifiedJsonContent = JsonNode.Parse(_engineEnvironmentSettings.Host.FileSystem.ReadAllText(jsonFilePath)); - Assert.NotNull(modifiedJsonContent); + Assert.IsNotNull(modifiedJsonContent); testCase.AssertionCallback((modifiedJsonContent, false)); } - [Theory] - [MemberData(nameof(ModifyJsonPostActionTestCase<(JsonNode, bool)>.SuccessTestCases), MemberType = typeof(ModifyJsonPostActionTestCase<(JsonNode, bool)>))] + [TestMethod] + [DynamicData(nameof(ModifyJsonPostActionTestCase<(JsonNode, bool)>.SuccessTestCases), typeof(ModifyJsonPostActionTestCase<(JsonNode, bool)>))] public void CanSuccessfullyCreateAndModifyJsonFileWhenAllowFileCreationAndPathCreationAreSet(ModifyJsonPostActionTestCase<(JsonNode, bool)> testCase) { string targetBasePath = _engineEnvironmentSettings.GetTempVirtualizedPath(); @@ -194,18 +212,18 @@ public void CanSuccessfullyCreateAndModifyJsonFileWhenAllowFileCreationAndPathCr new MockCreationResult(), targetBasePath); - Assert.True(result); + Assert.IsTrue(result); string jsonFilePath = Path.Combine(targetBasePath, jsonFileName); JsonNode? modifiedJsonContent = JsonNode.Parse(_engineEnvironmentSettings.Host.FileSystem.ReadAllText(jsonFilePath)); - Assert.NotNull(modifiedJsonContent); + Assert.IsNotNull(modifiedJsonContent); testCase.AssertionCallback((modifiedJsonContent, true)); } - [Theory] - [MemberData(nameof(ModifyJsonPostActionTestCase<(JsonNode, bool)>.SuccessTestCases), MemberType = typeof(ModifyJsonPostActionTestCase<(JsonNode, bool)>))] + [TestMethod] + [DynamicData(nameof(ModifyJsonPostActionTestCase<(JsonNode, bool)>.SuccessTestCases), typeof(ModifyJsonPostActionTestCase<(JsonNode, bool)>))] public void CanSuccessfullyModifyJsonFileWhenPathDoesNotExistAndAllowPathCreationIsSet(ModifyJsonPostActionTestCase<(JsonNode, bool)> testCase) { string targetBasePath = _engineEnvironmentSettings.GetTempVirtualizedPath(); @@ -231,16 +249,16 @@ public void CanSuccessfullyModifyJsonFileWhenPathDoesNotExistAndAllowPathCreatio new MockCreationResult(), targetBasePath); - Assert.True(result); + Assert.IsTrue(result); JsonNode? modifiedJsonContent = JsonNode.Parse(_engineEnvironmentSettings.Host.FileSystem.ReadAllText(jsonFilePath)); - Assert.NotNull(modifiedJsonContent); + Assert.IsNotNull(modifiedJsonContent); testCase.AssertionCallback((modifiedJsonContent, true)); } - [Fact] + [TestMethod] public void FailsWhenFileExistsButPathDoesNotExistAndAllowPathCreationIsNotSet() { string targetBasePath = _engineEnvironmentSettings.GetTempVirtualizedPath(); @@ -271,12 +289,12 @@ public void FailsWhenFileExistsButPathDoesNotExistAndAllowPathCreationIsNotSet() new MockCreationResult(), targetBasePath); - Assert.False(result); + Assert.IsFalse(result); - Assert.Equal(originalJsonContent, _engineEnvironmentSettings.Host.FileSystem.ReadAllText(jsonFilePath)); + Assert.AreEqual(originalJsonContent, _engineEnvironmentSettings.Host.FileSystem.ReadAllText(jsonFilePath)); } - [Fact] + [TestMethod] public void FailsWhenFileDoesNotExistAndAllowFileCreationIsNotSet() { string jsonFileName = Guid.NewGuid().ToString("N") + ".json"; @@ -304,13 +322,13 @@ public void FailsWhenFileDoesNotExistAndAllowFileCreationIsNotSet() new MockCreationResult(), targetBasePath); - Assert.False(result); + Assert.IsFalse(result); string jsonFilePath = Path.Combine(targetBasePath, jsonFileName); - Assert.False(_engineEnvironmentSettings.Host.FileSystem.FileExists(jsonFilePath)); + Assert.IsFalse(_engineEnvironmentSettings.Host.FileSystem.FileExists(jsonFilePath)); } - [Fact] + [TestMethod] public void FailsWhenFileDoesNotExistAndAllowFileCreationIsSetButAllowPathCreationIsNotSet() { string jsonFileName = Guid.NewGuid().ToString("N") + ".json"; @@ -339,13 +357,13 @@ public void FailsWhenFileDoesNotExistAndAllowFileCreationIsSetButAllowPathCreati new MockCreationResult(), targetBasePath); - Assert.False(result); + Assert.IsFalse(result); string jsonFilePath = Path.Combine(targetBasePath, jsonFileName); - Assert.Equal("{}", _engineEnvironmentSettings.Host.FileSystem.ReadAllText(jsonFilePath)); + Assert.AreEqual("{}", _engineEnvironmentSettings.Host.FileSystem.ReadAllText(jsonFilePath)); } - [Fact] + [TestMethod] public void RepoRootDetectionShouldPreferGlobalJson_NoSlnInvolved() { var physicalFileSystem = _engineEnvironmentSettings.Host.FileSystem; @@ -358,7 +376,7 @@ public void RepoRootDetectionShouldPreferGlobalJson_NoSlnInvolved() AddJsonPropertyPostActionProcessor.GetRootDirectory(physicalFileSystem, subDir).Should().Be(dirWithGlobalJson); } - [Fact] + [TestMethod] public void RepoRootDetectionShouldPreferGlobalJson_SlnInSubDirectory() { var physicalFileSystem = _engineEnvironmentSettings.Host.FileSystem; @@ -372,7 +390,7 @@ public void RepoRootDetectionShouldPreferGlobalJson_SlnInSubDirectory() AddJsonPropertyPostActionProcessor.GetRootDirectory(physicalFileSystem, subDir).Should().Be(dirWithGlobalJson); } - [Fact] + [TestMethod] public void RepoRootDetectionShouldPreferGlobalJson_SlnInParent() { var physicalFileSystem = _engineEnvironmentSettings.Host.FileSystem; @@ -386,7 +404,7 @@ public void RepoRootDetectionShouldPreferGlobalJson_SlnInParent() AddJsonPropertyPostActionProcessor.GetRootDirectory(physicalFileSystem, subDir).Should().Be(dirWithGlobalJson); } - [Fact] + [TestMethod] public void RepoRootDetectionShouldPreferGitDirectory_NoSlnInvolved() { var physicalFileSystem = _engineEnvironmentSettings.Host.FileSystem; @@ -399,7 +417,7 @@ public void RepoRootDetectionShouldPreferGitDirectory_NoSlnInvolved() AddJsonPropertyPostActionProcessor.GetRootDirectory(physicalFileSystem, subDir).Should().Be(dirWithGitDirectory); } - [Fact] + [TestMethod] public void RepoRootDetectionShouldPreferGitDirectory_SlnInSubDirectory() { var physicalFileSystem = _engineEnvironmentSettings.Host.FileSystem; @@ -413,7 +431,7 @@ public void RepoRootDetectionShouldPreferGitDirectory_SlnInSubDirectory() AddJsonPropertyPostActionProcessor.GetRootDirectory(physicalFileSystem, subDir).Should().Be(dirWithGitDirectory); } - [Fact] + [TestMethod] public void RepoRootDetectionShouldPreferGitDirectory_SlnInParent() { var physicalFileSystem = _engineEnvironmentSettings.Host.FileSystem; @@ -456,7 +474,7 @@ public record ModifyJsonPostActionTestCase( }, tuple => { - Assert.Equal("Watson", tuple.ResultingJson["person"]!["lastName"]!.ToString()); + Assert.AreEqual("Watson", tuple.ResultingJson["person"]!["lastName"]!.ToString()); }), new( @@ -471,7 +489,7 @@ public record ModifyJsonPostActionTestCase( }, tuple => { - Assert.Equal("street name", tuple.ResultingJson["person"]!["address"]!["street"]!.ToString()); + Assert.AreEqual("street name", tuple.ResultingJson["person"]!["address"]!["street"]!.ToString()); }), new( @@ -488,11 +506,11 @@ public record ModifyJsonPostActionTestCase( { if (tuple.IsNewJson) { - Assert.Equal(@"{""secondProperty"":""bar""}", tuple.ResultingJson.ToJsonString()); + Assert.AreEqual(@"{""secondProperty"":""bar""}", tuple.ResultingJson.ToJsonString()); } else { - Assert.Equal(@"{""firstProperty"":""foo"",""secondProperty"":""bar""}", tuple.ResultingJson.ToJsonString()); + Assert.AreEqual(@"{""firstProperty"":""foo"",""secondProperty"":""bar""}", tuple.ResultingJson.ToJsonString()); } }), @@ -510,11 +528,11 @@ public record ModifyJsonPostActionTestCase( { if (tuple.IsNewJson) { - Assert.Equal(@"{""rootProperty"":{""subProperty1"":{""subProperty2"":{""subProperty3"":{""foo"":""bar""}}}}}", tuple.ResultingJson.ToJsonString()); + Assert.AreEqual(@"{""rootProperty"":{""subProperty1"":{""subProperty2"":{""subProperty3"":{""foo"":""bar""}}}}}", tuple.ResultingJson.ToJsonString()); } else { - Assert.Equal(@"{""rootProperty"":{""subProperty1"":{""subProperty2"":{""subProperty3"":{""name"":""test"",""foo"":""bar""}}}}}", tuple.ResultingJson.ToJsonString()); + Assert.AreEqual(@"{""rootProperty"":{""subProperty1"":{""subProperty2"":{""subProperty3"":{""name"":""test"",""foo"":""bar""}}}}}", tuple.ResultingJson.ToJsonString()); } }) }; diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/TabularOutputTests.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/TabularOutputTests.cs index cd411bec698d..a3af7cf221ea 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/TabularOutputTests.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/TabularOutputTests.cs @@ -8,9 +8,10 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests { + [TestClass] public class TabularOutputTests { - [Fact] + [TestMethod] public void CanShrinkOneColumn() { TabularOutputSettings outputSettings = new( @@ -34,10 +35,10 @@ public void CanShrinkOneColumn() .DefineColumn(t => t.Item2, "Column 2"); string result = formatter.Layout(); - Assert.Equal(expectedOutput, result); + Assert.AreEqual(expectedOutput, result); } - [Fact] + [TestMethod] public void CanShrinkMultipleColumnsAndBalanceShrinking() { TabularOutputSettings outputSettings = new( @@ -61,10 +62,10 @@ public void CanShrinkMultipleColumnsAndBalanceShrinking() .DefineColumn(t => t.Item2, "Column 2", shrinkIfNeeded: true, minWidth: 2); string result = formatter.Layout(); - Assert.Equal(expectedOutput, result); + Assert.AreEqual(expectedOutput, result); } - [Fact] + [TestMethod] public void CannotShrinkOverMinimumWidth() { TabularOutputSettings outputSettings = new( @@ -88,10 +89,10 @@ public void CannotShrinkOverMinimumWidth() .DefineColumn(t => t.Item2, "Column 2", shrinkIfNeeded: true, minWidth: 8); string result = formatter.Layout(); - Assert.Equal(expectedOutput, result); + Assert.AreEqual(expectedOutput, result); } - [Fact] + [TestMethod] public void CanShowDefaultColumns() { TabularOutputSettings outputSettings = new( @@ -116,10 +117,10 @@ public void CanShowDefaultColumns() .DefineColumn(t => t.Item3, "Column 3", columnName: "column3", defaultColumn: false); string result = formatter.Layout(); - Assert.Equal(expectedOutput, result); + Assert.AreEqual(expectedOutput, result); } - [Fact] + [TestMethod] public void CanShowUserSelectedColumns() { TabularOutputSettings outputSettings = new( @@ -145,10 +146,10 @@ public void CanShowUserSelectedColumns() .DefineColumn(t => t.Item3, "Column 3", columnName: "column3", defaultColumn: false); string result = formatter.Layout(); - Assert.Equal(expectedOutput, result); + Assert.AreEqual(expectedOutput, result); } - [Fact] + [TestMethod] public void CanShowAllColumns() { TabularOutputSettings outputSettings = new(new MockEnvironment() { ConsoleBufferWidth = 10 }, displayAllColumns: true); @@ -169,10 +170,10 @@ public void CanShowAllColumns() .DefineColumn(t => t.Item3, "Column 3", columnName: "column3", defaultColumn: false); string result = formatter.Layout(); - Assert.Equal(expectedOutput, result); + Assert.AreEqual(expectedOutput, result); } - [Fact] + [TestMethod] public void CanCenterAlign() { TabularOutputSettings outputSettings = new(new MockEnvironment() { ConsoleBufferWidth = 10 }); @@ -192,10 +193,10 @@ public void CanCenterAlign() .DefineColumn(t => t.Item2, "Column 2", textAlign: TextAlign.Center); string result = formatter.Layout(); - Assert.Equal(expectedOutput, result); + Assert.AreEqual(expectedOutput, result); } - [Fact] + [TestMethod] public void CanRightAlign() { TabularOutputSettings outputSettings = new(new MockEnvironment() { ConsoleBufferWidth = 10 }); @@ -215,10 +216,10 @@ public void CanRightAlign() .DefineColumn(t => t.Item2, "Column 2", textAlign: TextAlign.Right); string result = formatter.Layout(); - Assert.Equal(expectedOutput, result); + Assert.AreEqual(expectedOutput, result); } - [Fact] + [TestMethod] public void CanCalculateWidthCorrectly() { TabularOutputSettings outputSettings = new( @@ -253,10 +254,10 @@ dotnet gitignore 文件 gitignore .DefineColumn(t => t.Item2, "短名称"); string result = formatter.Layout(); - Assert.Equal(expectedOutput, result); + Assert.AreEqual(expectedOutput, result); } - [Fact] + [TestMethod] public void CanShrinkWideCharsCorrectly() { TabularOutputSettings outputSettings = new( @@ -291,10 +292,10 @@ dotnet giti... gitignore .DefineColumn(t => t.Item2, "短名称"); string result = formatter.Layout(); - Assert.Equal(expectedOutput, result); + Assert.AreEqual(expectedOutput, result); } - [Fact] + [TestMethod] public void CanIndentAllRows() { TabularOutputSettings outputSettings = new(new MockEnvironment() { ConsoleBufferWidth = 10 }, displayAllColumns: true); @@ -315,10 +316,10 @@ public void CanIndentAllRows() .DefineColumn(t => t.Item3, "Column 3", columnName: "column3", defaultColumn: false); string result = formatter.Layout(1); - Assert.Equal(expectedOutput, result); + Assert.AreEqual(expectedOutput, result); } - [Fact] + [TestMethod] public void VerifyColumnsOptionHasAllColumnNamesDefined() { var columnOption = SharedOptionsFactory.CreateColumnsOption(); @@ -330,7 +331,7 @@ public void VerifyColumnsOptionHasAllColumnNamesDefined() //Gets constants defined in TabularOutputSettings.ColumnNams var columnNamesConstants = typeof(TabularOutputSettingsColumnNames).GetFields().Select(fi => (string?)fi.GetValue(null)).Order(); - Assert.Equal(suggestedValues, columnNamesConstants); + Assert.AreSequenceEqual(suggestedValues, columnNamesConstants); } } } diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/TelemetryHelperTests.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/TelemetryHelperTests.cs index f7f61ea14770..01c401e71ecc 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/TelemetryHelperTests.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/TelemetryHelperTests.cs @@ -9,9 +9,10 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests { + [TestClass] public class TelemetryHelperTests { - [Fact(DisplayName = nameof(NonChoiceParameterHasNullCanonicalValueTest))] + [TestMethod] public void NonChoiceParameterHasNullCanonicalValueTest() { ITemplateParameter param = new TemplateParameter("TestName", type: "parameter", datatype: "string", choices: null); @@ -25,10 +26,10 @@ public void NonChoiceParameterHasNullCanonicalValueTest() }; string? telemetryEntry = TelemetryHelper.PrepareHashedChoiceValue(templateInfo, parameterValues, "TestName"); - Assert.Null(telemetryEntry); + Assert.IsNull(telemetryEntry); } - [Fact(DisplayName = nameof(UnknownParameterNameHasNullCanonicalValueTest))] + [TestMethod] public void UnknownParameterNameHasNullCanonicalValueTest() { ITemplateParameter param = new TemplateParameter("TestName", type: "parameter", datatype: "string", choices: null); @@ -43,10 +44,10 @@ public void UnknownParameterNameHasNullCanonicalValueTest() }; string? telemetryEntry = TelemetryHelper.PrepareHashedChoiceValue(templateInfo, parameterValues, "OtherName"); - Assert.Null(telemetryEntry); + Assert.IsNull(telemetryEntry); } - [Fact(DisplayName = nameof(InvalidChoiceValueForParameterHasNullCanonicalValueTest))] + [TestMethod] public void InvalidChoiceValueForParameterHasNullCanonicalValueTest() { ITemplateParameter param = new TemplateParameter( @@ -68,10 +69,10 @@ public void InvalidChoiceValueForParameterHasNullCanonicalValueTest() }; string? telemetryEntry = TelemetryHelper.PrepareHashedChoiceValue(templateInfo, parameterValues, "TestName"); - Assert.Null(telemetryEntry); + Assert.IsNull(telemetryEntry); } - [Fact(DisplayName = nameof(ValidChoiceForParameterIsItsOwnCanonicalValueTest))] + [TestMethod] public void ValidChoiceForParameterIsItsOwnCanonicalValueTest() { ITemplateParameter param = new TemplateParameter( @@ -93,10 +94,10 @@ public void ValidChoiceForParameterIsItsOwnCanonicalValueTest() }; string? telemetryEntry = TelemetryHelper.PrepareHashedChoiceValue(templateInfo, parameterValues, "TestName"); - Assert.Equal(Sha256Hasher.HashWithNormalizedCasing("foo"), telemetryEntry); + Assert.AreEqual(Sha256Hasher.HashWithNormalizedCasing("foo"), telemetryEntry); } - [Fact] + [TestMethod] public void UniqueStartsWithValueDoesNotResolveCanonicalValueTest() { ITemplateParameter param = new TemplateParameter( @@ -117,10 +118,10 @@ public void UniqueStartsWithValueDoesNotResolveCanonicalValueTest() }; string? telemetryEntry = TelemetryHelper.PrepareHashedChoiceValue(templateInfo, parameterValues, "TestName"); - Assert.Null(telemetryEntry); + Assert.IsNull(telemetryEntry); } - [Fact(DisplayName = nameof(AmbiguousStartsWithValueHasNullCanonicalValueTest))] + [TestMethod] public void AmbiguousStartsWithValueHasNullCanonicalValueTest() { ITemplateParameter param = new TemplateParameter( @@ -143,10 +144,10 @@ public void AmbiguousStartsWithValueHasNullCanonicalValueTest() }; string? telemetryEntry = TelemetryHelper.PrepareHashedChoiceValue(templateInfo, parameterValues, "TestName"); - Assert.Null(telemetryEntry); + Assert.IsNull(telemetryEntry); } - [Fact(DisplayName = nameof(ChoiceValueCaseDifferenceIsAMatchTest))] + [TestMethod] public void ChoiceValueCaseDifferenceIsAMatchTest() { ITemplateParameter param = new TemplateParameter( @@ -167,10 +168,10 @@ public void ChoiceValueCaseDifferenceIsAMatchTest() }; string? telemetryEntry = TelemetryHelper.PrepareHashedChoiceValue(templateInfo, parameterValues, "TestName"); - Assert.Equal(Sha256Hasher.HashWithNormalizedCasing("FOO"), telemetryEntry); + Assert.AreEqual(Sha256Hasher.HashWithNormalizedCasing("FOO"), telemetryEntry); } - [Fact(DisplayName = nameof(ChoiceValueCaseDifferencesContributeToAmbiguousMatchTest))] + [TestMethod] public void ChoiceValueCaseDifferencesContributeToAmbiguousMatchTest() { ITemplateParameter param = new TemplateParameter( @@ -193,10 +194,10 @@ public void ChoiceValueCaseDifferencesContributeToAmbiguousMatchTest() }; string? telemetryEntry = TelemetryHelper.PrepareHashedChoiceValue(templateInfo, parameterValues, "TestName"); - Assert.Null(telemetryEntry); + Assert.IsNull(telemetryEntry); } - [Fact] + [TestMethod] public void MultiValueChoiceTest() { ITemplateParameter param = new TemplateParameter( @@ -219,10 +220,10 @@ public void MultiValueChoiceTest() }; string? telemetryEntry = TelemetryHelper.PrepareHashedChoiceValue(templateInfo, parameterValues, "TestName"); - Assert.Equal(Sha256Hasher.HashWithNormalizedCasing("foo") + ";" + Sha256Hasher.HashWithNormalizedCasing("bar"), telemetryEntry); + Assert.AreEqual(Sha256Hasher.HashWithNormalizedCasing("foo") + ";" + Sha256Hasher.HashWithNormalizedCasing("bar"), telemetryEntry); } - [Fact] + [TestMethod] public void MultiValueChoice_SkipsInvalidEntriesTest() { ITemplateParameter param = new TemplateParameter( @@ -245,7 +246,7 @@ public void MultiValueChoice_SkipsInvalidEntriesTest() }; string? telemetryEntry = TelemetryHelper.PrepareHashedChoiceValue(templateInfo, parameterValues, "TestName"); - Assert.Equal(Sha256Hasher.HashWithNormalizedCasing("foo") + ";" + Sha256Hasher.HashWithNormalizedCasing("bar"), telemetryEntry); + Assert.AreEqual(Sha256Hasher.HashWithNormalizedCasing("foo") + ";" + Sha256Hasher.HashWithNormalizedCasing("bar"), telemetryEntry); } } } diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/TemplatePackageCoordinatorTests.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/TemplatePackageCoordinatorTests.cs index 071819dcf72f..3bcffb4bce2d 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/TemplatePackageCoordinatorTests.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/TemplatePackageCoordinatorTests.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using FakeItEasy; @@ -15,9 +15,10 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests { + [TestClass] public class TemplatePackageCoordinatorTests { - [Fact] + [TestMethod] public void DisplayLocalPackageMetadata() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(); @@ -44,7 +45,7 @@ public void DisplayLocalPackageMetadata() .And.Contain($" {LocalizableStrings.DetailsCommand_Property_RepoUrl}: ANuGetSource"); } - [Fact] + [TestMethod] public void DisplayLocalPackageMetadata_NoData() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(); @@ -64,7 +65,7 @@ public void DisplayLocalPackageMetadata_NoData() .ContainSingle("testPackage"); } - [Fact] + [TestMethod] public void DisplayNuGetPackageMetadata() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(); @@ -110,7 +111,7 @@ public void DisplayNuGetPackageMetadata() .And.NotContain($" {LocalizableStrings.DetailsCommand_Property_PrefixReserved}: true"); } - [Fact] + [TestMethod] public void DisplayNuGetPackageMetadata_PrefixReserved() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(); @@ -157,7 +158,7 @@ public void DisplayNuGetPackageMetadata_PrefixReserved() .And.Contain($" {LocalizableStrings.DetailsCommand_Property_PrefixReserved}: True"); } - [Fact] + [TestMethod] public void DisplayNuGetPackageMetadata_MultipleAuthors() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(); @@ -200,7 +201,7 @@ public void DisplayNuGetPackageMetadata_MultipleAuthors() .And.Contain(" author3"); } - [Fact] + [TestMethod] public void DisplayNuGetPackageMetadata_MultipleOwners() { ICliTemplateEngineHost host = CliTestHostFactory.GetVirtualHost(); diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/TemplatePackageDisplayTest.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/TemplatePackageDisplayTest.cs index 1e086cbd19d4..b2239b86fb08 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/TemplatePackageDisplayTest.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/TemplatePackageDisplayTest.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.CommandLine; @@ -14,9 +14,12 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests { + [TestClass] public class TemplatePackageDisplayTest { - [Fact] + public TestContext TestContext { get; set; } = null!; + + [TestMethod] public void DisplayUpdateCheckResultTest() { var fakeOutputReporter = new FakeReporter(); @@ -47,10 +50,10 @@ public void DisplayUpdateCheckResultTest() var reportedErrors = fakeErrorReporter.ReportedStrings.ToString().UnixifyLineBreaks().Trim(); fakeOutputReporter.ReportedStrings.ToString().Should().BeNullOrEmpty(); reportedErrors.Should().NotBeEmpty(); - Assert.Equal(expectedErrors, reportedErrors); + Assert.AreEqual(expectedErrors, reportedErrors); } - [Fact] + [TestMethod] public async Task DisplayInstallResultTest_WithForceSpecified() { var fakeOutputReporter = new FakeReporter(); @@ -88,15 +91,15 @@ await packageDisplayer.DisplayInstallResultAsync( A.Fake(), A.Fake(), A.Fake(), - CancellationToken.None); + TestContext.CancellationTokenSource.Token); var reportedOutput = fakeOutputReporter.ReportedStrings.ToString().UnixifyLineBreaks().Trim(); reportedOutput.Should().NotBeEmpty(); fakeErrorReporter.ReportedStrings.ToString().Should().BeEmpty(); - Assert.Equal(expectedOutput, reportedOutput); + Assert.AreEqual(expectedOutput, reportedOutput); } - [Fact] + [TestMethod] public async Task DisplayInstallResultTest() { var fakeOutputReporter = new FakeReporter(); @@ -134,15 +137,15 @@ await packageDisplayer.DisplayInstallResultAsync( A.Fake(), A.Fake(), A.Fake(), - CancellationToken.None); + TestContext.CancellationTokenSource.Token); var reportedErrors = fakeErrorReporter.ReportedStrings.ToString().UnixifyLineBreaks().Trim(); fakeOutputReporter.ReportedStrings.ToString().Should().BeNullOrEmpty(); reportedErrors.Should().NotBeEmpty(); - Assert.Equal(expectedErrors, reportedErrors); + Assert.AreEqual(expectedErrors, reportedErrors); } - [Fact] + [TestMethod] public async Task DisplayInstallResultTest_UpdateRequest() { var fakeOutputReporter = new FakeReporter(); @@ -177,12 +180,12 @@ await packageDisplayer.DisplayInstallResultAsync( A.Fake(), A.Fake(), A.Fake(), - CancellationToken.None); + TestContext.CancellationTokenSource.Token); var reportedErrors = fakeErrorReporter.ReportedStrings.ToString().UnixifyLineBreaks().Trim(); fakeOutputReporter.ReportedStrings.ToString().Should().BeNullOrEmpty(); reportedErrors.Should().NotBeEmpty(); - Assert.Equal(expectedErrors, reportedErrors); + Assert.AreEqual(expectedErrors, reportedErrors); } private IManagedTemplatePackage GetFakedManagedTemplatePackage(string mountPointUri, string displayName) diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/TemplateResolutionTests/ListTemplateResolverTests.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/TemplateResolutionTests/ListTemplateResolverTests.cs index 55ec63b183d6..9e6c76f05d46 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/TemplateResolutionTests/ListTemplateResolverTests.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/TemplateResolutionTests/ListTemplateResolverTests.cs @@ -13,9 +13,12 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests.TemplateResolutionTests { + [TestClass] public class ListTemplateResolverTests : BaseTest { - [Fact(DisplayName = nameof(TestGetTemplateResolutionResult_UniqueNameMatchesCorrectly))] + public new TestContext TestContext { get; set; } = null!; + + [TestMethod] public async Task TestGetTemplateResolutionResult_UniqueNameMatchesCorrectly() { IReadOnlyList templatesToSearch = new List() @@ -28,16 +31,16 @@ public async Task TestGetTemplateResolutionResult_UniqueNameMatchesCorrectly() TemplateResolutionResult matchResult = await resolver.ResolveTemplatesAsync( GetListCommandArgsFor("new list console2"), defaultLanguage: null, - TestContext.Current.CancellationToken); + TestContext.CancellationTokenSource.Token); - Assert.True(matchResult.HasTemplateGroupWithTemplateInfoMatches); - Assert.NotNull(matchResult.UnambiguousTemplateGroup); - Assert.Equal("console2", matchResult.UnambiguousTemplateGroup?.Templates.Single().ShortNameList.Single()); - Assert.Equal("Console.App2", matchResult.UnambiguousTemplateGroup?.Templates.Single().Identity); - Assert.Single(matchResult.UnambiguousTemplateGroup?.Templates!); + Assert.IsTrue(matchResult.HasTemplateGroupWithTemplateInfoMatches); + Assert.IsNotNull(matchResult.UnambiguousTemplateGroup); + Assert.AreEqual("console2", matchResult.UnambiguousTemplateGroup?.Templates.Single().ShortNameList.Single()); + Assert.AreEqual("Console.App2", matchResult.UnambiguousTemplateGroup?.Templates.Single().Identity); + Assert.HasCount(1, matchResult.UnambiguousTemplateGroup?.Templates!); } - [Fact(DisplayName = nameof(TestGetTemplateResolutionResult_ExactMatchOnShortNameMatchesCorrectly))] + [TestMethod] public async Task TestGetTemplateResolutionResult_ExactMatchOnShortNameMatchesCorrectly() { List templatesToSearch = new() @@ -50,16 +53,16 @@ public async Task TestGetTemplateResolutionResult_ExactMatchOnShortNameMatchesCo TemplateResolutionResult matchResult = await resolver.ResolveTemplatesAsync( GetListCommandArgsFor("new list console"), defaultLanguage: null, - TestContext.Current.CancellationToken); + TestContext.CancellationTokenSource.Token); - Assert.True(matchResult.HasTemplateGroupWithTemplateInfoMatches); - Assert.Null(matchResult.UnambiguousTemplateGroup); - Assert.Equal(2, matchResult.TemplateGroupsWithMatchingTemplateInfo.Count()); - Assert.NotNull(matchResult.TemplateGroupsWithMatchingTemplateInfo.SelectMany(group => group.Templates).Single(t => t.Identity == "Console.App")); - Assert.NotNull(matchResult.TemplateGroupsWithMatchingTemplateInfo.SelectMany(group => group.Templates).Single(t => t.Identity == "Console.App2")); + Assert.IsTrue(matchResult.HasTemplateGroupWithTemplateInfoMatches); + Assert.IsNull(matchResult.UnambiguousTemplateGroup); + Assert.HasCount(2, matchResult.TemplateGroupsWithMatchingTemplateInfo); + Assert.IsNotNull(matchResult.TemplateGroupsWithMatchingTemplateInfo.SelectMany(group => group.Templates).Single(t => t.Identity == "Console.App")); + Assert.IsNotNull(matchResult.TemplateGroupsWithMatchingTemplateInfo.SelectMany(group => group.Templates).Single(t => t.Identity == "Console.App2")); } - [Fact(DisplayName = nameof(TestGetTemplateResolutionResult_UnambiguousGroupIsFound))] + [TestMethod] public async Task TestGetTemplateResolutionResult_UnambiguousGroupIsFound() { List templatesToSearch = new() @@ -73,16 +76,16 @@ public async Task TestGetTemplateResolutionResult_UnambiguousGroupIsFound() TemplateResolutionResult matchResult = await resolver.ResolveTemplatesAsync( GetListCommandArgsFor("new list console"), defaultLanguage: null, - TestContext.Current.CancellationToken); + TestContext.CancellationTokenSource.Token); - Assert.True(matchResult.HasTemplateGroupWithTemplateInfoMatches); - Assert.Single(matchResult.TemplateGroupsWithMatchingTemplateInfo); - Assert.Equal(3, matchResult.TemplateGroupsWithMatchingTemplateInfo.Single().Templates.Count); - Assert.NotNull(matchResult.UnambiguousTemplateGroup); - Assert.Equal(3, matchResult.UnambiguousTemplateGroup?.Templates.Count); + Assert.IsTrue(matchResult.HasTemplateGroupWithTemplateInfoMatches); + Assert.HasCount(1, matchResult.TemplateGroupsWithMatchingTemplateInfo); + Assert.AreEqual(3, matchResult.TemplateGroupsWithMatchingTemplateInfo.Single().Templates.Count); + Assert.IsNotNull(matchResult.UnambiguousTemplateGroup); + Assert.AreEqual(3, matchResult.UnambiguousTemplateGroup?.Templates.Count); } - [Fact(DisplayName = nameof(TestGetTemplateResolutionResult_MultipleGroupsAreFound))] + [TestMethod] public async Task TestGetTemplateResolutionResult_MultipleGroupsAreFound() { List templatesToSearch = new() @@ -98,15 +101,15 @@ public async Task TestGetTemplateResolutionResult_MultipleGroupsAreFound() TemplateResolutionResult matchResult = await resolver.ResolveTemplatesAsync( GetListCommandArgsFor("new list c"), defaultLanguage: null, - TestContext.Current.CancellationToken); + TestContext.CancellationTokenSource.Token); - Assert.True(matchResult.HasTemplateGroupWithTemplateInfoMatches); - Assert.Equal(2, matchResult.TemplateGroupsWithMatchingTemplateInfo.Count()); - Assert.Equal(5, matchResult.TemplateGroupsWithMatchingTemplateInfo.SelectMany(group => group.Templates).Count()); - Assert.Null(matchResult.UnambiguousTemplateGroup); + Assert.IsTrue(matchResult.HasTemplateGroupWithTemplateInfoMatches); + Assert.HasCount(2, matchResult.TemplateGroupsWithMatchingTemplateInfo); + Assert.HasCount(5, matchResult.TemplateGroupsWithMatchingTemplateInfo.SelectMany(group => group.Templates)); + Assert.IsNull(matchResult.UnambiguousTemplateGroup); } - [Fact(DisplayName = nameof(TestGetTemplateResolutionResult_DefaultLanguageDisambiguates))] + [TestMethod] public async Task TestGetTemplateResolutionResult_DefaultLanguageDisambiguates() { List templatesToSearch = new() @@ -119,17 +122,17 @@ public async Task TestGetTemplateResolutionResult_DefaultLanguageDisambiguates() TemplateResolutionResult matchResult = await resolver.ResolveTemplatesAsync( GetListCommandArgsFor("new list console"), defaultLanguage: null, - TestContext.Current.CancellationToken); - - Assert.True(matchResult.HasTemplateGroupWithTemplateInfoMatches); - Assert.NotNull(matchResult.UnambiguousTemplateGroup); - Assert.Single(matchResult.TemplateGroupsWithMatchingTemplateInfo); - Assert.Equal(2, matchResult.TemplateGroupsWithMatchingTemplateInfo.Single().Templates.Count); - Assert.NotNull(matchResult.TemplateGroupsWithMatchingTemplateInfo.Single().Templates.Single(t => t.Identity == "Console.App.L1")); - Assert.NotNull(matchResult.TemplateGroupsWithMatchingTemplateInfo.Single().Templates.Single(t => t.Identity == "Console.App.L2")); + TestContext.CancellationTokenSource.Token); + + Assert.IsTrue(matchResult.HasTemplateGroupWithTemplateInfoMatches); + Assert.IsNotNull(matchResult.UnambiguousTemplateGroup); + Assert.HasCount(1, matchResult.TemplateGroupsWithMatchingTemplateInfo); + Assert.AreEqual(2, matchResult.TemplateGroupsWithMatchingTemplateInfo.Single().Templates.Count); + Assert.IsNotNull(matchResult.TemplateGroupsWithMatchingTemplateInfo.Single().Templates.Single(t => t.Identity == "Console.App.L1")); + Assert.IsNotNull(matchResult.TemplateGroupsWithMatchingTemplateInfo.Single().Templates.Single(t => t.Identity == "Console.App.L2")); } - [Fact(DisplayName = nameof(TestGetTemplateResolutionResult_InputLanguageIsPreferredOverDefault))] + [TestMethod] public async Task TestGetTemplateResolutionResult_InputLanguageIsPreferredOverDefault() { List templatesToSearch = new() @@ -142,15 +145,15 @@ public async Task TestGetTemplateResolutionResult_InputLanguageIsPreferredOverDe TemplateResolutionResult matchResult = await resolver.ResolveTemplatesAsync( GetListCommandArgsFor("new list console --language L2"), defaultLanguage: null, - TestContext.Current.CancellationToken); + TestContext.CancellationTokenSource.Token); - Assert.True(matchResult.HasTemplateGroupWithTemplateInfoMatches); - Assert.NotNull(matchResult.UnambiguousTemplateGroup); - Assert.Equal(2, matchResult.TemplateGroupsWithMatchingTemplateInfo?.Single().Templates.Count); - Assert.Equal(2, matchResult.UnambiguousTemplateGroup?.Templates.Count); + Assert.IsTrue(matchResult.HasTemplateGroupWithTemplateInfoMatches); + Assert.IsNotNull(matchResult.UnambiguousTemplateGroup); + Assert.AreEqual(2, matchResult.TemplateGroupsWithMatchingTemplateInfo?.Single().Templates.Count); + Assert.AreEqual(2, matchResult.UnambiguousTemplateGroup?.Templates.Count); } - [Fact(DisplayName = nameof(TestGetTemplateResolutionResult_PartialMatch_HasLanguageMismatch))] + [TestMethod] public async Task TestGetTemplateResolutionResult_PartialMatch_HasLanguageMismatch() { List templatesToSearch = new() @@ -165,19 +168,19 @@ public async Task TestGetTemplateResolutionResult_PartialMatch_HasLanguageMismat TemplateResolutionResult matchResult = await resolver.ResolveTemplatesAsync( GetListCommandArgsFor("new list console --language L2"), defaultLanguage: null, - TestContext.Current.CancellationToken); - - Assert.False(matchResult.HasTemplateGroupWithTemplateInfoMatches); - Assert.Empty(matchResult.TemplateGroupsWithMatchingTemplateInfo); - Assert.Single(matchResult.TemplateGroups); - Assert.Single(matchResult.TemplateGroups.Single().Templates); - Assert.True(matchResult.HasLanguageMismatch); - Assert.False(matchResult.HasTypeMismatch); - Assert.False(matchResult.HasBaselineMismatch); - Assert.Null(matchResult.UnambiguousTemplateGroup); + TestContext.CancellationTokenSource.Token); + + Assert.IsFalse(matchResult.HasTemplateGroupWithTemplateInfoMatches); + Assert.IsFalse(matchResult.TemplateGroupsWithMatchingTemplateInfo.Any()); + Assert.HasCount(1, matchResult.TemplateGroups); + Assert.HasCount(1, matchResult.TemplateGroups.Single().Templates); + Assert.IsTrue(matchResult.HasLanguageMismatch); + Assert.IsFalse(matchResult.HasTypeMismatch); + Assert.IsFalse(matchResult.HasBaselineMismatch); + Assert.IsNull(matchResult.UnambiguousTemplateGroup); } - [Fact(DisplayName = nameof(TestGetTemplateResolutionResult_PartialMatch_HasContextMismatch))] + [TestMethod] public async Task TestGetTemplateResolutionResult_PartialMatch_HasContextMismatch() { List templatesToSearch = new() @@ -192,19 +195,19 @@ public async Task TestGetTemplateResolutionResult_PartialMatch_HasContextMismatc TemplateResolutionResult matchResult = await resolver.ResolveTemplatesAsync( GetListCommandArgsFor("new list console --type item"), defaultLanguage: null, - TestContext.Current.CancellationToken); - - Assert.False(matchResult.HasTemplateGroupWithTemplateInfoMatches); - Assert.Empty(matchResult.TemplateGroupsWithMatchingTemplateInfo); - Assert.Single(matchResult.TemplateGroups); - Assert.Single(matchResult.TemplateGroups.Single().Templates); - Assert.False(matchResult.HasLanguageMismatch); - Assert.True(matchResult.HasTypeMismatch); - Assert.False(matchResult.HasBaselineMismatch); - Assert.Null(matchResult.UnambiguousTemplateGroup); + TestContext.CancellationTokenSource.Token); + + Assert.IsFalse(matchResult.HasTemplateGroupWithTemplateInfoMatches); + Assert.IsFalse(matchResult.TemplateGroupsWithMatchingTemplateInfo.Any()); + Assert.HasCount(1, matchResult.TemplateGroups); + Assert.HasCount(1, matchResult.TemplateGroups.Single().Templates); + Assert.IsFalse(matchResult.HasLanguageMismatch); + Assert.IsTrue(matchResult.HasTypeMismatch); + Assert.IsFalse(matchResult.HasBaselineMismatch); + Assert.IsNull(matchResult.UnambiguousTemplateGroup); } - [Fact(DisplayName = nameof(TestGetTemplateResolutionResult_PartialMatch_HasBaselineMismatch))] + [TestMethod] public async Task TestGetTemplateResolutionResult_PartialMatch_HasBaselineMismatch() { List templatesToSearch = new() @@ -219,19 +222,19 @@ public async Task TestGetTemplateResolutionResult_PartialMatch_HasBaselineMismat TemplateResolutionResult matchResult = await resolver.ResolveTemplatesAsync( GetListCommandArgsFor("new list console --baseline core"), defaultLanguage: null, - TestContext.Current.CancellationToken); - - Assert.False(matchResult.HasTemplateGroupWithTemplateInfoMatches); - Assert.Empty(matchResult.TemplateGroupsWithMatchingTemplateInfo); - Assert.Single(matchResult.TemplateGroups); - Assert.Single(matchResult.TemplateGroups.Single().Templates); - Assert.False(matchResult.HasLanguageMismatch); - Assert.False(matchResult.HasTypeMismatch); - Assert.True(matchResult.HasBaselineMismatch); - Assert.Null(matchResult.UnambiguousTemplateGroup); + TestContext.CancellationTokenSource.Token); + + Assert.IsFalse(matchResult.HasTemplateGroupWithTemplateInfoMatches); + Assert.IsFalse(matchResult.TemplateGroupsWithMatchingTemplateInfo.Any()); + Assert.HasCount(1, matchResult.TemplateGroups); + Assert.HasCount(1, matchResult.TemplateGroups.Single().Templates); + Assert.IsFalse(matchResult.HasLanguageMismatch); + Assert.IsFalse(matchResult.HasTypeMismatch); + Assert.IsTrue(matchResult.HasBaselineMismatch); + Assert.IsNull(matchResult.UnambiguousTemplateGroup); } - [Fact(DisplayName = nameof(TestGetTemplateResolutionResult_PartialMatch_HasMultipleMismatches))] + [TestMethod] public async Task TestGetTemplateResolutionResult_PartialMatch_HasMultipleMismatches() { List templatesToSearch = new() @@ -246,19 +249,19 @@ public async Task TestGetTemplateResolutionResult_PartialMatch_HasMultipleMismat TemplateResolutionResult matchResult = await resolver.ResolveTemplatesAsync( GetListCommandArgsFor("new list console --language L2 --type item --baseline core"), defaultLanguage: null, - TestContext.Current.CancellationToken); - - Assert.False(matchResult.HasTemplateGroupWithTemplateInfoMatches); - Assert.Empty(matchResult.TemplateGroupsWithMatchingTemplateInfo); - Assert.Single(matchResult.TemplateGroups); - Assert.Single(matchResult.TemplateGroups.Single().Templates); - Assert.True(matchResult.HasLanguageMismatch); - Assert.True(matchResult.HasTypeMismatch); - Assert.True(matchResult.HasBaselineMismatch); - Assert.Null(matchResult.UnambiguousTemplateGroup); + TestContext.CancellationTokenSource.Token); + + Assert.IsFalse(matchResult.HasTemplateGroupWithTemplateInfoMatches); + Assert.IsFalse(matchResult.TemplateGroupsWithMatchingTemplateInfo.Any()); + Assert.HasCount(1, matchResult.TemplateGroups); + Assert.HasCount(1, matchResult.TemplateGroups.Single().Templates); + Assert.IsTrue(matchResult.HasLanguageMismatch); + Assert.IsTrue(matchResult.HasTypeMismatch); + Assert.IsTrue(matchResult.HasBaselineMismatch); + Assert.IsNull(matchResult.UnambiguousTemplateGroup); } - [Fact(DisplayName = nameof(TestGetTemplateResolutionResult_NoMatch))] + [TestMethod] public async Task TestGetTemplateResolutionResult_NoMatch() { List templatesToSearch = new() @@ -273,20 +276,20 @@ public async Task TestGetTemplateResolutionResult_NoMatch() TemplateResolutionResult matchResult = await resolver.ResolveTemplatesAsync( GetListCommandArgsFor("new list zzzzz --language L1 --type project --baseline app"), defaultLanguage: null, - TestContext.Current.CancellationToken); - - Assert.False(matchResult.HasTemplateGroupMatches); - Assert.False(matchResult.HasTemplateGroupWithTemplateInfoMatches); - Assert.Empty(matchResult.TemplateGroupsWithMatchingTemplateInfo); - Assert.Empty(matchResult.TemplateGroups); - Assert.False(matchResult.HasLanguageMismatch); - Assert.False(matchResult.HasTypeMismatch); - Assert.False(matchResult.HasBaselineMismatch); - Assert.False(matchResult.HasClassificationMismatch); - Assert.Null(matchResult.UnambiguousTemplateGroup); + TestContext.CancellationTokenSource.Token); + + Assert.IsFalse(matchResult.HasTemplateGroupMatches); + Assert.IsFalse(matchResult.HasTemplateGroupWithTemplateInfoMatches); + Assert.IsFalse(matchResult.TemplateGroupsWithMatchingTemplateInfo.Any()); + Assert.IsFalse(matchResult.TemplateGroups.Any()); + Assert.IsFalse(matchResult.HasLanguageMismatch); + Assert.IsFalse(matchResult.HasTypeMismatch); + Assert.IsFalse(matchResult.HasBaselineMismatch); + Assert.IsFalse(matchResult.HasClassificationMismatch); + Assert.IsNull(matchResult.UnambiguousTemplateGroup); } - [Fact(DisplayName = nameof(TestGetTemplateResolutionResult_MatchByTags))] + [TestMethod] public async Task TestGetTemplateResolutionResult_MatchByTags() { List templatesToSearch = new() @@ -302,18 +305,18 @@ public async Task TestGetTemplateResolutionResult_MatchByTags() TemplateResolutionResult matchResult = await resolver.ResolveTemplatesAsync( GetListCommandArgsFor("new list --tag Common"), defaultLanguage: null, - TestContext.Current.CancellationToken); - - Assert.True(matchResult.HasTemplateGroupWithTemplateInfoMatches); - Assert.Single(matchResult.TemplateGroupsWithMatchingTemplateInfo); - Assert.Single(matchResult.TemplateGroupsWithMatchingTemplateInfo.Single().Templates); - Assert.False(matchResult.HasLanguageMismatch); - Assert.False(matchResult.HasTypeMismatch); - Assert.False(matchResult.HasBaselineMismatch); - Assert.False(matchResult.HasClassificationMismatch); + TestContext.CancellationTokenSource.Token); + + Assert.IsTrue(matchResult.HasTemplateGroupWithTemplateInfoMatches); + Assert.HasCount(1, matchResult.TemplateGroupsWithMatchingTemplateInfo); + Assert.HasCount(1, matchResult.TemplateGroupsWithMatchingTemplateInfo.Single().Templates); + Assert.IsFalse(matchResult.HasLanguageMismatch); + Assert.IsFalse(matchResult.HasTypeMismatch); + Assert.IsFalse(matchResult.HasBaselineMismatch); + Assert.IsFalse(matchResult.HasClassificationMismatch); } - [Fact(DisplayName = nameof(TestGetTemplateResolutionResult_MatchByTagsIgnoredOnNameMatch))] + [TestMethod] public async Task TestGetTemplateResolutionResult_MatchByTagsIgnoredOnNameMatch() { List templatesToSearch = new() @@ -334,19 +337,19 @@ public async Task TestGetTemplateResolutionResult_MatchByTagsIgnoredOnNameMatch( TemplateResolutionResult matchResult = await resolver.ResolveTemplatesAsync( GetListCommandArgsFor("new list Test"), defaultLanguage: null, - TestContext.Current.CancellationToken); - - Assert.True(matchResult.HasTemplateGroupWithTemplateInfoMatches); - Assert.Single(matchResult.TemplateGroupsWithMatchingTemplateInfo); - Assert.Single(matchResult.TemplateGroupsWithMatchingTemplateInfo.Single().Templates); - Assert.False(matchResult.HasLanguageMismatch); - Assert.False(matchResult.HasTypeMismatch); - Assert.False(matchResult.HasBaselineMismatch); - Assert.Equal("console1", matchResult.UnambiguousTemplateGroup?.Templates.Single().ShortNameList.Single()); - Assert.Equal("Console.App.T1", matchResult.UnambiguousTemplateGroup?.Templates.Single().Identity); + TestContext.CancellationTokenSource.Token); + + Assert.IsTrue(matchResult.HasTemplateGroupWithTemplateInfoMatches); + Assert.HasCount(1, matchResult.TemplateGroupsWithMatchingTemplateInfo); + Assert.HasCount(1, matchResult.TemplateGroupsWithMatchingTemplateInfo.Single().Templates); + Assert.IsFalse(matchResult.HasLanguageMismatch); + Assert.IsFalse(matchResult.HasTypeMismatch); + Assert.IsFalse(matchResult.HasBaselineMismatch); + Assert.AreEqual("console1", matchResult.UnambiguousTemplateGroup?.Templates.Single().ShortNameList.Single()); + Assert.AreEqual("Console.App.T1", matchResult.UnambiguousTemplateGroup?.Templates.Single().Identity); } - [Fact(DisplayName = nameof(TestGetTemplateResolutionResult_MatchByTagsIgnoredOnShortNameMatch))] + [TestMethod] public async Task TestGetTemplateResolutionResult_MatchByTagsIgnoredOnShortNameMatch() { List templatesToSearch = new() @@ -367,19 +370,19 @@ public async Task TestGetTemplateResolutionResult_MatchByTagsIgnoredOnShortNameM TemplateResolutionResult matchResult = await resolver.ResolveTemplatesAsync( GetListCommandArgsFor("new list Console"), defaultLanguage: null, - TestContext.Current.CancellationToken); - - Assert.True(matchResult.HasTemplateGroupWithTemplateInfoMatches); - Assert.Single(matchResult.TemplateGroupsWithMatchingTemplateInfo); - Assert.Single(matchResult.TemplateGroupsWithMatchingTemplateInfo.Single().Templates); - Assert.False(matchResult.HasLanguageMismatch); - Assert.False(matchResult.HasTypeMismatch); - Assert.False(matchResult.HasBaselineMismatch); - Assert.Equal("console", matchResult.UnambiguousTemplateGroup?.Templates.Single().ShortNameList.Single()); - Assert.Equal("Console.App.T1", matchResult.UnambiguousTemplateGroup?.Templates.Single().Identity); + TestContext.CancellationTokenSource.Token); + + Assert.IsTrue(matchResult.HasTemplateGroupWithTemplateInfoMatches); + Assert.HasCount(1, matchResult.TemplateGroupsWithMatchingTemplateInfo); + Assert.HasCount(1, matchResult.TemplateGroupsWithMatchingTemplateInfo.Single().Templates); + Assert.IsFalse(matchResult.HasLanguageMismatch); + Assert.IsFalse(matchResult.HasTypeMismatch); + Assert.IsFalse(matchResult.HasBaselineMismatch); + Assert.AreEqual("console", matchResult.UnambiguousTemplateGroup?.Templates.Single().ShortNameList.Single()); + Assert.AreEqual("Console.App.T1", matchResult.UnambiguousTemplateGroup?.Templates.Single().Identity); } - [Fact(DisplayName = nameof(TestGetTemplateResolutionResult_MatchByTagsAndMismatchByOtherFilter))] + [TestMethod] public async Task TestGetTemplateResolutionResult_MatchByTagsAndMismatchByOtherFilter() { List templatesToSearch = new() @@ -395,25 +398,25 @@ public async Task TestGetTemplateResolutionResult_MatchByTagsAndMismatchByOtherF TemplateResolutionResult matchResult = await resolver.ResolveTemplatesAsync( GetListCommandArgsFor("new list --language L2 --type item --tag Common"), defaultLanguage: null, - TestContext.Current.CancellationToken); - - Assert.False(matchResult.HasTemplateGroupWithTemplateInfoMatches); - Assert.Empty(matchResult.TemplateGroupsWithMatchingTemplateInfo); - Assert.True(matchResult.HasTemplateGroupMatches); - Assert.Single(matchResult.TemplateGroups); - Assert.Single(matchResult.TemplateGroups.Single().Templates); - Assert.True(matchResult.HasLanguageMismatch); - Assert.True(matchResult.HasTypeMismatch); - Assert.False(matchResult.HasBaselineMismatch); + TestContext.CancellationTokenSource.Token); + + Assert.IsFalse(matchResult.HasTemplateGroupWithTemplateInfoMatches); + Assert.IsFalse(matchResult.TemplateGroupsWithMatchingTemplateInfo.Any()); + Assert.IsTrue(matchResult.HasTemplateGroupMatches); + Assert.HasCount(1, matchResult.TemplateGroups); + Assert.HasCount(1, matchResult.TemplateGroups.Single().Templates); + Assert.IsTrue(matchResult.HasLanguageMismatch); + Assert.IsTrue(matchResult.HasTypeMismatch); + Assert.IsFalse(matchResult.HasBaselineMismatch); } - [Theory(DisplayName = nameof(TestGetTemplateResolutionResult_AuthorMatch))] - [InlineData("TestAuthor", "Test", true)] - [InlineData("TestAuthor", "Other", false)] - [InlineData("TestAuthor", "TeST", true)] - [InlineData("TestAuthor", "Teşt", false)] - [InlineData("match_middle_test", "middle", true)] - [InlineData("input", "İnput", false)] + [TestMethod] + [DataRow("TestAuthor", "Test", true)] + [DataRow("TestAuthor", "Other", false)] + [DataRow("TestAuthor", "TeST", true)] + [DataRow("TestAuthor", "Teşt", false)] + [DataRow("match_middle_test", "middle", true)] + [DataRow("input", "İnput", false)] public async Task TestGetTemplateResolutionResult_AuthorMatch(string templateAuthor, string commandAuthor, bool matchExpected) { List templatesToSearch = new() @@ -429,40 +432,40 @@ public async Task TestGetTemplateResolutionResult_AuthorMatch(string templateAut TemplateResolutionResult matchResult = await resolver.ResolveTemplatesAsync( GetListCommandArgsFor($"new list console --author {commandAuthor}"), defaultLanguage: null, - TestContext.Current.CancellationToken); + TestContext.CancellationTokenSource.Token); if (matchExpected) { - Assert.True(matchResult.HasTemplateGroupWithTemplateInfoMatches); - Assert.Single(matchResult.TemplateGroupsWithMatchingTemplateInfo); - Assert.Single(matchResult.TemplateGroupsWithMatchingTemplateInfo.Single().Templates); - Assert.False(matchResult.HasAuthorMismatch); + Assert.IsTrue(matchResult.HasTemplateGroupWithTemplateInfoMatches); + Assert.HasCount(1, matchResult.TemplateGroupsWithMatchingTemplateInfo); + Assert.HasCount(1, matchResult.TemplateGroupsWithMatchingTemplateInfo.Single().Templates); + Assert.IsFalse(matchResult.HasAuthorMismatch); } else { - Assert.False(matchResult.HasTemplateGroupWithTemplateInfoMatches); - Assert.Empty(matchResult.TemplateGroupsWithMatchingTemplateInfo); - Assert.True(matchResult.HasTemplateGroupMatches); - Assert.Single(matchResult.TemplateGroups); - Assert.Single(matchResult.TemplateGroups.Single().Templates); - Assert.True(matchResult.HasAuthorMismatch); + Assert.IsFalse(matchResult.HasTemplateGroupWithTemplateInfoMatches); + Assert.IsFalse(matchResult.TemplateGroupsWithMatchingTemplateInfo.Any()); + Assert.IsTrue(matchResult.HasTemplateGroupMatches); + Assert.HasCount(1, matchResult.TemplateGroups); + Assert.HasCount(1, matchResult.TemplateGroups.Single().Templates); + Assert.IsTrue(matchResult.HasAuthorMismatch); } - Assert.False(matchResult.HasLanguageMismatch); - Assert.False(matchResult.HasTypeMismatch); - Assert.False(matchResult.HasBaselineMismatch); + Assert.IsFalse(matchResult.HasLanguageMismatch); + Assert.IsFalse(matchResult.HasTypeMismatch); + Assert.IsFalse(matchResult.HasBaselineMismatch); } - [Theory(DisplayName = nameof(TestGetTemplateResolutionResult_TagsMatch))] - [InlineData("TestTag", "TestTag", true)] - [InlineData("Tag1||Tag2", "Tag1", true)] - [InlineData("Tag1||Tag2", "Tag", false)] - [InlineData("", "Tag", false)] - [InlineData("TestTag", "Other", false)] - [InlineData("TestTag", "TeSTTag", true)] - [InlineData("TestTag", "TeştTag", false)] - [InlineData("match_middle_test", "middle", false)] - [InlineData("input", "İnput", false)] + [TestMethod] + [DataRow("TestTag", "TestTag", true)] + [DataRow("Tag1||Tag2", "Tag1", true)] + [DataRow("Tag1||Tag2", "Tag", false)] + [DataRow("", "Tag", false)] + [DataRow("TestTag", "Other", false)] + [DataRow("TestTag", "TeSTTag", true)] + [DataRow("TestTag", "TeştTag", false)] + [DataRow("match_middle_test", "middle", false)] + [DataRow("input", "İnput", false)] public async Task TestGetTemplateResolutionResult_TagsMatch(string templateTags, string commandTag, bool matchExpected) { const string separator = "||"; @@ -481,32 +484,32 @@ public async Task TestGetTemplateResolutionResult_TagsMatch(string templateTags, TemplateResolutionResult matchResult = await resolver.ResolveTemplatesAsync( GetListCommandArgsFor($"new list console --tag {commandTag}"), defaultLanguage: null, - TestContext.Current.CancellationToken); + TestContext.CancellationTokenSource.Token); if (matchExpected) { - Assert.True(matchResult.HasTemplateGroupWithTemplateInfoMatches); - Assert.Single(matchResult.TemplateGroupsWithMatchingTemplateInfo); - Assert.Single(matchResult.TemplateGroupsWithMatchingTemplateInfo.Single().Templates); - Assert.False(matchResult.HasClassificationMismatch); + Assert.IsTrue(matchResult.HasTemplateGroupWithTemplateInfoMatches); + Assert.HasCount(1, matchResult.TemplateGroupsWithMatchingTemplateInfo); + Assert.HasCount(1, matchResult.TemplateGroupsWithMatchingTemplateInfo.Single().Templates); + Assert.IsFalse(matchResult.HasClassificationMismatch); } else { - Assert.False(matchResult.HasTemplateGroupWithTemplateInfoMatches); - Assert.Empty(matchResult.TemplateGroupsWithMatchingTemplateInfo); - Assert.True(matchResult.HasTemplateGroupMatches); - Assert.Single(matchResult.TemplateGroups); - Assert.Single(matchResult.TemplateGroups.Single().Templates); - Assert.True(matchResult.HasClassificationMismatch); + Assert.IsFalse(matchResult.HasTemplateGroupWithTemplateInfoMatches); + Assert.IsFalse(matchResult.TemplateGroupsWithMatchingTemplateInfo.Any()); + Assert.IsTrue(matchResult.HasTemplateGroupMatches); + Assert.HasCount(1, matchResult.TemplateGroups); + Assert.HasCount(1, matchResult.TemplateGroups.Single().Templates); + Assert.IsTrue(matchResult.HasClassificationMismatch); } - Assert.False(matchResult.HasLanguageMismatch); - Assert.False(matchResult.HasTypeMismatch); - Assert.False(matchResult.HasBaselineMismatch); - Assert.False(matchResult.HasAuthorMismatch); + Assert.IsFalse(matchResult.HasLanguageMismatch); + Assert.IsFalse(matchResult.HasTypeMismatch); + Assert.IsFalse(matchResult.HasBaselineMismatch); + Assert.IsFalse(matchResult.HasAuthorMismatch); } - [Fact(DisplayName = nameof(TestGetTemplateResolutionResult_TemplateWithoutTypeShouldNotBeMatchedForContextFilter))] + [TestMethod] public async Task TestGetTemplateResolutionResult_TemplateWithoutTypeShouldNotBeMatchedForContextFilter() { List templatesToSearch = new() @@ -519,19 +522,19 @@ public async Task TestGetTemplateResolutionResult_TemplateWithoutTypeShouldNotBe TemplateResolutionResult matchResult = await resolver.ResolveTemplatesAsync( GetListCommandArgsFor("new list console --type item"), defaultLanguage: null, - TestContext.Current.CancellationToken); - - Assert.False(matchResult.HasTemplateGroupWithTemplateInfoMatches); - Assert.Empty(matchResult.TemplateGroupsWithMatchingTemplateInfo); - Assert.True(matchResult.HasTemplateGroupMatches); - Assert.Single(matchResult.TemplateGroups); - Assert.Single(matchResult.TemplateGroups.Single().Templates); - Assert.False(matchResult.HasLanguageMismatch); - Assert.True(matchResult.HasTypeMismatch); - Assert.False(matchResult.HasBaselineMismatch); + TestContext.CancellationTokenSource.Token); + + Assert.IsFalse(matchResult.HasTemplateGroupWithTemplateInfoMatches); + Assert.IsFalse(matchResult.TemplateGroupsWithMatchingTemplateInfo.Any()); + Assert.IsTrue(matchResult.HasTemplateGroupMatches); + Assert.HasCount(1, matchResult.TemplateGroups); + Assert.HasCount(1, matchResult.TemplateGroups.Single().Templates); + Assert.IsFalse(matchResult.HasLanguageMismatch); + Assert.IsTrue(matchResult.HasTypeMismatch); + Assert.IsFalse(matchResult.HasBaselineMismatch); } - [Fact] + [TestMethod] public async Task TestGetTemplateResolutionResult_ConstraintsMismatch() { List templatesToSearch = new() @@ -554,15 +557,15 @@ public async Task TestGetTemplateResolutionResult_ConstraintsMismatch() TemplateResolutionResult matchResult = await resolver.ResolveTemplatesAsync( args, defaultLanguage: null, - TestContext.Current.CancellationToken); + TestContext.CancellationTokenSource.Token); - Assert.Equal(2, matchResult.ContraintsMismatchGroupCount); - Assert.Empty(matchResult.TemplateGroupsWithMatchingTemplateInfoAndParameters); - Assert.True(matchResult.HasTemplateGroupMatches); - Assert.Equal(2, matchResult.TemplateGroups.Count()); + Assert.AreEqual(2, matchResult.ContraintsMismatchGroupCount); + Assert.IsFalse(matchResult.TemplateGroupsWithMatchingTemplateInfoAndParameters.Any()); + Assert.IsTrue(matchResult.HasTemplateGroupMatches); + Assert.HasCount(2, matchResult.TemplateGroups); } - [Fact] + [TestMethod] public async Task TestGetTemplateResolutionResult_IgnoreConstraintsMismatch() { List templatesToSearch = new() @@ -585,12 +588,12 @@ public async Task TestGetTemplateResolutionResult_IgnoreConstraintsMismatch() TemplateResolutionResult matchResult = await resolver.ResolveTemplatesAsync( args, defaultLanguage: null, - TestContext.Current.CancellationToken); + TestContext.CancellationTokenSource.Token); - Assert.Equal(0, matchResult.ContraintsMismatchGroupCount); - Assert.Equal(2, matchResult.TemplateGroupsWithMatchingTemplateInfoAndParameters.Count()); - Assert.True(matchResult.HasTemplateGroupMatches); - Assert.Equal(2, matchResult.TemplateGroups.Count()); + Assert.AreEqual(0, matchResult.ContraintsMismatchGroupCount); + Assert.HasCount(2, matchResult.TemplateGroupsWithMatchingTemplateInfoAndParameters); + Assert.IsTrue(matchResult.HasTemplateGroupMatches); + Assert.HasCount(2, matchResult.TemplateGroups); } private static ListCommandArgs GetListCommandArgsFor(string commandInput) diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/TemplateResolutionTests/TemplateMatchInfoTests.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/TemplateResolutionTests/TemplateMatchInfoTests.cs index d7ceacbf89e9..2d35ea06d89d 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/TemplateResolutionTests/TemplateMatchInfoTests.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/TemplateResolutionTests/TemplateMatchInfoTests.cs @@ -10,122 +10,123 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests { + [TestClass] public class TemplateMatchInfoTests { - [Fact(DisplayName = nameof(EmptyMatchDisposition_ReportsCorrectly))] + [TestMethod] public void EmptyMatchDisposition_ReportsCorrectly() { ITemplateInfo templateInfo = new MockTemplateInfo(); ITemplateMatchInfo templateMatchInfo = new TemplateMatchInfo(templateInfo); - Assert.False(WellKnownSearchFilters.MatchesAllCriteria(templateMatchInfo)); - Assert.False(WellKnownSearchFilters.MatchesAtLeastOneCriteria(templateMatchInfo)); - Assert.Empty(templateMatchInfo.GetInvalidParameterNames()); - Assert.Empty(templateMatchInfo.GetValidTemplateParameters()); + Assert.IsFalse(WellKnownSearchFilters.MatchesAllCriteria(templateMatchInfo)); + Assert.IsFalse(WellKnownSearchFilters.MatchesAtLeastOneCriteria(templateMatchInfo)); + Assert.IsFalse(templateMatchInfo.GetInvalidParameterNames().Any()); + Assert.IsFalse(templateMatchInfo.GetValidTemplateParameters().Any()); } - [Fact(DisplayName = nameof(NameExactMatch_ReportsCorrectly))] + [TestMethod] public void NameExactMatch_ReportsCorrectly() { ITemplateInfo templateInfo = new MockTemplateInfo(); ITemplateMatchInfo templateMatchInfo = new TemplateMatchInfo(templateInfo); templateMatchInfo.AddMatchDisposition(new MatchInfo(MatchInfo.BuiltIn.Name, "test", MatchKind.Exact)); - Assert.True(WellKnownSearchFilters.MatchesAllCriteria(templateMatchInfo)); - Assert.True(WellKnownSearchFilters.MatchesAtLeastOneCriteria(templateMatchInfo)); + Assert.IsTrue(WellKnownSearchFilters.MatchesAllCriteria(templateMatchInfo)); + Assert.IsTrue(WellKnownSearchFilters.MatchesAtLeastOneCriteria(templateMatchInfo)); } - [Fact(DisplayName = nameof(NamePartialMatch_ReportsCorrectly))] + [TestMethod] public void NamePartialMatch_ReportsCorrectly() { ITemplateInfo templateInfo = new MockTemplateInfo(); ITemplateMatchInfo templateMatchInfo = new TemplateMatchInfo(templateInfo); templateMatchInfo.AddMatchDisposition(new MatchInfo(MatchInfo.BuiltIn.Name, "test", MatchKind.Partial)); - Assert.True(WellKnownSearchFilters.MatchesAllCriteria(templateMatchInfo)); - Assert.True(WellKnownSearchFilters.MatchesAtLeastOneCriteria(templateMatchInfo)); + Assert.IsTrue(WellKnownSearchFilters.MatchesAllCriteria(templateMatchInfo)); + Assert.IsTrue(WellKnownSearchFilters.MatchesAtLeastOneCriteria(templateMatchInfo)); } - [Fact(DisplayName = nameof(NameMismatch_ReportsCorrectly))] + [TestMethod] public void NameMismatch_ReportsCorrectly() { ITemplateInfo templateInfo = new MockTemplateInfo(); ITemplateMatchInfo templateMatchInfo = new TemplateMatchInfo(templateInfo); templateMatchInfo.AddMatchDisposition(new MatchInfo(MatchInfo.BuiltIn.Name, "test", MatchKind.Mismatch)); - Assert.False(WellKnownSearchFilters.MatchesAllCriteria(templateMatchInfo)); - Assert.False(WellKnownSearchFilters.MatchesAtLeastOneCriteria(templateMatchInfo)); + Assert.IsFalse(WellKnownSearchFilters.MatchesAllCriteria(templateMatchInfo)); + Assert.IsFalse(WellKnownSearchFilters.MatchesAtLeastOneCriteria(templateMatchInfo)); } - [Fact(DisplayName = nameof(TypeMatch_ReportsCorrectly))] + [TestMethod] public void TypeMatch_ReportsCorrectly() { ITemplateInfo templateInfo = new MockTemplateInfo(); ITemplateMatchInfo templateMatchInfo = new TemplateMatchInfo(templateInfo); templateMatchInfo.AddMatchDisposition(new MatchInfo(MatchInfo.BuiltIn.Type, "test", MatchKind.Exact)); - Assert.True(WellKnownSearchFilters.MatchesAllCriteria(templateMatchInfo)); - Assert.True(WellKnownSearchFilters.MatchesAtLeastOneCriteria(templateMatchInfo)); + Assert.IsTrue(WellKnownSearchFilters.MatchesAllCriteria(templateMatchInfo)); + Assert.IsTrue(WellKnownSearchFilters.MatchesAtLeastOneCriteria(templateMatchInfo)); } - [Fact(DisplayName = nameof(TypeMismatch_ReportsCorrectly))] + [TestMethod] public void TypeMismatch_ReportsCorrectly() { ITemplateInfo templateInfo = new MockTemplateInfo(); ITemplateMatchInfo templateMatchInfo = new TemplateMatchInfo(templateInfo); templateMatchInfo.AddMatchDisposition(new MatchInfo(MatchInfo.BuiltIn.Type, "test", MatchKind.Mismatch)); - Assert.False(WellKnownSearchFilters.MatchesAllCriteria(templateMatchInfo)); - Assert.False(WellKnownSearchFilters.MatchesAtLeastOneCriteria(templateMatchInfo)); + Assert.IsFalse(WellKnownSearchFilters.MatchesAllCriteria(templateMatchInfo)); + Assert.IsFalse(WellKnownSearchFilters.MatchesAtLeastOneCriteria(templateMatchInfo)); } - [Fact(DisplayName = nameof(TypeMatch_NameMatch_ReportsCorrectly))] + [TestMethod] public void TypeMatch_NameMatch_ReportsCorrectly() { ITemplateInfo templateInfo = new MockTemplateInfo(); ITemplateMatchInfo templateMatchInfo = new TemplateMatchInfo(templateInfo); templateMatchInfo.AddMatchDisposition(new MatchInfo(MatchInfo.BuiltIn.Name, "test", MatchKind.Exact)); templateMatchInfo.AddMatchDisposition(new MatchInfo(MatchInfo.BuiltIn.Type, "test", MatchKind.Exact)); - Assert.True(WellKnownSearchFilters.MatchesAllCriteria(templateMatchInfo)); - Assert.True(WellKnownSearchFilters.MatchesAtLeastOneCriteria(templateMatchInfo)); + Assert.IsTrue(WellKnownSearchFilters.MatchesAllCriteria(templateMatchInfo)); + Assert.IsTrue(WellKnownSearchFilters.MatchesAtLeastOneCriteria(templateMatchInfo)); } - [Fact(DisplayName = nameof(TypeMatch_NameMismatch_ReportsCorrectly))] + [TestMethod] public void TypeMatch_NameMismatch_ReportsCorrectly() { ITemplateInfo templateInfo = new MockTemplateInfo(); ITemplateMatchInfo templateMatchInfo = new TemplateMatchInfo(templateInfo); templateMatchInfo.AddMatchDisposition(new MatchInfo(MatchInfo.BuiltIn.Name, "test", MatchKind.Mismatch)); templateMatchInfo.AddMatchDisposition(new MatchInfo(MatchInfo.BuiltIn.Type, "test", MatchKind.Exact)); - Assert.False(WellKnownSearchFilters.MatchesAllCriteria(templateMatchInfo)); - Assert.True(WellKnownSearchFilters.MatchesAtLeastOneCriteria(templateMatchInfo)); + Assert.IsFalse(WellKnownSearchFilters.MatchesAllCriteria(templateMatchInfo)); + Assert.IsTrue(WellKnownSearchFilters.MatchesAtLeastOneCriteria(templateMatchInfo)); } - [Fact(DisplayName = nameof(TypeMatch_NamePartialMatch_ReportsCorrectly))] + [TestMethod] public void TypeMatch_NamePartialMatch_ReportsCorrectly() { ITemplateInfo templateInfo = new MockTemplateInfo(); ITemplateMatchInfo templateMatchInfo = new TemplateMatchInfo(templateInfo); templateMatchInfo.AddMatchDisposition(new MatchInfo(MatchInfo.BuiltIn.Name, "test", MatchKind.Partial)); templateMatchInfo.AddMatchDisposition(new MatchInfo(MatchInfo.BuiltIn.Type, "test", MatchKind.Exact)); - Assert.True(WellKnownSearchFilters.MatchesAllCriteria(templateMatchInfo)); - Assert.True(WellKnownSearchFilters.MatchesAtLeastOneCriteria(templateMatchInfo)); + Assert.IsTrue(WellKnownSearchFilters.MatchesAllCriteria(templateMatchInfo)); + Assert.IsTrue(WellKnownSearchFilters.MatchesAtLeastOneCriteria(templateMatchInfo)); } - [Fact(DisplayName = nameof(TypeMismatch_NameMatch_ReportsCorrectly))] + [TestMethod] public void TypeMismatch_NameMatch_ReportsCorrectly() { ITemplateInfo templateInfo = new MockTemplateInfo(); ITemplateMatchInfo templateMatchInfo = new TemplateMatchInfo(templateInfo); templateMatchInfo.AddMatchDisposition(new MatchInfo(MatchInfo.BuiltIn.Name, "test", MatchKind.Exact)); templateMatchInfo.AddMatchDisposition(new MatchInfo(MatchInfo.BuiltIn.Type, "test", MatchKind.Mismatch)); - Assert.False(WellKnownSearchFilters.MatchesAllCriteria(templateMatchInfo)); - Assert.True(WellKnownSearchFilters.MatchesAtLeastOneCriteria(templateMatchInfo)); + Assert.IsFalse(WellKnownSearchFilters.MatchesAllCriteria(templateMatchInfo)); + Assert.IsTrue(WellKnownSearchFilters.MatchesAtLeastOneCriteria(templateMatchInfo)); } - [Fact(DisplayName = nameof(TypeMismatch_NamePartialMatch_ReportsCorrectly))] + [TestMethod] public void TypeMismatch_NamePartialMatch_ReportsCorrectly() { ITemplateInfo templateInfo = new MockTemplateInfo(); ITemplateMatchInfo templateMatchInfo = new TemplateMatchInfo(templateInfo); templateMatchInfo.AddMatchDisposition(new MatchInfo(MatchInfo.BuiltIn.Name, "test", MatchKind.Partial)); templateMatchInfo.AddMatchDisposition(new MatchInfo(MatchInfo.BuiltIn.Type, "test", MatchKind.Mismatch)); - Assert.False(WellKnownSearchFilters.MatchesAllCriteria(templateMatchInfo)); - Assert.True(WellKnownSearchFilters.MatchesAtLeastOneCriteria(templateMatchInfo)); + Assert.IsFalse(WellKnownSearchFilters.MatchesAllCriteria(templateMatchInfo)); + Assert.IsTrue(WellKnownSearchFilters.MatchesAtLeastOneCriteria(templateMatchInfo)); } } } diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/TemplateResolutionTests/TemplateResolutionResultTests.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/TemplateResolutionTests/TemplateResolutionResultTests.cs index 62865f27ddb2..893ab6c43df3 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/TemplateResolutionTests/TemplateResolutionResultTests.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/TemplateResolutionTests/TemplateResolutionResultTests.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using FakeItEasy; @@ -7,9 +7,10 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests.TemplateResolutionTests { + [TestClass] public class TemplateResolutionResultTests { - [Fact] + [TestMethod] public void GetAllMatchedParametersList_Basic() { var templateMatchInfo = A.Fake(); @@ -22,11 +23,11 @@ public void GetAllMatchedParametersList_Basic() var parameters = TemplateResolutionResult.GetAllMatchedParametersList(new[] { templateMatchInfo }); - Assert.Single(parameters); - Assert.Equal("paramValue", parameters["--param"]); + Assert.HasCount(1, parameters); + Assert.AreEqual("paramValue", parameters["--param"]); } - [Fact] + [TestMethod] public void GetAllMatchedParametersList_FallbackToName() { var templateMatchInfo = A.Fake(); @@ -39,11 +40,11 @@ public void GetAllMatchedParametersList_FallbackToName() var parameters = TemplateResolutionResult.GetAllMatchedParametersList(new[] { templateMatchInfo }); - Assert.Single(parameters); - Assert.Equal("paramValue", parameters["param"]); + Assert.HasCount(1, parameters); + Assert.AreEqual("paramValue", parameters["param"]); } - [Fact] + [TestMethod] public void GetAllMatchedParametersList_PreservesValueIfGiven() { var templateMatchInfo = A.Fake(); @@ -63,15 +64,15 @@ public void GetAllMatchedParametersList_PreservesValueIfGiven() }); var parameters = TemplateResolutionResult.GetAllMatchedParametersList(new[] { templateMatchInfo, templateMatchInfo2 }); - Assert.Single(parameters); - Assert.Equal("paramValue", parameters["--param"]); + Assert.HasCount(1, parameters); + Assert.AreEqual("paramValue", parameters["--param"]); parameters = TemplateResolutionResult.GetAllMatchedParametersList(new[] { templateMatchInfo2, templateMatchInfo }); - Assert.Single(parameters); - Assert.Equal("paramValue", parameters["--param"]); + Assert.HasCount(1, parameters); + Assert.AreEqual("paramValue", parameters["--param"]); } - [Fact] + [TestMethod] public void GetAllMatchedParametersList_IgnoresNonParameterMatches() { var templateMatchInfo = A.Fake(); @@ -84,11 +85,11 @@ public void GetAllMatchedParametersList_IgnoresNonParameterMatches() }); var parameters = TemplateResolutionResult.GetAllMatchedParametersList(new[] { templateMatchInfo }); - Assert.Single(parameters); - Assert.Equal("paramValue", parameters["--param"]); + Assert.HasCount(1, parameters); + Assert.AreEqual("paramValue", parameters["--param"]); } - [Fact] + [TestMethod] public void GetAllMatchedParametersList_DoesNotDependOnMatchKind() { var templateMatchInfo = A.Fake(); @@ -102,10 +103,10 @@ public void GetAllMatchedParametersList_DoesNotDependOnMatchKind() }); var parameters = TemplateResolutionResult.GetAllMatchedParametersList(new[] { templateMatchInfo }); - Assert.Equal(3, parameters.Count); - Assert.Equal("paramValue", parameters["--param"]); - Assert.Equal("paramValue2", parameters["--param2"]); - Assert.Equal("paramValue3", parameters["--param3"]); + Assert.AreEqual(3, parameters.Count); + Assert.AreEqual("paramValue", parameters["--param"]); + Assert.AreEqual("paramValue2", parameters["--param2"]); + Assert.AreEqual("paramValue3", parameters["--param3"]); } } } diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/TemplateSearchCoordinatorTests.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/TemplateSearchCoordinatorTests.cs index 9bbb81829cc7..25908b2b7c44 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/TemplateSearchCoordinatorTests.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/TemplateSearchCoordinatorTests.cs @@ -20,8 +20,11 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests { + [TestClass] public class TemplateSearchCoordinatorTests : BaseTest { + public new TestContext TestContext { get; set; } = null!; + #pragma warning disable SA1308 // Variable names should not be prefixed #pragma warning disable SA1311 // Static readonly fields should begin with upper-case letter private static readonly ITemplatePackageInfo s_packOneInfo = new MockTemplatePackageInfo("PackOne", "1.0.0"); @@ -59,15 +62,15 @@ public class TemplateSearchCoordinatorTests : BaseTest #pragma warning restore SA1311 // Static readonly fields should begin with upper-case letter #pragma warning restore SA1308 // Variable names should not be prefixed - [Fact] + [TestMethod] public void CliHostSearchCacheDataReaderReturnsDefaultForEmptyObject() { var result = CliHostSearchCacheData.Reader(new JsonObject()); - Assert.Same(HostSpecificTemplateData.Default, result); + Assert.AreSame(HostSpecificTemplateData.Default, result); } - [Fact] + [TestMethod] public async Task CacheSearchNameMatchTest() { string cacheLocation = TestUtils.CreateTemporaryFolder(); @@ -86,7 +89,7 @@ public async Task CacheSearchNameMatchTest() ParseResult parseResult = myCommand.Parse($"new search foo"); SearchCommandArgs args = new((SearchCommand)parseResult.CommandResult.Command, parseResult); - IReadOnlyList templatePackages = await templatePackageManager.GetManagedTemplatePackagesAsync(false, TestContext.Current.CancellationToken); + IReadOnlyList templatePackages = await templatePackageManager.GetManagedTemplatePackagesAsync(false, TestContext.CancellationTokenSource.Token); TemplateSearchCoordinator searchCoordinator = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(engineEnvironmentSettings); CliSearchFiltersFactory factory = new(templatePackages); @@ -96,16 +99,16 @@ public async Task CacheSearchNameMatchTest() IReadOnlyList searchResults = await searchCoordinator.SearchAsync( factory.GetPackFilter(args), CliSearchFiltersFactory.GetMatchingTemplatesFilter(args), - TestContext.Current.CancellationToken); + TestContext.CancellationTokenSource.Token); - Assert.Single(searchResults); - Assert.Single(searchResults, result => result.Provider.Factory.DisplayName == "NuGet.org"); + Assert.HasCount(1, searchResults); + Assert.AreEqual(1, searchResults.Count(result => result.Provider.Factory.DisplayName == "NuGet.org")); SearchResult nugetSearchResults = searchResults.Single(result => result.Provider.Factory.DisplayName == "NuGet.org"); - Assert.Equal(2, nugetSearchResults.SearchHits.Count); - (ITemplatePackageInfo _, IReadOnlyList packOneMatchedTemplates) = Assert.Single(nugetSearchResults.SearchHits, pack => pack.PackageInfo.Name.Equals(s_packOneInfo.Name)); - (ITemplatePackageInfo _, IReadOnlyList packTwoMatchedTemplates) = Assert.Single(nugetSearchResults.SearchHits, pack => pack.PackageInfo.Name.Equals(s_packTwoInfo.Name)); - Assert.Single(packOneMatchedTemplates, t => string.Equals(t.Name, s_fooOneTemplate.Name)); - Assert.Single(packTwoMatchedTemplates, t => string.Equals(t.Name, s_fooTwoTemplate.Name)); + Assert.AreEqual(2, nugetSearchResults.SearchHits.Count); + (ITemplatePackageInfo _, IReadOnlyList packOneMatchedTemplates) = nugetSearchResults.SearchHits.Single(pack => pack.PackageInfo.Name.Equals(s_packOneInfo.Name)); + (ITemplatePackageInfo _, IReadOnlyList packTwoMatchedTemplates) = nugetSearchResults.SearchHits.Single(pack => pack.PackageInfo.Name.Equals(s_packTwoInfo.Name)); + Assert.AreEqual(1, packOneMatchedTemplates.Count(t => string.Equals(t.Name, s_fooOneTemplate.Name))); + Assert.AreEqual(1, packTwoMatchedTemplates.Count(t => string.Equals(t.Name, s_fooTwoTemplate.Name))); } } @@ -113,7 +116,8 @@ public async Task CacheSearchNameMatchTest() // The _fooOneTemplate is a non-match because of a framework choice param value mismatch. // But the _fooTwoTemplate matches because the framework choice is valid for that template. #pragma warning disable xUnit1004 // Test methods should not be skipped - [Fact(Skip = "Fails due to matching on template options is not implemented.")] + [TestMethod] + [Ignore("Fails due to matching on template options is not implemented.")] #pragma warning restore xUnit1004 // Test methods should not be skipped public async Task CacheSearchCliSymbolNameFilterTest() { @@ -133,7 +137,7 @@ public async Task CacheSearchCliSymbolNameFilterTest() ParseResult parseResult = myCommand.Parse($"new search foo --framework netcoreapp2.0"); SearchCommandArgs args = new((SearchCommand)parseResult.CommandResult.Command, parseResult); - IReadOnlyList templatePackages = await templatePackageManager.GetManagedTemplatePackagesAsync(false, TestContext.Current.CancellationToken); + IReadOnlyList templatePackages = await templatePackageManager.GetManagedTemplatePackagesAsync(false, TestContext.CancellationTokenSource.Token); TemplateSearchCoordinator searchCoordinator = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(engineEnvironmentSettings); CliSearchFiltersFactory factory = new(templatePackages); @@ -143,21 +147,22 @@ public async Task CacheSearchCliSymbolNameFilterTest() IReadOnlyList searchResults = await searchCoordinator.SearchAsync( factory.GetPackFilter(args), CliSearchFiltersFactory.GetMatchingTemplatesFilter(args), - TestContext.Current.CancellationToken); + TestContext.CancellationTokenSource.Token); - Assert.Single(searchResults); - Assert.Single(searchResults, result => result.Provider.Factory.DisplayName == "NuGet.org"); + Assert.HasCount(1, searchResults); + Assert.AreEqual(1, searchResults.Count(result => result.Provider.Factory.DisplayName == "NuGet.org")); SearchResult nugetSearchResults = searchResults.Single(result => result.Provider.Factory.DisplayName == "NuGet.org"); - Assert.Single(nugetSearchResults.SearchHits); + Assert.HasCount(1, nugetSearchResults.SearchHits); - (ITemplatePackageInfo _, IReadOnlyList packTwoMatchedTemplates) = Assert.Single(nugetSearchResults.SearchHits, pack => pack.PackageInfo.Name.Equals(s_packTwoInfo.Name)); - Assert.Single(packTwoMatchedTemplates, t => string.Equals(t.Name, s_fooTwoTemplate.Name)); + (ITemplatePackageInfo _, IReadOnlyList packTwoMatchedTemplates) = nugetSearchResults.SearchHits.Single(pack => pack.PackageInfo.Name.Equals(s_packTwoInfo.Name)); + Assert.AreEqual(1, packTwoMatchedTemplates.Count(t => string.Equals(t.Name, s_fooTwoTemplate.Name))); } } // test that an invalid symbol makes the search be a non-match #pragma warning disable xUnit1004 // Test methods should not be skipped - [Fact(Skip = "Fails due to matching on template options is not implemented.")] + [TestMethod] + [Ignore("Fails due to matching on template options is not implemented.")] #pragma warning restore xUnit1004 // Test methods should not be skipped public async Task CacheSearchCliSymbolNameMismatchFilterTest() { @@ -177,7 +182,7 @@ public async Task CacheSearchCliSymbolNameMismatchFilterTest() ParseResult parseResult = myCommand.Parse($"new search foo --tfm netcoreapp2.0"); SearchCommandArgs args = new((SearchCommand)parseResult.CommandResult.Command, parseResult); - IReadOnlyList templatePackages = await templatePackageManager.GetManagedTemplatePackagesAsync(false, TestContext.Current.CancellationToken); + IReadOnlyList templatePackages = await templatePackageManager.GetManagedTemplatePackagesAsync(false, TestContext.CancellationTokenSource.Token); TemplateSearchCoordinator searchCoordinator = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(engineEnvironmentSettings); CliSearchFiltersFactory factory = new(templatePackages); @@ -187,17 +192,17 @@ public async Task CacheSearchCliSymbolNameMismatchFilterTest() IReadOnlyList searchResults = await searchCoordinator.SearchAsync( factory.GetPackFilter(args), CliSearchFiltersFactory.GetMatchingTemplatesFilter(args), - TestContext.Current.CancellationToken); + TestContext.CancellationTokenSource.Token); - Assert.Single(searchResults); - Assert.Single(searchResults, result => result.Provider.Factory.DisplayName == "NuGet.org"); + Assert.HasCount(1, searchResults); + Assert.AreEqual(1, searchResults.Count(result => result.Provider.Factory.DisplayName == "NuGet.org")); SearchResult nugetSearchResults = searchResults.Single(result => result.Provider.Factory.DisplayName == "NuGet.org"); - Assert.Empty(nugetSearchResults.SearchHits); + Assert.IsFalse(nugetSearchResults.SearchHits.Any()); } } // Tests that the input language causes the correct match filtering. - [Fact] + [TestMethod] public async Task CacheSearchLanguageFilterTest() { string cacheLocation = TestUtils.CreateTemporaryFolder(); @@ -216,7 +221,7 @@ public async Task CacheSearchLanguageFilterTest() ParseResult parseResult = myCommand.Parse($"new search bar --language F#"); SearchCommandArgs args = new((SearchCommand)parseResult.CommandResult.Command, parseResult); - IReadOnlyList templatePackages = await templatePackageManager.GetManagedTemplatePackagesAsync(false, TestContext.Current.CancellationToken); + IReadOnlyList templatePackages = await templatePackageManager.GetManagedTemplatePackagesAsync(false, TestContext.CancellationTokenSource.Token); TemplateSearchCoordinator searchCoordinator = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(engineEnvironmentSettings); CliSearchFiltersFactory factory = new(templatePackages); @@ -226,22 +231,22 @@ public async Task CacheSearchLanguageFilterTest() IReadOnlyList searchResults = await searchCoordinator.SearchAsync( factory.GetPackFilter(args), CliSearchFiltersFactory.GetMatchingTemplatesFilter(args), - TestContext.Current.CancellationToken); + TestContext.CancellationTokenSource.Token); - Assert.Single(searchResults); - Assert.Single(searchResults, result => result.Provider.Factory.DisplayName == "NuGet.org"); + Assert.HasCount(1, searchResults); + Assert.AreEqual(1, searchResults.Count(result => result.Provider.Factory.DisplayName == "NuGet.org")); SearchResult nugetSearchResults = searchResults.Single(result => result.Provider.Factory.DisplayName == "NuGet.org"); - Assert.Single(nugetSearchResults.SearchHits); - Assert.Single(nugetSearchResults.SearchHits[0].MatchedTemplates); - Assert.Equal(s_packThreeInfo.Name, nugetSearchResults.SearchHits[0].PackageInfo.Name); - Assert.Equal(s_barFSharpTemplate.Name, nugetSearchResults.SearchHits[0].MatchedTemplates[0].Name); + Assert.HasCount(1, nugetSearchResults.SearchHits); + Assert.HasCount(1, nugetSearchResults.SearchHits[0].MatchedTemplates); + Assert.AreEqual(s_packThreeInfo.Name, nugetSearchResults.SearchHits[0].PackageInfo.Name); + Assert.AreEqual(s_barFSharpTemplate.Name, nugetSearchResults.SearchHits[0].MatchedTemplates[0].Name); } } - [Theory] - [InlineData("", "test", 1)] - [InlineData("foo", "test", 1)] - [InlineData("", "Wrong", 0)] + [TestMethod] + [DataRow("", "test", 1)] + [DataRow("foo", "test", 1)] + [DataRow("", "Wrong", 0)] public async Task CacheSearchAuthorFilterTest(string commandTemplate, string commandAuthor, int matchCount) { string cacheLocation = TestUtils.CreateTemporaryFolder(); @@ -260,7 +265,7 @@ public async Task CacheSearchAuthorFilterTest(string commandTemplate, string com ParseResult parseResult = myCommand.Parse($"new search {commandTemplate} --author {commandAuthor}"); SearchCommandArgs args = new((SearchCommand)parseResult.CommandResult.Command, parseResult); - IReadOnlyList templatePackages = await templatePackageManager.GetManagedTemplatePackagesAsync(false, TestContext.Current.CancellationToken); + IReadOnlyList templatePackages = await templatePackageManager.GetManagedTemplatePackagesAsync(false, TestContext.CancellationTokenSource.Token); TemplateSearchCoordinator searchCoordinator = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(engineEnvironmentSettings); CliSearchFiltersFactory factory = new(templatePackages); @@ -270,19 +275,19 @@ public async Task CacheSearchAuthorFilterTest(string commandTemplate, string com IReadOnlyList searchResults = await searchCoordinator.SearchAsync( factory.GetPackFilter(args), CliSearchFiltersFactory.GetMatchingTemplatesFilter(args), - TestContext.Current.CancellationToken); + TestContext.CancellationTokenSource.Token); - Assert.Single(searchResults); - Assert.Single(searchResults, result => result.Provider.Factory.DisplayName == "NuGet.org"); + Assert.HasCount(1, searchResults); + Assert.AreEqual(1, searchResults.Count(result => result.Provider.Factory.DisplayName == "NuGet.org")); SearchResult nugetSearchResults = searchResults.Single(result => result.Provider.Factory.DisplayName == "NuGet.org"); - Assert.Equal(matchCount, nugetSearchResults.SearchHits.Count); + Assert.AreEqual(matchCount, nugetSearchResults.SearchHits.Count); } } - [Theory] - [InlineData("", "project", 1)] - [InlineData("foo", "project", 1)] - [InlineData("", "Wrong", 0)] + [TestMethod] + [DataRow("", "project", 1)] + [DataRow("foo", "project", 1)] + [DataRow("", "Wrong", 0)] public async Task CacheSearchTypeFilterTest(string commandTemplate, string commandType, int matchCount) { string cacheLocation = TestUtils.CreateTemporaryFolder(); @@ -302,7 +307,7 @@ public async Task CacheSearchTypeFilterTest(string commandTemplate, string comma ParseResult parseResult = myCommand.Parse($"new search {commandTemplate} --type {commandType}"); SearchCommandArgs args = new((SearchCommand)parseResult.CommandResult.Command, parseResult); - IReadOnlyList templatePackages = await templatePackageManager.GetManagedTemplatePackagesAsync(false, TestContext.Current.CancellationToken); + IReadOnlyList templatePackages = await templatePackageManager.GetManagedTemplatePackagesAsync(false, TestContext.CancellationTokenSource.Token); TemplateSearchCoordinator searchCoordinator = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(engineEnvironmentSettings); CliSearchFiltersFactory factory = new(templatePackages); @@ -312,20 +317,20 @@ public async Task CacheSearchTypeFilterTest(string commandTemplate, string comma IReadOnlyList searchResults = await searchCoordinator.SearchAsync( factory.GetPackFilter(args), CliSearchFiltersFactory.GetMatchingTemplatesFilter(args), - TestContext.Current.CancellationToken); + TestContext.CancellationTokenSource.Token); - Assert.Single(searchResults); - Assert.Single(searchResults, result => result.Provider.Factory.DisplayName == "NuGet.org"); + Assert.HasCount(1, searchResults); + Assert.AreEqual(1, searchResults.Count(result => result.Provider.Factory.DisplayName == "NuGet.org")); SearchResult nugetSearchResults = searchResults.Single(result => result.Provider.Factory.DisplayName == "NuGet.org"); - Assert.Equal(matchCount, nugetSearchResults.SearchHits.Count); + Assert.AreEqual(matchCount, nugetSearchResults.SearchHits.Count); } } - [Theory] - [InlineData("", "Three", 1, 2)] - [InlineData("barC", "Three", 1, 2)] - [InlineData("foo", "Three", 0, 0)] - [InlineData("", "Wrong", 0, 0)] + [TestMethod] + [DataRow("", "Three", 1, 2)] + [DataRow("barC", "Three", 1, 2)] + [DataRow("foo", "Three", 0, 0)] + [DataRow("", "Wrong", 0, 0)] public async Task CacheSearchPackageFilterTest(string commandTemplate, string commandPackage, int packMatchCount, int templateMatchCount) { string cacheLocation = TestUtils.CreateTemporaryFolder(); @@ -345,7 +350,7 @@ public async Task CacheSearchPackageFilterTest(string commandTemplate, string co ParseResult parseResult = myCommand.Parse($"new search {commandTemplate} --package {commandPackage}"); SearchCommandArgs args = new((SearchCommand)parseResult.CommandResult.Command, parseResult); - IReadOnlyList templatePackages = await templatePackageManager.GetManagedTemplatePackagesAsync(false, TestContext.Current.CancellationToken); + IReadOnlyList templatePackages = await templatePackageManager.GetManagedTemplatePackagesAsync(false, TestContext.CancellationTokenSource.Token); TemplateSearchCoordinator searchCoordinator = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(engineEnvironmentSettings); CliSearchFiltersFactory factory = new(templatePackages); @@ -355,25 +360,25 @@ public async Task CacheSearchPackageFilterTest(string commandTemplate, string co IReadOnlyList searchResults = await searchCoordinator.SearchAsync( factory.GetPackFilter(args), CliSearchFiltersFactory.GetMatchingTemplatesFilter(args), - TestContext.Current.CancellationToken); + TestContext.CancellationTokenSource.Token); - Assert.Single(searchResults); - Assert.Single(searchResults, result => result.Provider.Factory.DisplayName == "NuGet.org"); + Assert.HasCount(1, searchResults); + Assert.AreEqual(1, searchResults.Count(result => result.Provider.Factory.DisplayName == "NuGet.org")); SearchResult nugetSearchResults = searchResults.Single(result => result.Provider.Factory.DisplayName == "NuGet.org"); - Assert.Equal(packMatchCount, nugetSearchResults.SearchHits.Count); + Assert.AreEqual(packMatchCount, nugetSearchResults.SearchHits.Count); if (packMatchCount != 0) { - Assert.Equal(templateMatchCount, nugetSearchResults.SearchHits.Single(res => res.PackageInfo.Name == s_packThreeInfo.Name).MatchedTemplates.Count); + Assert.AreEqual(templateMatchCount, nugetSearchResults.SearchHits.Single(res => res.PackageInfo.Name == s_packThreeInfo.Name).MatchedTemplates.Count); } } } - [Theory] - [InlineData("", "CSharp", 3, 3)] - [InlineData("bar", "FSharp", 1, 1)] - [InlineData("foo", "Library", 1, 1)] - [InlineData("", "Wrong", 0, 0)] - [InlineData("", "Lib", 0, 0)] + [TestMethod] + [DataRow("", "CSharp", 3, 3)] + [DataRow("bar", "FSharp", 1, 1)] + [DataRow("foo", "Library", 1, 1)] + [DataRow("", "Wrong", 0, 0)] + [DataRow("", "Lib", 0, 0)] public async Task CacheSearchTagFilterTest(string commandTemplate, string commandTag, int packMatchCount, int templateMatchCount) { string cacheLocation = TestUtils.CreateTemporaryFolder(); @@ -392,7 +397,7 @@ public async Task CacheSearchTagFilterTest(string commandTemplate, string comman ParseResult parseResult = myCommand.Parse($"new search {commandTemplate} --tag {commandTag}"); SearchCommandArgs args = new((SearchCommand)parseResult.CommandResult.Command, parseResult); - IReadOnlyList templatePackages = await templatePackageManager.GetManagedTemplatePackagesAsync(false, TestContext.Current.CancellationToken); + IReadOnlyList templatePackages = await templatePackageManager.GetManagedTemplatePackagesAsync(false, TestContext.CancellationTokenSource.Token); TemplateSearchCoordinator searchCoordinator = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(engineEnvironmentSettings); CliSearchFiltersFactory factory = new(templatePackages); @@ -402,20 +407,20 @@ public async Task CacheSearchTagFilterTest(string commandTemplate, string comman IReadOnlyList searchResults = await searchCoordinator.SearchAsync( factory.GetPackFilter(args), CliSearchFiltersFactory.GetMatchingTemplatesFilter(args), - TestContext.Current.CancellationToken); + TestContext.CancellationTokenSource.Token); - Assert.Single(searchResults); - Assert.Single(searchResults, result => result.Provider.Factory.DisplayName == "NuGet.org"); + Assert.HasCount(1, searchResults); + Assert.AreEqual(1, searchResults.Count(result => result.Provider.Factory.DisplayName == "NuGet.org")); SearchResult nugetSearchResults = searchResults.Single(result => result.Provider.Factory.DisplayName == "NuGet.org"); - Assert.Equal(packMatchCount, nugetSearchResults.SearchHits.Count); + Assert.AreEqual(packMatchCount, nugetSearchResults.SearchHits.Count); if (packMatchCount != 0) { - Assert.Equal(templateMatchCount, nugetSearchResults.SearchHits.Sum(res => res.MatchedTemplates.Count)); + Assert.AreEqual(templateMatchCount, nugetSearchResults.SearchHits.Sum(res => res.MatchedTemplates.Count)); } } } - [Fact] + [TestMethod] public async Task CacheSearchLanguageMismatchFilterTest() { string cacheLocation = TestUtils.CreateTemporaryFolder(); @@ -434,7 +439,7 @@ public async Task CacheSearchLanguageMismatchFilterTest() ParseResult parseResult = myCommand.Parse($"new search bar --language VB"); SearchCommandArgs args = new((SearchCommand)parseResult.CommandResult.Command, parseResult); - IReadOnlyList templatePackages = await templatePackageManager.GetManagedTemplatePackagesAsync(false, TestContext.Current.CancellationToken); + IReadOnlyList templatePackages = await templatePackageManager.GetManagedTemplatePackagesAsync(false, TestContext.CancellationTokenSource.Token); TemplateSearchCoordinator searchCoordinator = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(engineEnvironmentSettings); CliSearchFiltersFactory factory = new(templatePackages); @@ -444,16 +449,16 @@ public async Task CacheSearchLanguageMismatchFilterTest() IReadOnlyList searchResults = await searchCoordinator.SearchAsync( factory.GetPackFilter(args), CliSearchFiltersFactory.GetMatchingTemplatesFilter(args), - TestContext.Current.CancellationToken); + TestContext.CancellationTokenSource.Token); - Assert.Single(searchResults); - Assert.Single(searchResults, result => result.Provider.Factory.DisplayName == "NuGet.org"); + Assert.HasCount(1, searchResults); + Assert.AreEqual(1, searchResults.Count(result => result.Provider.Factory.DisplayName == "NuGet.org")); SearchResult nugetSearchResults = searchResults.Single(result => result.Provider.Factory.DisplayName == "NuGet.org"); - Assert.Empty(nugetSearchResults.SearchHits); + Assert.IsFalse(nugetSearchResults.SearchHits.Any()); } } - [Fact] + [TestMethod] public async Task CacheSkipInvalidTemplatesTest() { string cacheLocation = TestUtils.CreateTemporaryFolder(); @@ -471,7 +476,7 @@ public async Task CacheSkipInvalidTemplatesTest() ParseResult parseResult = myCommand.Parse($"new search --unknown"); SearchCommandArgs args = new((SearchCommand)parseResult.CommandResult.Command, parseResult); - IReadOnlyList templatePackages = await templatePackageManager.GetManagedTemplatePackagesAsync(false, TestContext.Current.CancellationToken); + IReadOnlyList templatePackages = await templatePackageManager.GetManagedTemplatePackagesAsync(false, TestContext.CancellationTokenSource.Token); TemplateSearchCoordinator searchCoordinator = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(engineEnvironmentSettings); CliSearchFiltersFactory factory = new(templatePackages); @@ -479,28 +484,28 @@ public async Task CacheSkipInvalidTemplatesTest() IReadOnlyList searchResults = await searchCoordinator.SearchAsync( factory.GetPackFilter(args), CliSearchFiltersFactory.GetMatchingTemplatesFilter(args), - TestContext.Current.CancellationToken); + TestContext.CancellationTokenSource.Token); - Assert.Single(searchResults); - Assert.Single(searchResults, result => result.Provider.Factory.DisplayName == "NuGet.org"); + Assert.HasCount(1, searchResults); + Assert.AreEqual(1, searchResults.Count(result => result.Provider.Factory.DisplayName == "NuGet.org")); SearchResult nugetSearchResults = searchResults.Single(result => result.Provider.Factory.DisplayName == "NuGet.org"); - Assert.Empty(nugetSearchResults.SearchHits); + Assert.IsFalse(nugetSearchResults.SearchHits.Any()); } - [Theory] - [InlineData(12489, 3198, 1)] - [InlineData(3198, 12489, -1)] - [InlineData(124, 3198, -1)] - [InlineData(3198, 124, 1)] - [InlineData(0, 0, 0)] - [InlineData(-10, 0, 0)] - [InlineData(987, 0, 1)] - [InlineData(0, 10, -1)] - [InlineData(987, 1, 0)] - [InlineData(123, 345, 0)] + [TestMethod] + [DataRow(12489, 3198, 1)] + [DataRow(3198, 12489, -1)] + [DataRow(124, 3198, -1)] + [DataRow(3198, 124, 1)] + [DataRow(0, 0, 0)] + [DataRow(-10, 0, 0)] + [DataRow(987, 0, 1)] + [DataRow(0, 10, -1)] + [DataRow(987, 1, 0)] + [DataRow(123, 345, 0)] public void TestCompare(long x, long y, int expectedOutcome) { - Assert.Equal(expectedOutcome, CliTemplateSearchCoordinator.SearchResultTableRow.TotalDownloadsComparer.Compare(x, y)); + Assert.AreEqual(expectedOutcome, CliTemplateSearchCoordinator.SearchResultTableRow.TotalDownloadsComparer.Compare(x, y)); } #pragma warning disable CS0618 // Type or member is obsolete