Example #1
0
    def test_accepts(self):
        @V.accepts(a="fraction", b=int, body={"+field_ids": ["integer"],
                                              "?is_ok": bool,
                                              "?sex": "gender"})
        def f(a, b=1, **body):
            pass

        valid = [
            partial(f, 2.0, field_ids=[]),
            partial(f, Decimal(1), b=5, field_ids=[1], is_ok=True),
            partial(f, a=3j, b=-1, field_ids=[long(1), 2, long(5)], sex="male"),
            partial(f, 5 + 3j, 0, field_ids=[long(-12), 0, long(0)], is_ok=False, sex="female"),
            partial(f, 2.0, field_ids=[], additional="extra param allowed"),
        ]

        invalid = [
            partial(f, 1),  # 'a' is not a fraction
            partial(f, 1.0),  # missing 'field_ids' from body
            partial(f, 1.0, b=4.1, field_ids=[]),  # 'b' is not int
            partial(f, 1.0, b=2, field_ids=3),  # 'field_ids' is not a list
            partial(f, 1.0, b=1, field_ids=[3.0]),  # 'field_ids[0]' is not a integer
            partial(f, 1.0, b=1, field_ids=[], is_ok=1),  # 'is_ok' is not bool
            partial(f, 1.0, b=1, field_ids=[], sex="m"),  # 'sex' is not a gender
        ]

        for fcall in valid:
            fcall()
        for fcall in invalid:
            self.assertRaises(V.ValidationError, fcall)
Example #2
0
    def test_condition(self):
        def is_odd(n):
            return n % 2 == 1

        is_even = lambda n: n % 2 == 0

        class C(object):
            def is_odd_method(self, n):
                return is_odd(n)

            def is_even_method(self, n):
                return is_even(n)

            is_odd_static = staticmethod(is_odd)
            is_even_static = staticmethod(is_even)

        for obj in is_odd, C().is_odd_method, C.is_odd_static:
            self._testValidation(obj,
                                 valid=[1, long(3), -11, 9.0, True],
                                 invalid=[6, 2.1, False, "1", []])

        for obj in is_even, C().is_even_method, C.is_even_static:
            self._testValidation(obj,
                                 valid=[6, long(2), -42, 4.0, 0, 0.0, False],
                                 invalid=[1, 2.1, True, "2", []])

        self._testValidation(str.isalnum,
                             valid=["abc", "123", "ab32c"],
                             invalid=["a+b", "a 1", "", True, 2])

        self.assertRaises(TypeError, V.Condition, C)
        self.assertRaises(TypeError,
                          V.Condition(is_even, traps=()).validate, [2, 4])
Example #3
0
    def test_condition(self):
        def is_odd(n):
            return n % 2 == 1
        is_even = lambda n: n % 2 == 0

        class C(object):
            def is_odd_method(self, n):
                return is_odd(n)

            def is_even_method(self, n):
                return is_even(n)
            is_odd_static = staticmethod(is_odd)
            is_even_static = staticmethod(is_even)

        for obj in is_odd, C().is_odd_method, C.is_odd_static:
            self._testValidation(obj,
                                 valid=[1, long(3), -11, 9.0, True],
                                 invalid=[6, 2.1, False, "1", []])

        for obj in is_even, C().is_even_method, C.is_even_static:
            self._testValidation(obj,
                                 valid=[6, long(2), -42, 4.0, 0, 0.0, False],
                                 invalid=[1, 2.1, True, "2", []])

        self._testValidation(str.isalnum,
                             valid=["abc", "123", "ab32c"],
                             invalid=["a+b", "a 1", "", True, 2])

        self.assertRaises(TypeError, V.Condition, C)
        self.assertRaises(TypeError, V.Condition(is_even, traps=()).validate, [2, 4])
Example #4
0
 def test_homogeneous_sequence(self):
     for obj in V.HomogeneousSequence, V.HomogeneousSequence():
         self._testValidation(obj,
                              valid=[[], [1], (1, 2), [1, (2, 3), 4]],
                              invalid=[1, 1.1, "foo", u"bar", {}, False, True])
     self._testValidation(["number"],
                          valid=[[], [1, 2.1, long(3)], (1, long(4), 6)],
                          invalid=[[1, 2.1, long(3), u"x"]])
Example #5
0
 def test_homogeneous_sequence(self):
     for obj in V.HomogeneousSequence, V.HomogeneousSequence():
         self._testValidation(
             obj,
             valid=[[], [1], (1, 2), [1, (2, 3), 4]],
             invalid=[1, 1.1, "foo", u"bar", {}, False, True])
     self._testValidation(["number"],
                          valid=[[], [1, 2.1, long(3)], (1, long(4), 6)],
                          invalid=[[1, 2.1, long(3), u"x"]])
Example #6
0
 def test_nonnullable(self):
     for obj in V.NonNullable, V.NonNullable():
         self._testValidation(obj,
                              invalid=[None],
                              valid=[0, False, "", (), []])
     for obj in "+integer", V.NonNullable(V.Integer()), V.NonNullable("?integer"):
         self._testValidation(obj,
                              invalid=[None, False],
                              valid=[0, long(2)])
Example #7
0
 def test_nonnullable(self):
     for obj in V.NonNullable, V.NonNullable():
         self._testValidation(obj,
                              invalid=[None],
                              valid=[0, False, "", (), []])
     for obj in "+integer", V.NonNullable(
             V.Integer()), V.NonNullable("?integer"):
         self._testValidation(obj,
                              invalid=[None, False],
                              valid=[0, long(2)])
Example #8
0
    def test_accepts(self):
        @V.accepts(a="fraction",
                   b=int,
                   body={
                       "+field_ids": ["integer"],
                       "?is_ok": bool,
                       "?sex": "gender"
                   })
        def f(a, b=1, **body):
            pass

        valid = [
            partial(f, 2.0, field_ids=[]),
            partial(f, Decimal(1), b=5, field_ids=[1], is_ok=True),
            partial(f, a=3j, b=-1, field_ids=[long(1), 2, long(5)],
                    sex="male"),
            partial(f,
                    5 + 3j,
                    0,
                    field_ids=[long(-12), 0, long(0)],
                    is_ok=False,
                    sex="female"),
            partial(f, 2.0, field_ids=[], additional="extra param allowed"),
        ]

        invalid = [
            partial(f, 1),  # 'a' is not a fraction
            partial(f, 1.0),  # missing 'field_ids' from body
            partial(f, 1.0, b=4.1, field_ids=[]),  # 'b' is not int
            partial(f, 1.0, b=2, field_ids=3),  # 'field_ids' is not a list
            partial(f, 1.0, b=1,
                    field_ids=[3.0]),  # 'field_ids[0]' is not a integer
            partial(f, 1.0, b=1, field_ids=[], is_ok=1),  # 'is_ok' is not bool
            partial(f, 1.0, b=1, field_ids=[],
                    sex="m"),  # 'sex' is not a gender
        ]

        for fcall in valid:
            fcall()
        for fcall in invalid:
            self.assertRaises(V.ValidationError, fcall)
Example #9
0
    def test_complex_validation(self):

        for valid in [
            {'n': 2},
            {'n': 2.1, 'i': 3},
            {'n': -1, 'b': False},
            {'n': Decimal(3), 'e': "r"},
            {'n': long(2), 'd': datetime.now()},
            {'n': 0, 'd': date.today()},
            {'n': 0, 's': "abc"},
            {'n': 0, 'p': None},
            {'n': 0, 'p': "123"},
            {'n': 0, 'l': []},
            {'n': 0, 'l': [{"s2": "foo"}, {"s2": ""}]},
            {'n': 0, 't': (u"joe", 3.1)},
            {'n': 0, 'h': {5: ["foo", u"bar"], 0: []}},
            {'n': 0, 'o': {"i2": 3}},
        ]:
            self.complex_validator.validate(valid, adapt=False)

        for invalid in [
            None,
            {},
            {'n': None},
            {'n': True},
            {'n': 1, 'e': None},
            {'n': 1, 'e': "a"},
            {'n': 1, 'd': None},
            {'n': 1, 's': None},
            {'n': 1, 's': ''},
            {'n': 1, 's': '123456789'},
            {'n': 1, 'p': '123a'},
            {'n': 1, 'l': None},
            {'n': 1, 'l': [None]},
            {'n': 1, 'l': [{}]},
            {'n': 1, 'l': [{'s2': None}]},
            {'n': 1, 'l': [{'s2': 1}]},
            {'n': 1, 't': ()},
            {'n': 0, 't': (3.1, u"joe")},
            {'n': 0, 't': (u"joe", None)},
            {'n': 1, 'h': {5: ["foo", u"bar"], "0": []}},
            {'n': 1, 'h': {5: ["foo", 2.1], 0: []}},
            {'n': 1, 'o': {}},
            {'n': 1, 'o': {"i2": "2"}},
        ]:
            self.assertRaises(V.ValidationError,
                              self.complex_validator.validate, invalid, adapt=False)
Example #10
0
 def test_complex_adaptation(self):
     for value in [
         {'n': 2},
         {'n': 2.1, 'i': 3},
         {'n': -1, 'b': False},
         {'n': Decimal(3), 'e': "r"},
         {'n': long(2), 'd': datetime.now()},
         {'n': 0, 'd': date.today()},
         {'n': 0, 's': "abc"},
         {'n': 0, 'p': None},
         {'n': 0, 'p': "123"},
         {'n': 0, 'l': []},
         {'n': 0, 'l': [{"s2": "foo"}, {"s2": ""}]},
         {'n': 0, 't': (u"joe", 3.1)},
         {'n': 0, 'h': {5: ["foo", u"bar"], 0: []}},
         {'n': 0, 'o': {"i2": 3}},
     ]:
         adapted = self.complex_validator.validate(value)
         self.assertTrue(isinstance(adapted["n"], (int, long, float, Decimal)))
         self.assertTrue(isinstance(adapted["i"], int_types))
         self.assertTrue(adapted.get("b") is None or isinstance(adapted["b"], bool))
         self.assertTrue(adapted.get("d") is None or isinstance(adapted["d"], (date, datetime)))
         self.assertTrue(adapted.get("e") is None or adapted["e"] in "rgb")
         self.assertTrue(adapted.get("s") is None or isinstance(adapted["s"], string_types))
         self.assertTrue(adapted.get("l") is None or isinstance(adapted["l"], list))
         self.assertTrue(adapted.get("t") is None or isinstance(adapted["t"], tuple))
         self.assertTrue(adapted.get("h") is None or isinstance(adapted["h"], dict))
         if adapted.get("l") is not None:
             self.assertTrue(all(isinstance(item["s2"], string_types)
                                 for item in adapted["l"]))
         if adapted.get("t") is not None:
             self.assertEqual(len(adapted["t"]), 2)
             self.assertTrue(isinstance(adapted["t"][0], unicode))
             self.assertTrue(isinstance(adapted["t"][1], float))
         if adapted.get("h") is not None:
             self.assertTrue(all(isinstance(key, int)
                                 for key in adapted["h"].keys()))
             self.assertTrue(all(isinstance(value_item, string_types)
                                 for value in adapted["h"].values()
                                 for value_item in value))
         if adapted.get("o") is not None:
             self.assertTrue(isinstance(adapted["o"]["i2"], int_types))
Example #11
0
    def test_complex_validation(self):

        for valid in [
            {
                'n': 2
            },
            {
                'n': 2.1,
                'i': 3
            },
            {
                'n': -1,
                'b': False
            },
            {
                'n': Decimal(3),
                'e': "r"
            },
            {
                'n': long(2),
                'd': datetime.now()
            },
            {
                'n': 0,
                'd': date.today()
            },
            {
                'n': 0,
                's': "abc"
            },
            {
                'n': 0,
                'p': None
            },
            {
                'n': 0,
                'p': "123"
            },
            {
                'n': 0,
                'l': []
            },
            {
                'n': 0,
                'l': [{
                    "s2": "foo"
                }, {
                    "s2": ""
                }]
            },
            {
                'n': 0,
                't': (u"joe", 3.1)
            },
            {
                'n': 0,
                'h': {
                    5: ["foo", u"bar"],
                    0: []
                }
            },
            {
                'n': 0,
                'o': {
                    "i2": 3
                }
            },
        ]:
            self.complex_validator.validate(valid, adapt=False)

        for invalid in [
                None,
            {},
            {
                'n': None
            },
            {
                'n': True
            },
            {
                'n': 1,
                'e': None
            },
            {
                'n': 1,
                'e': "a"
            },
            {
                'n': 1,
                'd': None
            },
            {
                'n': 1,
                's': None
            },
            {
                'n': 1,
                's': ''
            },
            {
                'n': 1,
                's': '123456789'
            },
            {
                'n': 1,
                'p': '123a'
            },
            {
                'n': 1,
                'l': None
            },
            {
                'n': 1,
                'l': [None]
            },
            {
                'n': 1,
                'l': [{}]
            },
            {
                'n': 1,
                'l': [{
                    's2': None
                }]
            },
            {
                'n': 1,
                'l': [{
                    's2': 1
                }]
            },
            {
                'n': 1,
                't': ()
            },
            {
                'n': 0,
                't': (3.1, u"joe")
            },
            {
                'n': 0,
                't': (u"joe", None)
            },
            {
                'n': 1,
                'h': {
                    5: ["foo", u"bar"],
                    "0": []
                }
            },
            {
                'n': 1,
                'h': {
                    5: ["foo", 2.1],
                    0: []
                }
            },
            {
                'n': 1,
                'o': {}
            },
            {
                'n': 1,
                'o': {
                    "i2": "2"
                }
            },
        ]:
            self.assertRaises(V.ValidationError,
                              self.complex_validator.validate,
                              invalid,
                              adapt=False)
Example #12
0
 def test_complex_adaptation(self):
     for value in [
         {
             'n': 2
         },
         {
             'n': 2.1,
             'i': 3
         },
         {
             'n': -1,
             'b': False
         },
         {
             'n': Decimal(3),
             'e': "r"
         },
         {
             'n': long(2),
             'd': datetime.now()
         },
         {
             'n': 0,
             'd': date.today()
         },
         {
             'n': 0,
             's': "abc"
         },
         {
             'n': 0,
             'p': None
         },
         {
             'n': 0,
             'p': "123"
         },
         {
             'n': 0,
             'l': []
         },
         {
             'n': 0,
             'l': [{
                 "s2": "foo"
             }, {
                 "s2": ""
             }]
         },
         {
             'n': 0,
             't': (u"joe", 3.1)
         },
         {
             'n': 0,
             'h': {
                 5: ["foo", u"bar"],
                 0: []
             }
         },
         {
             'n': 0,
             'o': {
                 "i2": 3
             }
         },
     ]:
         adapted = self.complex_validator.validate(value)
         self.assertTrue(
             isinstance(adapted["n"], (int, long, float, Decimal)))
         self.assertTrue(isinstance(adapted["i"], int_types))
         self.assertTrue(
             adapted.get("b") is None or isinstance(adapted["b"], bool))
         self.assertTrue(
             adapted.get("d") is None or isinstance(adapted["d"],
                                                    (date, datetime)))
         self.assertTrue(adapted.get("e") is None or adapted["e"] in "rgb")
         self.assertTrue(
             adapted.get("s") is None
             or isinstance(adapted["s"], string_types))
         self.assertTrue(
             adapted.get("l") is None or isinstance(adapted["l"], list))
         self.assertTrue(
             adapted.get("t") is None or isinstance(adapted["t"], tuple))
         self.assertTrue(
             adapted.get("h") is None or isinstance(adapted["h"], dict))
         if adapted.get("l") is not None:
             self.assertTrue(
                 all(
                     isinstance(item["s2"], string_types)
                     for item in adapted["l"]))
         if adapted.get("t") is not None:
             self.assertEqual(len(adapted["t"]), 2)
             self.assertTrue(isinstance(adapted["t"][0], unicode))
             self.assertTrue(isinstance(adapted["t"][1], float))
         if adapted.get("h") is not None:
             self.assertTrue(
                 all(isinstance(key, int) for key in adapted["h"].keys()))
             self.assertTrue(
                 all(
                     isinstance(value_item, string_types)
                     for value in adapted["h"].values()
                     for value_item in value))
         if adapted.get("o") is not None:
             self.assertTrue(isinstance(adapted["o"]["i2"], int_types))