test_boto_cloudwatch_event.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. # -*- coding: utf-8 -*-
  2. # Import Python libs
  3. from __future__ import absolute_import, print_function, unicode_literals
  4. import logging
  5. import random
  6. import string
  7. import pytest
  8. # Import Salt libs
  9. import salt.config
  10. import salt.loader
  11. import salt.states.boto_cloudwatch_event as boto_cloudwatch_event
  12. from salt.ext.six.moves import range
  13. # Import Salt Testing libs
  14. from tests.support.mixins import LoaderModuleMockMixin
  15. from tests.support.mock import MagicMock, patch
  16. from tests.support.unit import TestCase, skipIf
  17. # pylint: disable=import-error,no-name-in-module
  18. from tests.unit.modules.test_boto_cloudwatch_event import (
  19. BotoCloudWatchEventTestCaseMixin,
  20. )
  21. # pylint: disable=unused-import
  22. # Import 3rd-party libs
  23. try:
  24. import boto3
  25. from botocore.exceptions import ClientError
  26. HAS_BOTO = True
  27. except ImportError:
  28. HAS_BOTO = False
  29. # pylint: enable=unused-import
  30. # pylint: enable=import-error,no-name-in-module
  31. region = "us-east-1"
  32. access_key = "GKTADJGHEIQSXMKKRBJ08H"
  33. secret_key = "askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs"
  34. conn_parameters = {
  35. "region": region,
  36. "key": access_key,
  37. "keyid": secret_key,
  38. "profile": {},
  39. }
  40. error_message = (
  41. "An error occurred (101) when calling the {0} operation: Test-defined error"
  42. )
  43. error_content = {"Error": {"Code": 101, "Message": "Test-defined error"}}
  44. if HAS_BOTO:
  45. not_found_error = ClientError(
  46. {
  47. "Error": {
  48. "Code": "ResourceNotFoundException",
  49. "Message": "Test-defined error",
  50. }
  51. },
  52. "msg",
  53. )
  54. rule_name = "test_thing_type"
  55. rule_desc = "test_thing_type_desc"
  56. rule_sched = "rate(20 min)"
  57. rule_arn = "arn:::::rule/arn"
  58. rule_ret = dict(
  59. Arn=rule_arn,
  60. Description=rule_desc,
  61. EventPattern=None,
  62. Name=rule_name,
  63. RoleArn=None,
  64. ScheduleExpression=rule_sched,
  65. State="ENABLED",
  66. )
  67. log = logging.getLogger(__name__)
  68. def _has_required_boto():
  69. """
  70. Returns True/False boolean depending on if Boto is installed and correct
  71. version.
  72. """
  73. if not HAS_BOTO:
  74. return False
  75. else:
  76. return True
  77. class BotoCloudWatchEventStateTestCaseBase(TestCase, LoaderModuleMockMixin):
  78. conn = None
  79. def setup_loader_modules(self):
  80. ctx = {}
  81. utils = salt.loader.utils(
  82. self.opts,
  83. whitelist=["boto3", "args", "systemd", "path", "platform"],
  84. context=ctx,
  85. )
  86. serializers = salt.loader.serializers(self.opts)
  87. self.funcs = funcs = salt.loader.minion_mods(
  88. self.opts, context=ctx, utils=utils, whitelist=["boto_cloudwatch_event"]
  89. )
  90. self.salt_states = salt.loader.states(
  91. opts=self.opts,
  92. functions=funcs,
  93. utils=utils,
  94. whitelist=["boto_cloudwatch_event"],
  95. serializers=serializers,
  96. )
  97. return {
  98. boto_cloudwatch_event: {
  99. "__opts__": self.opts,
  100. "__salt__": funcs,
  101. "__utils__": utils,
  102. "__states__": self.salt_states,
  103. "__serializers__": serializers,
  104. }
  105. }
  106. @classmethod
  107. def setUpClass(cls):
  108. cls.opts = salt.config.DEFAULT_MINION_OPTS.copy()
  109. cls.opts["grains"] = salt.loader.grains(cls.opts)
  110. @classmethod
  111. def tearDownClass(cls):
  112. del cls.opts
  113. def setUp(self):
  114. self.addCleanup(delattr, self, "funcs")
  115. self.addCleanup(delattr, self, "salt_states")
  116. # Set up MagicMock to replace the boto3 session
  117. # connections keep getting cached from prior tests, can't find the
  118. # correct context object to clear it. So randomize the cache key, to prevent any
  119. # cache hits
  120. conn_parameters["key"] = "".join(
  121. random.choice(string.ascii_lowercase + string.digits) for _ in range(50)
  122. )
  123. self.patcher = patch("boto3.session.Session")
  124. self.addCleanup(self.patcher.stop)
  125. self.addCleanup(delattr, self, "patcher")
  126. mock_session = self.patcher.start()
  127. session_instance = mock_session.return_value
  128. self.conn = MagicMock()
  129. self.addCleanup(delattr, self, "conn")
  130. session_instance.client.return_value = self.conn
  131. @skipIf(HAS_BOTO is False, "The boto module must be installed.")
  132. class BotoCloudWatchEventTestCase(
  133. BotoCloudWatchEventStateTestCaseBase, BotoCloudWatchEventTestCaseMixin
  134. ):
  135. @pytest.mark.slow_test(seconds=1) # Test takes >0.1 and <=1 seconds
  136. def test_present_when_failing_to_describe_rule(self):
  137. """
  138. Tests exceptions when checking rule existence
  139. """
  140. self.conn.list_rules.side_effect = ClientError(
  141. error_content, "error on list rules"
  142. )
  143. result = self.salt_states["boto_cloudwatch_event.present"](
  144. name="test present",
  145. Name=rule_name,
  146. Description=rule_desc,
  147. ScheduleExpression=rule_sched,
  148. Targets=[{"Id": "target1", "Arn": "arn::::::*"}],
  149. **conn_parameters
  150. )
  151. self.assertEqual(result.get("result"), False)
  152. self.assertTrue("error on list rules" in result.get("comment", {}))
  153. @pytest.mark.slow_test(seconds=1) # Test takes >0.1 and <=1 seconds
  154. def test_present_when_failing_to_create_a_new_rule(self):
  155. """
  156. Tests present on a rule name that doesn't exist and
  157. an error is thrown on creation.
  158. """
  159. self.conn.list_rules.return_value = {"Rules": []}
  160. self.conn.put_rule.side_effect = ClientError(error_content, "put_rule")
  161. result = self.salt_states["boto_cloudwatch_event.present"](
  162. name="test present",
  163. Name=rule_name,
  164. Description=rule_desc,
  165. ScheduleExpression=rule_sched,
  166. Targets=[{"Id": "target1", "Arn": "arn::::::*"}],
  167. **conn_parameters
  168. )
  169. self.assertEqual(result.get("result"), False)
  170. self.assertTrue("put_rule" in result.get("comment", ""))
  171. @pytest.mark.slow_test(seconds=1) # Test takes >0.1 and <=1 seconds
  172. def test_present_when_failing_to_describe_the_new_rule(self):
  173. """
  174. Tests present on a rule name that doesn't exist and
  175. an error is thrown when adding targets.
  176. """
  177. self.conn.list_rules.return_value = {"Rules": []}
  178. self.conn.put_rule.return_value = rule_ret
  179. self.conn.describe_rule.side_effect = ClientError(
  180. error_content, "describe_rule"
  181. )
  182. result = self.salt_states["boto_cloudwatch_event.present"](
  183. name="test present",
  184. Name=rule_name,
  185. Description=rule_desc,
  186. ScheduleExpression=rule_sched,
  187. Targets=[{"Id": "target1", "Arn": "arn::::::*"}],
  188. **conn_parameters
  189. )
  190. self.assertEqual(result.get("result"), False)
  191. self.assertTrue("describe_rule" in result.get("comment", ""))
  192. @pytest.mark.slow_test(seconds=1) # Test takes >0.1 and <=1 seconds
  193. def test_present_when_failing_to_create_a_new_rules_targets(self):
  194. """
  195. Tests present on a rule name that doesn't exist and
  196. an error is thrown when adding targets.
  197. """
  198. self.conn.list_rules.return_value = {"Rules": []}
  199. self.conn.put_rule.return_value = rule_ret
  200. self.conn.describe_rule.return_value = rule_ret
  201. self.conn.put_targets.side_effect = ClientError(error_content, "put_targets")
  202. result = self.salt_states["boto_cloudwatch_event.present"](
  203. name="test present",
  204. Name=rule_name,
  205. Description=rule_desc,
  206. ScheduleExpression=rule_sched,
  207. Targets=[{"Id": "target1", "Arn": "arn::::::*"}],
  208. **conn_parameters
  209. )
  210. self.assertEqual(result.get("result"), False)
  211. self.assertTrue("put_targets" in result.get("comment", ""))
  212. @pytest.mark.slow_test(seconds=1) # Test takes >0.1 and <=1 seconds
  213. def test_present_when_rule_does_not_exist(self):
  214. """
  215. Tests the successful case of creating a new rule, and updating its
  216. targets
  217. """
  218. self.conn.list_rules.return_value = {"Rules": []}
  219. self.conn.put_rule.return_value = rule_ret
  220. self.conn.describe_rule.return_value = rule_ret
  221. self.conn.put_targets.return_value = {"FailedEntryCount": 0}
  222. result = self.salt_states["boto_cloudwatch_event.present"](
  223. name="test present",
  224. Name=rule_name,
  225. Description=rule_desc,
  226. ScheduleExpression=rule_sched,
  227. Targets=[{"Id": "target1", "Arn": "arn::::::*"}],
  228. **conn_parameters
  229. )
  230. self.assertEqual(result.get("result"), True)
  231. @pytest.mark.slow_test(seconds=1) # Test takes >0.1 and <=1 seconds
  232. def test_present_when_failing_to_update_an_existing_rule(self):
  233. """
  234. Tests present on an existing rule where an error is thrown on updating the pool properties.
  235. """
  236. self.conn.list_rules.return_value = {"Rules": [rule_ret]}
  237. self.conn.describe_rule.side_effect = ClientError(
  238. error_content, "describe_rule"
  239. )
  240. result = self.salt_states["boto_cloudwatch_event.present"](
  241. name="test present",
  242. Name=rule_name,
  243. Description=rule_desc,
  244. ScheduleExpression=rule_sched,
  245. Targets=[{"Id": "target1", "Arn": "arn::::::*"}],
  246. **conn_parameters
  247. )
  248. self.assertEqual(result.get("result"), False)
  249. self.assertTrue("describe_rule" in result.get("comment", ""))
  250. @pytest.mark.slow_test(seconds=1) # Test takes >0.1 and <=1 seconds
  251. def test_present_when_failing_to_get_targets(self):
  252. """
  253. Tests present on an existing rule where put_rule succeeded, but an error
  254. is thrown on getting targets
  255. """
  256. self.conn.list_rules.return_value = {"Rules": [rule_ret]}
  257. self.conn.put_rule.return_value = rule_ret
  258. self.conn.describe_rule.return_value = rule_ret
  259. self.conn.list_targets_by_rule.side_effect = ClientError(
  260. error_content, "list_targets"
  261. )
  262. result = self.salt_states["boto_cloudwatch_event.present"](
  263. name="test present",
  264. Name=rule_name,
  265. Description=rule_desc,
  266. ScheduleExpression=rule_sched,
  267. Targets=[{"Id": "target1", "Arn": "arn::::::*"}],
  268. **conn_parameters
  269. )
  270. self.assertEqual(result.get("result"), False)
  271. self.assertTrue("list_targets" in result.get("comment", ""))
  272. @pytest.mark.slow_test(seconds=1) # Test takes >0.1 and <=1 seconds
  273. def test_present_when_failing_to_put_targets(self):
  274. """
  275. Tests present on an existing rule where put_rule succeeded, but an error
  276. is thrown on putting targets
  277. """
  278. self.conn.list_rules.return_value = {"Rules": []}
  279. self.conn.put_rule.return_value = rule_ret
  280. self.conn.describe_rule.return_value = rule_ret
  281. self.conn.list_targets.return_value = {"Targets": []}
  282. self.conn.put_targets.side_effect = ClientError(error_content, "put_targets")
  283. result = self.salt_states["boto_cloudwatch_event.present"](
  284. name="test present",
  285. Name=rule_name,
  286. Description=rule_desc,
  287. ScheduleExpression=rule_sched,
  288. Targets=[{"Id": "target1", "Arn": "arn::::::*"}],
  289. **conn_parameters
  290. )
  291. self.assertEqual(result.get("result"), False)
  292. self.assertTrue("put_targets" in result.get("comment", ""))
  293. @pytest.mark.slow_test(seconds=1) # Test takes >0.1 and <=1 seconds
  294. def test_present_when_putting_targets(self):
  295. """
  296. Tests present on an existing rule where put_rule succeeded, and targets
  297. must be added
  298. """
  299. self.conn.list_rules.return_value = {"Rules": []}
  300. self.conn.put_rule.return_value = rule_ret
  301. self.conn.describe_rule.return_value = rule_ret
  302. self.conn.list_targets.return_value = {"Targets": []}
  303. self.conn.put_targets.return_value = {"FailedEntryCount": 0}
  304. result = self.salt_states["boto_cloudwatch_event.present"](
  305. name="test present",
  306. Name=rule_name,
  307. Description=rule_desc,
  308. ScheduleExpression=rule_sched,
  309. Targets=[{"Id": "target1", "Arn": "arn::::::*"}],
  310. **conn_parameters
  311. )
  312. self.assertEqual(result.get("result"), True)
  313. @pytest.mark.slow_test(seconds=1) # Test takes >0.1 and <=1 seconds
  314. def test_present_when_removing_targets(self):
  315. """
  316. Tests present on an existing rule where put_rule succeeded, and targets
  317. must be removed
  318. """
  319. self.conn.list_rules.return_value = {"Rules": []}
  320. self.conn.put_rule.return_value = rule_ret
  321. self.conn.describe_rule.return_value = rule_ret
  322. self.conn.list_targets.return_value = {
  323. "Targets": [{"Id": "target1"}, {"Id": "target2"}]
  324. }
  325. self.conn.put_targets.return_value = {"FailedEntryCount": 0}
  326. result = self.salt_states["boto_cloudwatch_event.present"](
  327. name="test present",
  328. Name=rule_name,
  329. Description=rule_desc,
  330. ScheduleExpression=rule_sched,
  331. Targets=[{"Id": "target1", "Arn": "arn::::::*"}],
  332. **conn_parameters
  333. )
  334. self.assertEqual(result.get("result"), True)
  335. @pytest.mark.slow_test(seconds=1) # Test takes >0.1 and <=1 seconds
  336. def test_absent_when_failing_to_describe_rule(self):
  337. """
  338. Tests exceptions when checking rule existence
  339. """
  340. self.conn.list_rules.side_effect = ClientError(
  341. error_content, "error on list rules"
  342. )
  343. result = self.salt_states["boto_cloudwatch_event.absent"](
  344. name="test present", Name=rule_name, **conn_parameters
  345. )
  346. self.assertEqual(result.get("result"), False)
  347. self.assertTrue("error on list rules" in result.get("comment", {}))
  348. @pytest.mark.slow_test(seconds=1) # Test takes >0.1 and <=1 seconds
  349. def test_absent_when_rule_does_not_exist(self):
  350. """
  351. Tests absent on an non-existing rule
  352. """
  353. self.conn.list_rules.return_value = {"Rules": []}
  354. result = self.salt_states["boto_cloudwatch_event.absent"](
  355. name="test absent", Name=rule_name, **conn_parameters
  356. )
  357. self.assertEqual(result.get("result"), True)
  358. self.assertEqual(result["changes"], {})
  359. @pytest.mark.slow_test(seconds=1) # Test takes >0.1 and <=1 seconds
  360. def test_absent_when_failing_to_list_targets(self):
  361. """
  362. Tests absent on an rule when the list_targets call fails
  363. """
  364. self.conn.list_rules.return_value = {"Rules": [rule_ret]}
  365. self.conn.list_targets_by_rule.side_effect = ClientError(
  366. error_content, "list_targets"
  367. )
  368. result = self.salt_states["boto_cloudwatch_event.absent"](
  369. name="test absent", Name=rule_name, **conn_parameters
  370. )
  371. self.assertEqual(result.get("result"), False)
  372. self.assertTrue("list_targets" in result.get("comment", ""))
  373. @pytest.mark.slow_test(seconds=1) # Test takes >0.1 and <=1 seconds
  374. def test_absent_when_failing_to_remove_targets_exception(self):
  375. """
  376. Tests absent on an rule when the remove_targets call fails
  377. """
  378. self.conn.list_rules.return_value = {"Rules": [rule_ret]}
  379. self.conn.list_targets_by_rule.return_value = {"Targets": [{"Id": "target1"}]}
  380. self.conn.remove_targets.side_effect = ClientError(
  381. error_content, "remove_targets"
  382. )
  383. result = self.salt_states["boto_cloudwatch_event.absent"](
  384. name="test absent", Name=rule_name, **conn_parameters
  385. )
  386. self.assertEqual(result.get("result"), False)
  387. self.assertTrue("remove_targets" in result.get("comment", ""))
  388. @pytest.mark.slow_test(seconds=1) # Test takes >0.1 and <=1 seconds
  389. def test_absent_when_failing_to_remove_targets_nonexception(self):
  390. """
  391. Tests absent on an rule when the remove_targets call fails
  392. """
  393. self.conn.list_rules.return_value = {"Rules": [rule_ret]}
  394. self.conn.list_targets_by_rule.return_value = {"Targets": [{"Id": "target1"}]}
  395. self.conn.remove_targets.return_value = {"FailedEntryCount": 1}
  396. result = self.salt_states["boto_cloudwatch_event.absent"](
  397. name="test absent", Name=rule_name, **conn_parameters
  398. )
  399. self.assertEqual(result.get("result"), False)
  400. @pytest.mark.slow_test(seconds=1) # Test takes >0.1 and <=1 seconds
  401. def test_absent_when_failing_to_delete_rule(self):
  402. """
  403. Tests absent on an rule when the delete_rule call fails
  404. """
  405. self.conn.list_rules.return_value = {"Rules": [rule_ret]}
  406. self.conn.list_targets_by_rule.return_value = {"Targets": [{"Id": "target1"}]}
  407. self.conn.remove_targets.return_value = {"FailedEntryCount": 0}
  408. self.conn.delete_rule.side_effect = ClientError(error_content, "delete_rule")
  409. result = self.salt_states["boto_cloudwatch_event.absent"](
  410. name="test absent", Name=rule_name, **conn_parameters
  411. )
  412. self.assertEqual(result.get("result"), False)
  413. self.assertTrue("delete_rule" in result.get("comment", ""))
  414. @pytest.mark.slow_test(seconds=1) # Test takes >0.1 and <=1 seconds
  415. def test_absent(self):
  416. """
  417. Tests absent on an rule
  418. """
  419. self.conn.list_rules.return_value = {"Rules": [rule_ret]}
  420. self.conn.list_targets_by_rule.return_value = {"Targets": [{"Id": "target1"}]}
  421. self.conn.remove_targets.return_value = {"FailedEntryCount": 0}
  422. result = self.salt_states["boto_cloudwatch_event.absent"](
  423. name="test absent", Name=rule_name, **conn_parameters
  424. )
  425. self.assertEqual(result.get("result"), True)