From ace1fe03b6fc0bf58c5896480584c525b5c65abc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Luthi?= Date: Mon, 12 Aug 2024 18:00:28 +0200 Subject: [PATCH] feat: Improve parsing of Docker image tag version `MatchVersion(Predicate)` (#1231) --- src/Testcontainers/Images/DockerImage.cs | 12 ++++++++++-- .../Unit/Images/TestcontainersImageTest.cs | 14 ++++++++++---- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/src/Testcontainers/Images/DockerImage.cs b/src/Testcontainers/Images/DockerImage.cs index 468d292ee..1014d54e9 100644 --- a/src/Testcontainers/Images/DockerImage.cs +++ b/src/Testcontainers/Images/DockerImage.cs @@ -1,6 +1,7 @@ namespace DotNet.Testcontainers.Images { using System; + using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using JetBrains.Annotations; @@ -125,8 +126,15 @@ public bool MatchVersion(Predicate predicate) /// public bool MatchVersion(Predicate predicate) { - var versionMatch = Regex.Match(Tag, "^\\d+(\\.\\d+)?(\\.\\d+)?", RegexOptions.None, TimeSpan.FromSeconds(1)); - return versionMatch.Success && Version.TryParse(versionMatch.Value, out var version) && predicate(version); + var versionMatch = Regex.Match(Tag, @"^(\d+)(\.\d+)?(\.\d+)?", RegexOptions.None, TimeSpan.FromSeconds(1)); + if (!versionMatch.Success) + return false; + + if (Version.TryParse(versionMatch.Value, out var version)) + return predicate(version); + + // If the regex matches and Version.TryParse fails then it means it's a major version only (i.e. without any . in the version) + return predicate(new Version(int.Parse(versionMatch.Groups[1].Value, NumberStyles.None), 0)); } private static string TrimOrDefault(string value, string defaultValue = default) diff --git a/tests/Testcontainers.Tests/Unit/Images/TestcontainersImageTest.cs b/tests/Testcontainers.Tests/Unit/Images/TestcontainersImageTest.cs index bab17526a..af5ff7a43 100644 --- a/tests/Testcontainers.Tests/Unit/Images/TestcontainersImageTest.cs +++ b/tests/Testcontainers.Tests/Unit/Images/TestcontainersImageTest.cs @@ -99,12 +99,18 @@ public void MatchLatestOrNightly_TagIsNeither_ReturnsFalse() Assert.False(result); } - [Fact] - public void MatchVersion_ReturnsTrue_WhenVersionMatchesPredicate() + [Theory] + [InlineData("foo:2", 2, 0, -1, -1)] + [InlineData("foo:2-variant", 2, 0, -1, -1)] + [InlineData("foo:2.3", 2, 3, -1, -1)] + [InlineData("foo:2.3-variant", 2, 3, -1, -1)] + [InlineData("foo:2.3.4", 2, 3, 4, -1)] + [InlineData("foo:2.3.4-variant", 2, 3, 4, -1)] + public void MatchVersion_ReturnsTrue_WhenVersionMatchesPredicate(string image, int major, int minor, int build, int revision) { // Given - Predicate predicate = v => v.Major == 1 && v.Minor == 0 && v.Build == 0; - IImage dockerImage = new DockerImage("foo:1.0.0"); + Predicate predicate = v => v.Major == major && v.Minor == minor && v.Build == build && v.Revision == revision; + IImage dockerImage = new DockerImage(image); // When var result = dockerImage.MatchVersion(predicate);