forked from alecthomas/voluptuous
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtests.py
223 lines (177 loc) · 6.54 KB
/
tests.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
import copy
from nose.tools import assert_equal
import voluptuous
from voluptuous import (
Schema, Required, Extra, Invalid, In, Remove, Literal,
Url, MultipleInvalid, LiteralInvalid, NotIn
)
def test_required():
"""Verify that Required works."""
schema = Schema({Required('q'): 1})
# Can't use nose's raises (because we need to access the raised
# exception, nor assert_raises which fails with Python 2.6.9.
try:
schema({})
except Invalid as e:
assert_equal(str(e), "required key not provided @ data['q']")
else:
assert False, "Did not raise Invalid"
def test_extra_with_required():
"""Verify that Required does not break Extra."""
schema = Schema({Required('toaster'): str, Extra: object})
r = schema({'toaster': 'blue', 'another_valid_key': 'another_valid_value'})
assert_equal(
r, {'toaster': 'blue', 'another_valid_key': 'another_valid_value'})
def test_iterate_candidates():
"""Verify that the order for iterating over mapping candidates is right."""
schema = {
"toaster": str,
Extra: object,
}
# toaster should be first.
assert_equal(voluptuous._iterate_mapping_candidates(schema)[0][0],
'toaster')
def test_in():
"""Verify that In works."""
schema = Schema({"color": In(frozenset(["blue", "red", "yellow"]))})
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
schema = Schema({"weight": int,
Remove("color"): str,
Remove("amount"): int})
out_ = schema({"weight": 10, "color": "red", "amount": 1})
assert "color" not in out_ and "amount" not in out_
# remove keys by type
schema = Schema({"weight": float,
"amount": int,
# remvove str keys with int values
Remove(str): int,
# keep str keys with str values
str: str})
out_ = schema({"weight": 73.4,
"condition": "new",
"amount": 5,
"left": 2})
# amount should stay since it's defined
# other string keys with int values will be removed
assert "amount" in out_ and "left" not in out_
# string keys with string values will stay
assert "condition" in out_
# remove value from list
schema = Schema([Remove(1), int])
out_ = schema([1, 2, 3, 4, 1, 5, 6, 1, 1, 1])
assert_equal(out_, [2, 3, 4, 5, 6])
# remove values from list by type
schema = Schema([1.0, Remove(float), int])
out_ = schema([1, 2, 1.0, 2.0, 3.0, 4])
assert_equal(out_, [1, 2, 1.0, 4])
def test_extra_empty_errors():
schema = Schema({'a': {Extra: object}}, required=True)
schema({'a': {}})
def test_literal():
""" test with Literal """
schema = Schema([Literal({"a": 1}), Literal({"b": 1})])
schema([{"a": 1}])
schema([{"b": 1}])
schema([{"a": 1}, {"b": 1}])
try:
schema([{"c": 1}])
except Invalid as e:
assert_equal(str(e), 'invalid list value @ data[0]')
else:
assert False, "Did not raise Invalid"
schema = Schema(Literal({"a": 1}))
try:
schema({"b": 1})
except MultipleInvalid as e:
assert_equal(str(e), "{'b': 1} not match for {'a': 1}")
assert_equal(len(e.errors), 1)
assert_equal(type(e.errors[0]), LiteralInvalid)
else:
assert False, "Did not raise Invalid"
def test_url_validation():
""" test with valid URL """
schema = Schema({"url": Url()})
out_ = schema({"url": "http://example.com/"})
assert 'http://example.com/', out_.get("url")
def test_url_validation_with_none():
""" test with invalid None url"""
schema = Schema({"url": Url()})
try:
schema({"url": None})
except MultipleInvalid as e:
assert_equal(str(e),
"expected a URL for dictionary value @ data['url']")
else:
assert False, "Did not raise Invalid for None url"
def test_url_validation_with_empty_string():
""" test with empty string URL """
schema = Schema({"url": Url()})
try:
schema({"url": ''})
except MultipleInvalid as e:
assert_equal(str(e),
"expected a URL for dictionary value @ data['url']")
else:
assert False, "Did not raise Invalid for empty string url"
def test_url_validation_without_host():
""" test with empty host URL """
schema = Schema({"url": Url()})
try:
schema({"url": 'http://'})
except MultipleInvalid as e:
assert_equal(str(e),
"expected a URL for dictionary value @ data['url']")
else:
assert False, "Did not raise Invalid for empty string url"
def test_copy_dict_undefined():
""" test with a copied dictionary """
fields = {
Required("foo"): int
}
copied_fields = copy.deepcopy(fields)
schema = Schema(copied_fields)
# This used to raise a `TypeError` because the instance of `Undefined`
# was a copy, so object comparison would not work correctly.
try:
schema({"foo": "bar"})
except Exception as e:
assert isinstance(e, MultipleInvalid)
def test_sorting():
""" Expect alphabetic sorting """
foo = Required('foo')
bar = Required('bar')
items = [foo, bar]
expected = [bar, foo]
result = sorted(items)
assert result == expected
def test_schema_extend():
"""Verify that Schema.extend copies schema keys from both."""
base = Schema({'a': int}, required=True)
extension = {'b': str}
extended = base.extend(extension)
assert base.schema == {'a': int}
assert extension == {'b': str}
assert extended.schema == {'a': int, 'b': str}
assert extended.required == base.required
assert extended.extra == base.extra
def test_schema_extend_overrides():
"""Verify that Schema.extend can override required/extra parameters."""
base = Schema({'a': int}, required=True)
extended = base.extend({'b': str}, required=False, extra=voluptuous.ALLOW_EXTRA)
assert base.required == True
assert base.extra == voluptuous.PREVENT_EXTRA
assert extended.required == False
assert extended.extra == voluptuous.ALLOW_EXTRA