Browse Source

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

Yann Weber 9 years ago
parent
commit
ea51650ab3
1 changed files with 83 additions and 57 deletions
  1. 83
    57
      EditorialModel/test/test_model.py

+ 83
- 57
EditorialModel/test/test_model.py View File

1
 import unittest
1
 import unittest
2
-from unittest.mock import MagicMock, patch
2
+from unittest.mock import patch
3
 
3
 
4
 from EditorialModel.model import Model
4
 from EditorialModel.model import Model
5
 from EditorialModel.classes import EmClass
5
 from EditorialModel.classes import EmClass
20
 class TestModel(unittest.TestCase):
20
 class TestModel(unittest.TestCase):
21
 
21
 
22
     def setUp(self):
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
     def test_init(self):
25
     def test_init(self):
26
         """ Instanciation test """
26
         """ Instanciation test """
43
         """ Test components fetching """
43
         """ Test components fetching """
44
         uid_l = list()
44
         uid_l = list()
45
         for comp_class in [EmClass, EmType, EmField, EmFieldGroup]:
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
             #Testing types of returned components
47
             #Testing types of returned components
48
             for component in comp_l:
48
             for component in comp_l:
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)))
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
                 uid_l.append(component.uid)
50
                 uid_l.append(component.uid)
51
 
51
 
52
         #Testing that we have fetched all the components
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
             self.assertIn(uid, uid_l, "Component with uid %d was not fetched" % uid)
54
             self.assertIn(uid, uid_l, "Component with uid %d was not fetched" % uid)
55
 
55
 
56
         #Testing components method without parameters
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
             self.assertIn(uid, uid_l, "Component with uid %d was not fetched using me.components()" % uid)
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
     def test_component(self):
65
     def test_component(self):
66
         """ Test component fetching by uid """
66
         """ Test component fetching by uid """
67
         #assert that __hash__, __eq__ and components() are corrects
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
         for baduid in [-1, 0xffffff, "hello"]:
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
     def test_sort_components(self):
74
     def test_sort_components(self):
75
         """ Test that Model.sort_components method actually sort components """
75
         """ Test that Model.sort_components method actually sort components """
76
         # disordering an EmClass
76
         # disordering an EmClass
77
-        cl_l = self.me.components(EmClass)
77
+        cl_l = self.ed_mod.components(EmClass)
78
         last_class = cl_l[0]
78
         last_class = cl_l[0]
79
         last_class.rank = 10000
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
     def test_new_uid(self):
83
     def test_new_uid(self):
84
         """ Test that model.new_uid return a new uniq uid """
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
     def test_create_component_fails(self):
88
     def test_create_component_fails(self):
89
         """ Test the create_component method with invalid arguments """
89
         """ Test the create_component method with invalid arguments """
90
 
90
 
91
-        testDatas = {
91
+        test_datas = {
92
             'name': 'FooBar',
92
             'name': 'FooBar',
93
             'classtype': 'entity',
93
             'classtype': 'entity',
94
             'help_text': None,
94
             'help_text': None,
96
         }
96
         }
97
 
97
 
98
         #Invalid uid
98
         #Invalid uid
99
-        used_uid = self.me.components()[0].uid
99
+        used_uid = self.ed_mod.components()[0].uid
100
         for bad_uid in [used_uid, -1, -1000, 'HelloWorld']:
100
         for bad_uid in [used_uid, -1, -1000, 'HelloWorld']:
101
             with self.assertRaises(ValueError, msg="The component was created but the given uid (%s) whas invalid (allready used, negative or WTF)" % bad_uid):
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
         #Invalid component_type
104
         #Invalid component_type
105
         for bad_comp_name in ['EmComponent', 'EmFoobar', 'int', int]:
105
         for bad_comp_name in ['EmComponent', 'EmFoobar', 'int', int]:
106
             with self.assertRaises(ValueError, msg="The create_component don't raise when an invalid classname (%s) is given as parameter" % bad_comp_name):
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
         #Invalid rank
109
         #Invalid rank
110
         for invalid_rank in [-1, 10000]:
110
         for invalid_rank in [-1, 10000]:
111
             with self.assertRaises(ValueError, msg="A invalid rank (%s) was given" % invalid_rank):
111
             with self.assertRaises(ValueError, msg="A invalid rank (%s) was given" % invalid_rank):
112
-                foodat = testDatas.copy()
112
+                foodat = test_datas.copy()
113
                 foodat['rank'] = invalid_rank
113
                 foodat['rank'] = invalid_rank
114
-                self.me.create_component('EmClass', foodat)
114
+                self.ed_mod.create_component('EmClass', foodat)
115
         with self.assertRaises(TypeError, msg="A non integer rank was given"):
115
         with self.assertRaises(TypeError, msg="A non integer rank was given"):
116
-            foodat = testDatas.copy()
116
+            foodat = test_datas.copy()
117
             foodat['rank'] = 'hello world'
117
             foodat['rank'] = 'hello world'
118
-            self.me.create_component('EmClass', foodat)
118
+            self.ed_mod.create_component('EmClass', foodat)
119
 
119
 
120
         #Invalid datas
120
         #Invalid datas
121
         for invalid_datas in [dict(), [1, 2, 3, 4], ('hello', 'world')]:
121
         for invalid_datas in [dict(), [1, 2, 3, 4], ('hello', 'world')]:
122
             with self.assertRaises(TypeError, msg="Invalid datas was given in parameters"):
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
     def test_create_components(self):
125
     def test_create_components(self):
126
         """ Test the create_component method mocking the EmComponent constructors """
126
         """ Test the create_component method mocking the EmComponent constructors """
137
                 'cls': EmType,
137
                 'cls': EmType,
138
                 'cdats': {
138
                 'cdats': {
139
                     'name': 'FooType',
139
                     'name': 'FooType',
140
-                    'class_id': self.me.components(EmClass)[0].uid,
140
+                    'class_id': self.ed_mod.components(EmClass)[0].uid,
141
                     'fields_list': [],
141
                     'fields_list': [],
142
                 }
142
                 }
143
             },
143
             },
145
                 'cls': EmFieldGroup,
145
                 'cls': EmFieldGroup,
146
                 'cdats': {
146
                 'cdats': {
147
                     'name': 'FooFG',
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
             'EmField': {
151
             'EmField': {
152
                 'cls': EmFieldChar,
152
                 'cls': EmFieldChar,
153
                 'cdats': {
153
                 'cdats': {
154
                     'name': 'FooField',
154
                     'name': 'FooField',
155
-                    'fieldgroup_id': self.me.components(EmFieldGroup)[0].uid,
155
+                    'fieldgroup_id': self.ed_mod.components(EmFieldGroup)[0].uid,
156
                     'fieldtype': 'char',
156
                     'fieldtype': 'char',
157
                     'max_length': 64,
157
                     'max_length': 64,
158
                     'optional': True,
158
                     'optional': True,
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
             cdats['string'] = MlString()
171
             cdats['string'] = MlString()
172
             cdats['help_text'] = MlString()
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
                 try:
174
                 try:
175
-                    self.me.create_component(n, params[n]['cdats'])
175
+                    self.ed_mod.create_component(cnt, params[cnt]['cdats'])
176
                 except AttributeError:  # Raises because the component is a MagicMock
176
                 except AttributeError:  # Raises because the component is a MagicMock
177
                     pass
177
                     pass
178
                 cdats['uid'] = tmpuid
178
                 cdats['uid'] = tmpuid
179
-                cdats['model'] = self.me
179
+                cdats['model'] = self.ed_mod
180
                 #Check that the component __init__ method was called with the good arguments
180
                 #Check that the component __init__ method was called with the good arguments
181
                 initmock.assert_called_once_with(**cdats)
181
                 initmock.assert_called_once_with(**cdats)
182
 
182
 
184
         """ Test the delete_component method """
184
         """ Test the delete_component method """
185
 
185
 
186
         #Test that the delete_check() method is called
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
             with patch.object(comp.__class__, 'delete_check', return_value=False) as del_check_mock:
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
                 del_check_mock.assert_called_once_with()
190
                 del_check_mock.assert_called_once_with()
191
                 #Check that when the delete_check() returns False de delete_component() too
191
                 #Check that when the delete_check() returns False de delete_component() too
192
                 self.assertFalse(ret)
192
                 self.assertFalse(ret)
207
         """ Test the set_backend method """
207
         """ Test the set_backend method """
208
 
208
 
209
         for backend in [EmBackendJson('EditorialModel/test/me.json'), EmBackendDummy()]:
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
         for bad_backend in [None, 'wow', int, EmBackendJson]:
213
         for bad_backend in [None, 'wow', int, EmBackendJson]:
214
             with self.assertRaises(TypeError, msg="But bad argument (%s %s) was given" % (type(bad_backend), bad_backend)):
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
         """ Test that the migrate_handler() method create component in a good order """
218
         """ Test that the migrate_handler() method create component in a good order """
222
-
223
-        #Testing component creation
224
         with patch.object(Model, 'create_component', return_value=None) as create_mock:
219
         with patch.object(Model, 'create_component', return_value=None) as create_mock:
225
             try:
220
             try:
226
-                self.me.migrate_handler(None)
221
+                self.ed_mod.migrate_handler(None)
227
             except AttributeError:  # Raises because of the mock
222
             except AttributeError:  # Raises because of the mock
228
                 pass
223
                 pass
229
             order_comp = ['EmClass', 'EmType', 'EmFieldGroup', 'EmField']  # Excpected creation order
224
             order_comp = ['EmClass', 'EmType', 'EmFieldGroup', 'EmField']  # Excpected creation order
233
                 while order_comp[cur_comp] != mcall[1][0]:
228
                 while order_comp[cur_comp] != mcall[1][0]:
234
                     cur_comp += 1
229
                     cur_comp += 1
235
                     if cur_comp >= len(order_comp):
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
                 #Testing uid
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
                 self.assertEqual(mcall[1][0], ctype, "A component was created using a uid belonging to another component type")
236
                 self.assertEqual(mcall[1][0], ctype, "A component was created using a uid belonging to another component type")
242
                 #Testing arguments of create_component
237
                 #Testing arguments of create_component
243
                 comp_dump = comp.attr_dump()
238
                 comp_dump = comp.attr_dump()
248
 
243
 
249
                 self.assertEqual(mcall[1][1], comp_dump)
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
         with patch.object(DummyMigrationHandler, 'register_change', return_value=None) as mh_mock:
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
             last_call = mh_mock.mock_calls[-1]
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
     def test_hash(self):
288
     def test_hash(self):
263
         """ Test that __hash__ and __eq__ work properly on models """
289
         """ Test that __hash__ and __eq__ work properly on models """
291
 
317
 
292
         for comp_cls in [EmClass, EmFieldGroup, EmType]:
318
         for comp_cls in [EmClass, EmFieldGroup, EmType]:
293
             self.assertEqual(Model.name_from_emclass(comp_cls), comp_cls.__name__)
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
             self.assertEqual(Model.name_from_emclass(comp.__class__), 'EmField')
321
             self.assertEqual(Model.name_from_emclass(comp.__class__), 'EmField')
296
 
322
 
297
         for cls in [EmComponent, int, str]:
323
         for cls in [EmComponent, int, str]:

Loading…
Cancel
Save