From bf392074baf9e47182bf28eb9cd2191c0af8cbcb Mon Sep 17 00:00:00 2001 From: Tuukka Mustonen Date: Sun, 11 Sep 2016 13:26:41 +0300 Subject: [PATCH] Add Equal validator --- voluptuous/tests/tests.py | 18 +++++++++++++++++- voluptuous/validators.py | 29 +++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/voluptuous/tests/tests.py b/voluptuous/tests/tests.py index 11e136b..d545cf6 100644 --- a/voluptuous/tests/tests.py +++ b/voluptuous/tests/tests.py @@ -5,7 +5,7 @@ Schema, Required, Extra, Invalid, In, Remove, Literal, Url, MultipleInvalid, LiteralInvalid, NotIn, Match, Email, Replace, Range, Coerce, All, Any, Length, FqdnUrl, ALLOW_EXTRA, PREVENT_EXTRA, - validate_schema, ExactSequence + validate_schema, ExactSequence, Equal ) from voluptuous.humanize import humanize_error @@ -435,3 +435,19 @@ def fn(arg): def test_range_exlcudes_nan(): s = Schema(Range(min=0, max=10)) assert_raises(MultipleInvalid, s, float('nan')) + + +def test_equal(): + s = Schema(Equal(1)) + s(1) + assert_raises(Invalid, s, 2) + s = Schema(Equal('foo')) + s('foo') + assert_raises(Invalid, s, 'bar') + s = Schema(Equal([1, 2])) + s([1, 2]) + assert_raises(Invalid, s, []) + assert_raises(Invalid, s, [1, 2, 3]) + # Evaluates exactly, not through validators + s = Schema(Equal(str)) + assert_raises(Invalid, s, 'foo') diff --git a/voluptuous/validators.py b/voluptuous/validators.py index 7da697f..a2576e0 100644 --- a/voluptuous/validators.py +++ b/voluptuous/validators.py @@ -691,3 +691,32 @@ def __call__(self, v): def __repr__(self): return 'Unique()' + + +class Equal(object): + """Ensure that value matches target. + + >>> s = Schema(Equal(1)) + >>> s(1) + 1 + >>> with raises(Invalid): + ... s(2) + + Validators are not supported, match must be exact: + + >>> s = Schema(Equal(str)) + >>> with raises(Invalid): + ... s('foo') + """ + + def __init__(self, target, msg=None): + self.target = target + self.msg = msg + + def __call__(self, v): + if v != self.target: + raise Invalid(self.msg or 'Values are not equal: value:{} != target:{}'.format(v, self.target)) + return v + + def __repr__(self): + return 'Equal({})'.format(self.target)