Re-write way of compare APIVersionRequest's

`cmp` method was removed in Python 3, so it would be nice to use __lt__,
__le__, __eq__, __ne__, __gt__ and __ge__ instead, which are Py2 and Py3
compatible.

Change-Id: I1c89da0831b77b73f55d8681fd7d946535cc89b5
This commit is contained in:
Andrey Kurilin 2015-08-14 17:40:30 +03:00
parent c6c3d7c314
commit 9e78de9fa9
3 changed files with 38 additions and 6 deletions

View File

@ -15,6 +15,7 @@
import re
from nova import exception
from nova.i18n import _
# Define the minimum and maximum version of the API across all of the
# REST API. The format of the version is:
@ -108,16 +109,40 @@ class APIVersionRequest(object):
def is_null(self):
return self.ver_major == 0 and self.ver_minor == 0
def __cmp__(self, other):
if not isinstance(other, APIVersionRequest):
raise TypeError
return cmp((self.ver_major, self.ver_minor),
(other.ver_major, other.ver_minor))
def _format_type_error(self, other):
return TypeError(_("'%(other)s' should be an instance of '%(cls)s'") %
{"other": other, "cls": self.__class__})
def __lt__(self, other):
if not isinstance(other, APIVersionRequest):
raise self._format_type_error(other)
return ((self.ver_major, self.ver_minor) <
(other.ver_major, other.ver_minor))
def __eq__(self, other):
if not isinstance(other, APIVersionRequest):
raise self._format_type_error(other)
return ((self.ver_major, self.ver_minor) ==
(other.ver_major, other.ver_minor))
def __gt__(self, other):
if not isinstance(other, APIVersionRequest):
raise self._format_type_error(other)
return ((self.ver_major, self.ver_minor) >
(other.ver_major, other.ver_minor))
def __le__(self, other):
return self < other or self == other
def __ne__(self, other):
return not self.__eq__(other)
def __ge__(self, other):
return self > other or self == other
def matches(self, min_version, max_version):
"""Returns whether the version object represents a version
greater than or equal to the minimum version and less than

View File

@ -79,13 +79,19 @@ class APIVersionRequestTests(test.NoDBTestCase):
v4 = api_version_request.APIVersionRequest("2.0")
v_null = api_version_request.APIVersionRequest()
self.assertTrue(v_null < v2)
self.assertTrue(v1 < v2)
self.assertTrue(v1 <= v2)
self.assertTrue(v1 <= v4)
self.assertTrue(v2 > v_null)
self.assertTrue(v3 > v2)
self.assertTrue(v1 >= v4)
self.assertTrue(v3 >= v2)
self.assertTrue(v1 != v2)
self.assertTrue(v1 == v4)
self.assertTrue(v1 != v_null)
self.assertTrue(v_null == v_null)
self.assertRaises(TypeError, v1.__cmp__, "2.1")
self.assertRaises(TypeError, v1.__lt__, "2.1")
def test_version_matches(self):
v1 = api_version_request.APIVersionRequest("2.0")

View File

@ -37,6 +37,7 @@ commands =
find . -type f -name "*.pyc" -delete
python -m subunit.run discover -t . ./nova/tests/ --list
python -m testtools.run \
nova.tests.unit.api.openstack.test_api_version_request \
nova.tests.unit.compute.test_keypairs \
nova.tests.unit.db.test_db_api \
nova.tests.unit.scheduler.filters.test_affinity_filters \