standard_interface_tests.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. """
  2. Standard tests for behaviour common across the whole of cloudbridge.
  3. This includes:
  4. 1. Checking that every resource has an id property
  5. 2. Checking for object equality and repr
  6. 3. Checking standard behaviour for list, iter, find, get, delete
  7. """
  8. import uuid
  9. import tenacity
  10. from cloudbridge.base import helpers as cb_helpers
  11. from cloudbridge.interfaces.exceptions \
  12. import InvalidNameException
  13. from cloudbridge.interfaces.exceptions import InvalidParamException
  14. from cloudbridge.interfaces.resources import LabeledCloudResource
  15. from cloudbridge.interfaces.resources import ObjectLifeCycleMixin
  16. from cloudbridge.interfaces.resources import ResultList
  17. from cloudbridge.providers.aws.services import AWSImageService
  18. import tests.helpers as helpers
  19. def check_repr(test, obj):
  20. test.assertTrue(
  21. obj.id in repr(obj),
  22. "repr(obj) for %s contain the object id so that the object"
  23. " can be reconstructed, but does not. eval(repr(obj)) == obj"
  24. % (type(obj).__name__,))
  25. def check_json(test, obj):
  26. val = obj.to_json()
  27. test.assertEqual(val.get('id'), obj.id)
  28. test.assertEqual(val.get('name'), obj.name)
  29. if isinstance(obj, LabeledCloudResource):
  30. test.assertEqual(val.get('label'), obj.label)
  31. def check_obj_properties(test, obj):
  32. test.assertEqual(obj, obj, "Object should be equal to itself")
  33. test.assertFalse(obj != obj, "Object inequality should be false")
  34. check_obj_id(test, obj)
  35. check_obj_name(test, obj)
  36. check_obj_label(test, obj)
  37. @tenacity.retry(stop=tenacity.stop_after_attempt(10),
  38. retry=tenacity.retry_if_exception_type(AssertionError),
  39. wait=tenacity.wait_fixed(10),
  40. reraise=True)
  41. def check_list(test, service, obj):
  42. list_objs = service.list()
  43. test.assertIsInstance(list_objs, ResultList)
  44. all_records = list_objs
  45. while list_objs.is_truncated:
  46. list_objs = service.list(marker=list_objs.marker)
  47. all_records += list_objs
  48. match_objs = [o for o in all_records if o.id == obj.id]
  49. test.assertTrue(
  50. len(match_objs) == 1,
  51. "List objects for %s does not return the expected object id %s. Got %s"
  52. % (type(obj).__name__, obj.id, match_objs))
  53. return match_objs
  54. def check_iter(test, service, obj):
  55. # check iteration
  56. iter_objs = list(service)
  57. iter_ids = [o.id for o in service]
  58. test.assertEqual(len(set(iter_ids)), len(iter_ids),
  59. "Iteration should not return duplicates")
  60. match_objs = [o for o in iter_objs if o.id == obj.id]
  61. test.assertTrue(
  62. len(match_objs) == 1,
  63. "Iter objects for %s does not return the expected object id %s. Got %s"
  64. % (type(obj).__name__, obj.id, match_objs))
  65. return match_objs
  66. def check_find(test, service, obj):
  67. # check find
  68. if isinstance(obj, LabeledCloudResource):
  69. find_objs = service.find(label=obj.label)
  70. else:
  71. find_objs = service.find(name=obj.name)
  72. test.assertTrue(
  73. len(find_objs) == 1,
  74. "Find objects for %s does not return the expected object: %s. Got %s"
  75. % (type(obj).__name__, getattr(obj, 'label', obj.name), find_objs))
  76. test.assertEqual(find_objs[0].id, obj.id)
  77. return find_objs
  78. def check_find_non_existent(test, service, obj):
  79. args = {}
  80. # AWSImageService.find looks through all public images by default
  81. # In order to get tests to run faster, looking for these non existent
  82. # values only in images owned by the current user
  83. if isinstance(service, AWSImageService):
  84. args = {'owners': ['self']}
  85. if isinstance(obj, LabeledCloudResource):
  86. find_objs = service.find(label="random_imagined_obj_name", **args)
  87. else:
  88. find_objs = service.find(name="random_imagined_obj_name")
  89. with test.assertRaises(InvalidParamException):
  90. service.find(notaparameter="random_imagined_obj_name")
  91. test.assertTrue(
  92. len(find_objs) == 0,
  93. "Find non-existent object for %s returned unexpected objects: %s"
  94. % (type(service).__name__, find_objs))
  95. def check_get(test, service, obj):
  96. get_obj = service.get(obj.id)
  97. test.assertEqual(get_obj.id, obj.id)
  98. test.assertIsInstance(get_obj, type(obj))
  99. return get_obj
  100. def check_get_non_existent(test, service):
  101. # check get
  102. get_objs = service.get('tmp-' + str(uuid.uuid4())[:28])
  103. test.assertIsNone(
  104. get_objs,
  105. "Get non-existent object for %s returned unexpected objects: %s"
  106. % (type(service).__name__, get_objs))
  107. @tenacity.retry(stop=tenacity.stop_after_attempt(10),
  108. retry=tenacity.retry_if_exception_type(AssertionError),
  109. wait=tenacity.wait_fixed(10),
  110. reraise=True)
  111. def check_delete(test, service, obj, perform_delete=False):
  112. if perform_delete:
  113. obj.delete()
  114. objs = service.list()
  115. found_objs = [o for o in objs if o.id == obj.id]
  116. test.assertTrue(
  117. len(found_objs) == 0,
  118. "Object %s in service %s should have been deleted but still exists."
  119. % (found_objs, type(service).__name__))
  120. def check_obj_id(test, obj):
  121. id_property = getattr(type(obj), 'id', None)
  122. test.assertIsInstance(id_property, property)
  123. test.assertIsNone(id_property.fset, "Id should not have a setter")
  124. # Some delimiter characters can trip up djcloudbridge url reversing
  125. # so make sure ids do not contain them
  126. test.assertTrue("/" not in obj.id,
  127. "IDs should not contain slash but is: %s" % (obj.id,))
  128. def check_obj_name(test, obj):
  129. name_property = getattr(type(obj), 'name', None)
  130. test.assertIsInstance(name_property, property)
  131. test.assertIsNone(name_property.fset, "Name should not have a setter")
  132. def check_obj_label(test, obj):
  133. """
  134. Cloudbridge identifiers must be 1-63 characters long, and comply with
  135. RFC1035. In addition, identifiers should contain only lowercase letters,
  136. numeric characters, underscores, and dashes. International
  137. characters are allowed.
  138. """
  139. # if label property exists, make sure invalid values cannot be set
  140. label_property = getattr(type(obj), 'label', None)
  141. if isinstance(label_property, property):
  142. test.assertIsInstance(obj, LabeledCloudResource)
  143. original_label = obj.label
  144. # Three character labels should be allowed
  145. obj.label = "abc"
  146. VALID_LABEL = u"hello-world-123"
  147. obj.label = VALID_LABEL
  148. # Two character labels should not be allowed
  149. with test.assertRaises(InvalidNameException):
  150. obj.label = "ab"
  151. # A none value should not be allowed
  152. with test.assertRaises(InvalidNameException):
  153. obj.label = None
  154. # setting spaces should raise an exception
  155. with test.assertRaises(InvalidNameException):
  156. obj.label = "hello world"
  157. # setting upper case characters should raise an exception
  158. with test.assertRaises(InvalidNameException):
  159. obj.label = "helloWorld"
  160. # setting special characters should raise an exception
  161. with test.assertRaises(InvalidNameException):
  162. obj.label = "hello.world:how_goes_it"
  163. # Starting with a dash should raise an exception
  164. with test.assertRaises(InvalidNameException):
  165. obj.label = "-hello"
  166. # Ending with a dash should raise an exception
  167. with test.assertRaises(InvalidNameException):
  168. obj.label = "hello-"
  169. # setting a length > 63 should result in an exception
  170. with test.assertRaises(InvalidNameException,
  171. msg="Label of length > 64 is not allowed"):
  172. obj.label = "a" * 64
  173. # refreshing should yield the last successfully set label
  174. obj.refresh()
  175. test.assertEqual(obj.label, VALID_LABEL)
  176. obj.label = original_label
  177. def check_standard_behaviour(test, service, obj):
  178. """
  179. Checks standard behaviour in a given cloudbridge resource
  180. of a given service.
  181. """
  182. check_repr(test, obj)
  183. check_json(test, obj)
  184. check_obj_properties(test, obj)
  185. objs_list = check_list(test, service, obj)
  186. objs_iter = check_iter(test, service, obj)
  187. objs_find = check_find(test, service, obj)
  188. check_find_non_existent(test, service, obj)
  189. obj_get = check_get(test, service, obj)
  190. check_get_non_existent(test, service)
  191. test.assertTrue(
  192. obj.id == objs_list[0].id == objs_iter[0].id ==
  193. objs_find[0].id == obj_get.id,
  194. "Object Ids returned by list: {0}, iter: {1}, find: {2} and get: {3} "
  195. " are not as expected: {4}".format(objs_list[0].id, objs_iter[0].id,
  196. objs_find[0].id, obj_get.id,
  197. obj.id))
  198. test.assertTrue(
  199. obj.name == objs_list[0].name == objs_iter[0].name ==
  200. objs_find[0].name == obj_get.name,
  201. "Names returned by list: {0}, iter: {1}, find: {2} and get: {3} "
  202. " are not as expected: {4}".format(objs_list[0].id, objs_iter[0].id,
  203. objs_find[0].id, obj_get.id,
  204. obj.id))
  205. if isinstance(obj, LabeledCloudResource):
  206. test.assertTrue(
  207. obj.label == objs_list[0].label == objs_iter[0].label ==
  208. objs_find[0].label == obj_get.label,
  209. "Labels returned by list: {0}, iter: {1}, find: {2} and get: {3} "
  210. " are not as expected: {4}".format(objs_list[0].id,
  211. objs_iter[0].id,
  212. objs_find[0].id, obj_get.id,
  213. obj.id))
  214. def check_create(test, service, iface, name_prefix,
  215. create_func, cleanup_func):
  216. # check create with invalid label
  217. with test.assertRaises(InvalidNameException):
  218. # spaces should raise an exception
  219. create_func("hello world")
  220. # check create with invalid label
  221. with test.assertRaises(InvalidNameException):
  222. # uppercase characters should raise an exception
  223. create_func("helloWorld")
  224. # setting special characters should raise an exception
  225. with test.assertRaises(InvalidNameException):
  226. create_func("hello.world:how_goes_it")
  227. # Starting with a dash should raise an exception
  228. with test.assertRaises(InvalidNameException):
  229. create_func("-hello")
  230. # Ending with a dash should raise an exception
  231. with test.assertRaises(InvalidNameException):
  232. create_func("hello-")
  233. # underscores are not allowed
  234. with test.assertRaises(InvalidNameException):
  235. create_func("hello_bucket")
  236. # setting a length > 63 should result in an exception
  237. with test.assertRaises(InvalidNameException,
  238. msg="Label of length > 63 should be disallowed"):
  239. create_func("a" * 64)
  240. # name cannot be an IP address
  241. with test.assertRaises(InvalidNameException):
  242. create_func("197.10.100.42")
  243. # empty name are not allowed
  244. with test.assertRaises(InvalidNameException):
  245. create_func(None)
  246. # names of length less than 3 should raise an exception
  247. with test.assertRaises(InvalidNameException):
  248. create_func("cb")
  249. def check_crud(test, service, iface, label_prefix,
  250. create_func, cleanup_func, extra_test_func=None,
  251. custom_check_delete=None, skip_name_check=False):
  252. """
  253. Checks crud behaviour of a given cloudbridge service. The create_func will
  254. be used as a factory function to create a service object and the
  255. cleanup_func will be used to destroy the object. Once an object is created
  256. using the create_func, all other standard behavioural tests can be run
  257. against that object.
  258. :type test: ``TestCase``
  259. :param test: The TestCase object to use
  260. :type service: ``CloudService``
  261. :param service: The CloudService object under test. For example,
  262. a VolumeService object.
  263. :type iface: ``type``
  264. :param iface: The type to test behaviour against. This type must be a
  265. subclass of ``CloudResource``.
  266. :type label_prefix: ``str``
  267. :param label_prefix: The label to prefix all created objects with. This
  268. function will generated a new label with the
  269. specified label_prefix for each test object created
  270. and pass that label into the create_func
  271. :type create_func: ``func``
  272. :param create_func: The create_func must accept the label of the object to
  273. create as a parameter and return the constructed
  274. object.
  275. :type cleanup_func: ``func``
  276. :param cleanup_func: The cleanup_func must accept the created object
  277. and perform all cleanup tasks required to delete the
  278. object.
  279. :type extra_test_func: ``func``
  280. :param extra_test_func: This function will be called to perform additional
  281. tests after object construction and initialization,
  282. but before object cleanup. It will receive the
  283. created object as a parameter.
  284. :type custom_check_delete: ``func``
  285. :param custom_check_delete: If provided, this function will be called
  286. instead of the standard check_delete function
  287. to make sure that the object has been deleted.
  288. :type skip_name_check: ``boolean``
  289. :param skip_name_check: If True, the name related checking will be
  290. skipped.
  291. """
  292. obj = None
  293. with cb_helpers.cleanup_action(lambda: cleanup_func(obj)):
  294. label = "{0}-{1}".format(label_prefix, helpers.get_uuid())
  295. if not skip_name_check:
  296. check_create(test, service, iface, label_prefix,
  297. create_func, cleanup_func)
  298. obj = create_func(label)
  299. if issubclass(iface, ObjectLifeCycleMixin):
  300. obj.wait_till_ready()
  301. check_standard_behaviour(test, service, obj)
  302. if extra_test_func:
  303. extra_test_func(obj)
  304. if custom_check_delete:
  305. custom_check_delete(obj)
  306. else:
  307. check_delete(test, service, obj)