-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtest_base_model.py
executable file
·193 lines (162 loc) · 6.44 KB
/
test_base_model.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
#!/usr/bin/python3
"""Unittest module for the BaseModel Class."""
from models import storage
from models.base_model import BaseModel
from models.engine.file_storage import FileStorage
from datetime import datetime
import json
import os
import re
import time
import unittest
import uuid
class TestBaseModel(unittest.TestCase):
"""Test Cases for the BaseModel class."""
def setUp(self):
"""Sets up test methods."""
pass
def tearDown(self):
"""Tears down test methods."""
self.resetStorage()
pass
def resetStorage(self):
"""Resets FileStorage data."""
FileStorage._FileStorage__objects = {}
if os.path.isfile(FileStorage._FileStorage__file_path):
os.remove(FileStorage._FileStorage__file_path)
def test_3_instantiation(self):
"""Tests instantiation of BaseModel class."""
b = BaseModel()
self.assertEqual(str(type(b)), "<class 'models.base_model.BaseModel'>")
self.assertIsInstance(b, BaseModel)
self.assertTrue(issubclass(type(b), BaseModel))
def test_3_init_no_args(self):
"""Tests __init__ with no arguments."""
self.resetStorage()
with self.assertRaises(TypeError) as e:
BaseModel.__init__()
msg = "__init__() missing 1 required positional argument: 'self'"
self.assertEqual(str(e.exception), msg)
def test_3_init_many_args(self):
"""Tests __init__ with many arguments."""
self.resetStorage()
args = [i for i in range(1000)]
b = BaseModel(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
b = BaseModel(*args)
def test_3_attributes(self):
"""Tests attributes value for instance of a BaseModel class."""
attributes = storage.attributes()["BaseModel"]
o = BaseModel()
for k, v in attributes.items():
self.assertTrue(hasattr(o, k))
self.assertEqual(type(getattr(o, k, None)), v)
def test_3_datetime_created(self):
"""Tests if updated_at & created_at are current at creation."""
date_now = datetime.now()
b = BaseModel()
diff = b.updated_at - b.created_at
self.assertTrue(abs(diff.total_seconds()) < 0.01)
diff = b.created_at - date_now
self.assertTrue(abs(diff.total_seconds()) < 0.1)
def test_3_id(self):
"""Tests for unique user ids."""
nl = [BaseModel().id for i in range(1000)]
self.assertEqual(len(set(nl)), len(nl))
def test_3_save(self):
"""Tests the public instance method save()."""
b = BaseModel()
time.sleep(0.5)
date_now = datetime.now()
b.save()
diff = b.updated_at - date_now
self.assertTrue(abs(diff.total_seconds()) < 0.01)
def test_3_str(self):
"""Tests for __str__ method."""
b = BaseModel()
rex = re.compile(r"^\[(.*)\] \((.*)\) (.*)$")
res = rex.match(str(b))
self.assertIsNotNone(res)
self.assertEqual(res.group(1), "BaseModel")
self.assertEqual(res.group(2), b.id)
s = res.group(3)
s = re.sub(r"(datetime\.datetime\([^)]*\))", "'\\1'", s)
d = json.loads(s.replace("'", '"'))
d2 = b.__dict__.copy()
d2["created_at"] = repr(d2["created_at"])
d2["updated_at"] = repr(d2["updated_at"])
self.assertEqual(d, d2)
def test_3_to_dict(self):
"""Tests the public instance method to_dict()."""
b = BaseModel()
b.name = "Laura"
b.age = 23
d = b.to_dict()
self.assertEqual(d["id"], b.id)
self.assertEqual(d["__class__"], type(b).__name__)
self.assertEqual(d["created_at"], b.created_at.isoformat())
self.assertEqual(d["updated_at"], b.updated_at.isoformat())
self.assertEqual(d["name"], b.name)
self.assertEqual(d["age"], b.age)
def test_3_to_dict_no_args(self):
"""Tests to_dict() with no arguments."""
self.resetStorage()
with self.assertRaises(TypeError) as e:
BaseModel.to_dict()
msg = "to_dict() missing 1 required positional argument: 'self'"
self.assertEqual(str(e.exception), msg)
def test_3_to_dict_excess_args(self):
"""Tests to_dict() with too many arguments."""
self.resetStorage()
with self.assertRaises(TypeError) as e:
BaseModel.to_dict(self, 98)
msg = "to_dict() takes 1 positional argument but 2 were given"
self.assertEqual(str(e.exception), msg)
def test_4_instantiation(self):
"""Tests instantiation with **kwargs."""
my_model = BaseModel()
my_model.name = "Holberton"
my_model.my_number = 89
my_model_json = my_model.to_dict()
my_new_model = BaseModel(**my_model_json)
self.assertEqual(my_new_model.to_dict(), my_model.to_dict())
def test_4_instantiation_dict(self):
"""Tests instantiation with **kwargs from custom dict."""
d = {"__class__": "BaseModel",
"updated_at":
datetime(2050, 12, 30, 23, 59, 59, 123456).isoformat(),
"created_at": datetime.now().isoformat(),
"id": uuid.uuid4(),
"var": "foobar",
"int": 108,
"float": 3.14}
o = BaseModel(**d)
self.assertEqual(o.to_dict(), d)
def test_5_save(self):
"""Tests that storage.save() is called from save()."""
self.resetStorage()
b = BaseModel()
b.save()
key = "{}.{}".format(type(b).__name__, b.id)
d = {key: b.to_dict()}
self.assertTrue(os.path.isfile(FileStorage._FileStorage__file_path))
with open(FileStorage._FileStorage__file_path,
"r", encoding="utf-8") as f:
self.assertEqual(len(f.read()), len(json.dumps(d)))
f.seek(0)
self.assertEqual(json.load(f), d)
def test_5_save_no_args(self):
"""Tests save() with no arguments."""
self.resetStorage()
with self.assertRaises(TypeError) as e:
BaseModel.save()
msg = "save() missing 1 required positional argument: 'self'"
self.assertEqual(str(e.exception), msg)
def test_5_save_excess_args(self):
"""Tests save() with too many arguments."""
self.resetStorage()
with self.assertRaises(TypeError) as e:
BaseModel.save(self, 98)
msg = "save() takes 1 positional argument but 2 were given"
self.assertEqual(str(e.exception), msg)
if __name__ == '__main__':
unittest.main()