From 7f2611a960d7072c6fe07ab28697cd93f246eeeb Mon Sep 17 00:00:00 2001 From: Tamara Dahlgren <35777542+tldahlgren@users.noreply.github.com> Date: Fri, 8 Oct 2021 01:36:54 -0700 Subject: [PATCH] Allow Version('') and map it to the empty tuple (#25953) --- lib/spack/spack/test/versions.py | 14 ++++++++++++++ lib/spack/spack/version.py | 11 +++++++---- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/lib/spack/spack/test/versions.py b/lib/spack/spack/test/versions.py index 8a6fd77d8b..ee2a885306 100644 --- a/lib/spack/spack/test/versions.py +++ b/lib/spack/spack/test/versions.py @@ -614,3 +614,17 @@ def test_empty_version_range_raises(): assert VersionRange('2', '1.0') with pytest.raises(ValueError): assert ver('2:1.0') + + +def test_version_empty_slice(): + """Check an empty slice to confirm get "empty" version instead of + an IndexError (#25953). + """ + assert Version('1.')[1:] == Version('') + + +def test_version_wrong_idx_type(): + """Ensure exception raised if attempt to use non-integer index.""" + v = Version('1.1') + with pytest.raises(TypeError): + v['0:'] diff --git a/lib/spack/spack/version.py b/lib/spack/spack/version.py index 13fb798dfe..b943550240 100644 --- a/lib/spack/spack/version.py +++ b/lib/spack/spack/version.py @@ -177,7 +177,7 @@ def __init__(self, string): string = string.strip() self.string = string - if not VALID_VERSION.match(string): + if string and not VALID_VERSION.match(string): raise ValueError("Bad characters in version string: %s" % string) # An object that can lookup git commits to compare them to versions @@ -347,9 +347,12 @@ def __getitem__(self, idx): string_arg.append(str(token)) string_arg.append(str(sep)) - string_arg.pop() # We don't need the last separator - string_arg = ''.join(string_arg) - return cls(string_arg) + if string_arg: + string_arg.pop() # We don't need the last separator + string_arg = ''.join(string_arg) + return cls(string_arg) + else: + return Version('') message = '{cls.__name__} indices must be integers' raise TypeError(message.format(cls=cls))