-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy path5_singleton_testing.py
More file actions
75 lines (57 loc) · 1.9 KB
/
5_singleton_testing.py
File metadata and controls
75 lines (57 loc) · 1.9 KB
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
import unittest
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class Database(metaclass=Singleton):
def __init__(self):
self.population = {}
f = open('capitals.txt', 'r')
lines = f.readlines()
for i in range(0, len(lines), 2):
self.population[lines[i].strip()] = int(lines[i + 1].strip())
f.close()
class SingletonRecordFinder:
def total_population(self, cities):
result = 0
for c in cities:
result += Database().population[c]
return result
class ConfigurableRecordFinder:
def __init__(self, db):
self.db = db
def total_population(self, cities):
result = 0
for c in cities:
result += self.db.population[c]
return result
class DummyDatabase:
population = {
'alpha': 1,
'beta': 2,
'gamma': 3
}
def get_population(self, name):
return self.population[name]
class SingletonTests(unittest.TestCase):
def test_is_singleton(self):
db = Database()
db2 = Database()
self.assertEqual(db, db2)
def test_singleton_total_population(self):
""" This tests on a live database :( """
rf = SingletonRecordFinder()
names = ['Seoul', 'Mexico City']
tp = rf.total_population(names)
self.assertEqual(tp, 17500000 + 17400000) # what if these change?
ddb = DummyDatabase()
def test_dependent_total_population(self):
crf = ConfigurableRecordFinder(self.ddb)
self.assertEqual(
crf.total_population(['alpha', 'beta']),
3
)
if __name__ == '__main__':
unittest.main()