Skip to content

Commit

Permalink
implement Schema.__ne__ method to support != operator
Browse files Browse the repository at this point in the history
Previously only the __eq__ method was implemented, which could lead to
surprising behavior e.g.:

    Schema('foo') == Schema('foo')  # True
    Schema('foo') != Schema('foo')  # True

This adds the __ne__ method so that these operators are complementary as
one might expect.
  • Loading branch information
dtao committed Dec 6, 2017
1 parent 2c5c378 commit 0435511
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
3 changes: 3 additions & 0 deletions voluptuous/schema_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,9 @@ def __eq__(self, other):
return False
return other.schema == self.schema

def __ne__(self, other):
return not (self == other)

def __str__(self):
return str(self.schema)

Expand Down
31 changes: 31 additions & 0 deletions voluptuous/tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,37 @@ def test_equality_negative():
assert_false(Schema({'foo': 1, 'bar': 2}) == Schema("{'foo': 1, 'bar': 2}"))


def test_inequality():
assert_true(Schema('foo') != 'foo')

assert_true(Schema(['foo', 'bar']) != "['foo', 'bar']")
assert_true(Schema(['foo', 'bar']) != Schema("['foo', 'bar']"))

assert_true(Schema({'foo': 1, 'bar': 2}) != "{'foo': 1, 'bar': 2}")
assert_true(Schema({'foo': 1, 'bar': 2}) != Schema("{'foo': 1, 'bar': 2}"))


def test_inequality_negative():
assert_false(Schema('foo') != Schema('foo'))

assert_false(Schema(['foo', 'bar', 'baz']) !=
Schema(['foo', 'bar', 'baz']))

# Ensure two Schemas w/ two equivalent dicts initialized in a different
# order are considered equal.
dict_a = {}
dict_a['foo'] = 1
dict_a['bar'] = 2
dict_a['baz'] = 3

dict_b = {}
dict_b['baz'] = 3
dict_b['bar'] = 2
dict_b['foo'] = 1

assert_false(Schema(dict_a) != Schema(dict_b))


def test_repr():
"""Verify that __repr__ returns valid Python expressions"""
match = Match('a pattern', msg='message')
Expand Down

0 comments on commit 0435511

Please sign in to comment.