From f2241ce5edf6e16b3f3456f08f9b5bd7afe64a8d Mon Sep 17 00:00:00 2001 From: Peter Marsh Date: Wed, 20 Jan 2016 13:18:32 +0000 Subject: [PATCH] Add NotIn validation Relatively self explanitory, this is a valdiator that ensures values are not in a given collection of values, e.g. schema = Schema({"color": NotIn(frozenset(["blue", "red", "yellow"]))}) schema({"color": "orange"}) # valid schema({"color": "blue"}) # invalid --- tests.py | 14 +++++++++++++- voluptuous.py | 18 ++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/tests.py b/tests.py index b352789..249f7fe 100644 --- a/tests.py +++ b/tests.py @@ -4,7 +4,7 @@ import voluptuous from voluptuous import ( Schema, Required, Extra, Invalid, In, Remove, Literal, - Url, MultipleInvalid, LiteralInvalid + Url, MultipleInvalid, LiteralInvalid, NotIn ) @@ -46,6 +46,18 @@ def test_in(): schema({"color": "blue"}) +def test_not_in(): + """Verify that NotIn works.""" + schema = Schema({"color": NotIn(frozenset(["blue", "red", "yellow"]))}) + schema({"color": "orange"}) + try: + schema({"color": "blue"}) + except Invalid as e: + assert_equal(str(e), "value is not allowed for dictionary value @ data['color']") + else: + assert False, "Did not raise NotInInvalid" + + def test_remove(): """Verify that Remove works.""" # remove dict keys diff --git a/voluptuous.py b/voluptuous.py index 4b9bc01..05abba0 100644 --- a/voluptuous.py +++ b/voluptuous.py @@ -1584,6 +1584,24 @@ def validator(value): return validator +class NotInInvalid(Invalid): + pass + + +def NotIn(container, msg=None): + """Validate that a value is not in a collection.""" + @wraps(NotIn) + def validator(value): + try: + check = value in container + except TypeError: + check = True + if check: + raise NotInInvalid(msg or 'value is not allowed') + return value + return validator + + def Lower(v): """Transform a string to lower case.