No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_component.py 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. import os
  2. import datetime
  3. import time
  4. import logging
  5. import json
  6. import shutil
  7. #from django.test import TestCase
  8. from django.conf import settings
  9. from unittest import TestCase
  10. import unittest
  11. from EditorialModel.classes import EmClass
  12. from EditorialModel.classtypes import EmClassType
  13. from EditorialModel.components import EmComponent, EmComponentNotExistError, EmComponentExistError
  14. import EditorialModel.fieldtypes as ftypes
  15. from EditorialModel.test.utils import *
  16. from Lodel.utils.mlstring import MlString
  17. from Database import sqlutils
  18. from Database import sqlsetup
  19. import sqlalchemy as sqla
  20. from EditorialModel.model import Model
  21. from EditorialModel.backend.json_backend import EmBackendJson
  22. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Lodel.settings")
  23. TEST_COMPONENT_DBNAME = 'test_em_component_db.sqlite'
  24. EM_TEST = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'me.json')
  25. EM_TEST_OBJECT = None
  26. #=#############=#
  27. # TESTS SETUP #
  28. #=#############=#
  29. def setUpModule():
  30. """ This function is run once for this module.
  31. The goal are to overwrtie Db configs, and prepare objects for test_case initialisation
  32. """
  33. global EM_TEST_OBJECT
  34. EM_TEST_OBJECT = Model(EmBackendJson(EM_TEST))
  35. # cleanDb(TEST_COMPONENT_DBNAME)
  36. # setDbConf(TEST_COMPONENT_DBNAME)
  37. #Disable logging but CRITICAL
  38. logging.basicConfig(level=logging.CRITICAL)
  39. #testDB setup
  40. # tables = sqlsetup.get_schema()
  41. # ttest = { 'name':'ttest',
  42. # 'columns': [
  43. # {"name":"uid", "type":"INTEGER", "extra":{"foreignkey":"uids.uid", "nullable":False, "primarykey":True}},
  44. # {"name":"name", "type":"VARCHAR(50)", "extra":{"nullable":False, "unique":True}},
  45. # {"name":"string", "type":"TEXT"},
  46. # {"name":"help", "type":"TEXT"},
  47. # {"name":"rank", "type":"INTEGER"},
  48. # {"name":"rank_fam", "type":"VARCHAR(1)"},
  49. # {"name":"date_update", "type":"DATETIME"},
  50. # {"name":"date_create", "type":"DATETIME"}
  51. # ]
  52. # }
  53. # tables.append(ttest)
  54. #
  55. # globals()['tables'] = tables
  56. #Creating db structure
  57. # initTestDb(TEST_COMPONENT_DBNAME)
  58. # setDbConf(TEST_COMPONENT_DBNAME)
  59. # sqlsetup.init_db('default', False, tables)
  60. # dbe = sqlutils.get_engine('default')
  61. # Insertion of testings datas
  62. # conn = dbe.connect()
  63. # test_table = sqla.Table(EmTestComp.table, sqlutils.meta(dbe))
  64. # uids_table = sqla.Table('uids', sqlutils.meta(dbe))
  65. #Creating uid for the EmTestComp
  66. # for v in ComponentTestCase.test_values:
  67. # uid = v['uid']
  68. # req = uids_table.insert(values={'uid':uid, 'table': EmTestComp.table })
  69. # conn.execute(req)
  70. # WARNING !!! Rank has to be ordened and incremented by one for the modify_rank tests
  71. # for i in range(len(ComponentTestCase.test_values)):
  72. # ComponentTestCase.test_values[i]['date_create'] = datetime.datetime.utcnow()
  73. # ComponentTestCase.test_values[i]['date_update'] = datetime.datetime.utcnow()
  74. # ComponentTestCase.test_values[i]['rank_fam'] = '1'
  75. #
  76. #
  77. # req = test_table.insert(values=ComponentTestCase.test_values)
  78. # conn.execute(req)
  79. # conn.close()
  80. #
  81. # saveDbState(TEST_COMPONENT_DBNAME)
  82. # logging.getLogger().setLevel(logging.CRITICAL)
  83. pass
  84. def tearDownModule():
  85. # cleanDb(TEST_COMPONENT_DBNAME)
  86. """
  87. try:
  88. os.unlink(TEST_COMPONENT_DBNAME)
  89. except:pass
  90. try:
  91. os.unlink(TEST_COMPONENT_DBNAME+'_bck')
  92. except:pass
  93. """
  94. pass
  95. #A dummy EmComponent child class use to make tests
  96. #class EmTestComp(EmComponent):
  97. # table = 'ttest'
  98. # ranked_in = 'rank_fam'
  99. # _fields = [('rank_fam', ftypes.EmField_char)]
  100. # The parent class of all other test cases for component
  101. # It defines a SetUp function and some utility functions for EmComponent tests
  102. class ComponentTestCase(TestCase):
  103. test_values = []
  104. # test_values = [
  105. # {'uid': 1, 'name': 'test', 'string': '{"fr":"testcomp"}', 'help': '{"en":"help test", "fr":"test help"}', 'rank': 0},
  106. # {'uid': 2, 'name': 'test-em_comp', 'string': '{"fr":"Super test comp"}', 'help': '{}', 'rank': 1},
  107. # {'uid': 3, 'name': 'test2', 'string': '{}', 'help': '{}', 'rank': 2},
  108. # {'uid': 42, 'name': 'foo', 'string': '{"foo":"bar"}', 'help': '{"foo":"foobar"}', 'rank': 3},
  109. # {'uid': 84, 'name': '123', 'string': '{"num":"456"}', 'help': '{"num":"4242"}', 'rank': 4},
  110. # {'uid': 1025, 'name': 'name', 'string': '{}', 'help': '{}', 'rank': 5},
  111. # ]
  112. # @property
  113. # def tables(self):
  114. # return globals()['tables']
  115. def setUp(self):
  116. self.test_values.append(EM_TEST_OBJECT.create_component(EmClass.__name__,{'name': 'testclass1', 'classtype': 'entity'}))
  117. self.test_values.append(EM_TEST_OBJECT.create_component(EmClass.__name__,{'name': 'testclass2', 'classtype': 'entry'}))
  118. self.test_values.append(EM_TEST_OBJECT.create_component(EmClass.__name__,{'name': 'testclass3', 'classtype': 'person'}))
  119. # self.dber = sqlutils.get_engine('default')
  120. # self.test_values = self.__class__.test_values
  121. #Db RAZ
  122. #shutil.copyfile(TEST_COMPONENT_DBNAME+'_bck', globals()['component_test_dbfilename'])
  123. # restoreDbState(TEST_COMPONENT_DBNAME)
  124. '''
  125. def check_equals(self, excepted_val, test_comp, check_date=True, msg=''):
  126. """ This function check that a EmTestComp has excepted_val for values """
  127. val = excepted_val
  128. self.assertIsInstance(test_comp, EmTestComp, msg)
  129. for vname in val:
  130. if vname in ['string', 'help']: #Special test for mlStrings
  131. #MlString comparison
  132. vml = json.loads(val[vname])
  133. for vn in vml:
  134. self.assertEqual(vml[vn], getattr(test_comp, vname).get(vn), msg)
  135. elif vname in ['date_create', 'date_update']:
  136. # Datetime comparison
  137. if check_date:
  138. self.assertEqualDatetime(val[vname], getattr(test_comp, vname), vname+" assertion error : "+msg)
  139. else:
  140. prop = vname
  141. self.assertEqual(getattr(test_comp, prop), val[vname], msg+"Inconsistency for "+prop+" property")
  142. pass
  143. '''
  144. def assertEqualDatetime(self, d1,d2, msg=""):
  145. """ Compare a date from the database with a datetime (that have microsecs, in db we dont have microsecs) """
  146. self.assertTrue( d1.year == d2.year
  147. and d1.month == d2.month
  148. and d1.day == d2.day
  149. and d1.hour == d2.hour
  150. and d1.minute == d2.minute
  151. and d1.second == d2.second, msg+" Error the two dates differs : '"+str(d1)+"' '"+str(d2)+"'")
  152. def assertEqualMlString(self, ms1, ms2, msg=""):
  153. """ Compare two MlStrings """
  154. ms1t = ms1.translations
  155. ms2t = ms2.translations
  156. self.assertEqual(set(name for name in ms1t), set(name for name in ms2t), msg+" The two MlString hasn't the same lang list")
  157. for n in ms1t:
  158. self.assertEqual(ms1t[n], ms2t[n])
  159. '''
  160. def run(self, result=None):
  161. super(ComponentTestCase, self).run(result)
  162. '''
  163. #=#############=#
  164. # TESTS BEGIN #
  165. #=#############=#
  166. #===========================#
  167. # EmComponent.__init__ #
  168. #===========================#
  169. class TestInit(ComponentTestCase):
  170. def test_component_abstract_init(self):
  171. """ Test not valid call (from EmComponent) of __init__ """
  172. with self.assertRaises(NotImplementedError):
  173. test_comp = EmComponent(EmComponent, 2, 'testcomp')
  174. with self.assertRaises(NotImplementedError):
  175. test_comp = EmComponent(EmComponent, 2, 'name')
  176. def test_component_init_not_exist(self):
  177. """ Test __init__ with non existing objects """
  178. self.assertFalse(EM_TEST_OBJECT.component(4096))
  179. # with self.assertRaises(EmComponentNotExistError):
  180. # test_comp = EM_TEST_OBJECT.component(4096)
  181. # TODO this assertion depends of the EmComponent behavior when instanciate with an ID
  182. #with self.assertRaises(EmComponentNotExistError):
  183. # test_comp = EmTestComp(4096)
  184. def test_component_init_uid(self):
  185. """ Test __init__ with numerical ID """
  186. for val in self.test_values:
  187. test_comp = EM_TEST_OBJECT.component(val.uid)
  188. self.assertIsInstance(test_comp, EmClass)
  189. self.assertEqual(test_comp.uid, val.uid)
  190. def test_component_init_badargs(self):
  191. for badarg in [ print, json, [], [1,2,3,4,5,6], {'hello': 'world'} ]:
  192. if isinstance(badarg, list) or isinstance(badarg, dict):
  193. with self.assertRaises(TypeError):
  194. EM_TEST_OBJECT.component(badarg)
  195. else:
  196. self.assertFalse(EM_TEST_OBJECT.component(badarg))
  197. '''
  198. #=======================#
  199. # EmComponent.new_uid #
  200. #=======================#
  201. class TestUid(ComponentTestCase):
  202. def test_newuid(self):
  203. """ Test valid calls for new_uid method """
  204. for _ in range(10):
  205. nuid = EmTestComp.new_uid(self.dber)
  206. conn = self.dber.connect()
  207. tuid = sqla.Table('uids', sqlutils.meta(self.dber))
  208. req = sqla.select([tuid]).where(tuid.c.uid == nuid)
  209. rep = conn.execute(req)
  210. res = rep.fetchall()
  211. self.assertEqual(len(res), 1, "Error when selecting : mutliple rows returned for 1 UID")
  212. res = res[0]
  213. self.assertEqual(res.uid, nuid, "Selected UID didn't match created uid")
  214. self.assertEqual(res.table, EmTestComp.table, "Table not match with class table : expected '"+res.table+"' but got '"+EmTestComp.table+"'")
  215. pass
  216. def test_newuid_abstract(self):
  217. """ Test not valit call for new_uid method """
  218. with self.assertRaises(NotImplementedError):
  219. EmComponent.new_uid(self.dber)
  220. pass
  221. #=======================#
  222. # EmComponent.save #
  223. #=======================#
  224. class TestSave(ComponentTestCase):
  225. def _savecheck(self, test_comp, newval):
  226. """ Utility function for test_component_save_namechange """
  227. test_comp2 = EmTestComp(newval['name'])
  228. #Check if properties other than date are equals in the instance fetched from Db
  229. self.check_equals(newval, test_comp2, check_date=False)
  230. #Check if the date_update has been updated
  231. 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)+"'")
  232. #Check if the date_create didn't change
  233. self.assertEqualDatetime(newval['date_create'], test_comp2.date_create)
  234. #Check if the instance fecthed from Db and the one used to call save have the same properties
  235. for prop in ['name', 'help', 'string', 'date_update', 'date_create', 'rank' ]:
  236. if prop in ['string', 'help']:
  237. assertion = self.assertEqualMlString
  238. elif prop == 'date_create':
  239. assertion = self.assertEqualDatetime
  240. elif prop == 'date_update':
  241. assertion = self.assertLess
  242. else:
  243. assertion = self.assertEqual
  244. 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 Db : ")
  245. pass
  246. def test_component_save_setattr(self):
  247. """ Checking save method after different changes using setattr """
  248. val = self.test_values[0] #The row we will modify
  249. test_comp = EmTestComp(val['name'])
  250. self.check_equals(val, test_comp)
  251. newval = val.copy()
  252. 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']
  253. #name change
  254. newval['name'] = test_comp.name = 'newname'
  255. test_comp.save()
  256. self._savecheck(test_comp, newval)
  257. self.assertTrue(True)
  258. #help change
  259. newval['help'] = '{"fr": "help fr", "en":"help en", "es":"help es"}'
  260. test_comp.help = MlString.load(newval['help'])
  261. test_comp.save()
  262. self._savecheck(test_comp, newval)
  263. self.assertTrue(True)
  264. #string change
  265. newval['string'] = '{"fr": "string fr", "en":"string en", "es":"string es"}'
  266. test_comp.string = MlString.load(newval['string'])
  267. test_comp.save()
  268. self._savecheck(test_comp, newval)
  269. self.assertTrue(True)
  270. #no change
  271. test_comp.save()
  272. self._savecheck(test_comp, newval)
  273. self.assertTrue(True)
  274. #change all
  275. test_comp.name = newval['name'] = test_comp.name = 'newnewname'
  276. newval['help'] = '{"fr": "help fra", "en":"help eng", "es":"help esp"}'
  277. test_comp.help = MlString.load(newval['help'])
  278. newval['string'] = '{"fr": "string FR", "en":"string EN", "es":"string ES", "foolang":"foofoobar"}'
  279. test_comp.string = MlString.load(newval['string'])
  280. test_comp.save()
  281. self._savecheck(test_comp, newval)
  282. self.assertTrue(True)
  283. pass
  284. def test_component_save_illegalchanges(self):
  285. """ checking that the save method forbids some changes """
  286. val = self.test_values[1]
  287. changes = { 'date_create': datetime.datetime(1982,4,2,13,37), 'date_update': datetime.datetime(1982,4,2,22,43), 'rank': 42 }
  288. for prop in changes:
  289. test_comp = EmTestComp(val['name'])
  290. self.check_equals(val, test_comp, False)
  291. with self.assertRaises(TypeError):
  292. setattr(test_comp, prop, changes[prop])
  293. test_comp.save()
  294. test_comp2 = EmTestComp(val['name'])
  295. if prop == 'date_create':
  296. assertion = self.assertEqualDatetime
  297. elif prop == 'date_update':
  298. continue
  299. else: #rank
  300. assertion = self.assertEqual
  301. assertion(getattr(test_comp,prop), val[prop], "When using setattr the "+prop+" of a component is set : ")
  302. assertion(getattr(test_comp2, prop), val[prop], "When using setattr and save the "+prop+" of a loaded component is set : ")
  303. pass
  304. #====================#
  305. # EmComponent.create #
  306. #====================#
  307. class TestCreate(ComponentTestCase):
  308. def test_create(self):
  309. """Testing EmComponent.create()"""
  310. vals = {'name': 'created1', 'rank_fam': 'f', 'string': '{"fr":"testcomp"}', 'help': '{"en":"help test", "fr":"test help"}'}
  311. tc = EmTestComp.create(**vals)
  312. self.check_equals(vals, tc, "The created EmTestComp hasn't the good properties values")
  313. tcdb = EmTestComp('created1')
  314. self.check_equals(vals, tc, "When fetched from Db the created EmTestComp hasn't the good properties values")
  315. # This test assume that string and help has default values
  316. vals = { 'name': 'created2', 'rank_fam': 'f' }
  317. tc = EmTestComp.create(**vals)
  318. self.check_equals(vals, tc, "The created EmTestComp hasn't the good properties values")
  319. tcdb = EmTestComp('created1')
  320. self.check_equals(vals, tc, "When fetched from Db the created EmTestComp hasn't the good properties values")
  321. pass
  322. def test_create_badargs(self):
  323. """Testing EmComponent.create() with bad arguments"""
  324. with self.assertRaises(TypeError, msg="But given a function as argument"):
  325. tc = EmTestComp.create(print)
  326. with self.assertRaises(TypeError, msg="But values contains date_create and date_update"):
  327. vals = { 'name': 'created1', 'rank_fam': 'f', 'string': '{"fr":"testcomp"}', 'help': '{"en" :"help test", "fr":"test help"}', 'rank': 6, 'date_create': 0 , 'date_update': 0 }
  328. tc = EmTestComp.create(**vals)
  329. with self.assertRaises(TypeError, msg="But no name was given"):
  330. vals = { 'rank_fam': 'f', 'string': '{"fr":"testcomp"}', 'help': '{"en" :"help test", "fr":"test help"}', 'rank': 6, 'date_create': 0 , 'date_update': 0 }
  331. tc = EmTestComp.create(**vals)
  332. with self.assertRaises(TypeError, msg="But no rank_fam was given"):
  333. vals = { 'name': 'created1', 'string': '{"fr":"testcomp"}', 'help': '{"en" :"help test", "fr":"test help"}', 'rank': 6, 'date_create': 0 , 'date_update': 0 }
  334. tc = EmTestComp.create(**vals)
  335. with self.assertRaises(TypeError, msg="But invalid keyword argument given"):
  336. vals = {'invalid': 42, 'name': 'created1', 'rank_fam': 'f', 'string': '{"fr":"testcomp"}', 'help': '{"en":"help test", "fr":"test help"}'}
  337. tc = EmTestComp.create(**vals)
  338. pass
  339. def test_create_existing_failure(self):
  340. """ Testing that create fails when trying to create an EmComponent with an existing name but different properties """
  341. vals = {'name': 'created1', 'rank_fam': 'f', 'string': '{"fr":"testcomp"}', 'help': '{"en":"help test", "fr":"test help"}'}
  342. tc = EmTestComp.create(**vals)
  343. with self.assertRaises(EmComponentExistError, msg="Should raise because attribute differs for a same name"):
  344. vals['rank_fam'] = 'e'
  345. EmTestComp.create(**vals)
  346. pass
  347. def test_create_existing(self):
  348. """ Testing that create dont fails when trying to create twice the same EmComponent """
  349. vals = {'name': 'created1', 'rank_fam': 'f', 'string': '{"fr":"testcomp"}', 'help': '{"en":"help test", "fr":"test help"}'}
  350. tc = EmTestComp.create(**vals)
  351. try:
  352. tc2 = EmTestComp.create(**vals)
  353. except EmComponentExistError as e:
  354. self.fail("create raises but should return the existing EmComponent instance instead")
  355. self.assertEqual(tc.uid, tc2.uid, "Created twice the same EmComponent")
  356. pass
  357. def testGetMaxRank(self):
  358. old = EmTestComp._get_max_rank('f', self.dber)
  359. EmTestComp.create(name="foobartest", rank_fam = 'f')
  360. n = EmTestComp._get_max_rank('f', self.dber)
  361. self.assertEqual(old+1, n, "Excepted value was "+str(old+1)+" but got "+str(n))
  362. self.assertEqual(EmTestComp._get_max_rank('z', self.dber), -1)
  363. pass
  364. #====================#
  365. # EmComponent.delete #
  366. #====================#
  367. class TestDelete(ComponentTestCase):
  368. def test_delete(self):
  369. """ Create and delete TestComponent """
  370. vals = [
  371. {'name': 'created1', 'rank_fam': 'f', 'string': '{"fr":"testcomp"}', 'help': '{"en":"help test", "fr":"test help"}'},
  372. {'name': 'created2', 'rank_fam': 'f', 'string': '{"fr":"testcomp"}', 'help': '{"en":"help test", "fr":"test help"}'},
  373. {'name': 'created3', 'rank_fam': 'f', 'string': '{"fr":"testcomp"}', 'help': '{"en":"help test", "fr":"test help"}'},
  374. ]
  375. tcomps = []
  376. for val in vals:
  377. tcomps.append(EmTestComp.create(**val))
  378. failmsg = "This component should be deleted"
  379. for i,tcv in enumerate(vals):
  380. tc = EmTestComp(tcv['name'])
  381. tc.delete()
  382. with self.assertRaises(EmComponentNotExistError, msg = failmsg):
  383. tc2 = EmTestComp(tcv['name'])
  384. with self.assertRaises(EmComponentNotExistError, msg = failmsg):
  385. tmp = tc.uid
  386. with self.assertRaises(EmComponentNotExistError, msg = failmsg):
  387. tmp = tc.__str__()
  388. with self.assertRaises(EmComponentNotExistError, msg = failmsg):
  389. tmp = tc.name
  390. with self.assertRaises(EmComponentNotExistError, msg = failmsg):
  391. print(tc)
  392. for j in range(i+1,len(vals)):
  393. try:
  394. tc = EmTestComp(vals[j]['name'])
  395. except EmComponentNotExistError:
  396. self.fail('EmComponent should not be deleted')
  397. self.assertTrue(True)
  398. pass
  399. #===========================#
  400. # EmComponent.modify_rank #
  401. #===========================#
  402. class TestModifyRank(ComponentTestCase):
  403. def dump_ranks(self):
  404. names = [ v['name'] for v in self.test_values ]
  405. ranks=""
  406. for i in range(len(names)):
  407. tc = EmTestComp(names[i])
  408. ranks += " "+str(tc.rank)
  409. return ranks
  410. def test_modify_rank_absolute(self):
  411. """ Testing modify_rank with absolute rank """
  412. names = [ v['name'] for v in self.test_values ]
  413. nmax = len(names)-1
  414. #moving first to 3
  415. #-----------------
  416. test_comp = EmTestComp(names[0])
  417. test_comp.modify_rank(3, '=')
  418. self.assertEqual(test_comp.rank, 3, "Called modify_rank(3, '=') but rank is '"+str(test_comp.rank)+"'. Ranks dump : "+self.dump_ranks())
  419. tc2 = EmTestComp(names[0])
  420. self.assertEqual(tc2.rank, 3, "Called modify_rank(3, '=') but rank is '"+str(tc2.rank)+"'. Ranks dump : "+self.dump_ranks())
  421. for i in range(1,4):
  422. test_comp = EmTestComp(names[i])
  423. self.assertEqual(test_comp.rank, i-1, "Excepted rank was '"+str(i-1)+"' but found '"+str(test_comp.rank)+"'. Ranks dump : "+self.dump_ranks())
  424. for i in [4,nmax]:
  425. test_comp = EmTestComp(names[i])
  426. 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())
  427. #undoing last rank change
  428. test_comp = EmTestComp(names[0])
  429. test_comp.modify_rank(0,'=')
  430. self.assertEqual(test_comp.rank, 0)
  431. tc2 = EmTestComp(names[0])
  432. self.assertEqual(tc2.rank, 0)
  433. #moving last to 2
  434. #----------------
  435. test_comp = EmTestComp(names[nmax])
  436. test_comp.modify_rank(2, '=')
  437. for i in [0,1]:
  438. test_comp = EmTestComp(names[i])
  439. self.assertEqual(test_comp.rank, i)
  440. for i in range(3,nmax-1):
  441. test_comp = EmTestComp(names[i])
  442. self.assertEqual(test_comp.rank, i+1, "Excepted rank was '"+str(i+1)+"' but found '"+str(test_comp.rank)+"'. Ranks dump : "+self.dump_ranks())
  443. #undoing last rank change
  444. test_comp = EmTestComp(names[nmax])
  445. test_comp.modify_rank(nmax,'=')
  446. self.assertEqual(test_comp.rank, nmax)
  447. #Checking that we are in original state again
  448. for i,name in enumerate(names):
  449. test_comp = EmTestComp(name)
  450. self.assertEqual(test_comp.rank, i, "Excepted rank was '"+str(i-1)+"' but found '"+str(test_comp.rank)+"'. Ranks dump : "+self.dump_ranks())
  451. #Inverting the list
  452. #------------------
  453. for i,name in enumerate(names):
  454. test_comp = EmTestComp(name)
  455. test_comp.modify_rank(0,'=')
  456. self.assertEqual(test_comp.rank, 0)
  457. for j in range(0,i+1):
  458. test_comp = EmTestComp(names[j])
  459. self.assertEqual(test_comp.rank, i-j)
  460. for j in range(i+1,nmax+1):
  461. test_comp = EmTestComp(names[j])
  462. self.assertEqual(test_comp.rank, j)
  463. pass
  464. def test_modify_rank_relative(self):
  465. """ Testing modify_rank with relative rank modifier """
  466. names = [ v['name'] for v in self.test_values ]
  467. nmax = len(names)-1
  468. test_comp = EmTestComp(names[0])
  469. #Running modify_rank(i,'+') and the modify_rank(i,'-') for i in range(1,nmax)
  470. for i in range(1,nmax):
  471. test_comp.modify_rank(i,'+')
  472. 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)+"'")
  473. test_comp2 = EmTestComp(names[0])
  474. 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)+"'")
  475. for j in range(1,i+1):
  476. test_comp2 = EmTestComp(names[j])
  477. self.assertEqual(test_comp2.rank, j-1, self.dump_ranks())
  478. for j in range(i+1,nmax+1):
  479. test_comp2 = EmTestComp(names[j])
  480. self.assertEqual(test_comp2.rank, j, self.dump_ranks())
  481. test_comp.modify_rank(i,'-')
  482. 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)+"'")
  483. test_comp2 = EmTestComp(names[0])
  484. 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())
  485. for j in range(1,nmax+1):
  486. test_comp2 = EmTestComp(names[j])
  487. self.assertEqual(test_comp2.rank, j, self.dump_ranks())
  488. test_comp = EmTestComp(names[3])
  489. test_comp.modify_rank(2,'+')
  490. self.assertEqual(test_comp.rank, 5)
  491. tc2 = EmTestComp(names[3])
  492. self.assertEqual(tc2.rank,5)
  493. for i in [4,5]:
  494. tc2 = EmTestComp(names[i])
  495. self.assertEqual(tc2.rank, i-1)
  496. for i in range(0,3):
  497. tc2 = EmTestComp(names[i])
  498. self.assertEqual(tc2.rank, i)
  499. test_comp.modify_rank(2, '-')
  500. self.assertEqual(test_comp.rank, 3)
  501. for i in range(0,6):
  502. tc2 = EmTestComp(names[i])
  503. self.assertEqual(tc2.rank, i)
  504. pass
  505. def test_modify_rank_badargs(self):
  506. """ Testing modify_rank with bad arguments """
  507. names = [ v['name'] for v in self.test_values ]
  508. tc = EmTestComp(names[3])
  509. badargs = [
  510. #Bad types
  511. (('0','+'), TypeError),
  512. ((0, 43), TypeError),
  513. ((print, '='), TypeError),
  514. ((3, print), TypeError),
  515. ((0.0, '='), TypeError),
  516. #Bad new_rank
  517. ((-1, '='), ValueError),
  518. ((-1,), ValueError),
  519. #Bad sign
  520. ((2, 'a'), ValueError),
  521. ((1, '=='), ValueError),
  522. ((1, '+-'), ValueError),
  523. ((1, 'Hello world !'), ValueError),
  524. #Out of bounds
  525. ((42*10**9, '+'), ValueError),
  526. ((-42*10**9, '+'), ValueError),
  527. ((len(names), '+'), ValueError),
  528. ((len(names), '-'), ValueError),
  529. ((len(names), '='), ValueError),
  530. ((4, '-'), ValueError),
  531. ((3, '+'), ValueError),
  532. ]
  533. for (args, err) in badargs:
  534. with self.assertRaises(err, msg="Bad arguments supplied : "+str(args)+" for a component at rank 3 but no error raised"):
  535. tc.modify_rank(*args)
  536. self.assertEqual(tc.rank, 3, "The function raises an error but modify the rank")
  537. pass
  538. '''