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 26KB

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