From be924f580ced5047bdd642c51279d4ab011b204c Mon Sep 17 00:00:00 2001 From: Michael Grosser Date: Tue, 21 May 2024 11:46:24 +0200 Subject: [PATCH] add >= and <= --- version.go | 10 ++++++++ version_test.go | 66 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) diff --git a/version.go b/version.go index 3acbe5b..a1f2414 100644 --- a/version.go +++ b/version.go @@ -381,11 +381,21 @@ func (v *Version) LessThan(o *Version) bool { return v.Compare(o) < 0 } +// LessThanEqual tests if one version is less or equal than another one. +func (v *Version) LessThanEqual(o *Version) bool { + return v.Compare(o) <= 0 +} + // GreaterThan tests if one version is greater than another one. func (v *Version) GreaterThan(o *Version) bool { return v.Compare(o) > 0 } +// GreaterThanEqual tests if one version is greater or equal than another one. +func (v *Version) GreaterThanEqual(o *Version) bool { + return v.Compare(o) >= 0 +} + // Equal tests if two versions are equal to each other. // Note, versions can be equal with different metadata since metadata // is not considered part of the comparable version. diff --git a/version_test.go b/version_test.go index f98de25..74a1e91 100644 --- a/version_test.go +++ b/version_test.go @@ -303,6 +303,39 @@ func TestLessThan(t *testing.T) { } } +func TestLessThanEqual(t *testing.T) { + tests := []struct { + v1 string + v2 string + expected bool + }{ + {"1.2.3", "1.5.1", true}, + {"2.2.3", "1.5.1", false}, + {"1.5.1", "1.5.1", true}, + } + + for _, tc := range tests { + v1, err := NewVersion(tc.v1) + if err != nil { + t.Errorf("Error parsing version: %s", err) + } + + v2, err := NewVersion(tc.v2) + if err != nil { + t.Errorf("Error parsing version: %s", err) + } + + a := v1.LessThanEqual(v2) + e := tc.expected + if a != e { + t.Errorf( + "Comparison of '%s' and '%s' failed. Expected '%t', got '%t'", + tc.v1, tc.v2, e, a, + ) + } + } +} + func TestGreaterThan(t *testing.T) { tests := []struct { v1 string @@ -341,6 +374,39 @@ func TestGreaterThan(t *testing.T) { } } +func TestGreaterThanEqual(t *testing.T) { + tests := []struct { + v1 string + v2 string + expected bool + }{ + {"1.2.3", "1.5.1", false}, + {"2.2.3", "1.5.1", true}, + {"1.5.1", "1.5.1", true}, + } + + for _, tc := range tests { + v1, err := NewVersion(tc.v1) + if err != nil { + t.Errorf("Error parsing version: %s", err) + } + + v2, err := NewVersion(tc.v2) + if err != nil { + t.Errorf("Error parsing version: %s", err) + } + + a := v1.GreaterThanEqual(v2) + e := tc.expected + if a != e { + t.Errorf( + "Comparison of '%s' and '%s' failed. Expected '%t', got '%t'", + tc.v1, tc.v2, e, a, + ) + } + } +} + func TestEqual(t *testing.T) { tests := []struct { v1 *Version