瀏覽代碼

Added tests on Types hierarchy and selected field for migrate_handler() method

Yann Weber 9 年之前
父節點
當前提交
ea51650ab3
共有 1 個檔案被更改,包括 83 行新增57 行删除
  1. 83
    57
      EditorialModel/test/test_model.py

+ 83
- 57
EditorialModel/test/test_model.py 查看文件

@@ -1,5 +1,5 @@
1 1
 import unittest
2
-from unittest.mock import MagicMock, patch
2
+from unittest.mock import patch
3 3
 
4 4
 from EditorialModel.model import Model
5 5
 from EditorialModel.classes import EmClass
@@ -20,7 +20,7 @@ from EditorialModel.migrationhandler.dummy import DummyMigrationHandler
20 20
 class TestModel(unittest.TestCase):
21 21
 
22 22
     def setUp(self):
23
-        self.me = Model(EmBackendJson('EditorialModel/test/me.json'))
23
+        self.ed_mod = Model(EmBackendJson('EditorialModel/test/me.json'))
24 24
 
25 25
     def test_init(self):
26 26
         """ Instanciation test """
@@ -43,52 +43,52 @@ class TestModel(unittest.TestCase):
43 43
         """ Test components fetching """
44 44
         uid_l = list()
45 45
         for comp_class in [EmClass, EmType, EmField, EmFieldGroup]:
46
-            comp_l = self.me.components(comp_class)
46
+            comp_l = self.ed_mod.components(comp_class)
47 47
             #Testing types of returned components
48 48
             for component in comp_l:
49 49
                 self.assertTrue(isinstance(component, comp_class), "Model.components method doesn't return EmComponent of the right type. Asked for {} but got {}".format(type(comp_class), type(component)))
50 50
                 uid_l.append(component.uid)
51 51
 
52 52
         #Testing that we have fetched all the components
53
-        for uid in self.me._components['uids']:
53
+        for uid in self.ed_mod._components['uids']:
54 54
             self.assertIn(uid, uid_l, "Component with uid %d was not fetched" % uid)
55 55
 
56 56
         #Testing components method without parameters
57
-        uid_l = [comp.uid for comp in self.me.components()]
57
+        uid_l = [comp.uid for comp in self.ed_mod.components()]
58 58
 
59
-        for uid in self.me._components['uids']:
59
+        for uid in self.ed_mod._components['uids']:
60 60
             self.assertIn(uid, uid_l, "Component with uid %d was not fetched using me.components()" % uid)
61 61
 
62
-        self.assertFalse(self.me.components(EmComponent))
63
-        self.assertFalse(self.me.components(int))
62
+        self.assertFalse(self.ed_mod.components(EmComponent))
63
+        self.assertFalse(self.ed_mod.components(int))
64 64
 
65 65
     def test_component(self):
66 66
         """ Test component fetching by uid """
67 67
         #assert that __hash__, __eq__ and components() are corrects
68
-        for comp in self.me.components():
69
-            self.assertEqual(comp, self.me.component(comp.uid))
68
+        for comp in self.ed_mod.components():
69
+            self.assertEqual(comp, self.ed_mod.component(comp.uid))
70 70
 
71 71
         for baduid in [-1, 0xffffff, "hello"]:
72
-            self.assertFalse(self.me.component(baduid))
72
+            self.assertFalse(self.ed_mod.component(baduid))
73 73
 
74 74
     def test_sort_components(self):
75 75
         """ Test that Model.sort_components method actually sort components """
76 76
         # disordering an EmClass
77
-        cl_l = self.me.components(EmClass)
77
+        cl_l = self.ed_mod.components(EmClass)
78 78
         last_class = cl_l[0]
79 79
         last_class.rank = 10000
80
-        self.me.sort_components(EmClass)
81
-        self.assertEqual(self.me._components['EmClass'][-1].uid, last_class.uid, "The sort_components method doesn't really sort by rank")
80
+        self.ed_mod.sort_components(EmClass)
81
+        self.assertEqual(self.ed_mod._components['EmClass'][-1].uid, last_class.uid, "The sort_components method doesn't really sort by rank")
82 82
 
83 83
     def test_new_uid(self):
84 84
         """ Test that model.new_uid return a new uniq uid """
85
-        new_uid = self.me.new_uid()
86
-        self.assertNotIn(new_uid, self.me._components['uids'].keys())
85
+        new_uid = self.ed_mod.new_uid()
86
+        self.assertNotIn(new_uid, self.ed_mod._components['uids'].keys())
87 87
 
88 88
     def test_create_component_fails(self):
89 89
         """ Test the create_component method with invalid arguments """
90 90
 
91
-        testDatas = {
91
+        test_datas = {
92 92
             'name': 'FooBar',
93 93
             'classtype': 'entity',
94 94
             'help_text': None,
@@ -96,31 +96,31 @@ class TestModel(unittest.TestCase):
96 96
         }
97 97
 
98 98
         #Invalid uid
99
-        used_uid = self.me.components()[0].uid
99
+        used_uid = self.ed_mod.components()[0].uid
100 100
         for bad_uid in [used_uid, -1, -1000, 'HelloWorld']:
101 101
             with self.assertRaises(ValueError, msg="The component was created but the given uid (%s) whas invalid (allready used, negative or WTF)" % bad_uid):
102
-                self.me.create_component('EmClass', testDatas, uid=bad_uid)
102
+                self.ed_mod.create_component('EmClass', test_datas, uid=bad_uid)
103 103
 
104 104
         #Invalid component_type
105 105
         for bad_comp_name in ['EmComponent', 'EmFoobar', 'int', int]:
106 106
             with self.assertRaises(ValueError, msg="The create_component don't raise when an invalid classname (%s) is given as parameter" % bad_comp_name):
107
-                self.me.create_component(bad_comp_name, testDatas)
107
+                self.ed_mod.create_component(bad_comp_name, test_datas)
108 108
 
109 109
         #Invalid rank
110 110
         for invalid_rank in [-1, 10000]:
111 111
             with self.assertRaises(ValueError, msg="A invalid rank (%s) was given" % invalid_rank):
112
-                foodat = testDatas.copy()
112
+                foodat = test_datas.copy()
113 113
                 foodat['rank'] = invalid_rank
114
-                self.me.create_component('EmClass', foodat)
114
+                self.ed_mod.create_component('EmClass', foodat)
115 115
         with self.assertRaises(TypeError, msg="A non integer rank was given"):
116
-            foodat = testDatas.copy()
116
+            foodat = test_datas.copy()
117 117
             foodat['rank'] = 'hello world'
118
-            self.me.create_component('EmClass', foodat)
118
+            self.ed_mod.create_component('EmClass', foodat)
119 119
 
120 120
         #Invalid datas
121 121
         for invalid_datas in [dict(), [1, 2, 3, 4], ('hello', 'world')]:
122 122
             with self.assertRaises(TypeError, msg="Invalid datas was given in parameters"):
123
-                self.me.create_component('EmClass', invalid_datas)
123
+                self.ed_mod.create_component('EmClass', invalid_datas)
124 124
 
125 125
     def test_create_components(self):
126 126
         """ Test the create_component method mocking the EmComponent constructors """
@@ -137,7 +137,7 @@ class TestModel(unittest.TestCase):
137 137
                 'cls': EmType,
138 138
                 'cdats': {
139 139
                     'name': 'FooType',
140
-                    'class_id': self.me.components(EmClass)[0].uid,
140
+                    'class_id': self.ed_mod.components(EmClass)[0].uid,
141 141
                     'fields_list': [],
142 142
                 }
143 143
             },
@@ -145,14 +145,14 @@ class TestModel(unittest.TestCase):
145 145
                 'cls': EmFieldGroup,
146 146
                 'cdats': {
147 147
                     'name': 'FooFG',
148
-                    'class_id': self.me.components(EmClass)[0].uid,
148
+                    'class_id': self.ed_mod.components(EmClass)[0].uid,
149 149
                 },
150 150
             },
151 151
             'EmField': {
152 152
                 'cls': EmFieldChar,
153 153
                 'cdats': {
154 154
                     'name': 'FooField',
155
-                    'fieldgroup_id': self.me.components(EmFieldGroup)[0].uid,
155
+                    'fieldgroup_id': self.ed_mod.components(EmFieldGroup)[0].uid,
156 156
                     'fieldtype': 'char',
157 157
                     'max_length': 64,
158 158
                     'optional': True,
@@ -165,18 +165,18 @@ class TestModel(unittest.TestCase):
165 165
             }
166 166
         }
167 167
 
168
-        for n in params:
169
-            tmpuid = self.me.new_uid()
170
-            cdats = params[n]['cdats']
168
+        for cnt in params:
169
+            tmpuid = self.ed_mod.new_uid()
170
+            cdats = params[cnt]['cdats']
171 171
             cdats['string'] = MlString()
172 172
             cdats['help_text'] = MlString()
173
-            with patch.object(params[n]['cls'], '__init__', return_value=None) as initmock:
173
+            with patch.object(params[cnt]['cls'], '__init__', return_value=None) as initmock:
174 174
                 try:
175
-                    self.me.create_component(n, params[n]['cdats'])
175
+                    self.ed_mod.create_component(cnt, params[cnt]['cdats'])
176 176
                 except AttributeError:  # Raises because the component is a MagicMock
177 177
                     pass
178 178
                 cdats['uid'] = tmpuid
179
-                cdats['model'] = self.me
179
+                cdats['model'] = self.ed_mod
180 180
                 #Check that the component __init__ method was called with the good arguments
181 181
                 initmock.assert_called_once_with(**cdats)
182 182
 
@@ -184,9 +184,9 @@ class TestModel(unittest.TestCase):
184 184
         """ Test the delete_component method """
185 185
 
186 186
         #Test that the delete_check() method is called
187
-        for comp in self.me.components():
187
+        for comp in self.ed_mod.components():
188 188
             with patch.object(comp.__class__, 'delete_check', return_value=False) as del_check_mock:
189
-                ret = self.me.delete_component(comp.uid)
189
+                ret = self.ed_mod.delete_component(comp.uid)
190 190
                 del_check_mock.assert_called_once_with()
191 191
                 #Check that when the delete_check() returns False de delete_component() too
192 192
                 self.assertFalse(ret)
@@ -207,23 +207,18 @@ class TestModel(unittest.TestCase):
207 207
         """ Test the set_backend method """
208 208
 
209 209
         for backend in [EmBackendJson('EditorialModel/test/me.json'), EmBackendDummy()]:
210
-            self.me.set_backend(backend)
211
-            self.assertEqual(self.me.backend, backend)
210
+            self.ed_mod.set_backend(backend)
211
+            self.assertEqual(self.ed_mod.backend, backend)
212 212
 
213 213
         for bad_backend in [None, 'wow', int, EmBackendJson]:
214 214
             with self.assertRaises(TypeError, msg="But bad argument (%s %s) was given" % (type(bad_backend), bad_backend)):
215
-                self.me.set_backend(bad_backend)
215
+                self.ed_mod.set_backend(bad_backend)
216 216
 
217
-    ##
218
-    # @todo Test selected fields application
219
-    # @todo Test types hierarchy application
220
-    def test_migrate_handler(self):
217
+    def test_migrate_handler_order(self):
221 218
         """ Test that the migrate_handler() method create component in a good order """
222
-
223
-        #Testing component creation
224 219
         with patch.object(Model, 'create_component', return_value=None) as create_mock:
225 220
             try:
226
-                self.me.migrate_handler(None)
221
+                self.ed_mod.migrate_handler(None)
227 222
             except AttributeError:  # Raises because of the mock
228 223
                 pass
229 224
             order_comp = ['EmClass', 'EmType', 'EmFieldGroup', 'EmField']  # Excpected creation order
@@ -233,11 +228,11 @@ class TestModel(unittest.TestCase):
233 228
                 while order_comp[cur_comp] != mcall[1][0]:
234 229
                     cur_comp += 1
235 230
                     if cur_comp >= len(order_comp):
236
-                        self.assertTrue(False, 'The order of create_component() calls was not respected by migrate_handler() methods')
231
+                        self.fail('The order of create_component() calls was not respected by migrate_handler() methods')
237 232
 
238 233
                 #Testing uid
239
-                comp = self.me.component(mcall[1][2])
240
-                ctype = self.me.name_from_emclass(comp.__class__)
234
+                comp = self.ed_mod.component(mcall[1][2])
235
+                ctype = self.ed_mod.name_from_emclass(comp.__class__)
241 236
                 self.assertEqual(mcall[1][0], ctype, "A component was created using a uid belonging to another component type")
242 237
                 #Testing arguments of create_component
243 238
                 comp_dump = comp.attr_dump()
@@ -248,16 +243,47 @@ class TestModel(unittest.TestCase):
248 243
 
249 244
                 self.assertEqual(mcall[1][1], comp_dump)
250 245
 
251
-        #Now testing the select type application
252
-        pass
253
-        #Now testing the type hierarchy
254
-        pass
246
+    def test_migrate_handler_relations(self):
247
+        """ Test that the migrate_handler() method create Type relations correctly (selected fields and type hierarchy) """
248
+        field_list_orig = []
249
+        superiors_list_orig = dict()
250
+        field_list_new = []
251
+        superiors_list_new = dict()
252
+
253
+        for emtype in self.ed_mod.components(EmType):
254
+            for fluid in emtype.fields_list:
255
+                field_list_orig.append(fluid)
256
+            for nat, sup_l in emtype.superiors().items():
257
+                superiors_list_orig[nat] = [sup.uid for sup in sup_l]
255 258
 
256
-        #Now testing the hashes
257 259
         with patch.object(DummyMigrationHandler, 'register_change', return_value=None) as mh_mock:
258
-            new_me = self.me.migrate_handler(DummyMigrationHandler())
260
+            self.ed_mod.migrate_handler(DummyMigrationHandler())
261
+            #Getting cloned EM instance
262
+            new_me = mh_mock.mock_calls[-1][1][0]
263
+            for emtype in new_me.components(EmType):
264
+                for fluid in emtype.fields_list:
265
+                    field_list_new.append(fluid)
266
+                for nat, sup_l in emtype.superiors().items():
267
+                    superiors_list_new[nat] = [sup.uid for sup in sup_l]
268
+
269
+            for fluid in field_list_orig:
270
+                self.assertIn(fluid, field_list_orig, "Missing selected field (%d) when migrate_handler() is run" % fluid)
271
+            for fluid in field_list_new:
272
+                self.assertIn(fluid, field_list_new, "A field (%d) is selected when migrate_handler() is run but shouldn't be" % fluid)
273
+            for nat, sup_l in superiors_list_orig.items():
274
+                for supuid in sup_l:
275
+                    self.assertIn(supuid, superiors_list_new[nat], "Missing superiors (%d) when migrate_handler() is run" % supuid)
276
+            for nat, sup_l in superiors_list_new.items():
277
+                for supuid in sup_l:
278
+                    self.assertIn(supuid, superiors_list_orig[nat], "A superior (%d) is present when migrate_handler is called but shouldn't be" % supuid)
279
+
280
+    def test_migrate_handler_hashes(self):
281
+        """ Testing that the migrate_handler() method create an EM with the same hash as the original EM """
282
+        with patch.object(DummyMigrationHandler, 'register_change', return_value=None) as mh_mock:
283
+            self.ed_mod.migrate_handler(DummyMigrationHandler())
284
+            #Getting the cloned EM instance
259 285
             last_call = mh_mock.mock_calls[-1]
260
-            self.assertEqual(hash(last_call[1][0]), hash(self.me))
286
+            self.assertEqual(hash(last_call[1][0]), hash(self.ed_mod))
261 287
 
262 288
     def test_hash(self):
263 289
         """ Test that __hash__ and __eq__ work properly on models """
@@ -291,7 +317,7 @@ class TestModel(unittest.TestCase):
291 317
 
292 318
         for comp_cls in [EmClass, EmFieldGroup, EmType]:
293 319
             self.assertEqual(Model.name_from_emclass(comp_cls), comp_cls.__name__)
294
-        for comp in self.me.components(EmField):
320
+        for comp in self.ed_mod.components(EmField):
295 321
             self.assertEqual(Model.name_from_emclass(comp.__class__), 'EmField')
296 322
 
297 323
         for cls in [EmComponent, int, str]:

Loading…
取消
儲存