Skip to content

Commit 439cbbc

Browse files
committed
Fix #291: Disallow negative numbers in VersionInfo
Disallow negative numbers in major, minor, and patch in semver.VersionInfo. Reason: a version can only contain positive numbers
1 parent dd110f1 commit 439cbbc

File tree

2 files changed

+31
-3
lines changed

2 files changed

+31
-3
lines changed

semver.py

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -243,9 +243,23 @@ class VersionInfo(object):
243243
)
244244

245245
def __init__(self, major, minor=0, patch=0, prerelease=None, build=None):
246-
self._major = int(major)
247-
self._minor = int(minor)
248-
self._patch = int(patch)
246+
# Build a dictionary of the arguments except prerelease and build
247+
#
248+
version_parts = {
249+
n: k for n, k in locals().items() if n in ("major", "minor", "patch")
250+
}
251+
252+
for name, value in version_parts.items():
253+
value = int(value)
254+
version_parts[name] = value
255+
if value < 0:
256+
raise ValueError(
257+
"{!r} is negative. A version can only be positive.".format(name)
258+
)
259+
260+
self._major = version_parts["major"]
261+
self._minor = version_parts["minor"]
262+
self._patch = version_parts["patch"]
249263
self._prerelease = None if prerelease is None else str(prerelease)
250264
self._build = None if build is None else str(build)
251265

test_semver.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,20 @@ def test_fordocstrings(func):
7373
assert func.__doc__, "Need a docstring for function %r" % func.__name
7474

7575

76+
@pytest.mark.parametrize(
77+
"ver",
78+
[
79+
{"major": -1},
80+
{"major": 1, "minor": -2},
81+
{"major": 1, "minor": 2, "patch": -3},
82+
{"major": 1, "minor": -2, "patch": 3},
83+
],
84+
)
85+
def test_should_not_allow_negative_numbers(ver):
86+
with pytest.raises(ValueError, match=".* is negative. .*"):
87+
VersionInfo(**ver)
88+
89+
7690
@pytest.mark.parametrize(
7791
"version,expected",
7892
[

0 commit comments

Comments
 (0)