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

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