Xixuan Wu | 4099889 | 2017-08-29 14:32:26 -0700 | [diff] [blame] | 1 | # Copyright 2017 The Chromium OS Authors. All rights reserved. |
| 2 | # Use of this source code is governed by a BSD-style license that can be |
| 3 | # found in the LICENSE file. |
| 4 | |
| 5 | """Module for trigger_receiver unittests.""" |
| 6 | |
| 7 | import datetime |
| 8 | import os |
| 9 | import unittest |
| 10 | |
| 11 | import cloud_sql_client |
| 12 | import config_reader |
| 13 | import datastore_client |
| 14 | import file_getter |
| 15 | import mock |
| 16 | import time_converter |
| 17 | import trigger_receiver |
| 18 | |
| 19 | from google.appengine.ext import ndb |
| 20 | from google.appengine.ext import testbed |
| 21 | |
| 22 | # Ensure that SUITE_SCHEDULER_CONFIG_FILE is read only once. |
| 23 | _SUITE_CONFIG_READER = config_reader.ConfigReader( |
Xixuan Wu | 26d06e0 | 2017-09-20 14:50:28 -0700 | [diff] [blame] | 24 | file_getter.TEST_SUITE_SCHEDULER_CONFIG_FILE) |
Xixuan Wu | 4099889 | 2017-08-29 14:32:26 -0700 | [diff] [blame] | 25 | |
| 26 | |
| 27 | def now_generator(start_time, interval_min=30, last_days=7): |
| 28 | """A datetime.datetime.now generator. |
| 29 | |
| 30 | The generator will generate 'now' from start_time till start_time+last_days |
| 31 | for every interval_min. |
| 32 | |
| 33 | Args: |
| 34 | start_time: A datetime.datetime object representing the initial value of |
| 35 | the 'now'. |
| 36 | interval_min: The interval minutes between current 'now' and next 'now. |
| 37 | last_days: Representing how many days this generator will last. |
| 38 | |
| 39 | Yields: |
| 40 | a datetime.datetime object to mock the current time. |
| 41 | """ |
| 42 | cur_time = start_time |
| 43 | end_time = start_time + datetime.timedelta(days=last_days) |
| 44 | while cur_time < end_time: |
| 45 | yield cur_time |
| 46 | cur_time += datetime.timedelta(minutes=interval_min) |
| 47 | |
| 48 | |
Xixuan Wu | 4099889 | 2017-08-29 14:32:26 -0700 | [diff] [blame] | 49 | def _should_schedule_nightly_task(last_now, now): |
| 50 | """Check whether nightly task should be scheduled. |
| 51 | |
| 52 | A nightly task should be schduled when next hour is coming. |
| 53 | |
| 54 | Args: |
| 55 | last_now: the last time to check if nightly task should be scheduled |
| 56 | or not. |
| 57 | now: the current time to check if nightly task should be scheduled. |
| 58 | |
| 59 | Returns: |
| 60 | a boolean indicating whether there will be nightly tasks scheduled. |
| 61 | """ |
| 62 | if last_now is not None and last_now.hour != now.hour: |
| 63 | return True |
| 64 | |
| 65 | return False |
| 66 | |
| 67 | |
| 68 | def _should_schedule_weekly_task(last_now, now, weekly_time_info): |
| 69 | """Check whether weekly task should be scheduled. |
| 70 | |
| 71 | A weekly task should be schduled when it comes to the default weekly tasks |
| 72 | scheduling hour in next day. |
| 73 | |
| 74 | Args: |
| 75 | last_now: the last time to check if weekly task should be scheduled |
| 76 | or not. |
| 77 | now: the current time to check if weekly task should be scheduled. |
| 78 | weekly_time_info: the default weekly tasks scheduling time info. |
| 79 | |
| 80 | Returns: |
| 81 | a boolean indicating whether there will be weekly tasks scheduled. |
| 82 | """ |
| 83 | if (last_now is not None and last_now.hour != now.hour and |
| 84 | now.hour == weekly_time_info.hour): |
| 85 | return True |
| 86 | |
| 87 | return False |
| 88 | |
| 89 | |
| 90 | def _should_schedule_new_build_task(last_now, now): |
| 91 | """Check whether weekly task should be scheduled. |
| 92 | |
| 93 | A new_build task should be schduled when there're new builds between last |
| 94 | check and this check. |
| 95 | |
| 96 | Args: |
| 97 | last_now: the last time to check if new_build task should be scheduled. |
| 98 | now: the current time to check if new_build task should be scheduled. |
| 99 | |
| 100 | Returns: |
| 101 | a boolean indicating whether there will be new_build tasks scheduled. |
| 102 | """ |
| 103 | if last_now is not None and last_now != now: |
| 104 | return True |
| 105 | |
| 106 | return False |
| 107 | |
| 108 | |
| 109 | class FakeCIDBClient(object): |
| 110 | """Mock cloud_sql_client.CIDBClient.""" |
| 111 | |
| 112 | def get_passed_builds_since_date(self, since_date): |
| 113 | """Mock cloud_sql_client.CIDBClient.get_passed_builds_since_date.""" |
| 114 | del since_date # unused |
| 115 | return [cloud_sql_client.BuildInfo('link', '62', '9868.0.0', |
| 116 | 'link-release')] |
| 117 | |
| 118 | def get_latest_passed_builds(self, build_config): |
| 119 | """Mock cloud_sql_client.CIDBClient.get_latest_passed_builds.""" |
| 120 | del build_config # unused |
| 121 | return cloud_sql_client.BuildInfo('link', '62', '9868.0.0', build_config) |
| 122 | |
| 123 | |
| 124 | class FakeAndroidBuildRestClient(object): |
| 125 | """Mock rest_client.AndroidBuildRestClient.""" |
| 126 | |
| 127 | def get_latest_build_id(self, branch, target): |
| 128 | """Mock rest_client.AndroidBuildRestClient.get_latest_build_id.""" |
| 129 | del branch, target # unused |
| 130 | return '100' |
| 131 | |
| 132 | |
| 133 | class FakeLabConfig(object): |
| 134 | """Mock rest_client.AndroidBuildRestClient.""" |
| 135 | |
| 136 | def get_android_board_list(self): |
| 137 | """Mock config_reader.LabConfig.get_android_board_list.""" |
| 138 | return ('android-angler', 'android-bullhead') |
| 139 | |
| 140 | def get_firmware_ro_build_list(self, release_board): |
| 141 | """Mock config_reader.LabConfig.get_firmware_ro_build_list.""" |
| 142 | del release_board # unused |
| 143 | return 'firmware1,firmware2' |
| 144 | |
| 145 | |
Xixuan Wu | 008ee83 | 2017-10-12 16:59:34 -0700 | [diff] [blame^] | 146 | class TriggerReceiverBaseTestCase(unittest.TestCase): |
Xixuan Wu | 4099889 | 2017-08-29 14:32:26 -0700 | [diff] [blame] | 147 | |
| 148 | def setUp(self): |
| 149 | self.testbed = testbed.Testbed() |
| 150 | self.testbed.activate() |
| 151 | self.addCleanup(self.testbed.deactivate) |
| 152 | |
| 153 | self.testbed.init_datastore_v3_stub() |
| 154 | self.testbed.init_memcache_stub() |
| 155 | ndb.get_context().clear_cache() |
| 156 | self.testbed.init_taskqueue_stub( |
| 157 | root_path=os.path.join(os.path.dirname(__file__))) |
| 158 | self.taskqueue_stub = self.testbed.get_stub( |
| 159 | testbed.TASKQUEUE_SERVICE_NAME) |
| 160 | |
| 161 | mock_cidb_client = mock.patch('cloud_sql_client.CIDBClient') |
| 162 | self._mock_cidb_client = mock_cidb_client.start() |
| 163 | self.addCleanup(mock_cidb_client.stop) |
| 164 | |
| 165 | mock_android_client = mock.patch('rest_client.AndroidBuildRestClient') |
| 166 | self._mock_android_client = mock_android_client.start() |
| 167 | self.addCleanup(mock_android_client.stop) |
| 168 | |
Xixuan Wu | 4099889 | 2017-08-29 14:32:26 -0700 | [diff] [blame] | 169 | mock_lab_config = mock.patch('config_reader.LabConfig') |
| 170 | self._mock_lab_config = mock_lab_config.start() |
| 171 | self.addCleanup(mock_lab_config.stop) |
| 172 | |
| 173 | mock_utc_now = mock.patch('time_converter.utc_now') |
| 174 | self._mock_utc_now = mock_utc_now.start() |
| 175 | self.addCleanup(mock_utc_now.stop) |
| 176 | |
| 177 | self._mock_cidb_client.return_value = FakeCIDBClient() |
| 178 | self._mock_android_client.return_value = FakeAndroidBuildRestClient() |
Xixuan Wu | 4099889 | 2017-08-29 14:32:26 -0700 | [diff] [blame] | 179 | self._mock_lab_config.return_value = FakeLabConfig() |
| 180 | |
Xixuan Wu | 008ee83 | 2017-10-12 16:59:34 -0700 | [diff] [blame^] | 181 | |
| 182 | class TriggerReceiverFakeConfigTestCase(TriggerReceiverBaseTestCase): |
| 183 | |
| 184 | _TEST_PST_HOUR = 20 |
| 185 | _TEST_PST_DAY = 4 # Friday |
| 186 | _TEST_EVENT_PST_HOUR = 13 |
| 187 | |
| 188 | _FAKE_NIGHTLY_TASK_NAME = 'fake_nightly_task' |
| 189 | _FAKE_WEEKLY_TASK_NAME = 'fake_weekly_task' |
| 190 | |
| 191 | def setUp(self): |
| 192 | super(TriggerReceiverFakeConfigTestCase, self).setUp() |
| 193 | |
| 194 | self.fake_config = config_reader.ConfigReader(None) |
| 195 | self._add_nightly_tasks(self.fake_config) |
| 196 | self._add_weekly_tasks(self.fake_config) |
| 197 | |
| 198 | self.fake_config_with_settings = config_reader.ConfigReader(None) |
| 199 | self._add_weekly_tasks(self.fake_config_with_settings) |
| 200 | self._add_weekly_params(self.fake_config_with_settings) |
| 201 | |
| 202 | mock_config_reader = mock.patch('config_reader.ConfigReader') |
| 203 | self._mock_config_reader = mock_config_reader.start() |
| 204 | self.addCleanup(mock_config_reader.stop) |
| 205 | |
| 206 | def _add_nightly_tasks(self, fake_config): |
| 207 | fake_config.add_section(self._FAKE_NIGHTLY_TASK_NAME) |
| 208 | fake_config.set(self._FAKE_NIGHTLY_TASK_NAME, 'suite', 'fake_suite') |
| 209 | fake_config.set(self._FAKE_NIGHTLY_TASK_NAME, 'run_on', 'nightly') |
| 210 | fake_config.set(self._FAKE_NIGHTLY_TASK_NAME, 'hour', |
| 211 | str(self._TEST_PST_HOUR)) |
| 212 | |
| 213 | def _add_weekly_tasks(self, fake_config): |
| 214 | fake_config.add_section(self._FAKE_WEEKLY_TASK_NAME) |
| 215 | fake_config.set(self._FAKE_WEEKLY_TASK_NAME, 'suite', 'fake_suite') |
| 216 | fake_config.set(self._FAKE_WEEKLY_TASK_NAME, 'run_on', 'weekly') |
| 217 | fake_config.set(self._FAKE_WEEKLY_TASK_NAME, 'day', str(self._TEST_PST_DAY)) |
| 218 | |
| 219 | def _add_weekly_params(self, fake_config): |
| 220 | weekly_section_name = config_reader.EVENT_CLASSES['weekly'].section_name() |
| 221 | fake_config.add_section(weekly_section_name) |
| 222 | fake_config.set(weekly_section_name, 'hour', str(self._TEST_EVENT_PST_HOUR)) |
| 223 | |
| 224 | def testInitializeTriggerReceiverWithNightlyEvent(self): |
| 225 | """Test nightly event can be handled on right hour.""" |
| 226 | # A task with hour=20 should be scheduled at 20:00 in PST everyday, which |
| 227 | # is 3:00/4:00 in UTC everyday. |
| 228 | self._mock_config_reader.return_value = self.fake_config |
| 229 | given_utc_hour = time_converter.convert_time_info( |
| 230 | time_converter.TimeInfo(None, self._TEST_PST_HOUR)).hour |
| 231 | utc_now = datetime.datetime(2017, 8, 6, given_utc_hour, |
| 232 | tzinfo=time_converter.UTC_TZ) |
| 233 | last_exec_client = datastore_client.LastExecutionRecordStore() |
| 234 | last_exec_client.set_last_execute_time( |
| 235 | 'nightly', utc_now - datetime.timedelta(hours=1)) |
| 236 | self._mock_utc_now.return_value = utc_now |
| 237 | |
| 238 | suite_trigger = trigger_receiver.TriggerReceiver() |
| 239 | suite_trigger.cron() |
| 240 | self.assertTrue(suite_trigger.events['nightly'].should_handle) |
| 241 | self.assertEqual(len(suite_trigger.event_results['nightly']), 1) |
| 242 | self.assertEqual(suite_trigger.event_results['nightly'][0], |
| 243 | self._FAKE_NIGHTLY_TASK_NAME) |
| 244 | |
| 245 | def testInitializeTriggerReceiverWithWeeklyEventWithoutEventHour(self): |
| 246 | """Test weekly event without event settings can be handled on right day.""" |
| 247 | # A task with day=4 (Friday) and default event_hour (23) should be |
| 248 | # scheduled at Friday 23:00 in PST, which is Saturday 6:00 or 7:00 in UTC. |
| 249 | self._mock_config_reader.return_value = self.fake_config |
| 250 | given_utc_hour = time_converter.convert_time_info( |
| 251 | time_converter.TimeInfo( |
| 252 | self._TEST_PST_DAY, |
| 253 | config_reader.EVENT_CLASSES['weekly'].DEFAULT_PST_HOUR)).hour |
| 254 | utc_now = datetime.datetime(2017, 10, 14, given_utc_hour, |
| 255 | tzinfo=time_converter.UTC_TZ) |
| 256 | last_exec_client = datastore_client.LastExecutionRecordStore() |
| 257 | last_exec_client.set_last_execute_time( |
| 258 | 'weekly', utc_now - datetime.timedelta(days=1)) |
| 259 | self._mock_utc_now.return_value = utc_now |
| 260 | |
| 261 | suite_trigger = trigger_receiver.TriggerReceiver() |
| 262 | suite_trigger.cron() |
| 263 | self.assertTrue(suite_trigger.events['weekly'].should_handle) |
| 264 | self.assertEqual(len(suite_trigger.event_results['weekly']), 1) |
| 265 | self.assertEqual(suite_trigger.event_results['weekly'][0], |
| 266 | self._FAKE_WEEKLY_TASK_NAME) |
| 267 | |
| 268 | def testInitializeTriggerReceiverWithWeeklyEventWithEventHour(self): |
| 269 | """Test weekly event with event settings can be handled on right day.""" |
| 270 | # A task with day=4 (Friday) and event_hour=13 should be scheduled at |
| 271 | # Friday 13:00 in PST, which is Friday 20:00 or 21:00 in UTC. |
| 272 | self._mock_config_reader.return_value = self.fake_config_with_settings |
| 273 | given_utc_time_info = time_converter.convert_time_info( |
| 274 | time_converter.TimeInfo(self._TEST_PST_DAY, self._TEST_EVENT_PST_HOUR)) |
| 275 | |
| 276 | # Set the current time as a Friday 20:00 or 21:00 in UTC. |
| 277 | utc_now = datetime.datetime(2017, 10, 13, given_utc_time_info.hour, |
| 278 | tzinfo=time_converter.UTC_TZ) |
| 279 | last_exec_client = datastore_client.LastExecutionRecordStore() |
| 280 | last_exec_client.set_last_execute_time( |
| 281 | 'weekly', utc_now - datetime.timedelta(days=1)) |
| 282 | self._mock_utc_now.return_value = utc_now |
| 283 | |
| 284 | suite_trigger = trigger_receiver.TriggerReceiver() |
| 285 | suite_trigger.cron() |
| 286 | self.assertTrue(suite_trigger.events['weekly'].should_handle) |
| 287 | self.assertEqual(len(suite_trigger.event_results['weekly']), 1) |
| 288 | self.assertEqual(suite_trigger.event_results['weekly'][0], |
| 289 | self._FAKE_WEEKLY_TASK_NAME) |
| 290 | |
| 291 | |
| 292 | class TriggerReceiverRealConfigTestCase(TriggerReceiverBaseTestCase): |
| 293 | |
| 294 | def setUp(self): |
| 295 | super(TriggerReceiverRealConfigTestCase, self).setUp() |
| 296 | mock_config_reader = mock.patch('config_reader.ConfigReader') |
| 297 | self._mock_config_reader = mock_config_reader.start() |
| 298 | self.addCleanup(mock_config_reader.stop) |
| 299 | self._mock_config_reader.return_value = _SUITE_CONFIG_READER |
| 300 | |
| 301 | def _get_ground_truth_task_list_from_config(self): |
| 302 | """Get the ground truth of to-be-scheduled task list from config file.""" |
| 303 | self._mock_utc_now.return_value = datetime.datetime.now( |
| 304 | time_converter.UTC_TZ) |
| 305 | task_config = config_reader.TaskConfig(_SUITE_CONFIG_READER) |
| 306 | tasks = {} |
| 307 | for keyword, klass in config_reader.EVENT_CLASSES.iteritems(): |
| 308 | new_event = klass( |
| 309 | task_config.get_event_setting(klass.section_name()), None) |
| 310 | new_event.set_task_list( |
| 311 | task_config.get_tasks_by_keyword(klass.KEYWORD)['tasks']) |
| 312 | tasks[keyword] = new_event.task_list |
| 313 | |
| 314 | return tasks |
| 315 | |
Xixuan Wu | 4099889 | 2017-08-29 14:32:26 -0700 | [diff] [blame] | 316 | def testCronWithoutLastExec(self): |
| 317 | """Test the first round of cron can be successfully executed.""" |
| 318 | self._mock_utc_now.return_value = datetime.datetime.now( |
| 319 | time_converter.UTC_TZ) |
| 320 | suite_trigger = trigger_receiver.TriggerReceiver() |
| 321 | suite_trigger.cron() |
| 322 | self.assertFalse(suite_trigger.events['nightly'].should_handle) |
| 323 | self.assertFalse(suite_trigger.events['weekly'].should_handle) |
| 324 | self.assertFalse(suite_trigger.events['new_build'].should_handle) |
| 325 | |
| 326 | self.assertEqual(suite_trigger.event_results, {}) |
| 327 | |
| 328 | def testCronTriggerNightly(self): |
| 329 | """Test nightly event is read with available nightly last_exec_time.""" |
| 330 | utc_now = datetime.datetime.now(time_converter.UTC_TZ) |
| 331 | last_exec_client = datastore_client.LastExecutionRecordStore() |
| 332 | last_exec_client.set_last_execute_time( |
| 333 | 'nightly', utc_now - datetime.timedelta(hours=1)) |
| 334 | self._mock_utc_now.return_value = utc_now |
| 335 | suite_trigger = trigger_receiver.TriggerReceiver() |
| 336 | self.assertTrue(suite_trigger.events['nightly'].should_handle) |
| 337 | self.assertFalse(suite_trigger.events['weekly'].should_handle) |
| 338 | self.assertFalse(suite_trigger.events['new_build'].should_handle) |
| 339 | |
Xixuan Wu | 3317967 | 2017-09-12 11:44:04 -0700 | [diff] [blame] | 340 | def testCronTriggerNightlyOutdated(self): |
| 341 | """Test nightly event is read with available nightly last_exec_time.""" |
| 342 | utc_now = datetime.datetime.now(time_converter.UTC_TZ) |
| 343 | last_exec_client = datastore_client.LastExecutionRecordStore() |
| 344 | last_exec_client.set_last_execute_time( |
| 345 | 'nightly', utc_now - datetime.timedelta(days=3)) |
| 346 | self._mock_utc_now.return_value = utc_now |
| 347 | suite_trigger = trigger_receiver.TriggerReceiver() |
| 348 | self.assertFalse(suite_trigger.events['nightly'].should_handle) |
| 349 | |
| 350 | def testCronTriggerWeeklyOutdated(self): |
| 351 | """Test weekly event is read with available weekly last_exec_time.""" |
| 352 | utc_now = datetime.datetime.now(time_converter.UTC_TZ) |
| 353 | last_exec_client = datastore_client.LastExecutionRecordStore() |
| 354 | last_exec_client.set_last_execute_time( |
| 355 | 'weekly', utc_now - datetime.timedelta(days=8)) |
| 356 | self._mock_utc_now.return_value = utc_now |
| 357 | suite_trigger = trigger_receiver.TriggerReceiver() |
| 358 | self.assertFalse(suite_trigger.events['weekly'].should_handle) |
| 359 | |
Xixuan Wu | 4099889 | 2017-08-29 14:32:26 -0700 | [diff] [blame] | 360 | def testCronForWeeks(self): |
| 361 | """Ensure cron job can be successfully scheduled for several weeks.""" |
Xixuan Wu | 008ee83 | 2017-10-12 16:59:34 -0700 | [diff] [blame^] | 362 | all_tasks = self._get_ground_truth_task_list_from_config() |
| 363 | nightly_time_info = time_converter.convert_time_info( |
Xixuan Wu | 4099889 | 2017-08-29 14:32:26 -0700 | [diff] [blame] | 364 | time_converter.TimeInfo( |
| 365 | config_reader.EVENT_CLASSES['nightly'].DEFAULT_PST_DAY, |
| 366 | config_reader.EVENT_CLASSES['nightly'].DEFAULT_PST_HOUR)) |
Xixuan Wu | 008ee83 | 2017-10-12 16:59:34 -0700 | [diff] [blame^] | 367 | weekly_time_info = time_converter.convert_time_info( |
Xixuan Wu | 4099889 | 2017-08-29 14:32:26 -0700 | [diff] [blame] | 368 | time_converter.TimeInfo( |
| 369 | config_reader.EVENT_CLASSES['weekly'].DEFAULT_PST_DAY, |
| 370 | config_reader.EVENT_CLASSES['weekly'].DEFAULT_PST_HOUR)) |
| 371 | last_now = None |
| 372 | |
| 373 | for now in now_generator(datetime.datetime.now(time_converter.UTC_TZ)): |
| 374 | self._mock_utc_now.return_value = now |
| 375 | suite_trigger = trigger_receiver.TriggerReceiver() |
| 376 | suite_trigger.cron() |
| 377 | |
Xixuan Wu | 4099889 | 2017-08-29 14:32:26 -0700 | [diff] [blame] | 378 | should_scheduled_nightly_tasks = [ |
| 379 | t.name for t in all_tasks['nightly'] |
| 380 | if (t.hour is not None and t.hour == now.hour) or |
| 381 | (t.hour is None and now.hour == nightly_time_info.hour)] |
Xixuan Wu | 008ee83 | 2017-10-12 16:59:34 -0700 | [diff] [blame^] | 382 | |
Xixuan Wu | 4099889 | 2017-08-29 14:32:26 -0700 | [diff] [blame] | 383 | if (_should_schedule_nightly_task(last_now, now) and |
| 384 | should_scheduled_nightly_tasks): |
| 385 | self.assertEqual(suite_trigger.event_results['nightly'], |
| 386 | should_scheduled_nightly_tasks) |
| 387 | else: |
| 388 | self.assertNotIn('nightly', suite_trigger.event_results.keys()) |
| 389 | |
| 390 | # Verify weekly tasks |
| 391 | should_scheduled_weekly_tasks = [ |
| 392 | t.name for t in all_tasks['weekly'] |
| 393 | if (t.day is not None and now.weekday() == t.day) or |
| 394 | (t.day is None and now.weekday() == weekly_time_info.weekday)] |
| 395 | if (_should_schedule_weekly_task(last_now, now, weekly_time_info) and |
| 396 | should_scheduled_weekly_tasks): |
| 397 | self.assertEqual(suite_trigger.event_results['weekly'], |
| 398 | should_scheduled_weekly_tasks) |
| 399 | else: |
| 400 | self.assertNotIn('weekly', suite_trigger.event_results.keys()) |
| 401 | |
| 402 | # Verify new_build tasks |
| 403 | should_scheduled_new_build_tasks = [ |
| 404 | t.name for t in all_tasks['new_build']] |
| 405 | if (_should_schedule_new_build_task(last_now, now) and |
| 406 | should_scheduled_new_build_tasks): |
| 407 | self.assertEqual(suite_trigger.event_results['new_build'], |
| 408 | should_scheduled_new_build_tasks) |
| 409 | else: |
| 410 | self.assertNotIn('new_build', suite_trigger.event_results.keys()) |
| 411 | |
| 412 | last_now = now |
| 413 | |
| 414 | |
| 415 | if __name__ == '__main__': |
| 416 | unittest.main() |