diff --git a/test/Microsoft.DotNet.Test.MSTest.Utilities/TestLoggerFactory.cs b/test/Microsoft.DotNet.Test.MSTest.Utilities/TestLoggerFactory.cs index 15485a93f137..aa39246c863b 100644 --- a/test/Microsoft.DotNet.Test.MSTest.Utilities/TestLoggerFactory.cs +++ b/test/Microsoft.DotNet.Test.MSTest.Utilities/TestLoggerFactory.cs @@ -13,36 +13,17 @@ namespace Microsoft.DotNet.Test.MSTest.Utilities; /// public sealed class TestLoggerFactory : ILoggerFactory { - private readonly List _loggerProviders = new(); - private readonly List _factories = new(); + private readonly ILoggerFactory _loggerFactory; public TestLoggerFactory(TestContext? testContext = null) { - if (testContext is not null) - { - _loggerProviders.Add(new TestContextLoggerProvider(testContext)); - } - } - - public void Dispose() - { - while (_factories.Count > 0) - { - ILoggerFactory factory = _factories[0]; - _factories.RemoveAt(0); - factory.Dispose(); - } - } - - public ILogger CreateLogger(string categoryName) - { - ILoggerFactory loggerFactory = LoggerFactory.Create(builder => + _loggerFactory = LoggerFactory.Create(builder => { builder.SetMinimumLevel(LogLevel.Trace); - foreach (ILoggerProvider loggerProvider in _loggerProviders) + if (testContext is not null) { - builder.AddProvider(loggerProvider); + builder.AddProvider(new TestContextLoggerProvider(testContext)); } builder.AddSimpleConsole(options => @@ -52,14 +33,15 @@ public ILogger CreateLogger(string categoryName) options.IncludeScopes = true; }); }); - - _factories.Add(loggerFactory); - return loggerFactory.CreateLogger(categoryName); } + public void Dispose() => _loggerFactory.Dispose(); + + public ILogger CreateLogger(string categoryName) => _loggerFactory.CreateLogger(categoryName); + public ILogger CreateLogger() => CreateLogger("Test Host"); - public void AddProvider(ILoggerProvider provider) => _loggerProviders.Add(provider); + public void AddProvider(ILoggerProvider provider) => _loggerFactory.AddProvider(provider); private sealed class TestContextLoggerProvider(TestContext testContext) : ILoggerProvider { diff --git a/test/Microsoft.NET.Build.Containers.IntegrationTests/CreateImageIndexTests.cs b/test/Microsoft.NET.Build.Containers.IntegrationTests/CreateImageIndexTests.cs index 2ceadd1e46b1..55ba6468ea36 100644 --- a/test/Microsoft.NET.Build.Containers.IntegrationTests/CreateImageIndexTests.cs +++ b/test/Microsoft.NET.Build.Containers.IntegrationTests/CreateImageIndexTests.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; @@ -6,7 +6,6 @@ using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Microsoft.NET.Build.Containers.IntegrationTests; -using Microsoft.NET.Build.Containers.UnitTests; using NuGet.Protocol; using Task = System.Threading.Tasks.Task; diff --git a/test/Microsoft.NET.Build.Containers.IntegrationTests/CreateNewImageTests.cs b/test/Microsoft.NET.Build.Containers.IntegrationTests/CreateNewImageTests.cs index 774ce35156c5..5293fce8e81c 100644 --- a/test/Microsoft.NET.Build.Containers.IntegrationTests/CreateNewImageTests.cs +++ b/test/Microsoft.NET.Build.Containers.IntegrationTests/CreateNewImageTests.cs @@ -6,7 +6,6 @@ using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Microsoft.NET.Build.Containers.IntegrationTests; -using Microsoft.NET.Build.Containers.UnitTests; namespace Microsoft.NET.Build.Containers.Tasks.IntegrationTests; diff --git a/test/Microsoft.NET.Build.Containers.IntegrationTests/DockerAvailableAttributes.cs b/test/Microsoft.NET.Build.Containers.IntegrationTests/DockerAvailableAttributes.cs new file mode 100644 index 000000000000..aabc4299099f --- /dev/null +++ b/test/Microsoft.NET.Build.Containers.IntegrationTests/DockerAvailableAttributes.cs @@ -0,0 +1,84 @@ +// 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; + +namespace Microsoft.NET.Build.Containers.IntegrationTests; + +// xUnit-flavoured Docker availability attributes for the IntegrationTests project. +// +// The companion Microsoft.NET.Build.Containers.UnitTests project was migrated to +// MSTest.Sdk and now exposes a `DockerUnavailableCondition : ConditionBaseAttribute` +// instead of the previous `DockerAvailableFactAttribute : FactAttribute` / +// `DockerAvailableTheoryAttribute : TheoryAttribute` pair. IntegrationTests is still +// an xUnit project, so it needs its own xUnit-compatible attributes. +// +// Implementation mirrors the previous UnitTests version: each invocation shells out to +// the docker CLI on first use and caches the result. Caching lives in DockerCliStatus +// (file-scoped class) so it does not pollute the rest of the namespace. + +public class DockerAvailableTheoryAttribute : TheoryAttribute +{ + public static string LocalRegistry => DockerCliStatus.LocalRegistry; + + public DockerAvailableTheoryAttribute( + bool skipPodman = false, + [CallerFilePath] string? sourceFilePath = null, + [CallerLineNumber] int sourceLineNumber = 0) + : base(sourceFilePath, sourceLineNumber) + { + if (!DockerCliStatus.IsAvailable) + { + base.Skip = "Skipping test because Docker is not available on this host."; + } + + if (skipPodman && DockerCliStatus.Command == DockerCli.PodmanCommand) + { + base.Skip = $"Skipping test with {DockerCliStatus.Command} cli."; + } + } +} + +public class DockerAvailableFactAttribute : FactAttribute +{ + public static string LocalRegistry => DockerCliStatus.LocalRegistry; + + public DockerAvailableFactAttribute( + bool skipPodman = false, + bool checkContainerdStoreAvailability = false, + [CallerFilePath] string? sourceFilePath = null, + [CallerLineNumber] int sourceLineNumber = 0) + : base(sourceFilePath, sourceLineNumber) + { + if (!DockerCliStatus.IsAvailable) + { + base.Skip = "Skipping test because Docker is not available on this host."; + } + else if (checkContainerdStoreAvailability && DockerCliStatus.Command != DockerCli.PodmanCommand && !DockerCli.IsContainerdStoreEnabledForDocker()) + { + base.Skip = "Skipping test because Docker daemon is not using containerd as the storage driver."; + } + else if (skipPodman && DockerCliStatus.Command == DockerCli.PodmanCommand) + { + base.Skip = $"Skipping test with {DockerCliStatus.Command} cli."; + } + } +} + +// tiny optimization - since there are many instances of these attributes we should only +// query the daemon status once. +static file class DockerCliStatus +{ + public static readonly bool IsAvailable; + public static readonly string? Command; + public static string LocalRegistry + => Command == DockerCli.PodmanCommand ? KnownLocalRegistryTypes.Podman + : KnownLocalRegistryTypes.Docker; + + static DockerCliStatus() + { + DockerCli cli = new(new Microsoft.NET.TestFramework.TestLoggerFactory()); + IsAvailable = cli.IsAvailable(); + Command = cli.GetCommand(); + } +} diff --git a/test/Microsoft.NET.Build.Containers.IntegrationTests/DockerRegistryTests.cs b/test/Microsoft.NET.Build.Containers.IntegrationTests/DockerRegistryTests.cs index 24bfe1f73a89..9a0642013945 100644 --- a/test/Microsoft.NET.Build.Containers.IntegrationTests/DockerRegistryTests.cs +++ b/test/Microsoft.NET.Build.Containers.IntegrationTests/DockerRegistryTests.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.NET.Build.Containers.UnitTests; using ILogger = Microsoft.Extensions.Logging.ILogger; namespace Microsoft.NET.Build.Containers.IntegrationTests; diff --git a/test/Microsoft.NET.Build.Containers.IntegrationTests/EndToEndTests.cs b/test/Microsoft.NET.Build.Containers.IntegrationTests/EndToEndTests.cs index 8a8678cae54e..e4e5a10649e1 100644 --- a/test/Microsoft.NET.Build.Containers.IntegrationTests/EndToEndTests.cs +++ b/test/Microsoft.NET.Build.Containers.IntegrationTests/EndToEndTests.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.Formats.Tar; @@ -9,7 +9,6 @@ using Microsoft.DotNet.Cli.Utils; using Microsoft.NET.Build.Containers.LocalDaemons; using Microsoft.NET.Build.Containers.Resources; -using Microsoft.NET.Build.Containers.UnitTests; using ILogger = Microsoft.Extensions.Logging.ILogger; namespace Microsoft.NET.Build.Containers.IntegrationTests; diff --git a/test/Microsoft.NET.Build.Containers.IntegrationTests/Microsoft.NET.Build.Containers.IntegrationTests.csproj b/test/Microsoft.NET.Build.Containers.IntegrationTests/Microsoft.NET.Build.Containers.IntegrationTests.csproj index 2b580a92681a..1917229db766 100644 --- a/test/Microsoft.NET.Build.Containers.IntegrationTests/Microsoft.NET.Build.Containers.IntegrationTests.csproj +++ b/test/Microsoft.NET.Build.Containers.IntegrationTests/Microsoft.NET.Build.Containers.IntegrationTests.csproj @@ -25,7 +25,6 @@ - diff --git a/test/Microsoft.NET.Build.Containers.IntegrationTests/ParseContainerPropertiesTests.cs b/test/Microsoft.NET.Build.Containers.IntegrationTests/ParseContainerPropertiesTests.cs index 29790ea7e203..d5355fd67b91 100644 --- a/test/Microsoft.NET.Build.Containers.IntegrationTests/ParseContainerPropertiesTests.cs +++ b/test/Microsoft.NET.Build.Containers.IntegrationTests/ParseContainerPropertiesTests.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.NET.Build.Containers.IntegrationTests; -using Microsoft.NET.Build.Containers.UnitTests; using static Microsoft.NET.Build.Containers.KnownStrings; using static Microsoft.NET.Build.Containers.KnownStrings.Properties; diff --git a/test/Microsoft.NET.Build.Containers.UnitTests/AuthHandshakeMessageHandlerTests.cs b/test/Microsoft.NET.Build.Containers.UnitTests/AuthHandshakeMessageHandlerTests.cs index 21304ca608a0..2f8d256769d8 100644 --- a/test/Microsoft.NET.Build.Containers.UnitTests/AuthHandshakeMessageHandlerTests.cs +++ b/test/Microsoft.NET.Build.Containers.UnitTests/AuthHandshakeMessageHandlerTests.cs @@ -9,18 +9,26 @@ namespace Microsoft.NET.Build.Containers.UnitTests { + [TestClass] + // These tests mutate process-global environment variables (REGISTRY_AUTH_FILE and the + // registry credential vars) and rely on AuthHandshakeMessageHandler's static auth-header + // cache keyed by a shared registry name. Under MSTest method-level parallelism (the repo + // default) the methods/data rows race on that global state, so run them sequentially. + [DoNotParallelize] public class AuthHandshakeMessageHandlerTests { + public TestContext TestContext { get; set; } = default!; + private const string TestRegistryName = "registry.test"; private const string RequestUrl = $"https://{TestRegistryName}/v2"; private const string BearerRealmUrl = $"https://bearer.test/token"; - [Theory] - [InlineData("SDK_CONTAINER_REGISTRY_UNAME", "SDK_CONTAINER_REGISTRY_PWORD", (int)RegistryMode.Push)] - [InlineData("DOTNET_CONTAINER_PUSH_REGISTRY_UNAME", "DOTNET_CONTAINER_PUSH_REGISTRY_PWORD", (int)RegistryMode.Push)] - [InlineData("DOTNET_CONTAINER_PULL_REGISTRY_UNAME", "DOTNET_CONTAINER_PULL_REGISTRY_PWORD", (int)RegistryMode.Pull)] - [InlineData("DOTNET_CONTAINER_PULL_REGISTRY_UNAME", "DOTNET_CONTAINER_PULL_REGISTRY_PWORD", (int)RegistryMode.PullFromOutput)] - [InlineData("SDK_CONTAINER_REGISTRY_UNAME", "SDK_CONTAINER_REGISTRY_PWORD", (int)RegistryMode.PullFromOutput)] + [TestMethod] + [DataRow("SDK_CONTAINER_REGISTRY_UNAME", "SDK_CONTAINER_REGISTRY_PWORD", (int)RegistryMode.Push)] + [DataRow("DOTNET_CONTAINER_PUSH_REGISTRY_UNAME", "DOTNET_CONTAINER_PUSH_REGISTRY_PWORD", (int)RegistryMode.Push)] + [DataRow("DOTNET_CONTAINER_PULL_REGISTRY_UNAME", "DOTNET_CONTAINER_PULL_REGISTRY_PWORD", (int)RegistryMode.Pull)] + [DataRow("DOTNET_CONTAINER_PULL_REGISTRY_UNAME", "DOTNET_CONTAINER_PULL_REGISTRY_PWORD", (int)RegistryMode.PullFromOutput)] + [DataRow("SDK_CONTAINER_REGISTRY_UNAME", "SDK_CONTAINER_REGISTRY_PWORD", (int)RegistryMode.PullFromOutput)] public void GetDockerCredentialsFromEnvironment_ReturnsCorrectValues(string unameVarName, string pwordVarName, int mode) { string? originalUnameValue = Environment.GetEnvironmentVariable(unameVarName); @@ -31,8 +39,8 @@ public void GetDockerCredentialsFromEnvironment_ReturnsCorrectValues(string unam if (AuthHandshakeMessageHandler.GetDockerCredentialsFromEnvironment((RegistryMode)mode) is (string credU, string credP)) { - Assert.Equal("uname", credU); - Assert.Equal("pword", credP); + Assert.AreEqual("uname", credU); + Assert.AreEqual("pword", credP); } else { @@ -45,8 +53,8 @@ public void GetDockerCredentialsFromEnvironment_ReturnsCorrectValues(string unam Environment.SetEnvironmentVariable(pwordVarName, originalPwordValue); } - [Theory] - [MemberData(nameof(GetAuthenticateTestData))] + [TestMethod] + [DynamicData(nameof(GetAuthenticateTestData))] public async Task Authenticate(string authConf, Func server) { string authFile = Path.GetTempFileName(); @@ -58,8 +66,8 @@ public async Task Authenticate(string authConf, Func ServerWithBearerAuth(string if (request.RequestUri?.ToString() == BearerRealmUrl) { // Verify the method is the expected one. - Assert.Equal(method, request.Method); + Assert.AreEqual(method, request.Method); // Verify the query parameter are the expected ones. AssertParametersAreEqual(queryParameters, request.RequestUri.Query); @@ -229,13 +237,13 @@ static Func ServerWithBearerAuth(string AuthenticationHeaderValue? header = request.Headers.Authorization; if (authHeader is not null) { - Assert.NotNull(header); - Assert.Equal(header.Scheme, authHeader.Scheme); - Assert.Equal(header.Parameter, authHeader.Parameter); + Assert.IsNotNull(header); + Assert.AreEqual(header.Scheme, authHeader.Scheme); + Assert.AreEqual(header.Parameter, authHeader.Parameter); } else { - Assert.Null(header); + Assert.IsNull(header); } // Verify the content. @@ -264,9 +272,9 @@ static void AssertParametersAreEqual(Dictionary expected, string NameValueCollection parsedParameters = HttpUtility.ParseQueryString(actual); foreach (var parameter in expected) { - Assert.Equal(parameter.Value, parsedParameters.Get(parameter.Key)); + Assert.AreEqual(parameter.Value, parsedParameters.Get(parameter.Key)); } - Assert.Equal(expected.Count, parsedParameters.AllKeys.Length); + Assert.HasCount(expected.Count, parsedParameters.AllKeys); } } @@ -310,15 +318,15 @@ protected override Task SendAsync(HttpRequestMessage reques /// non-default ports and public-routable IP literals), and http realms are accepted only /// when the registry is configured as insecure (explicit operator opt-in to downgrade). /// - [Theory] - [InlineData("https://auth.example.com/token", false)] - [InlineData("https://auth.example.com:8443/token", false)] - [InlineData("https://203.0.113.10/token", false)] // TEST-NET-3 doc IP, outside every blocked range, must be allowed - [InlineData("http://auth.example.com/token", true)] // downgrade permitted only when insecure + [TestMethod] + [DataRow("https://auth.example.com/token", false)] + [DataRow("https://auth.example.com:8443/token", false)] + [DataRow("https://203.0.113.10/token", false)] // TEST-NET-3 doc IP, outside every blocked range, must be allowed + [DataRow("http://auth.example.com/token", true)] // downgrade permitted only when insecure public void ValidateRealmUri_AcceptsAllowedSchemes(string realm, bool isInsecureRegistry) { Uri uri = AuthHandshakeMessageHandler.ValidateRealmUri(realm, "registry.example.com", isInsecureRegistry); - Assert.Equal(realm, uri.AbsoluteUri); + Assert.AreEqual(realm, uri.AbsoluteUri); } /// @@ -326,14 +334,14 @@ public void ValidateRealmUri_AcceptsAllowedSchemes(string realm, bool isInsecure /// registry, and any non-http(s) scheme regardless of the insecure flag. Defends /// against credential downgrade and exfiltration to non-HTTP transports. /// - [Theory] - [InlineData("http://auth.example.com/token", false)] // http on secure registry - [InlineData("ftp://auth.example.com/token", false)] // unsupported scheme on secure registry - [InlineData("ftp://auth.example.com/token", true)] // unsupported scheme stays rejected even when insecure - [InlineData("file:///etc/passwd", false)] // file scheme + [TestMethod] + [DataRow("http://auth.example.com/token", false)] // http on secure registry + [DataRow("ftp://auth.example.com/token", false)] // unsupported scheme on secure registry + [DataRow("ftp://auth.example.com/token", true)] // unsupported scheme stays rejected even when insecure + [DataRow("file:///etc/passwd", false)] // file scheme public void ValidateRealmUri_RejectsDisallowedSchemes(string realm, bool isInsecureRegistry) { - Assert.Throws(() => + Assert.ThrowsExactly(() => AuthHandshakeMessageHandler.ValidateRealmUri(realm, "registry.example.com", isInsecureRegistry)); } @@ -343,13 +351,13 @@ public void ValidateRealmUri_RejectsDisallowedSchemes(string realm, bool isInsec /// rather than producing an opaque /// downstream failure. /// - [Theory] - [InlineData("not a url")] - [InlineData("/relative/path")] - [InlineData("auth.example.com/token")] + [TestMethod] + [DataRow("not a url")] + [DataRow("/relative/path")] + [DataRow("auth.example.com/token")] public void ValidateRealmUri_RejectsRelativeOrUnparseableRealms(string realm) { - Assert.Throws(() => + Assert.ThrowsExactly(() => AuthHandshakeMessageHandler.ValidateRealmUri(realm, "registry.example.com", isInsecureRegistry: false)); } @@ -360,42 +368,42 @@ public void ValidateRealmUri_RejectsRelativeOrUnparseableRealms(string realm) /// hardening: Unicode-dot forms (U+FF0E, U+3002) that a runtime would resolve back to /// a blocked IPv4 literal are rejected even though they appear as DNS-typed hosts. /// - [Theory] + [TestMethod] // IPv4 ranges that must be blocked. - [InlineData("https://127.0.0.1/token")] // loopback - [InlineData("https://127.5.6.7/token")] // 127/8 - [InlineData("https://0.0.0.0/token")] // unspecified - [InlineData("https://10.0.0.5/token")] // private - [InlineData("https://172.16.0.1/token")] // private - [InlineData("https://172.31.255.255/token")] // private edge - [InlineData("https://192.168.1.5/token")] // private - [InlineData("https://169.254.169.254/token")] // link-local (cloud metadata) - [InlineData("https://224.0.0.1/token")] // link-local multicast + [DataRow("https://127.0.0.1/token")] // loopback + [DataRow("https://127.5.6.7/token")] // 127/8 + [DataRow("https://0.0.0.0/token")] // unspecified + [DataRow("https://10.0.0.5/token")] // private + [DataRow("https://172.16.0.1/token")] // private + [DataRow("https://172.31.255.255/token")] // private edge + [DataRow("https://192.168.1.5/token")] // private + [DataRow("https://169.254.169.254/token")] // link-local (cloud metadata) + [DataRow("https://224.0.0.1/token")] // link-local multicast // IPv6 ranges that must be blocked. - [InlineData("https://[::1]/token")] // loopback - [InlineData("https://[::]/token")] // unspecified - [InlineData("https://[fe80::1]/token")] // link-local - [InlineData("https://[ff02::1]/token")] // link-local multicast - [InlineData("https://[fc00::1]/token")] // unique-local (private) - [InlineData("https://[fec0::1]/token")] // site-local (deprecated, still treated as private) - [InlineData("https://[::ffff:127.0.0.1]/token")] // IPv4-mapped IPv6 of loopback - [InlineData("https://[::ffff:169.254.169.254]/token")] // IPv4-mapped IPv6 of metadata + [DataRow("https://[::1]/token")] // loopback + [DataRow("https://[::]/token")] // unspecified + [DataRow("https://[fe80::1]/token")] // link-local + [DataRow("https://[ff02::1]/token")] // link-local multicast + [DataRow("https://[fc00::1]/token")] // unique-local (private) + [DataRow("https://[fec0::1]/token")] // site-local (deprecated, still treated as private) + [DataRow("https://[::ffff:127.0.0.1]/token")] // IPv4-mapped IPv6 of loopback + [DataRow("https://[::ffff:169.254.169.254]/token")] // IPv4-mapped IPv6 of metadata // Unicode-dot canonicalization bypasses: U+FF0E (fullwidth full stop) and U+3002 // (ideographic full stop) appear as DNS to Uri.HostNameType but Uri.IdnHost canonicalizes // them back to the underlying IPv4 literal that HttpClient actually connects to. - [InlineData("https://127\uFF0E0\uFF0E0\uFF0E1/token")] - [InlineData("https://169\uFF0E254\uFF0E169\uFF0E254/token")] - [InlineData("https://10\uFF0E0\uFF0E0\uFF0E1/token")] - [InlineData("https://127\u30020\u30020\u30021/token")] + [DataRow("https://127\uFF0E0\uFF0E0\uFF0E1/token")] + [DataRow("https://169\uFF0E254\uFF0E169\uFF0E254/token")] + [DataRow("https://10\uFF0E0\uFF0E0\uFF0E1/token")] + [DataRow("https://127\u30020\u30020\u30021/token")] // FQDN root-zone trailing dot: Uri.IdnHost preserves the trailing "." so neither // IPAddress.TryParse nor a plain DNS name match would catch these without normalization, // but every resolver treats "127.0.0.1." as equivalent to "127.0.0.1". - [InlineData("https://127.0.0.1./token")] - [InlineData("https://169.254.169.254./token")] - [InlineData("https://10.0.0.5./token")] + [DataRow("https://127.0.0.1./token")] + [DataRow("https://169.254.169.254./token")] + [DataRow("https://10.0.0.5./token")] public void ValidateRealmUri_RejectsBlockedIpLiterals_OnSecureRegistry(string realm) { - Assert.Throws(() => + Assert.ThrowsExactly(() => AuthHandshakeMessageHandler.ValidateRealmUri(realm, "registry.example.com", isInsecureRegistry: false)); } @@ -405,21 +413,21 @@ public void ValidateRealmUri_RejectsBlockedIpLiterals_OnSecureRegistry(string re /// host, and lookalike hostnames such as localhost.example.com do not trigger /// the RFC 6761 localhost-loopback exception. /// - [Theory] + [TestMethod] // Even for insecure registries, IP-literal realm hosts are blocked unless they match the registry host. - [InlineData("https://169.254.169.254/token", "192.168.1.5:5000")] - [InlineData("https://10.0.0.5/token", "192.168.1.5:5000")] - [InlineData("https://[::1]/token", "192.168.1.5:5000")] + [DataRow("https://169.254.169.254/token", "192.168.1.5:5000")] + [DataRow("https://10.0.0.5/token", "192.168.1.5:5000")] + [DataRow("https://[::1]/token", "192.168.1.5:5000")] // The localhost exception only widens loopback (RFC 6761) - non-loopback blocked IPs // are still rejected even when the registry name is "localhost". - [InlineData("https://169.254.169.254/token", "localhost:5000")] - [InlineData("https://192.168.1.5/token", "localhost:5000")] + [DataRow("https://169.254.169.254/token", "localhost:5000")] + [DataRow("https://192.168.1.5/token", "localhost:5000")] // A name that merely contains "localhost" but isn't localhost or a *.localhost subdomain // does not get the exception (e.g. "localhost.example.com" is a public DNS name). - [InlineData("https://127.0.0.1/token", "localhost.example.com:5000")] + [DataRow("https://127.0.0.1/token", "localhost.example.com:5000")] public void ValidateRealmUri_RejectsBlockedIpLiterals_OnInsecureRegistryWhenHostsDiffer(string realm, string registryName) { - Assert.Throws(() => + Assert.ThrowsExactly(() => AuthHandshakeMessageHandler.ValidateRealmUri(realm, registryName, isInsecureRegistry: true)); } @@ -428,24 +436,24 @@ public void ValidateRealmUri_RejectsBlockedIpLiterals_OnInsecureRegistryWhenHost /// registry is insecure and the realm host refers to the same machine as the registry /// host. /// - [Theory] + [TestMethod] // Exception: when registry is insecure AND realm host equals the registry host (port-independent), // an otherwise-blocked IP literal is permitted to support legitimate private/on-prem dev registries. - [InlineData("http://192.168.1.5/auth", "192.168.1.5")] - [InlineData("http://192.168.1.5:6000/auth", "192.168.1.5:5000")] // same host, different port - [InlineData("https://192.168.1.5/auth", "192.168.1.5:5000")] - [InlineData("http://127.0.0.1:7000/auth", "127.0.0.1:5000")] - [InlineData("https://[::1]:7000/auth", "[::1]:5000")] + [DataRow("http://192.168.1.5/auth", "192.168.1.5")] + [DataRow("http://192.168.1.5:6000/auth", "192.168.1.5:5000")] // same host, different port + [DataRow("https://192.168.1.5/auth", "192.168.1.5:5000")] + [DataRow("http://127.0.0.1:7000/auth", "127.0.0.1:5000")] + [DataRow("https://[::1]:7000/auth", "[::1]:5000")] // RFC 6761: "localhost" (and *.localhost subdomains) are reserved for loopback, so a // localhost-named registry returning a loopback IP-literal realm is legitimate. - [InlineData("http://127.0.0.1:5000/auth", "localhost:5000")] - [InlineData("http://127.0.0.1:5000/auth", "LocalHost:5000")] // case-insensitive - [InlineData("http://[::1]:5000/auth", "localhost:5000")] - [InlineData("http://127.0.0.1:5000/auth", "registry.localhost:5000")] + [DataRow("http://127.0.0.1:5000/auth", "localhost:5000")] + [DataRow("http://127.0.0.1:5000/auth", "LocalHost:5000")] // case-insensitive + [DataRow("http://[::1]:5000/auth", "localhost:5000")] + [DataRow("http://127.0.0.1:5000/auth", "registry.localhost:5000")] public void ValidateRealmUri_AllowsMatchingIpLiteralWhenInsecure(string realm, string registryName) { Uri uri = AuthHandshakeMessageHandler.ValidateRealmUri(realm, registryName, isInsecureRegistry: true); - Assert.Equal(realm, uri.AbsoluteUri); + Assert.AreEqual(realm, uri.AbsoluteUri); } /// @@ -455,28 +463,28 @@ public void ValidateRealmUri_AllowsMatchingIpLiteralWhenInsecure(string realm, s /// 127.0.0.1 even though they appear as DNS to Uri.HostNameType. Both the /// secure-registry case and the insecure-but-non-matching-registry case are covered. /// - [Theory] + [TestMethod] // Secure registry: loopback-name realms are always rejected. - [InlineData("https://localhost/token", "registry.example.com", false)] - [InlineData("https://localhost:5000/token", "registry.example.com", false)] - [InlineData("https://foo.localhost/token", "registry.example.com", false)] - [InlineData("https://LOCALHOST/token", "registry.example.com", false)] // case-insensitive + [DataRow("https://localhost/token", "registry.example.com", false)] + [DataRow("https://localhost:5000/token", "registry.example.com", false)] + [DataRow("https://foo.localhost/token", "registry.example.com", false)] + [DataRow("https://LOCALHOST/token", "registry.example.com", false)] // case-insensitive // FQDN root-zone trailing dot: "localhost." is equivalent to "localhost" to every // resolver. Uri.IdnHost preserves the dot so the validator must normalize it away. - [InlineData("https://localhost./token", "registry.example.com", false)] - [InlineData("https://foo.localhost./token", "registry.example.com", false)] + [DataRow("https://localhost./token", "registry.example.com", false)] + [DataRow("https://foo.localhost./token", "registry.example.com", false)] // Unicode trailing dot (U+3002 ideographic full stop) - Uri.IdnHost canonicalizes // it to "localhost.", so it must be caught by the same trailing-dot normalization. - [InlineData("https://localhost\u3002/token", "registry.example.com", false)] + [DataRow("https://localhost\u3002/token", "registry.example.com", false)] // Insecure registry: still rejected when registry isn't a loopback-equivalent host. - [InlineData("https://localhost/token", "192.168.1.5:5000", true)] - [InlineData("http://localhost/token", "192.168.1.5:5000", true)] + [DataRow("https://localhost/token", "192.168.1.5:5000", true)] + [DataRow("http://localhost/token", "192.168.1.5:5000", true)] // Lookalike that isn't actually localhost: "localhost.example.com" is a public DNS // name, so the registry doesn't match the loopback exception either. - [InlineData("http://localhost/token", "localhost.example.com:5000", true)] + [DataRow("http://localhost/token", "localhost.example.com:5000", true)] public void ValidateRealmUri_RejectsLoopbackDnsNameRealm(string realm, string registryName, bool isInsecureRegistry) { - Assert.Throws(() => + Assert.ThrowsExactly(() => AuthHandshakeMessageHandler.ValidateRealmUri(realm, registryName, isInsecureRegistry)); } @@ -487,18 +495,18 @@ public void ValidateRealmUri_RejectsLoopbackDnsNameRealm(string realm, string re /// Mirrors for the /// case where the realm side uses a DNS name instead of an IP literal. /// - [Theory] - [InlineData("http://localhost:5000/auth", "localhost:5000")] - [InlineData("https://localhost:5000/auth", "localhost:5000")] - [InlineData("http://localhost:7000/auth", "localhost:5000")] // port-independent - [InlineData("http://foo.localhost:5000/auth", "localhost:5000")] // *.localhost realm - [InlineData("http://localhost:5000/auth", "registry.localhost:5000")] // *.localhost registry - [InlineData("http://localhost:5000/auth", "127.0.0.1:5000")] // registry is loopback IP literal - [InlineData("http://localhost:5000/auth", "[::1]:5000")] // registry is IPv6 loopback literal + [TestMethod] + [DataRow("http://localhost:5000/auth", "localhost:5000")] + [DataRow("https://localhost:5000/auth", "localhost:5000")] + [DataRow("http://localhost:7000/auth", "localhost:5000")] // port-independent + [DataRow("http://foo.localhost:5000/auth", "localhost:5000")] // *.localhost realm + [DataRow("http://localhost:5000/auth", "registry.localhost:5000")] // *.localhost registry + [DataRow("http://localhost:5000/auth", "127.0.0.1:5000")] // registry is loopback IP literal + [DataRow("http://localhost:5000/auth", "[::1]:5000")] // registry is IPv6 loopback literal public void ValidateRealmUri_AllowsLoopbackDnsNameRealm_WhenInsecureAndRegistryIsLoopback(string realm, string registryName) { Uri uri = AuthHandshakeMessageHandler.ValidateRealmUri(realm, registryName, isInsecureRegistry: true); - Assert.Equal(realm, uri.AbsoluteUri); + Assert.AreEqual(realm, uri.AbsoluteUri); } /// @@ -506,14 +514,14 @@ public void ValidateRealmUri_AllowsLoopbackDnsNameRealm_WhenInsecureAndRegistryI /// IP literals) pass all guards regardless of the insecure flag - this is the /// expected shape for any production token endpoint. /// - [Theory] - [InlineData("https://auth.example.com/token", "registry.example.com", false)] - [InlineData("https://auth.docker.io/token", "registry-1.docker.io", false)] // real Docker Hub realm shape - [InlineData("http://auth.example.com:8080/token", "registry.example.com:5000", true)] + [TestMethod] + [DataRow("https://auth.example.com/token", "registry.example.com", false)] + [DataRow("https://auth.docker.io/token", "registry-1.docker.io", false)] // real Docker Hub realm shape + [DataRow("http://auth.example.com:8080/token", "registry.example.com:5000", true)] public void ValidateRealmUri_AllowsPublicDnsRealms(string realm, string registryName, bool isInsecureRegistry) { Uri uri = AuthHandshakeMessageHandler.ValidateRealmUri(realm, registryName, isInsecureRegistry); - Assert.Equal(realm, uri.AbsoluteUri); + Assert.AreEqual(realm, uri.AbsoluteUri); } /// @@ -522,7 +530,7 @@ public void ValidateRealmUri_AllowsPublicDnsRealms(string realm, string registry /// and dispatch zero requests to the /// realm host. /// - [Fact] + [TestMethod] public async Task SendAsync_ThrowsOnInvalidBearerRealm_WithoutTokenRequest() { // Use a unique registry name to avoid contamination from the static auth header cache. @@ -556,11 +564,11 @@ HttpResponseMessage Server(HttpRequestMessage request) RegistryMode.Pull); using var httpClient = new HttpClient(authHandler); - await Assert.ThrowsAsync(() => - httpClient.GetAsync(requestUrl, TestContext.Current.CancellationToken)); + await Assert.ThrowsExactlyAsync(() => + httpClient.GetAsync(requestUrl, TestContext.CancellationToken)); // The handler must not have followed the malicious realm. - Assert.Equal(0, tokenRequestCount); + Assert.AreEqual(0, tokenRequestCount); } } } diff --git a/test/Microsoft.NET.Build.Containers.UnitTests/ContainerHelpersTests.cs b/test/Microsoft.NET.Build.Containers.UnitTests/ContainerHelpersTests.cs index 27d2b7441bf4..847f9eaf7922 100644 --- a/test/Microsoft.NET.Build.Containers.UnitTests/ContainerHelpersTests.cs +++ b/test/Microsoft.NET.Build.Containers.UnitTests/ContainerHelpersTests.cs @@ -3,150 +3,151 @@ namespace Microsoft.NET.Build.Containers.UnitTests; +[TestClass] public class ContainerHelpersTests { private const string DefaultRegistry = "docker.io"; - [Theory] + [TestMethod] // Valid Tests - [InlineData("mcr.microsoft.com", true)] - [InlineData("mcr.microsoft.com:5001", true)] // Registries can have ports - [InlineData("docker.io", true)] // default docker registry is considered valid + [DataRow("mcr.microsoft.com", true)] + [DataRow("mcr.microsoft.com:5001", true)] // Registries can have ports + [DataRow("docker.io", true)] // default docker registry is considered valid // // Invalid tests - [InlineData("mcr.mi-=crosoft.com", false)] // invalid url - [InlineData("mcr.microsoft.com/", false)] // invalid url + [DataRow("mcr.mi-=crosoft.com", false)] // invalid url + [DataRow("mcr.microsoft.com/", false)] // invalid url public void IsValidRegistry(string registry, bool expectedReturn) { Console.WriteLine($"Domain pattern is '{ReferenceParser.AnchoredDomainRegexp.ToString()}'"); - Assert.Equal(expectedReturn, ContainerHelpers.IsValidRegistry(registry)); + Assert.AreEqual(expectedReturn, ContainerHelpers.IsValidRegistry(registry)); } - [Theory] - [InlineData("mcr.microsoft.com/dotnet/runtime@sha256:6cec36412a215aad2a033cfe259890482be0a1dcb680e81fccc393b2d4069455", true, "mcr.microsoft.com", "dotnet/runtime", null, "sha256:6cec36412a215aad2a033cfe259890482be0a1dcb680e81fccc393b2d4069455", true)] + [TestMethod] + [DataRow("mcr.microsoft.com/dotnet/runtime@sha256:6cec36412a215aad2a033cfe259890482be0a1dcb680e81fccc393b2d4069455", true, "mcr.microsoft.com", "dotnet/runtime", null, "sha256:6cec36412a215aad2a033cfe259890482be0a1dcb680e81fccc393b2d4069455", true)] // Handle both tag and digest - [InlineData("mcr.microsoft.com/dotnet/runtime:6.0@sha256:6cec36412a215aad2a033cfe259890482be0a1dcb680e81fccc393b2d4069455", true, "mcr.microsoft.com", "dotnet/runtime", "6.0", "sha256:6cec36412a215aad2a033cfe259890482be0a1dcb680e81fccc393b2d4069455", true)] - [InlineData("mcr.microsoft.com/dotnet/runtime:6.0", true, "mcr.microsoft.com", "dotnet/runtime", "6.0", null, true)] - [InlineData("mcr.microsoft.com/dotnet/runtime", true, "mcr.microsoft.com", "dotnet/runtime", null, null, true)] - [InlineData("mcr.microsoft.com/", false, null, null, null, null, false)] // no image = nothing resolves + [DataRow("mcr.microsoft.com/dotnet/runtime:6.0@sha256:6cec36412a215aad2a033cfe259890482be0a1dcb680e81fccc393b2d4069455", true, "mcr.microsoft.com", "dotnet/runtime", "6.0", "sha256:6cec36412a215aad2a033cfe259890482be0a1dcb680e81fccc393b2d4069455", true)] + [DataRow("mcr.microsoft.com/dotnet/runtime:6.0", true, "mcr.microsoft.com", "dotnet/runtime", "6.0", null, true)] + [DataRow("mcr.microsoft.com/dotnet/runtime", true, "mcr.microsoft.com", "dotnet/runtime", null, null, true)] + [DataRow("mcr.microsoft.com/", false, null, null, null, null, false)] // no image = nothing resolves // Ports tag along - [InlineData("mcr.microsoft.com:54/dotnet/runtime", true, "mcr.microsoft.com:54", "dotnet/runtime", null, null, true)] + [DataRow("mcr.microsoft.com:54/dotnet/runtime", true, "mcr.microsoft.com:54", "dotnet/runtime", null, null, true)] // Even if nonsensical - [InlineData("mcr.microsoft.com:0/dotnet/runtime", true, "mcr.microsoft.com:0", "dotnet/runtime", null, null, true)] + [DataRow("mcr.microsoft.com:0/dotnet/runtime", true, "mcr.microsoft.com:0", "dotnet/runtime", null, null, true)] // We don't allow hosts with missing ports when a port is anticipated - [InlineData("mcr.microsoft.com:/dotnet/runtime", false, null, null, null, null, false)] + [DataRow("mcr.microsoft.com:/dotnet/runtime", false, null, null, null, null, false)] // Use default registry when no registry specified. - [InlineData("ubuntu:jammy", true, DefaultRegistry, "library/ubuntu", "jammy", null, false)] - [InlineData("ubuntu/runtime:jammy", true, DefaultRegistry, "ubuntu/runtime", "jammy", null, false)] + [DataRow("ubuntu:jammy", true, DefaultRegistry, "library/ubuntu", "jammy", null, false)] + [DataRow("ubuntu/runtime:jammy", true, DefaultRegistry, "ubuntu/runtime", "jammy", null, false)] // Alias 'docker.io' to Docker registry. - [InlineData("docker.io/ubuntu:jammy", true, DefaultRegistry, "library/ubuntu", "jammy", null, true)] - [InlineData("docker.io/ubuntu/runtime:jammy", true, DefaultRegistry, "ubuntu/runtime", "jammy", null, true)] + [DataRow("docker.io/ubuntu:jammy", true, DefaultRegistry, "library/ubuntu", "jammy", null, true)] + [DataRow("docker.io/ubuntu/runtime:jammy", true, DefaultRegistry, "ubuntu/runtime", "jammy", null, true)] // 'localhost' registry. - [InlineData("localhost/ubuntu:jammy", true, "localhost", "ubuntu", "jammy", null, true)] + [DataRow("localhost/ubuntu:jammy", true, "localhost", "ubuntu", "jammy", null, true)] public void TryParseFullyQualifiedContainerName(string fullyQualifiedName, bool expectedReturn, string? expectedRegistry, string? expectedImage, string? expectedTag, string? expectedDigest, bool expectedIsRegistrySpecified) { - Assert.Equal(expectedReturn, ContainerHelpers.TryParseFullyQualifiedContainerName(fullyQualifiedName, out string? containerReg, out string? containerName, out string? containerTag, out string? containerDigest, out bool isRegistrySpecified)); - Assert.Equal(expectedRegistry, containerReg); - Assert.Equal(expectedImage, containerName); - Assert.Equal(expectedTag, containerTag); - Assert.Equal(expectedDigest, containerDigest); - Assert.Equal(expectedIsRegistrySpecified, isRegistrySpecified); + Assert.AreEqual(expectedReturn, ContainerHelpers.TryParseFullyQualifiedContainerName(fullyQualifiedName, out string? containerReg, out string? containerName, out string? containerTag, out string? containerDigest, out bool isRegistrySpecified)); + Assert.AreEqual(expectedRegistry, containerReg); + Assert.AreEqual(expectedImage, containerName); + Assert.AreEqual(expectedTag, containerTag); + Assert.AreEqual(expectedDigest, containerDigest); + Assert.AreEqual(expectedIsRegistrySpecified, isRegistrySpecified); } - [Theory] - [InlineData("dotnet/runtime", true)] - [InlineData("foo/bar", true)] - [InlineData("registry", true)] - [InlineData("-foo/bar", false)] - [InlineData(".foo/bar", false)] - [InlineData("_foo/bar", false)] - [InlineData("foo/bar-", false)] - [InlineData("foo/bar.", false)] - [InlineData("foo/bar_", false)] - [InlineData("--------", false)] + [TestMethod] + [DataRow("dotnet/runtime", true)] + [DataRow("foo/bar", true)] + [DataRow("registry", true)] + [DataRow("-foo/bar", false)] + [DataRow(".foo/bar", false)] + [DataRow("_foo/bar", false)] + [DataRow("foo/bar-", false)] + [DataRow("foo/bar.", false)] + [DataRow("foo/bar_", false)] + [DataRow("--------", false)] public void IsValidImageName(string imageName, bool expectedReturn) { - Assert.Equal(expectedReturn, ContainerHelpers.IsValidImageName(imageName)); + Assert.AreEqual(expectedReturn, ContainerHelpers.IsValidImageName(imageName)); } - [Theory] - [InlineData("0aa", "0aa", null, null)] - [InlineData("9zz", "9zz", null, null)] - [InlineData("aa0", "aa0", null, null)] - [InlineData("zz9", "zz9", null, null)] - [InlineData("runtime", "runtime", null, null)] - [InlineData("dotnet_runtime", "dotnet_runtime", null, null)] - [InlineData("dotnet-runtime", "dotnet-runtime", null, null)] - [InlineData("dotnet/runtime", "dotnet/runtime", null, null)] - [InlineData("dotnet runtime", "dotnet-runtime", "NormalizedContainerName", null)] - [InlineData("Api", "api", "NormalizedContainerName", null)] - [InlineData("API", "api", "NormalizedContainerName", null)] - [InlineData("$runtime", null, null, "InvalidImageName_NonAlphanumericStartCharacter")] - [InlineData("-%", null, null, "InvalidImageName_NonAlphanumericStartCharacter")] + [TestMethod] + [DataRow("0aa", "0aa", null, null)] + [DataRow("9zz", "9zz", null, null)] + [DataRow("aa0", "aa0", null, null)] + [DataRow("zz9", "zz9", null, null)] + [DataRow("runtime", "runtime", null, null)] + [DataRow("dotnet_runtime", "dotnet_runtime", null, null)] + [DataRow("dotnet-runtime", "dotnet-runtime", null, null)] + [DataRow("dotnet/runtime", "dotnet/runtime", null, null)] + [DataRow("dotnet runtime", "dotnet-runtime", "NormalizedContainerName", null)] + [DataRow("Api", "api", "NormalizedContainerName", null)] + [DataRow("API", "api", "NormalizedContainerName", null)] + [DataRow("$runtime", null, null, "InvalidImageName_NonAlphanumericStartCharacter")] + [DataRow("-%", null, null, "InvalidImageName_NonAlphanumericStartCharacter")] public void IsValidRepositoryName(string containerRepository, string? expectedNormalized, string? expectedWarning, string? expectedError) { var actual = ContainerHelpers.NormalizeRepository(containerRepository); - Assert.Equal(expectedNormalized, actual.normalizedImageName); - Assert.Equal(expectedWarning, actual.normalizationWarning?.Item1); - Assert.Equal(expectedError, actual.normalizationError?.Item1); + Assert.AreEqual(expectedNormalized, actual.normalizedImageName); + Assert.AreEqual(expectedWarning, actual.normalizationWarning?.Item1); + Assert.AreEqual(expectedError, actual.normalizationError?.Item1); } - [Theory] - [InlineData("6.0", true)] // baseline - [InlineData("5.2-asd123", true)] // with commit hash - [InlineData(".6.0", false)] // starts with . - [InlineData("-6.0", false)] // starts with - - [InlineData("---", false)] // malformed + [TestMethod] + [DataRow("6.0", true)] // baseline + [DataRow("5.2-asd123", true)] // with commit hash + [DataRow(".6.0", false)] // starts with . + [DataRow("-6.0", false)] // starts with - + [DataRow("---", false)] // malformed public void IsValidImageTag(string imageTag, bool expectedReturn) { - Assert.Equal(expectedReturn, ContainerHelpers.IsValidImageTag(imageTag)); + Assert.AreEqual(expectedReturn, ContainerHelpers.IsValidImageTag(imageTag)); } - [Fact] + [TestMethod] public void IsValidImageTag_InvalidLength() { - Assert.False(ContainerHelpers.IsValidImageTag(new string('a', 129))); + Assert.IsFalse(ContainerHelpers.IsValidImageTag(new string('a', 129))); } - [Theory] - [InlineData("80/tcp", true, 80, PortType.tcp, null)] - [InlineData("80", true, 80, PortType.tcp, null)] - [InlineData("125/dup", false, 125, PortType.tcp, ContainerHelpers.ParsePortError.InvalidPortType)] - [InlineData("invalidNumber", false, null, null, ContainerHelpers.ParsePortError.InvalidPortNumber)] - [InlineData("welp/unknowntype", false, null, null, (ContainerHelpers.ParsePortError)6)] - [InlineData("a/b/c", false, null, null, ContainerHelpers.ParsePortError.UnknownPortFormat)] - [InlineData("/tcp", false, null, null, ContainerHelpers.ParsePortError.MissingPortNumber)] + [TestMethod] + [DataRow("80/tcp", true, 80, PortType.tcp, null)] + [DataRow("80", true, 80, PortType.tcp, null)] + [DataRow("125/dup", false, 125, PortType.tcp, ContainerHelpers.ParsePortError.InvalidPortType)] + [DataRow("invalidNumber", false, null, null, ContainerHelpers.ParsePortError.InvalidPortNumber)] + [DataRow("welp/unknowntype", false, null, null, (ContainerHelpers.ParsePortError)6)] + [DataRow("a/b/c", false, null, null, ContainerHelpers.ParsePortError.UnknownPortFormat)] + [DataRow("/tcp", false, null, null, ContainerHelpers.ParsePortError.MissingPortNumber)] public void CanParsePort(string input, bool shouldParse, int? expectedPortNumber, PortType? expectedType, ContainerHelpers.ParsePortError? expectedError) { var parseSuccess = ContainerHelpers.TryParsePort(input, out var port, out var errors); - Assert.Equal(shouldParse, parseSuccess); + Assert.AreEqual(shouldParse, parseSuccess); if (shouldParse) { - Assert.NotNull(port); - Assert.Equal(port.Value.Number, expectedPortNumber); - Assert.Equal(port.Value.Type, expectedType); + Assert.IsNotNull(port); + Assert.AreEqual(expectedPortNumber, port.Value.Number); + Assert.AreEqual(expectedType, port.Value.Type); } else { - Assert.Null(port); - Assert.NotNull(errors); - Assert.Equal(expectedError, errors); + Assert.IsNull(port); + Assert.IsNotNull(errors); + Assert.AreEqual(expectedError, errors); } } - [Theory] - [InlineData("FOO", true)] - [InlineData("foo_bar", true)] - [InlineData("foo-bar", false)] - [InlineData("foo.bar", false)] - [InlineData("foo bar", false)] - [InlineData("1_NAME", false)] - [InlineData("ASPNETCORE_URLS", true)] - [InlineData("ASPNETCORE_URLS2", true)] + [TestMethod] + [DataRow("FOO", true)] + [DataRow("foo_bar", true)] + [DataRow("foo-bar", false)] + [DataRow("foo.bar", false)] + [DataRow("foo bar", false)] + [DataRow("1_NAME", false)] + [DataRow("ASPNETCORE_URLS", true)] + [DataRow("ASPNETCORE_URLS2", true)] public void CanRecognizeEnvironmentVariableNames(string envVarName, bool isValid) { var success = ContainerHelpers.IsValidEnvironmentVariable(envVarName); - Assert.Equal(isValid, success); + Assert.AreEqual(isValid, success); } } diff --git a/test/Microsoft.NET.Build.Containers.UnitTests/ContentStoreTests.cs b/test/Microsoft.NET.Build.Containers.UnitTests/ContentStoreTests.cs index f968e35aecd4..8c8714b03935 100644 --- a/test/Microsoft.NET.Build.Containers.UnitTests/ContentStoreTests.cs +++ b/test/Microsoft.NET.Build.Containers.UnitTests/ContentStoreTests.cs @@ -3,11 +3,12 @@ namespace Microsoft.NET.Build.Containers.UnitTests; +[TestClass] public class ContentStoreTests { - [Theory] - [InlineData("sha256:c5098cc7c2a2ad9bfc66e4c4cb242683a578e9d8f25fd8730b289dd5667916ad")] - [InlineData("sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")] + [TestMethod] + [DataRow("sha256:c5098cc7c2a2ad9bfc66e4c4cb242683a578e9d8f25fd8730b289dd5667916ad")] + [DataRow("sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")] public void PathForDescriptor_AcceptsWellFormedDigest(string digest) { Descriptor descriptor = CreateDescriptorWithDigest(digest); @@ -15,14 +16,14 @@ public void PathForDescriptor_AcceptsWellFormedDigest(string digest) Assert.StartsWith(ContentStore.ContentRoot, path); } - [Theory] - [InlineData("")] // empty string - [InlineData("sha256:../..\\xyz_not_hex!!")] // non-hex characters - [InlineData("c5098cc7c2a2ad9bfc66e4c4cb242683a578e9d8f25fd8730b289dd5667916ad")] // missing algorithm prefix + [TestMethod] + [DataRow("")] // empty string + [DataRow("sha256:../..\\xyz_not_hex!!")] // non-hex characters + [DataRow("c5098cc7c2a2ad9bfc66e4c4cb242683a578e9d8f25fd8730b289dd5667916ad")] // missing algorithm prefix public void PathForDescriptor_RejectsInvalidDigest(string digest) { Descriptor descriptor = CreateDescriptorWithDigest(digest); - Assert.Throws(() => + Assert.ThrowsExactly(() => ContentStore.PathForDescriptor(descriptor)); } diff --git a/test/Microsoft.NET.Build.Containers.UnitTests/CreateNewImageTests.cs b/test/Microsoft.NET.Build.Containers.UnitTests/CreateNewImageTests.cs index 3faeedc3f8ce..8de0b7c5c1ae 100644 --- a/test/Microsoft.NET.Build.Containers.UnitTests/CreateNewImageTests.cs +++ b/test/Microsoft.NET.Build.Containers.UnitTests/CreateNewImageTests.cs @@ -8,68 +8,69 @@ namespace Microsoft.NET.Build.Containers.UnitTests; +[TestClass] public class CreateNewImageTests { - [Theory] + [TestMethod] // Entrypoint, backwards compatibility. - [InlineData("", "entrypointArg", "appCommand", "", "", null, new[] { "appCommand" }, new[] { "entrypointArg" })] + [DataRow("", "entrypointArg", "appCommand", "", "", null, new[] { "appCommand" }, new[] { "entrypointArg" })] // When no entrypoint is specified, emit the AppCommand as the Entrypoint. - [InlineData("", "", "appCommand", "appCommandArgs", "defaultArgs", "baseEntrypoint", new[] { "appCommand", "appCommandArgs" }, new[] { "defaultArgs" })] + [DataRow("", "", "appCommand", "appCommandArgs", "defaultArgs", "baseEntrypoint", new[] { "appCommand", "appCommandArgs" }, new[] { "defaultArgs" })] // Set all properties. When an entrypoint is specified, emit the AppCommand as Cmd. - [InlineData("entrypoint", "entrypointArgs", "appCommand", "appCommandArgs", "defaultArgs", + [DataRow("entrypoint", "entrypointArgs", "appCommand", "appCommandArgs", "defaultArgs", "baseEntrypoint", new[] { "entrypoint", "entrypointArgs" }, new[] { "appCommand", "appCommandArgs", "defaultArgs" })] public void EntrypointAndCmd_NoInstruction(string entrypoint, string entrypointArgs, string appCommand, string appCommandArgs, string defaultArgs, string? baseImageEntrypoint, string[]? expectedEntrypoint, string[]? expectedCmd) => ValidateArgsAndCmd("", entrypoint, entrypointArgs, appCommand, appCommandArgs, defaultArgs, baseImageEntrypoint, expectedEntrypoint, expectedCmd); - [Theory] + [TestMethod] // Set all properties. - [InlineData("entrypoint", "entrypointArgs", "appCommand", "appCommandArgs", "defaultArgs", + [DataRow("entrypoint", "entrypointArgs", "appCommand", "appCommandArgs", "defaultArgs", "baseEntrypoint", new[] { "entrypoint", "entrypointArgs" }, new[] { "appCommand", "appCommandArgs", "defaultArgs" })] // No Entrypoint, AppCommand specified, base entrypoint is preserved. - [InlineData("", "", "appCommand", "", "", "", null, new[] { "appCommand" })] - [InlineData("", "", "appCommand", "appCommandArgs", "", "", null, new[] { "appCommand", "appCommandArgs" })] - [InlineData("", "", "appCommand", "appCommandArgs", "defaultArgs", "", null, new[] { "appCommand", "appCommandArgs", "defaultArgs" })] - [InlineData("", "", "appCommand", "", "", "baseEntrypoint", new[] { "baseEntrypoint" }, new[] { "appCommand" })] - [InlineData("", "", "appCommand", "appCommandArgs", "", "baseEntrypoint", new[] { "baseEntrypoint" }, new[] { "appCommand", "appCommandArgs" })] - [InlineData("", "", "appCommand", "appCommandArgs", "defaultArgs", "baseEntrypoint", new[] { "baseEntrypoint" }, new[] { "appCommand", "appCommandArgs", "defaultArgs" })] + [DataRow("", "", "appCommand", "", "", "", null, new[] { "appCommand" })] + [DataRow("", "", "appCommand", "appCommandArgs", "", "", null, new[] { "appCommand", "appCommandArgs" })] + [DataRow("", "", "appCommand", "appCommandArgs", "defaultArgs", "", null, new[] { "appCommand", "appCommandArgs", "defaultArgs" })] + [DataRow("", "", "appCommand", "", "", "baseEntrypoint", new[] { "baseEntrypoint" }, new[] { "appCommand" })] + [DataRow("", "", "appCommand", "appCommandArgs", "", "baseEntrypoint", new[] { "baseEntrypoint" }, new[] { "appCommand", "appCommandArgs" })] + [DataRow("", "", "appCommand", "appCommandArgs", "defaultArgs", "baseEntrypoint", new[] { "baseEntrypoint" }, new[] { "appCommand", "appCommandArgs", "defaultArgs" })] // No Entrypoint, AppCommand specified, 'dotnet' base entrypoint is ignored. - [InlineData("", "", "appCommand", "", "", "dotnet", null, new[] { "appCommand" })] - [InlineData("", "", "appCommand", "appCommandArgs", "", "dotnet", null, new[] { "appCommand", "appCommandArgs" })] - [InlineData("", "", "appCommand", "appCommandArgs", "defaultArgs", "dotnet", null, new[] { "appCommand", "appCommandArgs", "defaultArgs" })] + [DataRow("", "", "appCommand", "", "", "dotnet", null, new[] { "appCommand" })] + [DataRow("", "", "appCommand", "appCommandArgs", "", "dotnet", null, new[] { "appCommand", "appCommandArgs" })] + [DataRow("", "", "appCommand", "appCommandArgs", "defaultArgs", "dotnet", null, new[] { "appCommand", "appCommandArgs", "defaultArgs" })] // No Entrypoint, AppCommand specified, '/usr/bin/dotnet' base entrypoint is ignored. - [InlineData("", "", "appCommand", "", "", "/usr/bin/dotnet", null, new[] { "appCommand" })] - [InlineData("", "", "appCommand", "appCommandArgs", "", "/usr/bin/dotnet", null, new[] { "appCommand", "appCommandArgs" })] - [InlineData("", "", "appCommand", "appCommandArgs", "defaultArgs", "/usr/bin/dotnet", null, new[] { "appCommand", "appCommandArgs", "defaultArgs" })] + [DataRow("", "", "appCommand", "", "", "/usr/bin/dotnet", null, new[] { "appCommand" })] + [DataRow("", "", "appCommand", "appCommandArgs", "", "/usr/bin/dotnet", null, new[] { "appCommand", "appCommandArgs" })] + [DataRow("", "", "appCommand", "appCommandArgs", "defaultArgs", "/usr/bin/dotnet", null, new[] { "appCommand", "appCommandArgs", "defaultArgs" })] public void EntrypointAndCmd_DefaultArgsInstruction(string entrypoint, string entrypointArgs, string appCommand, string appCommandArgs, string defaultArgs, string? baseImageEntrypoint, string[]? expectedEntrypoint, string[]? expectedCmd) => ValidateArgsAndCmd("DefaultArgs", entrypoint, entrypointArgs, appCommand, appCommandArgs, defaultArgs, baseImageEntrypoint, expectedEntrypoint, expectedCmd); - [Theory] + [TestMethod] // Set all properties except entrypoint and entrypointArgs. - [InlineData("", "", "appCommand", "appCommandArgs", "defaultArgs", "baseEntrypoint", new[] { "appCommand", "appCommandArgs" }, new[] { "defaultArgs" })] + [DataRow("", "", "appCommand", "appCommandArgs", "defaultArgs", "baseEntrypoint", new[] { "appCommand", "appCommandArgs" }, new[] { "defaultArgs" })] // Can't set entrypoint or entrypointArgs with instruction 'Entrypoint'. - [InlineData("entrypoint", "entrypointArgs", "appCommand", "appCommandArgs", "defaultArgs", "baseEntrypoint", null, null)] - [InlineData("", "entrypointArgs", "appCommand", "appCommandArgs", "defaultArgs", "baseEntrypoint", null, null)] - [InlineData("entrypoint", "", "appCommand", "appCommandArgs", "defaultArgs", "baseEntrypoint", null, null)] + [DataRow("entrypoint", "entrypointArgs", "appCommand", "appCommandArgs", "defaultArgs", "baseEntrypoint", null, null)] + [DataRow("", "entrypointArgs", "appCommand", "appCommandArgs", "defaultArgs", "baseEntrypoint", null, null)] + [DataRow("entrypoint", "", "appCommand", "appCommandArgs", "defaultArgs", "baseEntrypoint", null, null)] public void EntrypointAndCmd_EntrypointInstruction(string entrypoint, string entrypointArgs, string appCommand, string appCommandArgs, string defaultArgs, string? baseImageEntrypoint, string[]? expectedEntrypoint, string[]? expectedCmd) => ValidateArgsAndCmd("Entrypoint", entrypoint, entrypointArgs, appCommand, appCommandArgs, defaultArgs, baseImageEntrypoint, expectedEntrypoint, expectedCmd); - [Theory] + [TestMethod] // Set all properties except appCommand and appCommandArgs. - [InlineData("entrypoint", "entrypointArgs", "", "", "defaultArgs", "baseEntrypoint", new[] { "entrypoint", "entrypointArgs" }, new[] { "defaultArgs" })] + [DataRow("entrypoint", "entrypointArgs", "", "", "defaultArgs", "baseEntrypoint", new[] { "entrypoint", "entrypointArgs" }, new[] { "defaultArgs" })] // Can't set appCommand or appCommandArgs with instruction 'None'. - [InlineData("entrypoint", "entrypointArgs", "appCommand", "appCommandArgs", "defaultArgs", "baseEntrypoint", null, null)] - [InlineData("entrypoint", "entrypointArgs", "", "appCommandArgs", "defaultArgs", "baseEntrypoint", null, null)] - [InlineData("entrypoint", "entrypointArgs", "appCommand", "", "defaultArgs", "baseEntrypoint", null, null)] + [DataRow("entrypoint", "entrypointArgs", "appCommand", "appCommandArgs", "defaultArgs", "baseEntrypoint", null, null)] + [DataRow("entrypoint", "entrypointArgs", "", "appCommandArgs", "defaultArgs", "baseEntrypoint", null, null)] + [DataRow("entrypoint", "entrypointArgs", "appCommand", "", "defaultArgs", "baseEntrypoint", null, null)] public void EntrypointAndCmd_NoneInstruction(string entrypoint, string entrypointArgs, string appCommand, string appCommandArgs, string defaultArgs, string? baseImageEntrypoint, string[]? expectedEntrypoint, string[]? expectedCmd) => ValidateArgsAndCmd("None", entrypoint, entrypointArgs, appCommand, appCommandArgs, defaultArgs, baseImageEntrypoint, expectedEntrypoint, expectedCmd); - [Theory] + [TestMethod] // Set all properties accepted. - [InlineData("entrypoint", "entrypointArgs", "appCommand", "appCommandArgs", "defaultArgs", "baseEntrypoint", new[] { "entrypoint", "entrypointArgs" }, new[] { "appCommand", "appCommandArgs", "defaultArgs" })] + [DataRow("entrypoint", "entrypointArgs", "appCommand", "appCommandArgs", "defaultArgs", "baseEntrypoint", new[] { "entrypoint", "entrypointArgs" }, new[] { "appCommand", "appCommandArgs", "defaultArgs" })] // Set all properties except entrypoint fails: can't set entrypointArgs without setting entrypoint. - [InlineData("", "entrypointArgs", "appCommand", "appCommandArgs", "defaultArgs", "baseEntrypoint", null, null)] + [DataRow("", "entrypointArgs", "appCommand", "appCommandArgs", "defaultArgs", "baseEntrypoint", null, null)] // Set all properties except appCommand fails: can't set appCommandArgs without setting appCommand. - [InlineData("entrypoint", "entrypointArgs", "", "appCommandArgs", "defaultArgs", "baseEntrypoint", null, null)] + [DataRow("entrypoint", "entrypointArgs", "", "appCommandArgs", "defaultArgs", "baseEntrypoint", null, null)] public void EntrypointAndCmd_RequiredProperties(string entrypoint, string entrypointArgs, string appCommand, string appCommandArgs, string defaultArgs, string? baseImageEntrypoint, string[]? expectedEntrypoint, string[]? expectedCmd) => ValidateArgsAndCmd("DefaultArgs", entrypoint, entrypointArgs, appCommand, appCommandArgs, defaultArgs, baseImageEntrypoint, expectedEntrypoint, expectedCmd); @@ -88,9 +89,9 @@ private static void ValidateArgsAndCmd(string appCommandInstruction, string entr (string[] imageEntrypoint, string[] imageCmd) = newImage.DetermineEntrypointAndCmd(baseImageEntrypoint?.Split(';', StringSplitOptions.RemoveEmptyEntries)); - Assert.Equal(newImage.Log.HasLoggedErrors, imageEntrypoint.Length == 0 && imageCmd.Length == 0); - Assert.Equal(expectedEntrypoint ?? Array.Empty(), imageEntrypoint); - Assert.Equal(expectedCmd ?? Array.Empty(), imageCmd); + Assert.AreEqual(newImage.Log.HasLoggedErrors, imageEntrypoint.Length == 0 && imageCmd.Length == 0); + Assert.AreSequenceEqual(expectedEntrypoint ?? Array.Empty(), imageEntrypoint); + Assert.AreSequenceEqual(expectedCmd ?? Array.Empty(), imageCmd); static ITaskItem[] CreateTaskItems(string value) => value.Split(';', StringSplitOptions.RemoveEmptyEntries).Select(s => new TaskItem(s)).ToArray(); diff --git a/test/Microsoft.NET.Build.Containers.UnitTests/DescriptorTests.cs b/test/Microsoft.NET.Build.Containers.UnitTests/DescriptorTests.cs index f689bd4c7944..2cc46b638fbe 100644 --- a/test/Microsoft.NET.Build.Containers.UnitTests/DescriptorTests.cs +++ b/test/Microsoft.NET.Build.Containers.UnitTests/DescriptorTests.cs @@ -5,9 +5,10 @@ namespace Microsoft.NET.Build.Containers.UnitTests; +[TestClass] public class DescriptorTests { - [Fact] + [TestMethod] public void BasicConstructor() { Descriptor d = new( @@ -17,12 +18,12 @@ public void BasicConstructor() Console.WriteLine(JsonSerializer.Serialize(d, new JsonSerializerOptions { WriteIndented = true })); - Assert.Equal("application/vnd.oci.image.manifest.v1+json", d.MediaType); - Assert.Equal("sha256:5b0bcabd1ed22e9fb1310cf6c2dec7cdef19f0ad69efa1f392e94a4333501270", d.Digest); - Assert.Equal(7_682, d.Size); + Assert.AreEqual("application/vnd.oci.image.manifest.v1+json", d.MediaType); + Assert.AreEqual("sha256:5b0bcabd1ed22e9fb1310cf6c2dec7cdef19f0ad69efa1f392e94a4333501270", d.Digest); + Assert.AreEqual(7_682, d.Size); - Assert.Null(d.Annotations); - Assert.Null(d.Data); - Assert.Null(d.Urls); + Assert.IsNull(d.Annotations); + Assert.IsNull(d.Data); + Assert.IsNull(d.Urls); } } diff --git a/test/Microsoft.NET.Build.Containers.UnitTests/DigestUtilsTests.cs b/test/Microsoft.NET.Build.Containers.UnitTests/DigestUtilsTests.cs index c477b533d86e..545525a923ef 100644 --- a/test/Microsoft.NET.Build.Containers.UnitTests/DigestUtilsTests.cs +++ b/test/Microsoft.NET.Build.Containers.UnitTests/DigestUtilsTests.cs @@ -3,65 +3,66 @@ namespace Microsoft.NET.Build.Containers.UnitTests; +[TestClass] public class DigestUtilsTests { - [Theory] - [InlineData("sha256:0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000")] - [InlineData("sha256:c5098cc7c2a2ad9bfc66e4c4cb242683a578e9d8f25fd8730b289dd5667916ad", "c5098cc7c2a2ad9bfc66e4c4cb242683a578e9d8f25fd8730b289dd5667916ad")] - [InlineData("sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")] + [TestMethod] + [DataRow("sha256:0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000")] + [DataRow("sha256:c5098cc7c2a2ad9bfc66e4c4cb242683a578e9d8f25fd8730b289dd5667916ad", "c5098cc7c2a2ad9bfc66e4c4cb242683a578e9d8f25fd8730b289dd5667916ad")] + [DataRow("sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")] public void GetEncoded_AcceptsValidDigest(string digest, string expectedEncoded) { string encoded = DigestUtils.GetEncoded(digest); - Assert.Equal(expectedEncoded, encoded); + Assert.AreEqual(expectedEncoded, encoded); } - [Theory] - [InlineData("")] // empty - [InlineData("sha256:")] // missing encoded value - [InlineData("sha256:../..\\xyz_not_hex!!")] // path traversal / invalid characters - [InlineData("c5098cc7c2a2ad9bfc66e4c4cb242683a578e9d8f25fd8730b289dd5667916ad")] // missing algorithm prefix - [InlineData("0000000c5098cc7c2a2ad9bfc66e4c4cb242683a578e9d8f25fd8730b289dd5667916ad")] // correct string length, no algorithm prefix - [InlineData("sha256:abc")] // too short for sha256 - [InlineData("sha256:c5098cc7c2a2ad9bfc66e4c4cb242683a578e9d8f25fd8730b289dd5667916a")] // 63 hex chars (1 too short for sha256) - [InlineData("sha256:c5098cc7c2a2ad9bfc66e4c4cb242683a578e9d8f25fd8730b289dd5667916adF")] // uppercase hex not allowed per OCI spec - [InlineData("sha256:c5098cc7c2a2ad9bfc66e4c4cb242683a578e9d8f25fd8730b289dd5667916ad000000000000")] // too long for sha256 - [InlineData("sha256:FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")] // uppercase hex not allowed per OCI spec - [InlineData("md5:5b0bcabd1ed22e9fb1310cf6")] // unregistered algorithm - [InlineData("sha512:abc")] // sha512 not currently supported - [InlineData("blake3:abc")] // blake3 not currently supported + [TestMethod] + [DataRow("")] // empty + [DataRow("sha256:")] // missing encoded value + [DataRow("sha256:../..\\xyz_not_hex!!")] // path traversal / invalid characters + [DataRow("c5098cc7c2a2ad9bfc66e4c4cb242683a578e9d8f25fd8730b289dd5667916ad")] // missing algorithm prefix + [DataRow("0000000c5098cc7c2a2ad9bfc66e4c4cb242683a578e9d8f25fd8730b289dd5667916ad")] // correct string length, no algorithm prefix + [DataRow("sha256:abc")] // too short for sha256 + [DataRow("sha256:c5098cc7c2a2ad9bfc66e4c4cb242683a578e9d8f25fd8730b289dd5667916a")] // 63 hex chars (1 too short for sha256) + [DataRow("sha256:c5098cc7c2a2ad9bfc66e4c4cb242683a578e9d8f25fd8730b289dd5667916adF")] // uppercase hex not allowed per OCI spec + [DataRow("sha256:c5098cc7c2a2ad9bfc66e4c4cb242683a578e9d8f25fd8730b289dd5667916ad000000000000")] // too long for sha256 + [DataRow("sha256:FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")] // uppercase hex not allowed per OCI spec + [DataRow("md5:5b0bcabd1ed22e9fb1310cf6")] // unregistered algorithm + [DataRow("sha512:abc")] // sha512 not currently supported + [DataRow("blake3:abc")] // blake3 not currently supported public void GetEncoded_RejectsInvalidDigest(string digest) { - Assert.Throws(() => + Assert.ThrowsExactly(() => DigestUtils.GetEncoded(digest)); } - [Fact] + [TestMethod] public void ComputeSha256Digest_ReturnsCorrectDigest() { // Well-known: SHA-256 of empty string string digest = DigestUtils.ComputeSha256Digest(""); - Assert.Equal("sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", digest); + Assert.AreEqual("sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", digest); } - [Fact] + [TestMethod] public void ComputeSha256_ReturnsLowercaseHex() { string hash = DigestUtils.ComputeSha256(""); - Assert.Equal("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", hash); + Assert.AreEqual("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", hash); } - [Fact] + [TestMethod] public void FormatSha256Digest_FormatsCorrectly() { string digest = DigestUtils.FormatSha256Digest("abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890"); - Assert.Equal("sha256:abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890", digest); + Assert.AreEqual("sha256:abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890", digest); } - [Fact] + [TestMethod] public void ComputeSha256Digest_RoundTrips_Through_GetEncoded() { string digest = DigestUtils.ComputeSha256Digest("hello world"); string encoded = DigestUtils.GetEncoded(digest); - Assert.Equal(DigestUtils.ComputeSha256("hello world"), encoded); + Assert.AreEqual(DigestUtils.ComputeSha256("hello world"), encoded); } } diff --git a/test/Microsoft.NET.Build.Containers.UnitTests/DockerAvailableUtils.cs b/test/Microsoft.NET.Build.Containers.UnitTests/DockerAvailableUtils.cs index e0b2cd7458f7..cf5198f1d7ec 100644 --- a/test/Microsoft.NET.Build.Containers.UnitTests/DockerAvailableUtils.cs +++ b/test/Microsoft.NET.Build.Containers.UnitTests/DockerAvailableUtils.cs @@ -1,56 +1,32 @@ // 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; - namespace Microsoft.NET.Build.Containers.UnitTests; -public class DockerAvailableTheoryAttribute : TheoryAttribute +public sealed class DockerUnavailableCondition : ConditionBaseAttribute { - public static string LocalRegistry => DockerCliStatus.LocalRegistry; - - public DockerAvailableTheoryAttribute( - bool skipPodman = false, - [CallerFilePath] string? sourceFilePath = null, - [CallerLineNumber] int sourceLineNumber = 0) - : base(sourceFilePath, sourceLineNumber) + public DockerUnavailableCondition() + : base(ConditionMode.Exclude) { - if (!DockerCliStatus.IsAvailable) - { - base.Skip = "Skipping test because Docker is not available on this host."; - } - - if (skipPodman && DockerCliStatus.Command == DockerCli.PodmanCommand) - { - base.Skip = $"Skipping test with {DockerCliStatus.Command} cli."; - } + IgnoreMessage = "Skipping test because Docker is not available on this host."; } + + public override string GroupName => nameof(DockerUnavailableCondition); + + public override bool IsConditionMet => !DockerCliStatus.IsAvailable; } -public class DockerAvailableFactAttribute : FactAttribute +public sealed class PodmanCliCondition : ConditionBaseAttribute { - public static string LocalRegistry => DockerCliStatus.LocalRegistry; - - public DockerAvailableFactAttribute( - bool skipPodman = false, - bool checkContainerdStoreAvailability = false, - [CallerFilePath] string? sourceFilePath = null, - [CallerLineNumber] int sourceLineNumber = 0) - : base(sourceFilePath, sourceLineNumber) + public PodmanCliCondition() + : base(ConditionMode.Exclude) { - if (!DockerCliStatus.IsAvailable) - { - base.Skip = "Skipping test because Docker is not available on this host."; - } - else if (checkContainerdStoreAvailability && DockerCliStatus.Command != DockerCli.PodmanCommand && !DockerCli.IsContainerdStoreEnabledForDocker()) - { - base.Skip = "Skipping test because Docker daemon is not using containerd as the storage driver."; - } - else if (skipPodman && DockerCliStatus.Command == DockerCli.PodmanCommand) - { - base.Skip = $"Skipping test with {DockerCliStatus.Command} cli."; - } + IgnoreMessage = "Skipping test with podman cli."; } + + public override string GroupName => nameof(PodmanCliCondition); + + public override bool IsConditionMet => DockerCliStatus.Command == DockerCli.PodmanCommand; } // tiny optimization - since there are many instances of this attribute we should only get diff --git a/test/Microsoft.NET.Build.Containers.UnitTests/DockerDaemonTests.cs b/test/Microsoft.NET.Build.Containers.UnitTests/DockerDaemonTests.cs index 52848726311a..96789f16b33d 100644 --- a/test/Microsoft.NET.Build.Containers.UnitTests/DockerDaemonTests.cs +++ b/test/Microsoft.NET.Build.Containers.UnitTests/DockerDaemonTests.cs @@ -3,21 +3,17 @@ namespace Microsoft.NET.Build.Containers.UnitTests; -[CollectionDefinition("Daemon Tests")] -public class DaemonTestsCollection -{ -} - -[Collection("Daemon Tests")] +[TestClass] public class DockerDaemonTests : IDisposable { - private ITestOutputHelper _testOutput; private readonly TestLoggerFactory _loggerFactory; - public DockerDaemonTests(ITestOutputHelper testOutput) + public TestContext TestContext { get; } + + public DockerDaemonTests(TestContext testContext) { - _testOutput = testOutput; - _loggerFactory = new TestLoggerFactory(testOutput); + TestContext = testContext; + _loggerFactory = new TestLoggerFactory(testContext); } public void Dispose() @@ -25,7 +21,9 @@ public void Dispose() _loggerFactory.Dispose(); } - [DockerAvailableFact(skipPodman: true)] // podman is a local cli not meant for connecting to remote Docker daemons. + [TestMethod] + [DockerUnavailableCondition] + [PodmanCliCondition] // podman is a local cli not meant for connecting to remote Docker daemons. public async Task Can_detect_when_no_daemon_is_running() { // mimic no daemon running by setting the DOCKER_HOST to a nonexistent socket @@ -33,7 +31,7 @@ public async Task Can_detect_when_no_daemon_is_running() { Environment.SetEnvironmentVariable("DOCKER_HOST", "tcp://123.123.123.123:12345"); var available = await new DockerCli(_loggerFactory).IsAvailableAsync(default).ConfigureAwait(false); - Assert.False(available, "No daemon should be listening at that port"); + Assert.IsFalse(available, "No daemon should be listening at that port"); } finally { @@ -41,10 +39,11 @@ public async Task Can_detect_when_no_daemon_is_running() } } - [DockerAvailableFact(Skip = "https://github.com/dotnet/sdk/issues/49502")] + [TestMethod] + [Ignore("https://github.com/dotnet/sdk/issues/49502")] public async Task Can_detect_when_daemon_is_running() { var available = await new DockerCli(_loggerFactory).IsAvailableAsync(default).ConfigureAwait(false); - Assert.True(available, "Should have found a working daemon"); + Assert.IsTrue(available, "Should have found a working daemon"); } } diff --git a/test/Microsoft.NET.Build.Containers.UnitTests/FallbackToHttpMessageHandlerTests.cs b/test/Microsoft.NET.Build.Containers.UnitTests/FallbackToHttpMessageHandlerTests.cs index 18a3a76c554a..d76afe36c207 100644 --- a/test/Microsoft.NET.Build.Containers.UnitTests/FallbackToHttpMessageHandlerTests.cs +++ b/test/Microsoft.NET.Build.Containers.UnitTests/FallbackToHttpMessageHandlerTests.cs @@ -11,17 +11,20 @@ namespace Microsoft.NET.Build.Containers.UnitTests { + [TestClass] public class FallbackToHttpMessageHandlerTests { - [Theory] - [InlineData("mcr.microsoft.com", 80)] - [InlineData("mcr.microsoft.com:443", 443)] - [InlineData("mcr.microsoft.com:80", 80)] - [InlineData("mcr.microsoft.com:5555", 5555)] - [InlineData("[2408:8120:245:49a0:f041:d7bb:bb13:5b64]", 80)] - [InlineData("[2408:8120:245:49a0:f041:d7bb:bb13:5b64]:443", 443)] - [InlineData("[2408:8120:245:49a0:f041:d7bb:bb13:5b64]:80", 80)] - [InlineData("[2408:8120:245:49a0:f041:d7bb:bb13:5b64]:5555", 5555)] + public TestContext TestContext { get; set; } = default!; + + [TestMethod] + [DataRow("mcr.microsoft.com", 80)] + [DataRow("mcr.microsoft.com:443", 443)] + [DataRow("mcr.microsoft.com:80", 80)] + [DataRow("mcr.microsoft.com:5555", 5555)] + [DataRow("[2408:8120:245:49a0:f041:d7bb:bb13:5b64]", 80)] + [DataRow("[2408:8120:245:49a0:f041:d7bb:bb13:5b64]:443", 443)] + [DataRow("[2408:8120:245:49a0:f041:d7bb:bb13:5b64]:80", 80)] + [DataRow("[2408:8120:245:49a0:f041:d7bb:bb13:5b64]:5555", 5555)] public async Task FallBackToHttpPortShouldAsExpected(string registry, int expectedPort) { var uri = new Uri($"https://{registry}"); @@ -50,8 +53,8 @@ public async Task FallBackToHttpPortShouldAsExpected(string registry, int expect NullLogger.Instance ); using var httpClient = new HttpClient(handler); - var response = await httpClient.GetAsync(uri, TestContext.Current.CancellationToken); - Assert.Equal(expectedPort, response.RequestMessage?.RequestUri?.Port); + var response = await httpClient.GetAsync(uri, TestContext.CancellationToken); + Assert.AreEqual(expectedPort, response.RequestMessage?.RequestUri?.Port); } private sealed class ServerMessageHandler : HttpMessageHandler diff --git a/test/Microsoft.NET.Build.Containers.UnitTests/ImageBuilderTests.cs b/test/Microsoft.NET.Build.Containers.UnitTests/ImageBuilderTests.cs index adf8457962d2..849826edab2f 100644 --- a/test/Microsoft.NET.Build.Containers.UnitTests/ImageBuilderTests.cs +++ b/test/Microsoft.NET.Build.Containers.UnitTests/ImageBuilderTests.cs @@ -6,18 +6,28 @@ namespace Microsoft.NET.Build.Containers.UnitTests; +[TestClass] public class ImageBuilderTests { private readonly TestLoggerFactory _loggerFactory; private static readonly string StaticKnownDigestValue = "sha256:338c0b702da88157ba4bb706678e43346ece2e4397b888d59fb2d9f6113c8070"; - public ImageBuilderTests(ITestOutputHelper output) + public TestContext TestContext { get; } + + public ImageBuilderTests(TestContext testContext) + { + TestContext = testContext; + _loggerFactory = new TestLoggerFactory(testContext); + } + + [TestCleanup] + public void Cleanup() { - _loggerFactory = new TestLoggerFactory(output); + _loggerFactory.Dispose(); } - [Fact] + [TestMethod] public void CanAddLabelsToImage() { string simpleImageConfig = @@ -65,7 +75,7 @@ public void CanAddLabelsToImage() """; JsonNode? node = JsonNode.Parse(simpleImageConfig); - Assert.NotNull(node); + Assert.IsNotNull(node); ImageConfig baseConfig = new(node); @@ -77,14 +87,14 @@ public void CanAddLabelsToImage() JsonNode? result = JsonNode.Parse(readyImage); var resultLabels = result?["config"]?["Labels"] as JsonObject; - Assert.NotNull(resultLabels); + Assert.IsNotNull(resultLabels); - Assert.Equal(2, resultLabels.Count); - Assert.Equal("v1", resultLabels["testLabel1"]?.ToString()); - Assert.Equal("v2", resultLabels["testLabel2"]?.ToString()); + Assert.AreEqual(2, resultLabels.Count); + Assert.AreEqual("v1", resultLabels["testLabel1"]?.ToString()); + Assert.AreEqual("v2", resultLabels["testLabel2"]?.ToString()); } - [Fact] + [TestMethod] public void CanPreserveExistingLabels() { string simpleImageConfig = @@ -136,7 +146,7 @@ public void CanPreserveExistingLabels() """; JsonNode? node = JsonNode.Parse(simpleImageConfig); - Assert.NotNull(node); + Assert.IsNotNull(node); ImageConfig baseConfig = new(node); @@ -148,15 +158,15 @@ public void CanPreserveExistingLabels() JsonNode? result = JsonNode.Parse(readyImage); var resultLabels = result?["config"]?["Labels"] as JsonObject; - Assert.NotNull(resultLabels); + Assert.IsNotNull(resultLabels); - Assert.Equal(3, resultLabels.Count); - Assert.Equal("v1", resultLabels["testLabel1"]?.ToString()); - Assert.Equal("v2", resultLabels["existing2"]?.ToString()); - Assert.Equal("e1", resultLabels["existing"]?.ToString()); + Assert.AreEqual(3, resultLabels.Count); + Assert.AreEqual("v1", resultLabels["testLabel1"]?.ToString()); + Assert.AreEqual("v2", resultLabels["existing2"]?.ToString()); + Assert.AreEqual("e1", resultLabels["existing"]?.ToString()); } - [Fact] + [TestMethod] public void CanAddPortsToImage() { string simpleImageConfig = @@ -204,7 +214,7 @@ public void CanAddPortsToImage() """; JsonNode? node = JsonNode.Parse(simpleImageConfig); - Assert.NotNull(node); + Assert.IsNotNull(node); ImageConfig baseConfig = new(node); @@ -216,14 +226,14 @@ public void CanAddPortsToImage() JsonNode? result = JsonNode.Parse(readyImage); var resultPorts = result?["config"]?["ExposedPorts"] as JsonObject; - Assert.NotNull(resultPorts); + Assert.IsNotNull(resultPorts); - Assert.Equal(2, resultPorts.Count); - Assert.NotNull(resultPorts["6000/tcp"] as JsonObject); - Assert.NotNull(resultPorts["6010/udp"] as JsonObject); + Assert.AreEqual(2, resultPorts.Count); + Assert.IsNotNull(resultPorts["6000/tcp"] as JsonObject); + Assert.IsNotNull(resultPorts["6010/udp"] as JsonObject); } - [Fact] + [TestMethod] public void CanPreserveExistingPorts() { string simpleImageConfig = @@ -276,7 +286,7 @@ public void CanPreserveExistingPorts() """; JsonNode? node = JsonNode.Parse(simpleImageConfig); - Assert.NotNull(node); + Assert.IsNotNull(node); ImageConfig baseConfig = new(node); @@ -290,17 +300,17 @@ public void CanPreserveExistingPorts() JsonNode? result = JsonNode.Parse(readyImage); var resultPorts = result?["config"]?["ExposedPorts"] as JsonObject; - Assert.NotNull(resultPorts); - - Assert.Equal(5, resultPorts.Count); - Assert.NotNull(resultPorts["6000/tcp"] as JsonObject); - Assert.NotNull(resultPorts["6010/udp"] as JsonObject); - Assert.NotNull(resultPorts["6100/udp"] as JsonObject); - Assert.NotNull(resultPorts["6100/tcp"] as JsonObject); - Assert.NotNull(resultPorts["6200/tcp"] as JsonObject); + Assert.IsNotNull(resultPorts); + + Assert.AreEqual(5, resultPorts.Count); + Assert.IsNotNull(resultPorts["6000/tcp"] as JsonObject); + Assert.IsNotNull(resultPorts["6010/udp"] as JsonObject); + Assert.IsNotNull(resultPorts["6100/udp"] as JsonObject); + Assert.IsNotNull(resultPorts["6100/tcp"] as JsonObject); + Assert.IsNotNull(resultPorts["6200/tcp"] as JsonObject); } - [Fact] + [TestMethod] public void HistoryEntriesMatchNonEmptyLayers() { // Note how the base image config is already "corrupt" by having @@ -365,7 +375,7 @@ public void HistoryEntriesMatchNonEmptyLayers() """; JsonNode? node = JsonNode.Parse(simpleImageConfig); - Assert.NotNull(node); + Assert.IsNotNull(node); ImageConfig baseConfig = new(node); @@ -374,19 +384,19 @@ public void HistoryEntriesMatchNonEmptyLayers() JsonNode? result = JsonNode.Parse(readyImage); var historyNode = result?["history"]; - Assert.NotNull(historyNode); + Assert.IsNotNull(historyNode); var layerDiffsNode = result?["rootfs"]?["diff_ids"]; - Assert.NotNull(layerDiffsNode); + Assert.IsNotNull(layerDiffsNode); int nonEmptyHistoryNodes = historyNode.AsArray() .Count(h => h?.AsObject()["empty_layer"]?.GetValue() is null or false); int layerCount = layerDiffsNode.AsArray().Count; - Assert.Equal(nonEmptyHistoryNodes, layerCount); + Assert.AreEqual(nonEmptyHistoryNodes, layerCount); } - [Fact] + [TestMethod] public void CanSetUserFromAppUIDEnvVarFromBaseImage() { var expectedUid = "12345"; @@ -423,12 +433,12 @@ public void CanSetUserFromAppUIDEnvVarFromBaseImage() var builtImage = builder.Build(); JsonNode? result = JsonNode.Parse(builtImage.Config); - Assert.NotNull(result); + Assert.IsNotNull(result); var assignedUid = result["config"]?["User"]?.GetValue(); - Assert.Equal(assignedUid, expectedUid); + Assert.AreEqual(expectedUid, assignedUid); } - [Fact] + [TestMethod] public void CanSetUserFromAppUIDEnvVarFromUser() { var expectedUid = "12345"; @@ -465,15 +475,15 @@ public void CanSetUserFromAppUIDEnvVarFromUser() var builtImage = builder.Build(); JsonNode? result = JsonNode.Parse(builtImage.Config); - Assert.NotNull(result); + Assert.IsNotNull(result); var assignedUser = result["config"]?["User"]?.GetValue(); - Assert.Equal(assignedUser, expectedUid); + Assert.AreEqual(expectedUid, assignedUser); } - [InlineData("ASPNETCORE_URLS", "https://*:12345;http://+:1234;http://localhost:123;http://1.2.3.4:12", 12345, 1234, 123, 12)] - [InlineData("ASPNETCORE_HTTP_PORTS", "999;666", 999, 666)] - [InlineData("ASPNETCORE_HTTPS_PORTS", "456;789", 456, 789)] - [Theory] + [DataRow("ASPNETCORE_URLS", "https://*:12345;http://+:1234;http://localhost:123;http://1.2.3.4:12", 12345, 1234, 123, 12)] + [DataRow("ASPNETCORE_HTTP_PORTS", "999;666", 999, 666)] + [DataRow("ASPNETCORE_HTTPS_PORTS", "456;789", 456, 789)] + [TestMethod] public void CanSetPortFromEnvVarFromBaseImage(string envVar, string envValue, params int[] expectedPorts) { var builder = FromBaseImageConfig($$""" @@ -509,16 +519,16 @@ public void CanSetPortFromEnvVarFromBaseImage(string envVar, string envValue, pa var builtImage = builder.Build(); JsonNode? result = JsonNode.Parse(builtImage.Config); - Assert.NotNull(result); + Assert.IsNotNull(result); var portsObject = result["config"]?["ExposedPorts"]?.AsObject(); var assignedPorts = portsObject?.AsEnumerable().Select(portString => int.Parse(portString.Key.Split('/')[0])).ToArray(); - Assert.Equal(assignedPorts, expectedPorts); + Assert.AreSequenceEqual(expectedPorts, assignedPorts); } - [InlineData("ASPNETCORE_URLS", "https://*:12345;http://+:1234;http://localhost:123;http://1.2.3.4:12", 12345, 1234, 123, 12)] - [InlineData("ASPNETCORE_HTTP_PORTS", "999;666", 999, 666)] - [InlineData("ASPNETCORE_HTTPS_PORTS", "456;789", 456, 789)] - [Theory] + [DataRow("ASPNETCORE_URLS", "https://*:12345;http://+:1234;http://localhost:123;http://1.2.3.4:12", 12345, 1234, 123, 12)] + [DataRow("ASPNETCORE_HTTP_PORTS", "999;666", 999, 666)] + [DataRow("ASPNETCORE_HTTPS_PORTS", "456;789", 456, 789)] + [TestMethod] public void CanSetPortFromEnvVarFromUser(string envVar, string envValue, params int[] expectedPorts) { var builder = FromBaseImageConfig($$""" @@ -555,14 +565,14 @@ public void CanSetPortFromEnvVarFromUser(string envVar, string envValue, params var builtImage = builder.Build(); JsonNode? result = JsonNode.Parse(builtImage.Config); - Assert.NotNull(result); + Assert.IsNotNull(result); var portsObject = result["config"]?["ExposedPorts"]?.AsObject(); var assignedPorts = portsObject?.AsEnumerable().Select(portString => int.Parse(portString.Key.Split('/')[0])).ToArray(); - Assert.Equal(assignedPorts, expectedPorts); + Assert.AreSequenceEqual(expectedPorts, assignedPorts); } - [Fact] + [TestMethod] public void CanSetContainerUserAndOverrideAppUID() { var userId = "1646"; @@ -598,10 +608,10 @@ public void CanSetContainerUserAndOverrideAppUID() baseConfigBuilder.SetUser(userId); var config = JsonNode.Parse(baseConfigBuilder.Build().Config); - config!["config"]?["User"]?.GetValue().Should().Be(expected: userId, because: "The precedence of SetUser should override inferred user ids"); + Assert.AreEqual(userId, config!["config"]?["User"]?.GetValue()); } - [Fact] + [TestMethod] public void WhenMultipleUrlSourcesAreSetOnlyAspnetcoreUrlsIsUsed() { int[] expected = [12345]; @@ -638,13 +648,13 @@ public void WhenMultipleUrlSourcesAreSetOnlyAspnetcoreUrlsIsUsed() builder.AddEnvironmentVariable(ImageBuilder.EnvironmentVariables.ASPNETCORE_HTTPS_PORTS, "456"); var builtImage = builder.Build(); JsonNode? result = JsonNode.Parse(builtImage.Config); - Assert.NotNull(result); + Assert.IsNotNull(result); var portsObject = result["config"]?["ExposedPorts"]?.AsObject(); var assignedPorts = portsObject?.AsEnumerable().Select(portString => int.Parse(portString.Key.Split('/')[0])).ToArray(); - Assert.Equal(expected, assignedPorts); + Assert.AreSequenceEqual(expected, assignedPorts); } - [Fact] + [TestMethod] public void CanSetBaseImageDigestLabel() { var builder = FromBaseImageConfig($$""" @@ -679,10 +689,10 @@ public void CanSetBaseImageDigestLabel() builder.AddBaseImageDigestLabel(); var builtImage = builder.Build(); JsonNode? result = JsonNode.Parse(builtImage.Config); - Assert.NotNull(result); + Assert.IsNotNull(result); var labels = result["config"]?["Labels"]?.AsObject(); var digest = labels?.AsEnumerable().First(label => label.Key == "org.opencontainers.image.base.digest").Value!; - digest.GetValue().Should().Be(StaticKnownDigestValue); + Assert.AreEqual(StaticKnownDigestValue, digest.GetValue()); } private ImageBuilder FromBaseImageConfig(string baseImageConfig, [CallerMemberName] string testName = "") diff --git a/test/Microsoft.NET.Build.Containers.UnitTests/ImageConfigTests.cs b/test/Microsoft.NET.Build.Containers.UnitTests/ImageConfigTests.cs index 25d3cafe2268..da884160594a 100644 --- a/test/Microsoft.NET.Build.Containers.UnitTests/ImageConfigTests.cs +++ b/test/Microsoft.NET.Build.Containers.UnitTests/ImageConfigTests.cs @@ -5,6 +5,7 @@ namespace Microsoft.NET.Build.Containers.UnitTests; +[TestClass] public class ImageConfigTests { private const string SampleImageConfig = """ @@ -43,15 +44,15 @@ public class ImageConfigTests } """; - [InlineData("User")] - [InlineData("Volumes")] - [InlineData("StopSignal")] - [Theory] + [DataRow("User")] + [DataRow("Volumes")] + [DataRow("StopSignal")] + [TestMethod] public void PassesThroughPropertyEvenThoughPropertyIsntExplicitlyHandled(string property) { ImageConfig c = new(SampleImageConfig); JsonNode after = JsonNode.Parse(c.BuildConfig())!; JsonNode? prop = after["config"]?[property]; - Assert.NotNull(prop); + Assert.IsNotNull(prop); } } diff --git a/test/Microsoft.NET.Build.Containers.UnitTests/ImageIndexGeneratorTests.cs b/test/Microsoft.NET.Build.Containers.UnitTests/ImageIndexGeneratorTests.cs index 1acc846dcdcd..9e45b8b91b19 100644 --- a/test/Microsoft.NET.Build.Containers.UnitTests/ImageIndexGeneratorTests.cs +++ b/test/Microsoft.NET.Build.Containers.UnitTests/ImageIndexGeneratorTests.cs @@ -5,25 +5,26 @@ namespace Microsoft.NET.Build.Containers.UnitTests; +[TestClass] public class ImageIndexGeneratorTests { - [Fact] + [TestMethod] public void ImagesCannotBeEmpty() { BuiltImage[] images = Array.Empty(); - var ex = Assert.Throws(() => ImageIndexGenerator.GenerateImageIndex(images)); - Assert.Equal(Strings.ImagesEmpty, ex.Message); + var ex = Assert.ThrowsExactly(() => ImageIndexGenerator.GenerateImageIndex(images)); + Assert.AreEqual(Strings.ImagesEmpty, ex.Message); } - [Fact] + [TestMethod] public void ImagesCannotBeEmpty_SpecifiedMediaType() { BuiltImage[] images = Array.Empty(); - var ex = Assert.Throws(() => ImageIndexGenerator.GenerateImageIndex(images, "manifestMediaType", "imageIndexMediaType")); - Assert.Equal(Strings.ImagesEmpty, ex.Message); + var ex = Assert.ThrowsExactly(() => ImageIndexGenerator.GenerateImageIndex(images, "manifestMediaType", "imageIndexMediaType")); + Assert.AreEqual(Strings.ImagesEmpty, ex.Message); } - [Fact] + [TestMethod] public void UnsupportedMediaTypeThrows() { BuiltImage[] images = @@ -37,13 +38,13 @@ public void UnsupportedMediaTypeThrows() } ]; - var ex = Assert.Throws(() => ImageIndexGenerator.GenerateImageIndex(images)); - Assert.Equal(string.Format(Strings.UnsupportedMediaType, "unsupported"), ex.Message); + var ex = Assert.ThrowsExactly(() => ImageIndexGenerator.GenerateImageIndex(images)); + Assert.AreEqual(string.Format(Strings.UnsupportedMediaType, "unsupported"), ex.Message); } - [Theory] - [InlineData(SchemaTypes.DockerManifestV2)] - [InlineData(SchemaTypes.OciManifestV1)] + [TestMethod] + [DataRow(SchemaTypes.DockerManifestV2)] + [DataRow(SchemaTypes.OciManifestV1)] public void ImagesWithMixedMediaTypes(string supportedMediaType) { BuiltImage[] images = @@ -64,11 +65,11 @@ public void ImagesWithMixedMediaTypes(string supportedMediaType) } ]; - var ex = Assert.Throws(() => ImageIndexGenerator.GenerateImageIndex(images)); - Assert.Equal(Strings.MixedMediaTypes, ex.Message); + var ex = Assert.ThrowsExactly(() => ImageIndexGenerator.GenerateImageIndex(images)); + Assert.AreEqual(Strings.MixedMediaTypes, ex.Message); } - [Fact] + [TestMethod] public void GenerateDockerManifestList() { BuiltImage[] images = @@ -94,11 +95,11 @@ public void GenerateDockerManifestList() ]; var (imageIndex, mediaType) = ImageIndexGenerator.GenerateImageIndex(images); - Assert.Equal("{\"schemaVersion\":2,\"mediaType\":\"application/vnd.docker.distribution.manifest.list.v2+json\",\"manifests\":[{\"mediaType\":\"application/vnd.docker.distribution.manifest.v2+json\",\"size\":3,\"digest\":\"sha256:digest1\",\"platform\":{\"architecture\":\"arch1\",\"os\":\"os1\"}},{\"mediaType\":\"application/vnd.docker.distribution.manifest.v2+json\",\"size\":3,\"digest\":\"sha256:digest2\",\"platform\":{\"architecture\":\"arch2\",\"os\":\"os2\"}}]}", imageIndex); - Assert.Equal(SchemaTypes.DockerManifestListV2, mediaType); + Assert.AreEqual("{\"schemaVersion\":2,\"mediaType\":\"application/vnd.docker.distribution.manifest.list.v2+json\",\"manifests\":[{\"mediaType\":\"application/vnd.docker.distribution.manifest.v2+json\",\"size\":3,\"digest\":\"sha256:digest1\",\"platform\":{\"architecture\":\"arch1\",\"os\":\"os1\"}},{\"mediaType\":\"application/vnd.docker.distribution.manifest.v2+json\",\"size\":3,\"digest\":\"sha256:digest2\",\"platform\":{\"architecture\":\"arch2\",\"os\":\"os2\"}}]}", imageIndex); + Assert.AreEqual(SchemaTypes.DockerManifestListV2, mediaType); } - [Fact] + [TestMethod] public void GenerateOciImageIndex() { BuiltImage[] images = @@ -124,14 +125,14 @@ public void GenerateOciImageIndex() ]; var (imageIndex, mediaType) = ImageIndexGenerator.GenerateImageIndex(images); - Assert.Equal("{\"schemaVersion\":2,\"mediaType\":\"application/vnd.oci.image.index.v1+json\",\"manifests\":[{\"mediaType\":\"application/vnd.oci.image.manifest.v1+json\",\"size\":3,\"digest\":\"sha256:digest1\",\"platform\":{\"architecture\":\"arch1\",\"os\":\"os1\"}},{\"mediaType\":\"application/vnd.oci.image.manifest.v1+json\",\"size\":3,\"digest\":\"sha256:digest2\",\"platform\":{\"architecture\":\"arch2\",\"os\":\"os2\"}}]}", imageIndex); - Assert.Equal(SchemaTypes.OciImageIndexV1, mediaType); + Assert.AreEqual("{\"schemaVersion\":2,\"mediaType\":\"application/vnd.oci.image.index.v1+json\",\"manifests\":[{\"mediaType\":\"application/vnd.oci.image.manifest.v1+json\",\"size\":3,\"digest\":\"sha256:digest1\",\"platform\":{\"architecture\":\"arch1\",\"os\":\"os1\"}},{\"mediaType\":\"application/vnd.oci.image.manifest.v1+json\",\"size\":3,\"digest\":\"sha256:digest2\",\"platform\":{\"architecture\":\"arch2\",\"os\":\"os2\"}}]}", imageIndex); + Assert.AreEqual(SchemaTypes.OciImageIndexV1, mediaType); } - [Fact] + [TestMethod] public void GenerateImageIndexWithAnnotations() { string imageIndex = ImageIndexGenerator.GenerateImageIndexWithAnnotations("mediaType", "sha256:digest", 3, "repository", ["1.0", "2.0"]); - Assert.Equal("{\"schemaVersion\":2,\"mediaType\":\"application/vnd.oci.image.index.v1+json\",\"manifests\":[{\"mediaType\":\"mediaType\",\"size\":3,\"digest\":\"sha256:digest\",\"platform\":{},\"annotations\":{\"io.containerd.image.name\":\"docker.io/library/repository:1.0\",\"org.opencontainers.image.ref.name\":\"1.0\"}},{\"mediaType\":\"mediaType\",\"size\":3,\"digest\":\"sha256:digest\",\"platform\":{},\"annotations\":{\"io.containerd.image.name\":\"docker.io/library/repository:2.0\",\"org.opencontainers.image.ref.name\":\"2.0\"}}]}", imageIndex); + Assert.AreEqual("{\"schemaVersion\":2,\"mediaType\":\"application/vnd.oci.image.index.v1+json\",\"manifests\":[{\"mediaType\":\"mediaType\",\"size\":3,\"digest\":\"sha256:digest\",\"platform\":{},\"annotations\":{\"io.containerd.image.name\":\"docker.io/library/repository:1.0\",\"org.opencontainers.image.ref.name\":\"1.0\"}},{\"mediaType\":\"mediaType\",\"size\":3,\"digest\":\"sha256:digest\",\"platform\":{},\"annotations\":{\"io.containerd.image.name\":\"docker.io/library/repository:2.0\",\"org.opencontainers.image.ref.name\":\"2.0\"}}]}", imageIndex); } } diff --git a/test/Microsoft.NET.Build.Containers.UnitTests/Microsoft.NET.Build.Containers.UnitTests.csproj b/test/Microsoft.NET.Build.Containers.UnitTests/Microsoft.NET.Build.Containers.UnitTests.csproj index 8b77b42790a9..1bbaf68ac664 100644 --- a/test/Microsoft.NET.Build.Containers.UnitTests/Microsoft.NET.Build.Containers.UnitTests.csproj +++ b/test/Microsoft.NET.Build.Containers.UnitTests/Microsoft.NET.Build.Containers.UnitTests.csproj @@ -1,19 +1,24 @@ - + - $(SdkTargetFramework) + + $(SdkTargetFramework) enable - false - true MicrosoftShared - Exe - + + + + + + + + diff --git a/test/Microsoft.NET.Build.Containers.UnitTests/RegistryTests.cs b/test/Microsoft.NET.Build.Containers.UnitTests/RegistryTests.cs index 5f20f4c82058..900d30883cc8 100644 --- a/test/Microsoft.NET.Build.Containers.UnitTests/RegistryTests.cs +++ b/test/Microsoft.NET.Build.Containers.UnitTests/RegistryTests.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.Net; @@ -14,15 +14,17 @@ namespace Microsoft.NET.Build.Containers.UnitTests; +[TestClass] public class RegistryTests : IDisposable { - private ITestOutputHelper _testOutput; private readonly TestLoggerFactory _loggerFactory; - public RegistryTests(ITestOutputHelper testOutput) + public TestContext TestContext { get; } + + public RegistryTests(TestContext testContext) { - _testOutput = testOutput; - _loggerFactory = new TestLoggerFactory(testOutput); + TestContext = testContext; + _loggerFactory = new TestLoggerFactory(testContext); } public void Dispose() @@ -30,27 +32,27 @@ public void Dispose() _loggerFactory.Dispose(); } - [InlineData("us-south1-docker.pkg.dev", true)] - [InlineData("us.gcr.io", false)] - [Theory] - public void CheckIfGoogleArtifactRegistry(string registryName, bool isECR) + [DataRow("us-south1-docker.pkg.dev", true)] + [DataRow("us.gcr.io", false)] + [TestMethod] + public void CheckIfGoogleArtifactRegistry(string registryName, bool expectedIsGoogleArtifactRegistry) { ILogger logger = _loggerFactory.CreateLogger(nameof(CheckIfGoogleArtifactRegistry)); Registry registry = new(registryName, logger, RegistryMode.Push); - Assert.Equal(isECR, registry.IsGoogleArtifactRegistry); + Assert.AreEqual(expectedIsGoogleArtifactRegistry, registry.IsGoogleArtifactRegistry); } - [Fact] + [TestMethod] public void DockerIoAlias() { ILogger logger = _loggerFactory.CreateLogger(nameof(DockerIoAlias)); Registry registry = new("docker.io", logger, RegistryMode.Push); - Assert.True(registry.IsDockerHub); - Assert.Equal("docker.io", registry.RegistryName); - Assert.Equal("registry-1.docker.io", registry.BaseUri.Host); + Assert.IsTrue(registry.IsDockerHub); + Assert.AreEqual("docker.io", registry.RegistryName); + Assert.AreEqual("registry-1.docker.io", registry.BaseUri.Host); } - [Fact] + [TestMethod] public async Task RegistriesThatProvideNoUploadSizeAttemptFullUpload() { ILogger logger = _loggerFactory.CreateLogger(nameof(RegistriesThatProvideNoUploadSizeAttemptFullUpload)); @@ -75,7 +77,7 @@ public async Task RegistriesThatProvideNoUploadSizeAttemptFullUpload() api.Verify(api => api.Blob.Upload.UploadAtomicallyAsync(uploadPath, It.IsAny(), It.IsAny()), Times.Once()); } - [Fact] + [TestMethod] public async Task RegistriesThatProvideUploadSizePrefersFullUploadWhenChunkSizeIsLowerThanContentLength() { ILogger logger = _loggerFactory.CreateLogger(nameof(RegistriesThatProvideUploadSizePrefersFullUploadWhenChunkSizeIsLowerThanContentLength)); @@ -109,7 +111,7 @@ public async Task RegistriesThatProvideUploadSizePrefersFullUploadWhenChunkSizeI api.Verify(api => api.Blob.Upload.UploadChunkAsync(It.IsIn(absoluteUploadUri, uploadPath), It.IsAny(), It.IsAny()), Times.Never); } - [Fact] + [TestMethod] public async Task RegistriesThatFailAtomicUploadFallbackToChunked() { ILogger logger = _loggerFactory.CreateLogger(nameof(RegistriesThatFailAtomicUploadFallbackToChunked)); @@ -144,7 +146,7 @@ public async Task RegistriesThatFailAtomicUploadFallbackToChunked() api.Verify(api => api.Blob.Upload.UploadChunkAsync(It.IsIn(absoluteUploadUri, uploadPath), It.IsAny(), It.IsAny()), Times.Exactly(contentLength / chunkSizeLessThanContentLength)); } - [Fact] + [TestMethod] public async Task ChunkedUploadCalculatesChunksCorrectly() { ILogger logger = _loggerFactory.CreateLogger(nameof(RegistriesThatFailAtomicUploadFallbackToChunked)); @@ -186,10 +188,10 @@ public async Task ChunkedUploadCalculatesChunksCorrectly() api.Verify(api => api.Blob.Upload.UploadChunkAsync(It.IsIn(absoluteUploadUri, uploadPath), It.IsAny(), It.IsAny()), Times.Exactly(10)); } - [Fact] + [TestMethod] public async Task PushAsync_Logging() { - using TestLoggerFactory loggerFactory = new(_testOutput); + using TestLoggerFactory loggerFactory = new(TestContext); List<(LogLevel, string)> loggedMessages = new(); loggerFactory.AddProvider(new InMemoryLoggerProvider(loggedMessages)); ILogger logger = loggerFactory.CreateLogger(nameof(PushAsync_Logging)); @@ -211,14 +213,14 @@ public async Task PushAsync_Logging() Registry registry = new("public.ecr.aws", logger, api.Object); await registry.PushLayerAsync(mockLayer.Object, repoName, CancellationToken.None); - Assert.NotEmpty(loggedMessages); - Assert.True(loggedMessages.All(m => m.Item1 == LogLevel.Trace)); + Assert.IsNotEmpty(loggedMessages); + Assert.IsTrue(loggedMessages.All(m => m.Item1 == LogLevel.Trace)); var messages = loggedMessages.Select(m => m.Item2).ToList(); - Assert.Contains(messages, m => m == "Started upload session for sha256:fafafafafafafafafafafafafafafafa"); - Assert.Contains(messages, m => m == "Finalized upload session for sha256:fafafafafafafafafafafafafafafafa"); + Assert.Contains("Started upload session for sha256:fafafafafafafafafafafafafafafafa", messages); + Assert.Contains("Finalized upload session for sha256:fafafafafafafafafafafafafafafafa", messages); } - [Fact] + [TestMethod] public async Task PushAsync_ForceChunkedUpload() { ILogger logger = _loggerFactory.CreateLogger(nameof(PushAsync_ForceChunkedUpload)); @@ -260,7 +262,7 @@ public async Task PushAsync_ForceChunkedUpload() api.Verify(api => api.Blob.Upload.UploadChunkAsync(It.IsIn(absoluteUploadUri, uploadPath), It.IsAny(), It.IsAny()), Times.Exactly(10)); } - [Fact] + [TestMethod] public async Task CanParseRegistryDeclaredChunkSize_FromRange() { ILogger logger = _loggerFactory.CreateLogger(nameof(CanParseRegistryDeclaredChunkSize_FromRange)); @@ -279,10 +281,10 @@ public async Task CanParseRegistryDeclaredChunkSize_FromRange() DefaultBlobUploadOperations operations = new(new Uri("https://my-registy.com"), finalClient, logger); StartUploadInformation result = await operations.StartAsync(repoName, CancellationToken.None); - Assert.Equal("https://my-registy.com/v2/testRepo/blobs/uploads/", result.UploadUri.AbsoluteUri); + Assert.AreEqual("https://my-registy.com/v2/testRepo/blobs/uploads/", result.UploadUri.AbsoluteUri); } - [Fact] + [TestMethod] public async Task CanParseRegistryDeclaredChunkSize_FromOCIChunkMinLength() { ILogger logger = _loggerFactory.CreateLogger(nameof(CanParseRegistryDeclaredChunkSize_FromOCIChunkMinLength)); @@ -301,10 +303,10 @@ public async Task CanParseRegistryDeclaredChunkSize_FromOCIChunkMinLength() DefaultBlobUploadOperations operations = new(new Uri("https://my-registy.com"), finalClient, logger); StartUploadInformation result = await operations.StartAsync(repoName, CancellationToken.None); - Assert.Equal("https://my-registy.com/v2/testRepo/blobs/uploads/", result.UploadUri.AbsoluteUri); + Assert.AreEqual("https://my-registy.com/v2/testRepo/blobs/uploads/", result.UploadUri.AbsoluteUri); } - [Fact] + [TestMethod] public async Task CanParseRegistryDeclaredChunkSize_None() { ILogger logger = _loggerFactory.CreateLogger(nameof(CanParseRegistryDeclaredChunkSize_None)); @@ -322,10 +324,10 @@ public async Task CanParseRegistryDeclaredChunkSize_None() DefaultBlobUploadOperations operations = new(new Uri("https://my-registy.com"), finalClient, logger); StartUploadInformation result = await operations.StartAsync(repoName, CancellationToken.None); - Assert.Equal("https://my-registy.com/v2/testRepo/blobs/uploads/", result.UploadUri.AbsoluteUri); + Assert.AreEqual("https://my-registy.com/v2/testRepo/blobs/uploads/", result.UploadUri.AbsoluteUri); } - [Fact] + [TestMethod] public async Task UploadBlobChunkedAsync_NormalFlow() { ILogger logger = _loggerFactory.CreateLogger(nameof(UploadBlobChunkedAsync_NormalFlow)); @@ -359,7 +361,7 @@ public async Task UploadBlobChunkedAsync_NormalFlow() api.Verify(api => api.Blob.Upload.UploadChunkAsync(It.IsIn(absoluteUploadUri, uploadPath), It.IsAny(), It.IsAny()), Times.Exactly(5)); } - [Fact] + [TestMethod] public async Task UploadBlobChunkedAsync_Failure() { ILogger logger = _loggerFactory.CreateLogger(nameof(UploadBlobChunkedAsync_NormalFlow)); @@ -389,19 +391,20 @@ public async Task UploadBlobChunkedAsync_Failure() }; Registry registry = new(registryUri, logger, api.Object, settings); - ApplicationException receivedException = await Assert.ThrowsAsync(() => registry.UploadBlobChunkedAsync(testStream, new StartUploadInformation(absoluteUploadUri), CancellationToken.None)); + ApplicationException receivedException = await Assert.ThrowsExactlyAsync(() => registry.UploadBlobChunkedAsync(testStream, new StartUploadInformation(absoluteUploadUri), CancellationToken.None)); - Assert.Equal(preparedException, receivedException); + Assert.AreEqual(preparedException, receivedException); api.Verify(api => api.Blob.Upload.UploadChunkAsync(It.IsIn(absoluteUploadUri, uploadPath), It.IsAny(), It.IsAny()), Times.Exactly(1)); } - [Theory(Skip = "https://github.com/dotnet/sdk/issues/42820")] - [InlineData(true, true, true)] - [InlineData(false, true, true)] - [InlineData(true, false, true)] - [InlineData(false, false, true)] - [InlineData(false, false, false)] + [TestMethod] + [Ignore("https://github.com/dotnet/sdk/issues/42820")] + [DataRow(true, true, true)] + [DataRow(false, true, true)] + [DataRow(true, false, true)] + [DataRow(false, false, true)] + [DataRow(false, false, false)] public async Task InsecureRegistry(bool isInsecureRegistry, bool serverIsHttps, bool httpServerCloseAbortive) { ILogger logger = _loggerFactory.CreateLogger(nameof(InsecureRegistry)); @@ -431,20 +434,20 @@ public async Task InsecureRegistry(bool isInsecureRegistry, bool serverIsHttps, { while (true) { - using TcpClient client = await listener.AcceptTcpClientAsync(); + using TcpClient client = await listener.AcceptTcpClientAsync(TestContext.CancellationToken); try { using Stream stream = serverIsHttps ? new SslStream(client.GetStream(), leaveInnerStreamOpen: false) : client.GetStream(); if (stream is SslStream sslStream) { - await sslStream.AuthenticateAsServerAsync(sslOptions!, default(CancellationToken)); + await sslStream.AuthenticateAsServerAsync(sslOptions!, TestContext.CancellationToken); } byte[] buffer = new byte[10]; - await stream.ReadAtLeastAsync(buffer, buffer.Length); // Wait for the request. + await stream.ReadAtLeastAsync(buffer, buffer.Length, cancellationToken: TestContext.CancellationToken); // Wait for the request. // Repond if we see '/v2/' in the buffer (since we expect that as part of the request path). if (buffer.AsSpan().IndexOf("/v2/"u8) != 0) { - await stream.WriteAsync("HTTP/1.0 200 OK\r\nContent-Length: 0\r\n\r\n"u8.ToArray()); + await stream.WriteAsync("HTTP/1.0 200 OK\r\nContent-Length: 0\r\n\r\n"u8.ToArray(), TestContext.CancellationToken); } else { @@ -457,7 +460,7 @@ public async Task InsecureRegistry(bool isInsecureRegistry, bool serverIsHttps, catch { } } - }, TestContext.Current.CancellationToken); + }, TestContext.CancellationToken); RegistrySettings settings = new() { @@ -472,12 +475,12 @@ public async Task InsecureRegistry(bool isInsecureRegistry, bool serverIsHttps, { // Falls back to http (when serverIsHttps is false) or ignores https certificate errors (when serverIsHttps is true). // Results in throwing: CONTAINER2003: The manifest for dotnet/runtime:latest from registry hwas an unknown type. - await Assert.ThrowsAsync(() => getManifest); + await Assert.ThrowsExactlyAsync(() => getManifest); } else { // Does not fall back and throws HttpRequestException with SecureConnectionError. - Exception? exception = await Assert.ThrowsAnyAsync(() => getManifest); + Exception? exception = await Assert.ThrowsAsync(() => getManifest); try { // The AuthHandshakeMessageHandler may reach its retry limit and throw an ApplicationException. @@ -485,15 +488,14 @@ public async Task InsecureRegistry(bool isInsecureRegistry, bool serverIsHttps, { // Find the exception for the first failed attempt. exception = (exception.InnerException as AggregateException)?.InnerExceptions.FirstOrDefault(); - Assert.NotNull(exception); + Assert.IsNotNull(exception); } - Assert.IsType(exception); - HttpRequestException requestException = (HttpRequestException)exception; - Assert.Equal(HttpRequestError.SecureConnectionError, requestException.HttpRequestError); + HttpRequestException requestException = Assert.IsExactInstanceOfType(exception); + Assert.AreEqual(HttpRequestError.SecureConnectionError, requestException.HttpRequestError); // The FallbackToHttpMessageHandler should fall back (if this registry was configured as insecure). - Assert.True(FallbackToHttpMessageHandler.ShouldAttemptFallbackToHttp(requestException)); + Assert.IsTrue(FallbackToHttpMessageHandler.ShouldAttemptFallbackToHttp(requestException)); } catch { @@ -524,15 +526,15 @@ public async Task InsecureRegistry(bool isInsecureRegistry, bool serverIsHttps, } } - [InlineData("localhost", null, true)] - [InlineData("localhost:5000", null, true)] - [InlineData("public.ecr.aws", null, false)] - [InlineData("public.ecr.aws", "public.ecr.aws", true)] - [InlineData("public.ecr.aws", "Public.ecr.aws", true)] // ignore case - [InlineData("public.ecr.aws", "public.ecr.aws;docker.io", true)] // multiple registries - [InlineData("public.ecr.aws", ";public.ecr.aws ; docker.io ", true)] // ignore whitespace - [InlineData("public.ecr.aws", "public.ecr.aws2;docker.io ", false)] // full name match - [Theory] + [DataRow("localhost", null, true)] + [DataRow("localhost:5000", null, true)] + [DataRow("public.ecr.aws", null, false)] + [DataRow("public.ecr.aws", "public.ecr.aws", true)] + [DataRow("public.ecr.aws", "Public.ecr.aws", true)] // ignore case + [DataRow("public.ecr.aws", "public.ecr.aws;docker.io", true)] // multiple registries + [DataRow("public.ecr.aws", ";public.ecr.aws ; docker.io ", true)] // ignore whitespace + [DataRow("public.ecr.aws", "public.ecr.aws2;docker.io ", false)] // full name match + [TestMethod] public void IsRegistryInsecure(string registryName, string? insecureRegistriesEnvvar, bool expectedInsecure) { var environment = new Dictionary(); @@ -543,10 +545,10 @@ public void IsRegistryInsecure(string registryName, string? insecureRegistriesEn var registrySettings = new RegistrySettings(registryName, new MockEnvironmentProvider(environment)); - Assert.Equal(expectedInsecure, registrySettings.IsInsecure); + Assert.AreEqual(expectedInsecure, registrySettings.IsInsecure); } - [Fact] + [TestMethod] public async Task DownloadBlobAsync_RetriesOnFailure() { // Arrange @@ -572,8 +574,8 @@ public async Task DownloadBlobAsync_RetriesOnFailure() result = await registry.DownloadBlobAsync(repoName, descriptor, cancellationToken); // Assert - Assert.NotNull(result); - Assert.True(File.Exists(result)); // Ensure the file was successfully downloaded + Assert.IsNotNull(result); + Assert.IsTrue(File.Exists(result)); // Ensure the file was successfully downloaded mockRegistryAPI.Verify(api => api.Blob.GetStreamAsync(repoName, descriptor.Digest, cancellationToken), Times.Exactly(3)); // Verify retries } finally @@ -586,7 +588,7 @@ public async Task DownloadBlobAsync_RetriesOnFailure() } } - [Fact] + [TestMethod] public async Task DownloadBlobAsync_ThrowsAfterMaxRetries() { // Arrange @@ -609,7 +611,7 @@ public async Task DownloadBlobAsync_ThrowsAfterMaxRetries() Registry registry = new(repoName, logger, mockRegistryAPI.Object, null, () => TimeSpan.Zero); // Act & Assert - await Assert.ThrowsAsync(async () => + await Assert.ThrowsExactlyAsync(async () => { await registry.DownloadBlobAsync(repoName, descriptor, cancellationToken); }); diff --git a/test/Microsoft.NET.Build.Containers.UnitTests/Resources/ResourceTests.cs b/test/Microsoft.NET.Build.Containers.UnitTests/Resources/ResourceTests.cs index 16181d50edd6..7322f5d5f67d 100644 --- a/test/Microsoft.NET.Build.Containers.UnitTests/Resources/ResourceTests.cs +++ b/test/Microsoft.NET.Build.Containers.UnitTests/Resources/ResourceTests.cs @@ -8,25 +8,26 @@ namespace Microsoft.NET.Build.Containers.UnitTests.Resources { + [TestClass] public class ResourceTests { - [Fact] + [TestMethod] public void GetString_ReturnsValueFromResources() { - Assert.Equal("CONTAINER0000: Value for unit test {0}", Resource.GetString(nameof(Strings._Test))); + Assert.AreEqual("CONTAINER0000: Value for unit test {0}", Resource.GetString(nameof(Strings._Test))); } - [Fact] + [TestMethod] public void FormatString_ReturnsValueFromResources() { - Assert.Equal("CONTAINER0000: Value for unit test 1", Resource.FormatString(nameof(Strings._Test), 1)); + Assert.AreEqual("CONTAINER0000: Value for unit test 1", Resource.FormatString(nameof(Strings._Test), 1)); } - [Fact] + [TestMethod] public void EnsureErrorCodeUniqueness() { ResourceSet? resourceSet = Resource.Manager.GetResourceSet(CultureInfo.InvariantCulture, true, true); - Assert.NotNull(resourceSet); + Assert.IsNotNull(resourceSet); IEnumerable> groups = resourceSet .OfType() @@ -44,7 +45,10 @@ public void EnsureErrorCodeUniqueness() { string prefix = group.First().Key!.ToString()!.Split('_')[0]; - Assert.All(group, e => e.Key!.ToString()!.StartsWith(prefix, StringComparison.Ordinal)); + foreach (DictionaryEntry entry in group) + { + Assert.StartsWith(prefix, entry.Key!.ToString()!, StringComparison.Ordinal); + } } } }