This repository has been archived by the owner on Jun 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathtests.py
executable file
·94 lines (72 loc) · 2.63 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
import unittest
from flaskext.jsonify import jsonify, JSONStatusResponse
from datetime import datetime
from json import JSONEncoder, dumps
class CustomEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
else:
return super(CustomEncoder, self).default(obj)
class JsonifyTests(unittest.TestCase):
def setUp(self):
self.easy_object = {
'name': 'Chris',
'age': 23,
'friend': {
'name': 'Alex'
},
'is_male': True
}
self.hard_object = {
'name': 'Chris',
'age': 23,
'friend': {
'name': 'Alex'
},
'is_male': True,
'date': datetime.now()
}
# ----- Test Cases ----------------------------------------------
# Serializing an object without a custom class that should
# be serializable with the default class should not raise an exception
@jsonify
def easy_obj_no_custom_class(self):
return self.easy_object
def test_easy_obj_no_decorator(self):
self.easy_obj_no_custom_class()
# Serializing an object with a custom class that should
# be serializable with the default class should also not raise an exception
@jsonify(cls=CustomEncoder)
def easy_obj_with_custom_class(self):
return self.easy_object
def test_easy_obj_with_decorator(self):
self.easy_obj_with_custom_class()
# Serializing an object without a custom class that is not
# serializable with the default class should raise an exception
@jsonify
def hard_obj_no_custom_class(self):
return self.hard_object
def test_hard_obj_no_decorator(self):
try:
self.hard_obj_no_custom_class()
self.fail("Uh oh, this case should fail and it doesn't")
except:
pass
# Serializing an object with a custom class that is not
# serializable with the default class should succeed
@jsonify(cls=CustomEncoder)
def hard_obj_with_custom_class(self):
return self.hard_object
def test_hard_obj_with_decorator(self):
self.hard_obj_with_custom_class()
# Returning an error response that preserves the error code
@jsonify
def error_code_function(self):
return JSONStatusResponse(404, {'message': 'error'})
def test_error_code(self):
response = self.error_code_function()
self.assertTrue(response.status_code == 404)
self.assertTrue(response.data == dumps({"message": "error"}))
if __name__ == '__main__':
unittest.main()