Няма описание
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

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