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

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