test_schedule.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. # -*- coding: utf-8 -*-
  2. '''
  3. :codeauthor: Nicole Thomas <nicole@saltstack.com>
  4. '''
  5. # Import python libs
  6. from __future__ import absolute_import, print_function, unicode_literals
  7. import copy
  8. import datetime
  9. import logging
  10. import os
  11. # Import Salt Testing Libs
  12. from tests.support.unit import skipIf, TestCase
  13. from tests.support.mock import MagicMock, patch
  14. from tests.support.runtests import RUNTIME_VARS
  15. # Import Salt Libs
  16. import salt.config
  17. from salt.utils.schedule import Schedule
  18. # pylint: disable=import-error,unused-import
  19. try:
  20. import croniter
  21. _CRON_SUPPORTED = True
  22. except ImportError:
  23. _CRON_SUPPORTED = False
  24. # pylint: enable=import-error
  25. log = logging.getLogger(__name__)
  26. # pylint: disable=too-many-public-methods,invalid-name
  27. class ScheduleTestCase(TestCase):
  28. '''
  29. Unit tests for salt.utils.schedule module
  30. '''
  31. @classmethod
  32. def setUpClass(cls):
  33. root_dir = os.path.join(RUNTIME_VARS.TMP, 'schedule-unit-tests')
  34. default_config = salt.config.minion_config(None)
  35. default_config['conf_dir'] = default_config['root_dir'] = root_dir
  36. default_config['sock_dir'] = os.path.join(root_dir, 'test-socks')
  37. default_config['pki_dir'] = os.path.join(root_dir, 'pki')
  38. default_config['cachedir'] = os.path.join(root_dir, 'cache')
  39. cls.default_config = default_config
  40. @classmethod
  41. def tearDownClass(cls):
  42. delattr(cls, 'default_config')
  43. def setUp(self):
  44. with patch('salt.utils.schedule.clean_proc_dir', MagicMock(return_value=None)):
  45. self.schedule = Schedule(copy.deepcopy(self.default_config), {}, returners={})
  46. self.addCleanup(delattr, self, 'schedule')
  47. # delete_job tests
  48. def test_delete_job_exists(self):
  49. '''
  50. Tests ensuring the job exists and deleting it
  51. '''
  52. self.schedule.opts.update({'schedule': {'foo': 'bar'}, 'pillar': {}})
  53. self.assertIn('foo', self.schedule.opts['schedule'])
  54. self.schedule.delete_job('foo')
  55. self.assertNotIn('foo', self.schedule.opts['schedule'])
  56. def test_delete_job_in_pillar(self):
  57. '''
  58. Tests ignoring deletion job from pillar
  59. '''
  60. self.schedule.opts.update({'pillar': {'schedule': {'foo': 'bar'}}, 'schedule': {}})
  61. self.assertIn('foo', self.schedule.opts['pillar']['schedule'])
  62. self.schedule.delete_job('foo')
  63. self.assertIn('foo', self.schedule.opts['pillar']['schedule'])
  64. def test_delete_job_intervals(self):
  65. '''
  66. Tests removing job from intervals
  67. '''
  68. self.schedule.opts.update({'pillar': {}, 'schedule': {}})
  69. self.schedule.intervals = {'foo': 'bar'}
  70. self.schedule.delete_job('foo')
  71. self.assertNotIn('foo', self.schedule.intervals)
  72. def test_delete_job_prefix(self):
  73. '''
  74. Tests ensuring jobs exists and deleting them by prefix
  75. '''
  76. self.schedule.opts.update({'schedule': {'foobar': 'bar', 'foobaz': 'baz', 'fooboo': 'boo'},
  77. 'pillar': {}})
  78. ret = copy.deepcopy(self.schedule.opts)
  79. del ret['schedule']['foobar']
  80. del ret['schedule']['foobaz']
  81. self.schedule.delete_job_prefix('fooba')
  82. self.assertEqual(self.schedule.opts, ret)
  83. def test_delete_job_prefix_in_pillar(self):
  84. '''
  85. Tests ignoring deletion jobs by prefix from pillar
  86. '''
  87. self.schedule.opts.update({'pillar': {'schedule': {'foobar': 'bar', 'foobaz': 'baz', 'fooboo': 'boo'}},
  88. 'schedule': {}})
  89. ret = copy.deepcopy(self.schedule.opts)
  90. self.schedule.delete_job_prefix('fooba')
  91. self.assertEqual(self.schedule.opts, ret)
  92. # add_job tests
  93. def test_add_job_data_not_dict(self):
  94. '''
  95. Tests if data is a dictionary
  96. '''
  97. data = 'foo'
  98. self.assertRaises(ValueError, Schedule.add_job, self.schedule, data)
  99. def test_add_job_multiple_jobs(self):
  100. '''
  101. Tests if more than one job is scheduled at a time
  102. '''
  103. data = {'key1': 'value1', 'key2': 'value2'}
  104. self.assertRaises(ValueError, Schedule.add_job, self.schedule, data)
  105. def test_add_job(self):
  106. '''
  107. Tests adding a job to the schedule
  108. '''
  109. data = {'foo': {'bar': 'baz'}}
  110. ret = copy.deepcopy(self.schedule.opts)
  111. ret.update({'schedule': {'foo': {'bar': 'baz', 'enabled': True},
  112. 'hello': {'world': 'peace', 'enabled': True}},
  113. 'pillar': {}})
  114. self.schedule.opts.update({'schedule': {'hello': {'world': 'peace', 'enabled': True}},
  115. 'pillar': {}})
  116. Schedule.add_job(self.schedule, data)
  117. self.assertEqual(self.schedule.opts, ret)
  118. # enable_job tests
  119. def test_enable_job(self):
  120. '''
  121. Tests enabling a job
  122. '''
  123. self.schedule.opts.update({'schedule': {'name': {'enabled': 'foo'}}})
  124. Schedule.enable_job(self.schedule, 'name')
  125. self.assertTrue(self.schedule.opts['schedule']['name']['enabled'])
  126. def test_enable_job_pillar(self):
  127. '''
  128. Tests ignoring enable a job from pillar
  129. '''
  130. self.schedule.opts.update({'pillar': {'schedule': {'name': {'enabled': False}}}})
  131. Schedule.enable_job(self.schedule, 'name', persist=False)
  132. self.assertFalse(self.schedule.opts['pillar']['schedule']['name']['enabled'])
  133. # disable_job tests
  134. def test_disable_job(self):
  135. '''
  136. Tests disabling a job
  137. '''
  138. self.schedule.opts.update({'schedule': {'name': {'enabled': 'foo'}}, 'pillar': {}})
  139. Schedule.disable_job(self.schedule, 'name')
  140. self.assertFalse(self.schedule.opts['schedule']['name']['enabled'])
  141. def test_disable_job_pillar(self):
  142. '''
  143. Tests ignoring disable a job in pillar
  144. '''
  145. self.schedule.opts.update({'pillar': {'schedule': {'name': {'enabled': True}}}, 'schedule': {}})
  146. Schedule.disable_job(self.schedule, 'name', persist=False)
  147. self.assertTrue(self.schedule.opts['pillar']['schedule']['name']['enabled'])
  148. # modify_job tests
  149. def test_modify_job(self):
  150. '''
  151. Tests modifying a job in the scheduler
  152. '''
  153. schedule = {'foo': 'bar'}
  154. self.schedule.opts.update({'schedule': {'name': 'baz'}, 'pillar': {}})
  155. ret = copy.deepcopy(self.schedule.opts)
  156. ret.update({'schedule': {'name': {'foo': 'bar'}}})
  157. Schedule.modify_job(self.schedule, 'name', schedule)
  158. self.assertEqual(self.schedule.opts, ret)
  159. def test_modify_job_not_exists(self):
  160. '''
  161. Tests modifying a job in the scheduler if jobs not exists
  162. '''
  163. schedule = {'foo': 'bar'}
  164. self.schedule.opts.update({'schedule': {}, 'pillar': {}})
  165. ret = copy.deepcopy(self.schedule.opts)
  166. ret.update({'schedule': {'name': {'foo': 'bar'}}})
  167. Schedule.modify_job(self.schedule, 'name', schedule)
  168. self.assertEqual(self.schedule.opts, ret)
  169. def test_modify_job_pillar(self):
  170. '''
  171. Tests ignoring modification of job from pillar
  172. '''
  173. schedule = {'foo': 'bar'}
  174. self.schedule.opts.update({'schedule': {}, 'pillar': {'schedule': {'name': 'baz'}}})
  175. ret = copy.deepcopy(self.schedule.opts)
  176. Schedule.modify_job(self.schedule, 'name', schedule, persist=False)
  177. self.assertEqual(self.schedule.opts, ret)
  178. maxDiff = None
  179. # enable_schedule tests
  180. def test_enable_schedule(self):
  181. '''
  182. Tests enabling the scheduler
  183. '''
  184. with patch('salt.utils.schedule.Schedule.persist', MagicMock(return_value=None)) as persist_mock:
  185. self.schedule.opts.update({'schedule': {'enabled': 'foo'}, 'pillar': {}})
  186. Schedule.enable_schedule(self.schedule)
  187. self.assertTrue(self.schedule.opts['schedule']['enabled'])
  188. persist_mock.assert_called()
  189. # disable_schedule tests
  190. def test_disable_schedule(self):
  191. '''
  192. Tests disabling the scheduler
  193. '''
  194. with patch('salt.utils.schedule.Schedule.persist', MagicMock(return_value=None)) as persist_mock:
  195. self.schedule.opts.update({'schedule': {'enabled': 'foo'}, 'pillar': {}})
  196. Schedule.disable_schedule(self.schedule)
  197. self.assertFalse(self.schedule.opts['schedule']['enabled'])
  198. persist_mock.assert_called()
  199. # reload tests
  200. def test_reload_update_schedule_key(self):
  201. '''
  202. Tests reloading the schedule from saved schedule where both the
  203. saved schedule and self.schedule.opts contain a schedule key
  204. '''
  205. saved = {'schedule': {'foo': 'bar'}}
  206. ret = copy.deepcopy(self.schedule.opts)
  207. ret.update({'schedule': {'foo': 'bar', 'hello': 'world'}})
  208. self.schedule.opts.update({'schedule': {'hello': 'world'}})
  209. Schedule.reload(self.schedule, saved)
  210. self.assertEqual(self.schedule.opts, ret)
  211. def test_reload_update_schedule_no_key(self):
  212. '''
  213. Tests reloading the schedule from saved schedule that does not
  214. contain a schedule key but self.schedule.opts does
  215. '''
  216. saved = {'foo': 'bar'}
  217. ret = copy.deepcopy(self.schedule.opts)
  218. ret.update({'schedule': {'foo': 'bar', 'hello': 'world'}})
  219. self.schedule.opts.update({'schedule': {'hello': 'world'}})
  220. Schedule.reload(self.schedule, saved)
  221. self.assertEqual(self.schedule.opts, ret)
  222. def test_reload_no_schedule_in_opts(self):
  223. '''
  224. Tests reloading the schedule from saved schedule that does not
  225. contain a schedule key and neither does self.schedule.opts
  226. '''
  227. saved = {'foo': 'bar'}
  228. ret = copy.deepcopy(self.schedule.opts)
  229. ret['schedule'] = {'foo': 'bar'}
  230. self.schedule.opts.pop('schedule', None)
  231. Schedule.reload(self.schedule, saved)
  232. self.assertEqual(self.schedule.opts, ret)
  233. def test_reload_schedule_in_saved_but_not_opts(self):
  234. '''
  235. Tests reloading the schedule from saved schedule that contains
  236. a schedule key, but self.schedule.opts does not
  237. '''
  238. saved = {'schedule': {'foo': 'bar'}}
  239. ret = copy.deepcopy(self.schedule.opts)
  240. ret['schedule'] = {'foo': 'bar'}
  241. self.schedule.opts.pop('schedule', None)
  242. Schedule.reload(self.schedule, saved)
  243. self.assertEqual(self.schedule.opts, ret)
  244. # eval tests
  245. def test_eval_schedule_is_not_dict(self):
  246. '''
  247. Tests eval if the schedule is not a dictionary
  248. '''
  249. self.schedule.opts.update({'schedule': '', 'pillar': {'schedule': {}}})
  250. self.assertRaises(ValueError, Schedule.eval, self.schedule)
  251. def test_eval_schedule_is_not_dict_in_pillar(self):
  252. '''
  253. Tests eval if the schedule from pillar is not a dictionary
  254. '''
  255. self.schedule.opts.update({'schedule': {}, 'pillar': {'schedule': ''}})
  256. self.assertRaises(ValueError, Schedule.eval, self.schedule)
  257. def test_eval_schedule_time(self):
  258. '''
  259. Tests eval if the schedule setting time is in the future
  260. '''
  261. self.schedule.opts.update({'pillar': {'schedule': {}}})
  262. self.schedule.opts.update({'schedule': {'testjob': {'function': 'test.true', 'seconds': 60}}})
  263. now = datetime.datetime.now()
  264. self.schedule.eval()
  265. self.assertTrue(self.schedule.opts['schedule']['testjob']['_next_fire_time'] > now)
  266. def test_eval_schedule_time_eval(self):
  267. '''
  268. Tests eval if the schedule setting time is in the future plus splay
  269. '''
  270. self.schedule.opts.update({'pillar': {'schedule': {}}})
  271. self.schedule.opts.update(
  272. {'schedule': {'testjob': {'function': 'test.true', 'seconds': 60, 'splay': 5}}})
  273. now = datetime.datetime.now()
  274. self.schedule.eval()
  275. self.assertTrue(self.schedule.opts['schedule']['testjob']['_splay'] - now > datetime.timedelta(seconds=60))
  276. @skipIf(not _CRON_SUPPORTED, 'croniter module not installed')
  277. def test_eval_schedule_cron(self):
  278. '''
  279. Tests eval if the schedule is defined with cron expression
  280. '''
  281. self.schedule.opts.update({'pillar': {'schedule': {}}})
  282. self.schedule.opts.update({'schedule': {'testjob': {'function': 'test.true', 'cron': '* * * * *'}}})
  283. now = datetime.datetime.now()
  284. self.schedule.eval()
  285. self.assertTrue(self.schedule.opts['schedule']['testjob']['_next_fire_time'] > now)
  286. @skipIf(not _CRON_SUPPORTED, 'croniter module not installed')
  287. def test_eval_schedule_cron_splay(self):
  288. '''
  289. Tests eval if the schedule is defined with cron expression plus splay
  290. '''
  291. self.schedule.opts.update({'pillar': {'schedule': {}}})
  292. self.schedule.opts.update(
  293. {'schedule': {'testjob': {'function': 'test.true', 'cron': '* * * * *', 'splay': 5}}})
  294. self.schedule.eval()
  295. self.assertTrue(self.schedule.opts['schedule']['testjob']['_splay'] >
  296. self.schedule.opts['schedule']['testjob']['_next_fire_time'])
  297. def test_handle_func_schedule_minion_blackout(self):
  298. '''
  299. Tests eval if the schedule from pillar is not a dictionary
  300. '''
  301. self.schedule.opts.update({'pillar': {'schedule': {}}})
  302. self.schedule.opts.update({'grains': {'minion_blackout': True}})
  303. self.schedule.opts.update(
  304. {'schedule': {'testjob': {'function': 'test.true',
  305. 'seconds': 60}}})
  306. data = {'function': 'test.true',
  307. '_next_scheduled_fire_time': datetime.datetime(2018,
  308. 11,
  309. 21,
  310. 14,
  311. 9,
  312. 53,
  313. 903438),
  314. 'run': True,
  315. 'name': 'testjob',
  316. 'seconds': 60,
  317. '_splay': None,
  318. '_seconds': 60,
  319. 'jid_include': True,
  320. 'maxrunning': 1,
  321. '_next_fire_time': datetime.datetime(2018,
  322. 11,
  323. 21,
  324. 14,
  325. 8,
  326. 53,
  327. 903438)}
  328. with patch.object(salt.utils.schedule, 'log') as log_mock:
  329. with patch('salt.utils.process.daemonize'), \
  330. patch('sys.platform', 'linux2'):
  331. self.schedule.handle_func(False, 'test.ping', data)
  332. self.assertTrue(log_mock.exception.called)