浏览代码

Rewrite tests for EmComponent and Model

Yann Weber 9 年前
父节点
当前提交
9d77bb6a52
共有 2 个文件被更改,包括 132 次插入671 次删除
  1. 65
    671
      EditorialModel/test/test_component.py
  2. 67
    0
      EditorialModel/test/test_model.py

+ 65
- 671
EditorialModel/test/test_component.py 查看文件

@@ -1,700 +1,94 @@
1
-import os
2
-import datetime
3
-import time
4
-import logging
5
-import json
6
-import shutil
7
-
8
-#from django.test import TestCase
9
-from django.conf import settings
10
-
11
-from unittest import TestCase
12 1
 import unittest
13 2
 
3
+from EditorialModel.model import Model
4
+from EditorialModel.components import EmComponent
14 5
 from EditorialModel.classes import EmClass
15
-from EditorialModel.classtypes import EmClassType
16
-
17
-from EditorialModel.components import EmComponent, EmComponentNotExistError, EmComponentExistError
18
-import EditorialModel.fieldtypes as ftypes
6
+from EditorialModel.types import EmType
7
+from EditorialModel.fieldgroups import EmFieldGroup
8
+from EditorialModel.fields import EmField
19 9
 
20
-from EditorialModel.test.utils import *
21
-
22
-from Lodel.utils.mlstring import MlString
23
-
24
-from Database import sqlutils
25
-from Database import sqlsetup
26
-import sqlalchemy as sqla
27
-
28
-import copy
29
-from EditorialModel.model import Model
30 10
 from EditorialModel.backend.json_backend import EmBackendJson
11
+from EditorialModel.migrationhandler.dummy import DummyMigrationHandler
31 12
 
32
-os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Lodel.settings")
33
-
34
-TEST_COMPONENT_DBNAME = 'test_em_component_db.sqlite'
35
-
36
-EM_TEST = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'me.json')
37
-EM_TEST_OBJECT = None
38
-
39
-#=#############=#
40
-#  TESTS SETUP  #
41
-#=#############=#
42
-
43
-def setUpModule():
44
-    """ This function is run once for this module.
45
-
46
-        The goal are to overwrtie Db configs, and prepare objects for test_case initialisation
47
-    """
48
-    global EM_TEST_OBJECT
49
-    EM_TEST_OBJECT = Model(EmBackendJson(EM_TEST))
50
-
51
-    # cleanDb(TEST_COMPONENT_DBNAME)
52
-
53
-    # setDbConf(TEST_COMPONENT_DBNAME)
54
-    #Disable logging but CRITICAL
55
-    logging.basicConfig(level=logging.CRITICAL)
56
-
57
-    #testDB setup
58
-    # tables = sqlsetup.get_schema()
59
-    # ttest = {   'name':'ttest',
60
-    #             'columns':  [
61
-    #                 {"name":"uid",          "type":"INTEGER", "extra":{"foreignkey":"uids.uid", "nullable":False, "primarykey":True}},
62
-    #                 {"name":"name",         "type":"VARCHAR(50)", "extra":{"nullable":False, "unique":True}},
63
-    #                 {"name":"string",       "type":"TEXT"},
64
-    #                 {"name":"help",         "type":"TEXT"},
65
-    #                 {"name":"rank",         "type":"INTEGER"},
66
-    #                 {"name":"rank_fam",    "type":"VARCHAR(1)"},
67
-    #                 {"name":"date_update",  "type":"DATETIME"},
68
-    #                 {"name":"date_create",  "type":"DATETIME"}
69
-    #             ]
70
-    #         }
71
-    # tables.append(ttest)
72
-    #
73
-    # globals()['tables'] = tables
74
-
75
-    #Creating db structure
76
-
77
-    # initTestDb(TEST_COMPONENT_DBNAME)
78
-    # setDbConf(TEST_COMPONENT_DBNAME)
79
-
80
-    # sqlsetup.init_db('default', False, tables)
81
-
82
-    # dbe = sqlutils.get_engine('default')
83
-
84
-    # Insertion of testings datas
85
-    # conn = dbe.connect()
86
-    # test_table = sqla.Table(EmTestComp.table, sqlutils.meta(dbe))
87
-    # uids_table = sqla.Table('uids', sqlutils.meta(dbe))
88
-
89
-    #Creating uid for the EmTestComp
90
-    # for v in ComponentTestCase.test_values:
91
-    #     uid = v['uid']
92
-    #     req = uids_table.insert(values={'uid':uid, 'table': EmTestComp.table })
93
-    #     conn.execute(req)
94
-
95
-    # WARNING !!! Rank has to be ordened and incremented by one for the modify_rank tests
96
-
97
-    # for i in range(len(ComponentTestCase.test_values)):
98
-    #     ComponentTestCase.test_values[i]['date_create'] = datetime.datetime.utcnow()
99
-    #     ComponentTestCase.test_values[i]['date_update'] = datetime.datetime.utcnow()
100
-    #     ComponentTestCase.test_values[i]['rank_fam'] = '1'
101
-    #
102
-    #
103
-    # req = test_table.insert(values=ComponentTestCase.test_values)
104
-    # conn.execute(req)
105
-    # conn.close()
106
-    #
107
-    # saveDbState(TEST_COMPONENT_DBNAME)
108
-
109
-    # logging.getLogger().setLevel(logging.CRITICAL)
110
-    pass
111
-
112
-def tearDownModule():
113
-    # cleanDb(TEST_COMPONENT_DBNAME)
114
-    """
115
-    try:
116
-        os.unlink(TEST_COMPONENT_DBNAME)
117
-    except:pass
118
-    try:
119
-        os.unlink(TEST_COMPONENT_DBNAME+'_bck')
120
-    except:pass
121
-    """
122
-    pass
123
-
124
-
125
-#A dummy EmComponent child class use to make tests
126
-#class EmTestComp(EmComponent):
127
-#    table = 'ttest'
128
-#    ranked_in = 'rank_fam'
129
-#    _fields = [('rank_fam', ftypes.EmField_char)]
130
-
131
-# The parent class of all other test cases for component
132
-# It defines a SetUp function and some utility functions for EmComponent tests
133
-class ComponentTestCase(TestCase):
134 13
 
135
-    test_values = []
136
-
137
-    test_values = [
138
-         {'classtype': 'entity', 'name': 'foo', 'string': MlString({"foo":"bar"}), 'help_text': MlString({"foo":"foobar"})},
139
-         {'classtype': 'entity', 'name': '123', 'string': MlString({"num":"456"}), 'help_text': MlString({"num":"4242"})},
140
-         {'classtype':'entity', 'name': 'name', 'string': MlString({}), 'help_text': MlString({})}
141
-    ]
142
-
143
-    # @property
144
-    # def tables(self):
145
-    #     return globals()['tables']
14
+class TestEmComponent(unittest.TestCase):
146 15
     def setUp(self):
147
-
148
-        # self.dber = sqlutils.get_engine('default')
149
-        # self.test_values = self.__class__.test_values
150
-        #Db RAZ
151
-        #shutil.copyfile(TEST_COMPONENT_DBNAME+'_bck', globals()['component_test_dbfilename'])
152
-        # restoreDbState(TEST_COMPONENT_DBNAME)
153
-        pass
154
-
155
-    def check_equals(self, component_class, expected_val, test_comp, check_date=True, msg=''):
156
-        """ This function checks that a EmTestComp has expected_val for values"""
157
-        val = expected_val
158
-        self.assertIsInstance(test_comp, component_class, msg)
159
-        for vname in val:
160
-            if vname in ['string', 'help']:  # Special test for mlstrings
161
-                # MlString comparison
162
-                if isinstance(val[vname], MlString):
163
-                    vml = val[vname].translations
164
-                else:
165
-                    vml = json.loads(val[vname])
166
-                for vn in vml:
167
-                    self.assertEqual(vml[vn], getattr(test_comp, vname).get(vn), msg)
168
-            elif vname in ['date_create', 'date_update']:
169
-                # Datetime comparison
170
-                if check_date:
171
-                    self.assertEqualDatetime(val[vname], getattr(test_comp, vname), vname + " assertion error : " + msg)
172
-            else:
173
-                prop = vname
174
-                self.assertEqual(getattr(test_comp, prop), val[vname], msg + " Inconsistecy for " + prop + " property")
175
-
176
-    '''
177
-    def check_equals(self, excepted_val, test_comp, check_date=True, msg=''):
178
-        """ This function check that a EmTestComp has excepted_val for values """
179
-        val = excepted_val
180
-        self.assertIsInstance(test_comp, EmTestComp, msg)
181
-        for vname in val:
182
-            if vname in ['string', 'help']: #Special test for mlStrings
183
-                #MlString comparison
184
-                vml = json.loads(val[vname])
185
-                for vn in vml:
186
-                    self.assertEqual(vml[vn], getattr(test_comp, vname).get(vn), msg)
187
-            elif vname in ['date_create', 'date_update']:
188
-                # Datetime comparison
189
-                if check_date:
190
-                    self.assertEqualDatetime(val[vname], getattr(test_comp, vname), vname+" assertion error : "+msg)
191
-            else:
192
-                prop = vname
193
-                self.assertEqual(getattr(test_comp, prop), val[vname], msg+"Inconsistency for "+prop+" property")
194
-        pass
195
-    '''
196
-
197
-    def assertEqualDatetime(self, d1,d2, msg=""):
198
-        """ Compare a date from the database with a datetime (that have microsecs, in db we dont have microsecs) """
199
-        self.assertTrue(    d1.year == d2.year
200
-                            and d1.month == d2.month
201
-                            and d1.day == d2.day
202
-                            and d1.hour == d2.hour
203
-                            and d1.minute == d2.minute
204
-                            and d1.second == d2.second, msg+" Error the two dates differs : '"+str(d1)+"' '"+str(d2)+"'")
205
-
206
-    def assertEqualMlString(self, ms1, ms2, msg=""):
207
-        """ Compare two MlStrings """
208
-        ms1t = ms1.translations
209
-        ms2t = ms2.translations
210
-        self.assertEqual(set(name for name in ms1t), set(name for name in ms2t), msg+" The two MlString hasn't the same lang list")
211
-        for n in ms1t:
212
-            self.assertEqual(ms1t[n], ms2t[n])
213
-    '''
214
-    def run(self, result=None):
215
-        super(ComponentTestCase, self).run(result)
216
-    '''
217
-#=#############=#
218
-#  TESTS BEGIN  #
219
-#=#############=#
220
-
221
-
222
-#===========================#
223
-#   EmComponent.__init__    #
224
-#===========================#
225
-class TestInit(ComponentTestCase):
226
-
227
-    def test_component_abstract_init(self):
228
-        """ Test not valid call (from EmComponent) of __init__ """
229
-        with self.assertRaises(NotImplementedError):
230
-            test_comp = EmComponent(EmComponent, 2, 'testcomp')
231
-        with self.assertRaises(NotImplementedError):
232
-            test_comp = EmComponent(EmComponent, 2, 'name')
233
-
234
-    def test_component_init_not_exist(self):
235
-        """ Test __init__ with non existing objects """
236
-        self.assertFalse(EM_TEST_OBJECT.component(4096))
237
-
238
-        # with self.assertRaises(EmComponentNotExistError):
239
-        #     test_comp = EM_TEST_OBJECT.component(4096)
240
-
241
-        # TODO this assertion depends of the EmComponent behavior when instanciate with an ID
242
-        #with self.assertRaises(EmComponentNotExistError):
243
-        #    test_comp = EmTestComp(4096)
244
-
245
-    def test_component_init_uid(self):
246
-        """ Test __init__ with numerical ID """
247
-
248
-        for val in self.test_values:
249
-            test_comp = EM_TEST_OBJECT.create_component(EmClass.__name__, val)
250
-            self.assertIsInstance(test_comp, EmClass)
251
-            self.assertEqual(test_comp.uid, val['uid'])
252
-
253
-    def test_component_init_badargs(self):
254
-        for badarg in [ print, json, [], [1,2,3,4,5,6], {'hello': 'world'} ]:
255
-            if isinstance(badarg, list) or isinstance(badarg, dict):
256
-                with self.assertRaises(TypeError):
257
-                    EM_TEST_OBJECT.component(badarg)
258
-            else:
259
-                self.assertFalse(EM_TEST_OBJECT.component(badarg))
260
-
261
-
262
-#=======================#
263
-#   EmComponent.new_uid  #
264
-#=======================#
265
-# TODO A réimplémenter
266
-'''
267
-class TestUid(ComponentTestCase):
268
-
269
-
270
-   def test_newuid(self):
271
-        """ Test valid calls for new_uid method """
272
-        for _ in range(10):
273
-            nuid = EmTestComp.new_uid(self.dber)
274
-
275
-            conn = self.dber.connect()
276
-            tuid = sqla.Table('uids', sqlutils.meta(self.dber))
277
-            req = sqla.select([tuid]).where(tuid.c.uid == nuid)
278
-            rep = conn.execute(req)
279
-            res = rep.fetchall()
280
-
281
-            self.assertEqual(len(res), 1, "Error when selecting : mutliple rows returned for 1 UID")
282
-            res = res[0]
283
-            self.assertEqual(res.uid, nuid, "Selected UID didn't match created uid")
284
-            self.assertEqual(res.table, EmTestComp.table, "Table not match with class table : expected '"+res.table+"' but got '"+EmTestComp.table+"'")
285
-        pass
286
-
287
-    def test_newuid_abstract(self):
288
-        """ Test not valit call for new_uid method """
16
+        self.me =  Model(EmBackendJson('EditorialModel/test/me.json'))
17
+    
18
+    def test_init(self):
19
+        """ Testing that __init__ is abstract for an EmComponent """
289 20
         with self.assertRaises(NotImplementedError):
290
-            EmComponent.new_uid(self.dber)
291
-        pass
292
-'''
293
-
294
-
295
-#=======================#
296
-#   EmComponent.save    #
297
-#=======================#
298
-class TestSave(ComponentTestCase):
299
-
300
-    def _savecheck(self, test_comp, newval):
301
-        """ Utility function for test_component_save_namechange """
302
-        test_comp2 = EM_TEST_OBJECT.component(newval.uid)
303
-
304
-        # Check if properties other than date are equals in the instance fetched from the backend
305
-        self.check_equals(EmClass, newval, test_comp2, check_date=False)
306
-
307
-        #Check if the date_update has been updated
308
-        self.assertTrue(newval.date_update < test_comp2.date_update, "The updated date_update is more in past than its previous value : old date : '"+str(newval.date_update)+"' new date '"+str(test_comp2.date_update)+"'")
309
-
310
-        #Check if the date_create didn't change
311
-        self.assertEqualDatetime(newval.date_create, test_comp2.date_create)
312
-
313
-        #Check if the instance fecthed from Db and the one used to call save have the same properties
314
-        for prop in ['name', 'help', 'string', 'date_update', 'date_create', 'rank' ]:
315
-            if prop in ['string', 'help']:
316
-                assertion = self.assertEqualMlString
317
-            elif prop == 'date_create':
318
-                assertion = self.assertEqualDatetime
319
-            elif prop == 'date_update':
320
-                assertion = self.assertLess
321
-            else:
322
-                assertion = self.assertEqual
323
-
324
-            assertion(getattr(test_comp, prop), getattr(test_comp2, prop), "Save don't propagate modification properly. The '" + prop + "' property hasn't the exepted value in instance fetched from Backend : ")
325
-
326
-    @unittest.skip("Not implemented yet")
327
-    def test_component_save_setattr(self):
328
-        """ Checking save method after different changes using setattr """
329
-        val = self.test_values[0] # The component we will update
330
-        test_comp = EM_TEST_OBJECT.component(val['uid'])
331
-        self.check_equals(EmClass, val, test_comp)
332
-
333
-        newval = copy.copy(test_comp)
334
-        time.sleep(2)  # We have to sleep 2 secs here, so the update_date will be at least 2 secs more than newval.date_update
335
-
336
-        # name change
337
-        newval.name = test_comp.name = 'newname'
338
-        EM_TEST_OBJECT.save()
339
-        self._savecheck(test_comp, newval)
340
-        self.assertTrue(True)
341
-
342
-        #help change
343
-        newval.help = '{"fr": "help fr", "en":"help en", "es":"help es"}'
344
-        test_comp.help = MlString.load(newval.help)
345
-        EM_TEST_OBJECT.save()
346
-        self._savecheck(test_comp, newval)
347
-        self.assertTrue(True)
348
-
349
-        # string change
350
-        newval.string = '{"fr": "string fr", "en":"string en", "es":"string es"}'
351
-        test_comp.string = MlString.load(newval.string)
352
-        EM_TEST_OBJECT.save()
353
-        self._savecheck(EmClass, test_comp, newval)
354
-        self.assertTrue(True)
355
-
356
-        #no change
357
-        EM_TEST_OBJECT.save()
358
-        self._savecheck(EmClass, test_comp, newval)
359
-        self.assertTrue(True)
360
-
361
-        #change all
362
-        test_comp.name = newval.name = test_comp.name = 'newnewname'
363
-        newval.help = '{"fr": "help fra", "en":"help eng", "es":"help esp"}'
364
-        test_comp.help = MlString.load(newval.help)
365
-        newval.string = '{"fr": "string FR", "en":"string EN", "es":"string ES", "foolang":"foofoobar"}'
366
-        test_comp.string = MlString.load(newval.string)
367
-
368
-        EM_TEST_OBJECT.save()
369
-        self._savecheck(EmClass, test_comp, newval)
370
-        self.assertTrue(True)
371
-
372
-    @unittest.skip("Not implemented yet")
373
-    def test_component_save_illegalchanges(self):
374
-        """ checking that the save method forbids some changes """
375
-        val = self.test_values[1]
376
-        changes = {'date_create': datetime.datetime(1982,4,2,13,37), 'date_update': datetime.datetime(1982,4,22,13,43), 'rank': 42}
377
-
378
-        for prop in changes:
379
-            test_comp = EM_TEST_OBJECT.component(val['uid'])
380
-            self.check_equals(EmClass, val, test_comp, False)
381
-
382
-            # TODO La commande ne lève pas d'exception
383
-            #with self.assertRaises(TypeError):
384
-            setattr(test_comp, prop, changes[prop])
385
-
386
-
387
-            EM_TEST_OBJECT.save()
388
-
389
-            test_comp2 = EM_TEST_OBJECT.component(val['uid'])
390
-
391
-            if prop  == 'date_create':
392
-                assertion = self.assertEqualDatetime
393
-            elif prop == 'date_update':
394
-                continue
395
-            else: #rank
396
-                assertion = self.assertEqual
397
-
398
-            assertion(getattr(test_comp, prop), val[prop], "When using setattr the " + prop + " of a component is set : ")
399
-            assertion(getattr(test_comp2, prop), val[prop], "When using setattr and save the " + prop + " of a loaded component is set : ")
400
-
401
-
402
-#====================#
403
-# EmComponent.create #
404
-#====================#
405
-class TestCreate(ComponentTestCase):
406
-
407
-    def test_create(self):
408
-        """ Testing EmComponent.create() """
409
-        newuid = EM_TEST_OBJECT.new_uid()
410
-        vals = {'name': 'created1', 'classtype': 'entity', 'string': MlString({"fr": "testcomp"}), 'help_text': MlString({"en": "help test", "fr": "test help"})}
411
-        tc = EM_TEST_OBJECT.create_component(EmClass.__name__, vals)
412
-        self.check_equals(EmClass, vals, tc, "The created EmTestComp hasn't the good property values")
413
-
414
-'''
415
-#====================#
416
-# EmComponent.create #
417
-#====================#
418
-class TestCreate(ComponentTestCase):
419
-
420
-    def test_create(self):
421
-        """Testing EmComponent.create()"""
422
-        vals = {'name': 'created1', 'rank_fam': 'f', 'string': '{"fr":"testcomp"}', 'help': '{"en":"help test", "fr":"test help"}'}
423
-        tc = EmTestComp.create(**vals)
424
-        self.check_equals(vals, tc, "The created EmTestComp hasn't the good properties values")
425
-        tcdb = EmTestComp('created1')
426
-        self.check_equals(vals, tc, "When fetched from Db the created EmTestComp hasn't the good properties values")
427
-
428
-        # This test assume that string and help has default values
429
-        vals = { 'name': 'created2', 'rank_fam': 'f' }
430
-        tc = EmTestComp.create(**vals)
431
-        self.check_equals(vals, tc, "The created EmTestComp hasn't the good properties values")
432
-        tcdb = EmTestComp('created1')
433
-        self.check_equals(vals, tc, "When fetched from Db the created EmTestComp hasn't the good properties values")
434
-        pass
435
-
436
-    def test_create_badargs(self):
437
-        """Testing EmComponent.create() with bad arguments"""
438
-        with self.assertRaises(TypeError, msg="But given a function as argument"):
439
-            tc = EmTestComp.create(print)
440
-        with self.assertRaises(TypeError, msg="But values contains date_create and date_update"):
441
-            vals = { 'name': 'created1', 'rank_fam': 'f', 'string': '{"fr":"testcomp"}', 'help': '{"en" :"help test", "fr":"test help"}', 'rank': 6, 'date_create': 0 , 'date_update': 0 }
442
-            tc = EmTestComp.create(**vals)
443
-
444
-        with self.assertRaises(TypeError, msg="But no name was given"):
445
-            vals = { 'rank_fam': 'f', 'string': '{"fr":"testcomp"}', 'help': '{"en" :"help test", "fr":"test help"}', 'rank': 6, 'date_create': 0 , 'date_update': 0 }
446
-            tc = EmTestComp.create(**vals)
447
-        with self.assertRaises(TypeError, msg="But no rank_fam was given"):
448
-            vals = { 'name': 'created1', 'string': '{"fr":"testcomp"}', 'help': '{"en" :"help test", "fr":"test help"}', 'rank': 6, 'date_create': 0 , 'date_update': 0 }
449
-            tc = EmTestComp.create(**vals)
450
-        with self.assertRaises(TypeError, msg="But invalid keyword argument given"):
451
-            vals = {'invalid': 42, 'name': 'created1', 'rank_fam': 'f', 'string': '{"fr":"testcomp"}', 'help': '{"en":"help test", "fr":"test help"}'}
452
-            tc = EmTestComp.create(**vals)
453
-
454
-        pass
455
-
456
-    def test_create_existing_failure(self):
457
-        """ Testing that create fails when trying to create an EmComponent with an existing name but different properties """
458
-        vals = {'name': 'created1', 'rank_fam': 'f', 'string': '{"fr":"testcomp"}', 'help': '{"en":"help test", "fr":"test help"}'}
459
-        tc = EmTestComp.create(**vals)
460
-        with self.assertRaises(EmComponentExistError, msg="Should raise because attribute differs for a same name"):
461
-            vals['rank_fam'] = 'e'
462
-            EmTestComp.create(**vals)
463
-        pass
464
-
465
-    def test_create_existing(self):
466
-        """ Testing that create dont fails when trying to create twice the same EmComponent """
467
-        vals = {'name': 'created1', 'rank_fam': 'f', 'string': '{"fr":"testcomp"}', 'help': '{"en":"help test", "fr":"test help"}'}
468
-        tc = EmTestComp.create(**vals)
469
-        try:
470
-            tc2 = EmTestComp.create(**vals)
471
-        except EmComponentExistError as e:
472
-            self.fail("create raises but should return the existing EmComponent instance instead")
473
-        self.assertEqual(tc.uid, tc2.uid, "Created twice the same EmComponent")
474
-        pass
475
-
476
-    def testGetMaxRank(self):
477
-        old = EmTestComp._get_max_rank('f', self.dber)
478
-        EmTestComp.create(name="foobartest", rank_fam = 'f')
479
-        n = EmTestComp._get_max_rank('f', self.dber)
480
-        self.assertEqual(old+1, n, "Excepted value was "+str(old+1)+" but got "+str(n))
481
-        self.assertEqual(EmTestComp._get_max_rank('z', self.dber), -1)
482
-        pass
483
-
484
-#====================#
485
-# EmComponent.delete #
486
-#====================#
487
-class TestDelete(ComponentTestCase):
488
-
489
-    def test_delete(self):
490
-        """ Create and delete TestComponent """
491
-        vals = [
492
-            {'name': 'created1', 'rank_fam': 'f', 'string': '{"fr":"testcomp"}', 'help': '{"en":"help test", "fr":"test help"}'},
493
-            {'name': 'created2', 'rank_fam': 'f', 'string': '{"fr":"testcomp"}', 'help': '{"en":"help test", "fr":"test help"}'},
494
-            {'name': 'created3', 'rank_fam': 'f', 'string': '{"fr":"testcomp"}', 'help': '{"en":"help test", "fr":"test help"}'},
495
-        ]
496
-
497
-        tcomps = []
498
-
499
-        for val in vals:
500
-            tcomps.append(EmTestComp.create(**val))
501
-
502
-        failmsg = "This component should be deleted"
503
-
504
-        for i,tcv in enumerate(vals):
505
-            tc = EmTestComp(tcv['name'])
506
-            tc.delete()
507
-
508
-            with self.assertRaises(EmComponentNotExistError, msg = failmsg):
509
-                tc2 = EmTestComp(tcv['name'])
510
-
511
-            with self.assertRaises(EmComponentNotExistError, msg = failmsg):
512
-                tmp = tc.uid
513
-            with self.assertRaises(EmComponentNotExistError, msg = failmsg):
514
-                tmp = tc.__str__()
515
-            with self.assertRaises(EmComponentNotExistError, msg = failmsg):
516
-                tmp = tc.name
517
-            with self.assertRaises(EmComponentNotExistError, msg = failmsg):
518
-                print(tc)
519
-
520
-            for j in range(i+1,len(vals)):
521
-                try:
522
-                    tc = EmTestComp(vals[j]['name'])
523
-                except EmComponentNotExistError:
524
-                    self.fail('EmComponent should not be deleted')
525
-        self.assertTrue(True)
526
-        pass
527
-
528
-
529
-
530
-
531
-#===========================#
532
-# EmComponent.modify_rank   #
533
-#===========================#
534
-class TestModifyRank(ComponentTestCase):
535
-
536
-    def dump_ranks(self):
537
-        names = [ v['name'] for v in self.test_values ]
538
-        ranks=""
539
-        for i in range(len(names)):
540
-            tc = EmTestComp(names[i])
541
-            ranks += " "+str(tc.rank)
542
-        return ranks
543
-
544
-    def test_modify_rank_absolute(self):
545
-        """ Testing modify_rank with absolute rank """
546
-
547
-        names = [ v['name'] for v in self.test_values ]
548
-        nmax = len(names)-1
549
-
550
-        #moving first to 3
551
-        #-----------------
552
-        test_comp = EmTestComp(names[0])
553
-
554
-        test_comp.modify_rank(3, '=')
555
-        self.assertEqual(test_comp.rank, 3, "Called modify_rank(3, '=') but rank is '"+str(test_comp.rank)+"'. Ranks dump : "+self.dump_ranks())
556
-        tc2 = EmTestComp(names[0])
557
-        self.assertEqual(tc2.rank, 3, "Called modify_rank(3, '=') but rank is '"+str(tc2.rank)+"'. Ranks dump : "+self.dump_ranks())
558
-
559
-        for i in range(1,4):
560
-            test_comp = EmTestComp(names[i])
561
-            self.assertEqual(test_comp.rank, i-1, "Excepted rank was '"+str(i-1)+"' but found '"+str(test_comp.rank)+"'. Ranks dump : "+self.dump_ranks())
562
-
563
-        for i in [4,nmax]:
564
-            test_comp = EmTestComp(names[i])
565
-            self.assertEqual(test_comp.rank, i, "Rank wasn't excepted to change, but : previous value was '"+str(i)+"' current value is '"+str(test_comp.rank)+"'. Ranks dump : "+self.dump_ranks())
566
-
567
-        #undoing last rank change
568
-        test_comp = EmTestComp(names[0])
569
-        test_comp.modify_rank(0,'=')
570
-        self.assertEqual(test_comp.rank, 0)
571
-        tc2 = EmTestComp(names[0])
572
-        self.assertEqual(tc2.rank, 0)
573
-
574
-        #moving last to 2
575
-        #----------------
576
-        test_comp = EmTestComp(names[nmax])
577
-
578
-        test_comp.modify_rank(2, '=')
21
+            foo = EmComponent(self.me, self.me.new_uid(), 'invalid instanciation')
579 22
 
580
-        for i in [0,1]:
581
-            test_comp = EmTestComp(names[i])
582
-            self.assertEqual(test_comp.rank, i)
583
-        for i in range(3,nmax-1):
584
-            test_comp = EmTestComp(names[i])
585
-            self.assertEqual(test_comp.rank, i+1, "Excepted rank was '"+str(i+1)+"' but found '"+str(test_comp.rank)+"'. Ranks dump : "+self.dump_ranks())
23
+    def test_hashes(self):
24
+        """ Testing __hash__ and __eq__ methos """
25
+        me1 =  Model(EmBackendJson('EditorialModel/test/me.json'))
26
+        me2 =  Model(EmBackendJson('EditorialModel/test/me.json'), migration_handler = DummyMigrationHandler(True))
27
+        
28
+        for comp_class in [EmClass, EmType, EmField, EmFieldGroup]:
29
+            comp_l1 = me1.components(comp_class)
30
+            comp_l2 = me2.components(comp_class)
586 31
 
587
-        #undoing last rank change
588
-        test_comp = EmTestComp(names[nmax])
589
-        test_comp.modify_rank(nmax,'=')
590
-        self.assertEqual(test_comp.rank, nmax)
32
+            for i, comp1 in enumerate(comp_l1):
33
+                comp2 = comp_l2[i]
34
+                self.assertEqual(hash(comp1), hash(comp2), "hashes differs for two EmComponent({}) instanciated from the same backend and files".format(comp_class.__name__))
35
+                self.assertTrue(comp1 == comp2)
591 36
 
592
-        #Checking that we are in original state again
593
-        for i,name in enumerate(names):
594
-            test_comp = EmTestComp(name)
595
-            self.assertEqual(test_comp.rank, i, "Excepted rank was '"+str(i-1)+"' but found '"+str(test_comp.rank)+"'. Ranks dump : "+self.dump_ranks())
37
+                comp1.modify_rank(1)
596 38
 
597
-        #Inverting the list
598
-        #------------------
599
-        for i,name in enumerate(names):
600
-            test_comp = EmTestComp(name)
601
-            test_comp.modify_rank(0,'=')
602
-            self.assertEqual(test_comp.rank, 0)
603
-            for j in range(0,i+1):
604
-                test_comp = EmTestComp(names[j])
605
-                self.assertEqual(test_comp.rank, i-j)
606
-            for j in range(i+1,nmax+1):
607
-                test_comp = EmTestComp(names[j])
608
-                self.assertEqual(test_comp.rank, j)
609
-        pass
39
+                self.assertNotEqual(hash(comp1), hash(comp2), "hashes are the same after a modification of rank on one of the two components")
40
+                self.assertFalse(comp1 == comp2)
610 41
 
611
-    def test_modify_rank_relative(self):
612
-        """ Testing modify_rank with relative rank modifier """
613
-        names = [ v['name'] for v in self.test_values ]
614
-        nmax = len(names)-1
42
+                comp2.modify_rank(2)
43
+                self.assertEqual(hash(comp1), hash(comp2), "hashes differs for two EmComponent({}) after applying the same modifications on both".format(comp_class.__name__))
44
+                self.assertTrue(comp1 == comp2)
615 45
 
616
-        test_comp = EmTestComp(names[0])
617
-        #Running modify_rank(i,'+') and the modify_rank(i,'-') for i in range(1,nmax)
618
-        for i in range(1,nmax):
619
-            test_comp.modify_rank(i,'+')
620
-            self.assertEqual(test_comp.rank, i, "The instance (name="+names[0]+") on wich we applied the modify_rank doesn't have expected rank : expected '"+str(i)+"' but got '"+str(test_comp.rank)+"'")
621
-            test_comp2 = EmTestComp(names[0])
622
-            self.assertEqual(test_comp.rank, i, "The instance fetched in Db does'n't have expected rank : expected '"+str(i)+"' but got '"+str(test_comp.rank)+"'")
46
+    def test_modify_rank(self):
47
+        """ Testing modify_rank and set_rank method """
48
+        cls = self.me.classes()[0]
49
+        orig_rank = cls.rank
623 50
 
624
-            for j in range(1,i+1):
625
-                test_comp2 = EmTestComp(names[j])
626
-                self.assertEqual(test_comp2.rank, j-1, self.dump_ranks())
627
-            for j in range(i+1,nmax+1):
628
-                test_comp2 = EmTestComp(names[j])
629
-                self.assertEqual(test_comp2.rank, j, self.dump_ranks())
51
+        cls.modify_rank(1)
52
+        self.assertEqual(orig_rank, cls.rank - 1)
630 53
 
631
-            test_comp.modify_rank(i,'-')
632
-            self.assertEqual(test_comp.rank, 0, "The instance on wich we applied the modify_rank -"+str(i)+" doesn't have excepted rank : excepted '0' but got '"+str(test_comp.rank)+"'")
633
-            test_comp2 = EmTestComp(names[0])
634
-            self.assertEqual(test_comp.rank, 0, "The instance fetched in Db does'n't have expected rank : expected '0' but got '"+str(test_comp.rank)+"'"+self.dump_ranks())
54
+        cls.modify_rank(-1)
55
+        self.assertEqual(orig_rank, cls.rank)
635 56
 
636
-            for j in range(1,nmax+1):
637
-                test_comp2 = EmTestComp(names[j])
638
-                self.assertEqual(test_comp2.rank, j, self.dump_ranks())
57
+        cls.set_rank(1)
58
+        self.assertEqual(cls.rank, 1)
639 59
 
640
-        test_comp = EmTestComp(names[3])
641
-        test_comp.modify_rank(2,'+')
642
-        self.assertEqual(test_comp.rank, 5)
643
-        tc2 = EmTestComp(names[3])
644
-        self.assertEqual(tc2.rank,5)
645
-        for i in [4,5]:
646
-            tc2 = EmTestComp(names[i])
647
-            self.assertEqual(tc2.rank, i-1)
648
-        for i in range(0,3):
649
-            tc2 = EmTestComp(names[i])
650
-            self.assertEqual(tc2.rank, i)
60
+        cls.set_rank(2)
61
+        self.assertEqual(cls.rank, 2)
651 62
 
652
-        test_comp.modify_rank(2, '-')
653
-        self.assertEqual(test_comp.rank, 3)
654
-        for i in range(0,6):
655
-            tc2 = EmTestComp(names[i])
656
-            self.assertEqual(tc2.rank, i)
63
+        max_rank = cls.get_max_rank()
64
+        cls.set_rank(max_rank)
65
+        self.assertEqual(cls.rank, max_rank)
657 66
 
658
-        pass
67
+        with self.assertRaises(ValueError):
68
+            cls.modify_rank(1)
659 69
 
660
-    def test_modify_rank_badargs(self):
661
-        """ Testing modify_rank with bad arguments """
662
-        names = [ v['name'] for v in self.test_values ]
663
-        tc = EmTestComp(names[3])
70
+        with self.assertRaises(ValueError):
71
+            cls.modify_rank(-10)
664 72
 
665
-        badargs = [
666
-            #Bad types
667
-            (('0','+'), TypeError),
668
-            ((0, 43), TypeError),
669
-            ((print, '='), TypeError),
670
-            ((3, print), TypeError),
671
-            ((0.0, '='), TypeError),
73
+        with self.assertRaises(ValueError):
74
+            cls.set_rank(0)
672 75
 
673
-            #Bad new_rank
674
-            ((-1, '='), ValueError),
675
-            ((-1,), ValueError),
76
+        with self.assertRaises(ValueError):
77
+            cls.set_rank(10)
676 78
 
677
-            #Bad sign
678
-            ((2, 'a'), ValueError),
679
-            ((1, '=='), ValueError),
680
-            ((1, '+-'), ValueError),
681
-            ((1, 'Hello world !'), ValueError),
79
+        with self.assertRaises(ValueError):
80
+            cls.set_rank(-10)
682 81
 
683
-            #Out of bounds
684
-            ((42*10**9, '+'), ValueError),
685
-            ((-42*10**9, '+'), ValueError),
686
-            ((len(names), '+'), ValueError),
687
-            ((len(names), '-'), ValueError),
688
-            ((len(names), '='), ValueError),
689
-            ((4, '-'), ValueError),
690
-            ((3, '+'), ValueError),
691
-        ]
82
+    def test_check(self):
83
+        """ Testing check method """
84
+        cls = self.me.classes()[0]
85
+        cls.rank = 10000
692 86
 
693
-        for (args, err) in badargs:
694
-            with self.assertRaises(err, msg="Bad arguments supplied : "+str(args)+" for a component at rank 3 but no error raised"):
695
-                tc.modify_rank(*args)
696
-            self.assertEqual(tc.rank, 3, "The function raises an error but modify the rank")
697
-        pass
87
+        cls.check()
88
+        self.assertEqual(cls.rank, cls.get_max_rank())
698 89
 
90
+        cls.rank = -1000
91
+        cls.check()
92
+        self.assertEqual(cls.rank, 1)
699 93
 
700
-'''
94
+        

+ 67
- 0
EditorialModel/test/test_model.py 查看文件

@@ -0,0 +1,67 @@
1
+import unittest
2
+
3
+from EditorialModel.model import Model
4
+from EditorialModel.classes import EmClass
5
+from EditorialModel.types import EmType
6
+from EditorialModel.fieldgroups import EmFieldGroup
7
+from EditorialModel.fields import EmField
8
+
9
+from EditorialModel.backend.json_backend import EmBackendJson
10
+from EditorialModel.migrationhandler.dummy import DummyMigrationHandler
11
+
12
+class TestModel(unittest.TestCase):
13
+
14
+    def setUp(self):
15
+        self.me =  Model(EmBackendJson('EditorialModel/test/me.json'))
16
+
17
+    def test_init(self):
18
+        """ Instanciation test """
19
+        model = Model(EmBackendJson('EditorialModel/test/me.json'))
20
+        self.assertTrue(isinstance(model, Model))
21
+        model = Model(EmBackendJson('EditorialModel/test/me.json'), migration_handler = DummyMigrationHandler(True))
22
+
23
+        self.assertTrue(isinstance(model, Model))
24
+
25
+    def test_components(self):
26
+        """ Test components fetching """
27
+        for comp_class in [EmClass, EmType, EmField, EmFieldGroup]:
28
+            comp_l = self.me.components(comp_class)
29
+            for component in comp_l:
30
+                self.assertTrue(isinstance(component, comp_class), "Model.components method don't return EmComponent of the right type. Asked for {} but got {}".format(type(comp_class), type(component)))
31
+
32
+    def test_sort_components(self):
33
+        """ Test that Model.sort_components method actually sort components """
34
+        #disordering an EmClass
35
+        cl_l = self.me.components(EmClass)
36
+        last_class = cl_l[0]
37
+        last_class.rank = 10000
38
+        self.me.sort_components(EmClass)
39
+        self.assertEqual(self.me._components['EmClass'][-1].uid, last_class.uid, "The methode sort_components don't really sort by rank")
40
+
41
+    def test_new_uid(self):
42
+        """ Test that Model.new_uid return a new uniq uid """
43
+        new_uid = self.me.new_uid()
44
+        self.assertNotIn(new_uid, self.me._components['uids'].keys())
45
+
46
+    
47
+    def test_hash(self):
48
+        """ Test that __hash__ and __eq__ works properly on models """
49
+        me =  Model(EmBackendJson('EditorialModel/test/me.json'))
50
+        me2 =  Model(EmBackendJson('EditorialModel/test/me.json'), migration_handler = DummyMigrationHandler(True))
51
+
52
+        self.assertEqual(hash(me), hash(me2), "When instanciate from the same backend & file but with another migration handler the hashes differs")
53
+        self.assertTrue(me, me2)
54
+
55
+        cl_l = me.classes()
56
+        cl_l[0].modify_rank(1)
57
+
58
+        self.assertNotEqual(hash(me), hash(me2), "After a class rank modification the hashes are the same")
59
+        self.assertFalse(me, me2)
60
+
61
+        cl_l = me2.classes()
62
+        cl_l[0].modify_rank(1)
63
+
64
+        self.assertEqual(hash(me), hash(me2), "After doing sames modifications in the two models the hashes differs")
65
+        self.assertTrue(me, me2)
66
+
67
+

正在加载...
取消
保存