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_fieldgroups.py 8.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. import os
  2. import logging
  3. import datetime
  4. import shutil
  5. from django.conf import settings
  6. from unittest import TestCase
  7. import unittest
  8. from EditorialModel.components import EmComponent, EmComponentNotExistError
  9. from EditorialModel.fieldgroups import EmFieldGroup
  10. from EditorialModel.classes import EmClass
  11. from EditorialModel.types import EmType
  12. from EditorialModel.fields import EmField
  13. from EditorialModel.classtypes import EmClassType
  14. from EditorialModel.fieldtypes import *
  15. from EditorialModel.test.utils import *
  16. from Database import sqlutils
  17. import sqlalchemy as sqla
  18. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Lodel.settings")
  19. #=###########=#
  20. # TESTS SETUP #
  21. #=###########=#
  22. TEST_FIELDGROUP_DBNAME = 'test_em_fieldgroup_db.sqlite'
  23. def setUpModule():
  24. logging.basicConfig(level=logging.CRITICAL)
  25. initTestDb(TEST_FIELDGROUP_DBNAME)
  26. setDbConf(TEST_FIELDGROUP_DBNAME)
  27. #Classes creation
  28. EmClass.create("entity1", EmClassType.entity)
  29. EmClass.create("entity2", EmClassType.entity)
  30. EmClass.create("entry1", EmClassType.entry)
  31. EmClass.create("entry2", EmClassType.entry)
  32. EmClass.create("person1", EmClassType.person)
  33. EmClass.create("person2", EmClassType.person)
  34. saveDbState(TEST_FIELDGROUP_DBNAME)
  35. #shutil.copyfile(TEST_FIELDGROUP_DBNAME, globals()['fieldgroup_test_dbfilename']+'_bck')
  36. def tearDownModule():
  37. cleanDb(TEST_FIELDGROUP_DBNAME)
  38. pass
  39. class FieldGroupTestCase(TestCase):
  40. def setUp(self):
  41. restoreDbState(TEST_FIELDGROUP_DBNAME)
  42. pass
  43. #======================#
  44. # EmFielgroup.__init__ #
  45. #======================#
  46. class TestInit(FieldGroupTestCase):
  47. def setUp(self):
  48. super(TestInit, self).setUp()
  49. dbe = sqlutils.get_engine()
  50. conn = sqlutils.get_engine().connect()
  51. ent1 = EmClass('entity1')
  52. idx1 = EmClass('entry1')
  53. self.creadate = datetime.datetime.utcnow()
  54. #Test fieldgroup
  55. self.tfg = [
  56. { 'uid': EmFieldGroup.new_uid(dbe), 'name': 'fg1', 'string': '{"fr":"Super Fieldgroup"}', 'help': '{"en":"help"}', 'rank': 0 , 'class_id': ent1.uid, 'date_create' : self.creadate, 'date_update': self.creadate},
  57. { 'uid': EmFieldGroup.new_uid(dbe), 'name': 'fg2', 'string': '{"fr":"Super Fieldgroup"}', 'help': '{"en":"help"}', 'rank': 1 , 'class_id': ent1.uid, 'date_create': self.creadate, 'date_update': self.creadate},
  58. { 'uid': EmFieldGroup.new_uid(dbe), 'name': 'fg3', 'string': '{"fr":"Super Fieldgroup"}', 'help': '{"en":"help"}', 'rank': 2 , 'class_id': idx1.uid, 'date_create': self.creadate, 'date_update': self.creadate},
  59. ]
  60. req = sqla.Table('em_fieldgroup', sqlutils.meta(sqlutils.get_engine())).insert(self.tfg)
  61. conn.execute(req)
  62. conn.close()
  63. pass
  64. def test_init(self):
  65. """ Test that EmFieldgroup are correctly instanciated compare to self.tfg """
  66. for tfg in self.tfg:
  67. fg = EmFieldGroup(tfg['name'])
  68. for attr in tfg:
  69. if attr in ['string', 'help']:
  70. v = MlString.load(tfg[attr])
  71. else:
  72. v = tfg[attr]
  73. self.assertEqual(getattr(fg, attr), v, "The propertie '"+attr+"' fetched from Db don't match excepted value")
  74. for tfg in self.tfg:
  75. fg = EmFieldGroup(tfg['uid'])
  76. for attr in tfg:
  77. if attr in ['string', 'help']:
  78. v = MlString.load(tfg[attr])
  79. else:
  80. v = tfg[attr]
  81. self.assertEqual(getattr(fg, attr), v, "The propertie '"+attr+"' fetched from Db don't match excepted value")
  82. pass
  83. def test_init_badargs(self):
  84. """ Test that EmFieldgroup fail when bad arguments are given """
  85. baduid = self.tfg[2]['uid'] + 4096
  86. badname = 'NonExistingName'
  87. with self.assertRaises(EmComponentNotExistError, msg="Should raise because fieldgroup with id "+str(baduid)+" should not exist"):
  88. fg = EmFieldGroup(baduid)
  89. with self.assertRaises(EmComponentNotExistError, msg="Should raise because fieldgroup named "+badname+" should not exist"):
  90. fg = EmFieldGroup(badname)
  91. with self.assertRaises(TypeError, msg="Should raise a TypeError when crazy arguments are given"):
  92. fg = EmFieldGroup(print)
  93. with self.assertRaises(TypeError, msg="Should raise a TypeError when crazy arguments are given"):
  94. fg = EmFieldGroup(['hello', 'world'])
  95. pass
  96. #=====================#
  97. # EmFieldgroup.create #
  98. #=====================#
  99. class TestCreate(FieldGroupTestCase):
  100. def test_create(self):
  101. """ Does create actually create a fieldgroup ? """
  102. params = { 'EmClass entity instance': EmClass('entity1'),
  103. 'EmClass entry instance': EmClass('entry1'),
  104. 'EmClass person instance': EmClass('person1'),
  105. }
  106. for i,param_name in enumerate(params):
  107. arg = params[param_name]
  108. if isinstance(arg, EmClass):
  109. cl = arg
  110. else:
  111. cl = EmClass(arg)
  112. fgname = 'new_fg'+str(i)
  113. fg = EmFieldGroup.create(fgname, arg)
  114. self.assertEqual(fg.name, fgname, "EmFieldGroup.create() dont instanciate name correctly")
  115. self.assertEqual(fg.class_id, cl.uid, "EmFieldGroup.create() dont instanciate class_id correctly")
  116. nfg = EmFieldGroup(fgname)
  117. #Checking object property
  118. for fname in fg._fields:
  119. self.assertEqual(getattr(nfg,fname), getattr(fg,fname), "Msg inconsistency when a created fieldgroup is fecthed from Db (in "+fname+" property)")
  120. pass
  121. def test_create_badargs(self):
  122. """ Does create fails when badargs given ? """
  123. badargs = { 'EmClass type (not an instance)': EmClass,
  124. 'Non Existing name': 'fooClassThatDontExist',
  125. 'Non Existing Id': 4042, #Hope that it didnt exist ;)
  126. 'Another component instance': EmType.create('fooType', EmClass('entity1')),
  127. 'A function': print
  128. }
  129. for i,badarg_name in enumerate(badargs):
  130. with self.assertRaises(TypeError, msg="Should raise because trying to give "+badarg_name+" as em_class"):
  131. fg = EmFieldGroup.create('new_fg'+i, badargs[badarg_name])
  132. #Creating a fieldgroup to test duplicate name
  133. exfg = EmFieldGroup.create('existingfg', EmClass('entity1'))
  134. badargs = { 'an integer': (42, TypeError),
  135. 'a function': (print, TypeError),
  136. 'an EmClass': (EmClass('entry1'), TypeError),
  137. }
  138. for badarg_name in badargs:
  139. (badarg,expt) = badargs[badarg_name]
  140. with self.assertRaises(expt, msg="Should raise because trying to give "+badarg_name+" as first argument"):
  141. fg = EmFieldGroup.create(badarg, EmClass('entity1'))
  142. #=====================#
  143. # EmFieldgroup.fields #
  144. #=====================#
  145. class TestFields(FieldGroupTestCase):
  146. def setUp(self):
  147. super(TestFields, self).setUp()
  148. self.fg1 = EmFieldGroup.create('testfg', EmClass('entity1'))
  149. self.fg2 = EmFieldGroup.create('testfg2', EmClass('entry1'))
  150. self.fg3 = EmFieldGroup.create('testfg3', EmClass('entry1'))
  151. def test_fields(self):
  152. """ Does it returns actually associated fields ? """
  153. #Creating fields
  154. test_fields1 = [
  155. { 'name': 'field1', 'fieldgroup': self.fg1, 'fieldtype': EmField_integer() },
  156. { 'name': 'field2', 'fieldgroup': self.fg1, 'fieldtype': EmField_integer() },
  157. { 'name': 'field4', 'fieldgroup': self.fg1, 'fieldtype': EmField_integer() },
  158. ]
  159. test_fields2 = [
  160. { 'name': 'field3', 'fieldgroup': self.fg2, 'fieldtype': EmField_integer() },
  161. ]
  162. excepted1 = []
  163. for finfo in test_fields1:
  164. f = EmField.create(**finfo)
  165. excepted1.append(f.uid)
  166. for finfo in test_fields2:
  167. f = EmField.create(**finfo)
  168. excepted1 = set(excepted1)
  169. tests = {
  170. 'newly': EmFieldGroup('testfg'),
  171. 'old' : self.fg1
  172. }
  173. for name in tests:
  174. fg = tests[name]
  175. flist = fg.fields()
  176. res = []
  177. for f in flist:
  178. res.append(f.uid)
  179. self.assertEqual(set(res), set(excepted1))
  180. def test_empty_fields(self):
  181. """ Testing fields method on an empty fieldgroup """
  182. fg = self.fg3
  183. flist = fg.fields()
  184. self.assertEqual(len(flist), 0)
  185. pass