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__

Without the change in base.py, if r1==r2, the follow code should all
pass.
    self.assertEqual(r1, r2)
    self.assertNotEqual(r1, r2)
The change here is for a way to self.assertNotEqual(r1, r2) as
expected.

Change-Id: I72485d38eab8b5a2034a621e1eebf33b86832f35
Closes-Bug: #1586268
This commit is contained in:
yuyafei 2016-08-13 15:42:08 +08:00 committed by yuyafei
parent c67f7d56d4
commit ee60b3aabe
2 changed files with 14 additions and 2 deletions

View File

@ -506,6 +506,9 @@ class Resource(object):
return self.id == other.id
return self._info == other._info
def __ne__(self, other):
return not self == other
def is_loaded(self):
return self._loaded

View File

@ -28,19 +28,28 @@ class BaseTest(utils.TestCase):
def test_eq(self):
# Two resources of the same type with the same id: 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 = common_base.Resource(None, {'id': 1, 'name': 'hi'})
r2 = common_base.Resource(None, {'id': 1, 'name': 'hello'})
self.assertEqual(r1, r2)
self.assertTrue(r1 == r2)
self.assertFalse(r1 != r2)
# Two resources of different types: never equal
r1 = common_base.Resource(None, {'id': 1})
r2 = shares.Share(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 = common_base.Resource(None, {'name': 'joe', 'age': 12})
r2 = common_base.Resource(None, {'name': 'joe', 'age': 12})
self.assertEqual(r1, r2)
self.assertTrue(r1 == r2)
self.assertFalse(r1 != r2)
def test_findall_invalid_attribute(self):
# Make sure findall with an invalid attribute doesn't cause errors.