-
Notifications
You must be signed in to change notification settings - Fork 1
/
flask_validictory_tests.py
84 lines (69 loc) · 2.37 KB
/
flask_validictory_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
import unittest
from flask import Flask, json
from validictory import FieldValidationError
from flask.ext.validictory import expects_json
app = Flask(__name__)
app.config['DEBUG'] = True
test1_schema = {
'type': 'object',
'properties':
{
'name': {'type': 'string'},
'address': {'type': 'string'},
'zip': {'type': 'integer', 'minLength': 5, 'maxLength': 10},
'country': {'type': 'string', 'minLength': 2, 'maxLength': 2},
'date-of-birth': {'type': 'string', 'format': 'date'},
'gender': {'type': 'string', 'required': False, 'enum': ['male', 'female']},
'email': {'type': 'string', 'format': 'email'},
'phones':
{
'type': 'object',
'properties':
{
'home': {'required': False, 'type': 'string', 'format': 'phone'},
'cell': {'required': False, 'type': 'string', 'format': 'phone'}
}
}
}
}
test2_schema = {'type': 'object',
'properties': {'name': {'type': 'string'}, 'email': {'type': 'string', 'format': 'email'}},
'required': ['email']}
@app.route('/test1', methods=['POST'])
@expects_json(test1_schema)
def test1():
return 'success'
@app.route('/test2', methods=['POST'])
@expects_json(test2_schema)
def test2():
return 'success'
@app.errorhandler(FieldValidationError)
def on_error(e):
return 'error'
client = app.test_client()
class JsonSchemaTests(unittest.TestCase):
def test_valid_json(self):
r = client.post(
'/test1',
content_type='application/json',
data=json.dumps({
'name': 'Mark Angrish',
'address': 'Imaginationland',
'zip': 90210,
'country': 'AU',
'date-of-birth': '1999-12-12',
'gender': 'male',
'email': 'me@you.com',
'phones': {'cell': '+1 650-555-1234'}
})
)
self.assertIn('success', r.data)
def test_invalid_json(self):
r = client.post(
'/test2',
content_type='application/json',
data=json.dumps({
'name': 'Britney Spears'
})
)
self.assertIn('error', r.data)