Add __ne__ built-in function

In Python 3 __ne__ by default delegates to __eq__ and inverts the
result, but in Python 2 they urge you to define __ne__ when you
define __eq__ for it to work properly [1].There are no implied
relationships among the comparison operators. The truth of x==y
does not imply that x!=y is false. Accordingly, when defining
__eq__(), one should also define __ne__() so that the operators
will behave as expected.
[1]https://docs.python.org/2/reference/datamodel.html#object.__ne__
Also fixes spelling errors:resoruces.

Change-Id: Iae4ce0fe84fae810711cc8c3fdb94eb9ca1d772e
Closes-Bug: #1586268
This commit is contained in:
yuyafei 2016-07-05 15:21:02 +08:00
parent 64d458fcf8
commit ef34175095
2 changed files with 19 additions and 3 deletions

View File

@ -523,6 +523,10 @@ class Resource(object):
return False
return self._info == other._info
def __ne__(self, other):
"""Define inequality for resources."""
return not self == other
def is_loaded(self):
return self._loaded

View File

@ -58,25 +58,37 @@ class BaseTest(utils.TestCase):
r1 = base.Resource(None, {'id': 1, 'name': 'hi'})
r2 = base.Resource(None, {'id': 1, 'name': 'hello'})
self.assertNotEqual(r1, r2)
self.assertTrue(r1 != r2)
# Two resources with same ID: equal if their info is equal
# The truth of r1==r2 does not imply that r1!=r2 is false in PY2.
# Test that inequality operator is defined and that comparing equal
# items returns False
r1 = base.Resource(None, {'id': 1, 'name': 'hello'})
r2 = base.Resource(None, {'id': 1, 'name': 'hello'})
self.assertEqual(r1, r2)
self.assertTrue(r1 == r2)
self.assertFalse(r1 != r2)
# Two resoruces of different types: never equal
# Two resources of different types: never equal
r1 = base.Resource(None, {'id': 1})
r2 = roles.Role(None, {'id': 1})
self.assertNotEqual(r1, r2)
self.assertTrue(r1 != r2)
# Two resources with no ID: equal if their info is equal
# The truth of r1==r2 does not imply that r1!=r2 is false in PY2.
# Test that inequality operator is defined and that comparing equal
# items returns False.
r1 = base.Resource(None, {'name': 'joe', 'age': 12})
r2 = base.Resource(None, {'name': 'joe', 'age': 12})
self.assertEqual(r1, r2)
self.assertTrue(r1 == r2)
self.assertFalse(r1 != r2)
r1 = base.Resource(None, {'id': 1})
self.assertNotEqual(r1, object())
self.assertTrue(r1 != object())
self.assertNotEqual(r1, {'id': 1})
self.assertTrue(r1 != {'id': 1})
def test_human_id(self):
r = base.Resource(None, {"name": "1 of !"})