Fix potential crash when comparing snap versions

When comparing two snap versions that meet the following conditions, a
TypeError was raised:

 * a.major == b.major
 * a.minor == b.minor
 * a.git_build_id is None and b.git_build_id is None

Fixed by first converting the git_build_id of both variables to a float
before comapring them.

Also added a unit-test to cover this scenario.

Signed-off-by: Olivier Gayot <olivier.gayot@canonical.com>
This commit is contained in:
Olivier Gayot 2022-01-14 14:01:57 +01:00
parent de19b3abee
commit f196db8cd1
2 changed files with 9 additions and 5 deletions

View File

@ -76,9 +76,9 @@ class SnapVersion:
elif self.patch < other.patch:
return False
if self.git_build_id is not None and other.git_build_id is None:
return True
elif self.git_build_id is None and other.git_build_id is not None:
return False
build_id_self = \
float("-inf") if self.git_build_id is None else self.git_build_id
build_id_other = \
float("-inf") if other.git_build_id is None else other.git_build_id
return self.git_build_id > other.git_build_id
return build_id_self > build_id_other

View File

@ -43,3 +43,7 @@ class TestSnapVersion(unittest.TestCase):
# Make sure we ignore the build ID when the patch version is different
self.assertLess(SnapVersion.from_string("21.10.2+git255.deadbeef"),
SnapVersion.from_string("21.10.3+git135.deadbeef"))
snap_version = SnapVersion.from_string("21.10.02")
self.assertFalse(snap_version < snap_version)
self.assertFalse(snap_version > snap_version)