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.9KB

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