Best Python code snippet using molotov_python
test_update.py
Source:test_update.py
...111 self.session = session.TestSession(self)112 def tearDown(self):113 self.session.clean()114 self.module = None115 def init_session(self, mock_setconfigfield=None, mock_commands=[]):116 # create module instance117 self.module = self.session.setup(Update)118 # add command mocks119 for command in mock_commands:120 self.session.add_mock_command(command)121 if 'get_modules' not in self.session.get_handled_commands():122 self.session.add_mock_command(self.session.make_mock_command('get_modules', data=INVENTORY_GETMODULES))123 if mock_setconfigfield:124 self.module._set_config_field = mock_setconfigfield125 # start module126 self.session.start_module(self.module)127 @patch('backend.update.CLEEP_VERSION', '6.6.6')128 def test_configure(self):129 mock_setconfigfield = Mock()130 self.init_session(mock_setconfigfield=mock_setconfigfield)131 mock_setconfigfield.assert_called_with('cleepversion', '6.6.6')132 def test_get_module_config(self):133 self.init_session()134 before = self.module._get_config()135 config = self.module.get_module_config()136 after = self.module._get_config()137 self.assertFalse('cleepupdatelogs' in before)138 self.assertTrue('cleepupdatelogs' in config)139 self.assertFalse('cleepupdatelogs' in after)140 def test_on_event_updates_allowed(self):141 self.init_session()142 self.module._set_config_field('cleepupdateenabled', True)143 self.module._set_config_field('modulesupdateenabled', True)144 self.module.check_cleep_updates = Mock()145 self.module.check_modules_updates = Mock()146 self.module.update_cleep = Mock()147 self.module.update_modules = Mock()148 event = {149 'event': 'parameters.time.now',150 'params': {151 'hour': self.module._check_update_time['hour'],152 'minute': self.module._check_update_time['minute'],153 },154 }155 self.module.on_event(event)156 self.assertTrue(self.module.check_cleep_updates.called)157 self.assertTrue(self.module.check_modules_updates.called)158 self.assertTrue(self.module.update_cleep.called)159 self.assertFalse(self.module.update_modules.called)160 def test_on_event_updates_not_allowed(self):161 self.init_session()162 self.module._set_config_field('cleepupdateenabled', False)163 self.module._set_config_field('modulesupdateenabled', False)164 self.module.check_cleep_updates = Mock()165 self.module.check_modules_updates = Mock()166 self.module.update_cleep = Mock()167 self.module.update_modules = Mock()168 event = {169 'event': 'parameters.time.now',170 'params': {171 'hour': self.module._check_update_time['hour'],172 'minute': self.module._check_update_time['minute'],173 },174 }175 self.module.on_event(event)176 self.assertTrue(self.module.check_cleep_updates.called)177 self.assertTrue(self.module.check_modules_updates.called)178 self.assertFalse(self.module.update_cleep.called)179 self.assertFalse(self.module.update_modules.called)180 def test_on_event_update_modules(self):181 self.init_session()182 self.module._set_config_field('cleepupdateenabled', False)183 self.module._set_config_field('modulesupdateenabled', True)184 self.module.check_cleep_updates = Mock()185 self.module.check_modules_updates = Mock()186 self.module.update_cleep = Mock()187 self.module.update_modules = Mock()188 event = {189 'event': 'parameters.time.now',190 'params': {191 'hour': self.module._check_update_time['hour'],192 'minute': self.module._check_update_time['minute'],193 },194 }195 self.module.on_event(event)196 self.assertTrue(self.module.check_cleep_updates.called)197 self.assertTrue(self.module.check_modules_updates.called)198 self.assertFalse(self.module.update_cleep.called)199 self.assertTrue(self.module.update_modules.called)200 def test_get_modules_logs(self):201 self.init_session()202 self.module._get_last_update_logs = Mock(side_effect=[{'dummy': 'dummy'}, {'dummy': 'dummy'}])203 self.module._get_installed_modules_names = Mock(return_value=['system'])204 205 with patch('os.listdir', Mock(return_value=['cleep', 'system', 'audio'])):206 with patch('os.path.exists', Mock(return_value=True)):207 logs = self.module.get_modules_logs()208 logging.debug('Logs: %s' % logs)209 self.assertCountEqual(['audio', 'system'], list(logs.keys()))210 self.assertTrue('dummy' in logs['system'])211 self.assertTrue('name' in logs['system'])212 self.assertTrue('installed' in logs['system'])213 self.assertTrue(logs['system']['installed'])214 self.assertFalse(logs['audio']['installed'])215 def test_get_modules_logs_no_file_for_module(self):216 self.init_session()217 self.module._get_last_update_logs = Mock(side_effect=[{'dummy': 'dummy'}, None])218 self.module._get_installed_modules_names = Mock(return_value=['system'])219 220 with patch('os.listdir', Mock(return_value=['cleep', 'system', 'audio'])):221 with patch('os.path.exists', Mock(return_value=True)):222 logs = self.module.get_modules_logs()223 logging.debug('Logs: %s' % logs)224 self.assertCountEqual(['system'], list(logs.keys()))225 self.assertTrue('dummy' in logs['system'])226 self.assertTrue('name' in logs['system'])227 self.assertTrue('installed' in logs['system'])228 self.assertTrue(logs['system']['installed'])229 self.assertFalse('audio' in logs)230 def test_get_modules_logs_no_install_path(self):231 self.init_session()232 with patch('os.path.exists', Mock(return_value=False)):233 logs = self.module.get_modules_logs()234 logging.debug('Logs: %s' % logs)235 self.assertEqual(logs, {})236 def test_get_last_update_logs(self):237 self.init_session()238 # success239 with patch('os.path.exists', Mock(return_value=True)):240 with patch('os.path.getmtime', Mock(side_effect=[666, 665])):241 logs = self.module._get_last_update_logs('module')242 logging.debug('Logs: %s' % logs)243 self.assertEqual(logs['timestamp'], 666)244 self.assertFalse(logs['failed'])245 self.assertEqual(logs['path'], '/opt/cleep/install/module/process_success.log')246 # failure247 with patch('os.path.exists', Mock(side_effect=[False, True])):248 with patch('os.path.getmtime', Mock(return_value=666)):249 logs = self.module._get_last_update_logs('module')250 logging.debug('Logs: %s' % logs)251 self.assertEqual(logs['timestamp'], 666)252 self.assertTrue(logs['failed'])253 self.assertEqual(logs['path'], '/opt/cleep/install/module/process_failure.log')254 # neither success nor failure255 with patch('os.path.exists', Mock(side_effect=[False, False])):256 with patch('os.path.getmtime', Mock(return_value=666)):257 logs = self.module._get_last_update_logs('module')258 logging.debug('Logs: %s' % logs)259 self.assertEqual(logs, None)260 def test_get_logs(self):261 self.init_session()262 self.module.cleep_filesystem.read_data = Mock(return_value='hello world')263 # success264 with patch('os.path.exists', side_effect=[True, False]):265 with patch('os.path.getmtime', Mock(return_value=666)):266 logs = self.module.get_logs('module')267 logging.debug('Logs: %s' % logs)268 self.assertEqual(logs, 'hello world')269 # failure270 with patch('os.path.exists', side_effect=[False, True]):271 with patch('os.path.getmtime', Mock(return_value=666)):272 logs = self.module.get_logs('module')273 logging.debug('Logs: %s' % logs)274 self.assertEqual(logs, 'hello world')275 # neither success nor failure276 with patch('os.path.exists', side_effect=[False, False]):277 with self.assertRaises(CommandError) as cm:278 logs = self.module.get_logs('module')279 self.assertEqual(str(cm.exception), 'There is no logs for app "module"')280 def test_get_logs_error_read(self):281 self.init_session()282 self.module.cleep_filesystem.read_data = Mock(return_value=None)283 # success284 with patch('os.path.exists', side_effect=[True, False]):285 with patch('os.path.getmtime', Mock(return_value=666)):286 with self.assertRaises(CommandError) as cm:287 logs = self.module.get_logs('module')288 self.assertEqual(str(cm.exception), 'Error reading app "module" logs file')289 def test_reset_module_update_data(self):290 self.init_session()291 self.module._modules_updates['module'] = self.module._Update__get_module_update_data('module', '0.0.0')292 self.module._modules_updates['module']['processing'] = True293 self.module._modules_updates['module']['pending'] = True294 self.module._modules_updates['module']['updatable'] = True295 self.module._modules_updates['module']['update']['progress'] = 55296 self.module._modules_updates['module']['update']['failed'] = True297 self.module._Update__reset_module_update_data('module')298 self.assertFalse(self.module._modules_updates['module']['processing'])299 self.assertTrue(self.module._modules_updates['module']['pending'])300 self.assertTrue(self.module._modules_updates['module']['updatable'])301 self.assertEqual(self.module._modules_updates['module']['update']['progress'], 0)302 self.assertFalse(self.module._modules_updates['module']['update']['failed'])303 def test_restart_cleep(self):304 mock_restart = self.session.make_mock_command('restart_cleep')305 self.init_session(mock_commands=[mock_restart])306 self.module._restart_cleep()307 self.assertEqual(self.session.command_call_count('restart_cleep'), 1)308 def test_restart_cleep_failed(self):309 mock_restart = self.session.make_mock_command('restart_cleep', fail=True)310 self.init_session(mock_commands=[mock_restart])311 self.module._restart_cleep()312 self.assertEqual(self.session.command_call_count('restart_cleep'), 1)313 def test_get_cleep_updates(self):314 self.init_session()315 updates = self.module.get_cleep_updates()316 logging.debug('Cleep updates: %s' % updates)317 self.assertTrue(all([k in updates for k in ['updatable', 'processing', 'pending', 'failed', 'version', 'changelog', 'packageurl', 'checksumurl']]))318 @patch('backend.update.CleepGithub')319 @patch('backend.update.CLEEP_VERSION', '0.0.19')320 def test_check_cleep_updates_update_available(self, mock_cleepgithub):321 mock_cleepgithub.return_value.get_releases.return_value = GITHUB_SAMPLE322 mock_cleepgithub.return_value.get_release_version.return_value = '0.0.20'323 mock_cleepgithub.return_value.get_release_changelog.return_value = 'hello world'324 mock_cleepgithub.return_value.get_release_assets_infos.return_value = GITHUB_SAMPLE[0]['assets']325 self.init_session()326 update = self.module.check_cleep_updates()327 logging.debug('update: %s' % update)328 self.assertEqual(update['version'], '0.0.20')329 self.assertEqual(update['changelog'], 'hello world')330 self.assertEqual(update['packageurl'], 'https://api.github.com/repos/tangb/cleep/releases/assets/15425504')331 self.assertEqual(update['checksumurl'], 'https://api.github.com/repos/tangb/cleep/releases/assets/15425531')332 @patch('backend.update.CleepGithub')333 @patch('backend.update.CLEEP_VERSION', '0.0.20')334 def test_check_cleep_updates_no_update_available(self, mock_cleepgithub):335 mock_cleepgithub.return_value.get_releases.return_value = GITHUB_SAMPLE336 mock_cleepgithub.return_value.get_release_version.return_value = '0.0.20'337 mock_cleepgithub.return_value.get_release_changelog.return_value = 'hello world'338 mock_cleepgithub.return_value.get_release_assets_infos.return_value = GITHUB_SAMPLE[0]['assets']339 self.init_session()340 update = self.module.check_cleep_updates()341 logging.debug('update: %s' % update)342 self.assertEqual(update['version'], None)343 self.assertEqual(update['changelog'], None)344 self.assertEqual(update['packageurl'], None)345 self.assertEqual(update['checksumurl'], None)346 @patch('backend.update.CleepGithub')347 @patch('backend.update.CLEEP_VERSION', '0.0.19')348 def test_check_cleep_updates_no_release_found(self, mock_cleepgithub):349 mock_cleepgithub.return_value.get_releases.return_value = []350 mock_cleepgithub.return_value.get_release_version.return_value = '0.0.20'351 mock_cleepgithub.return_value.get_release_changelog.return_value = 'hello world'352 mock_cleepgithub.return_value.get_release_assets_infos.return_value = GITHUB_SAMPLE[0]['assets']353 self.init_session()354 update = self.module.check_cleep_updates()355 logging.debug('update: %s' % update)356 self.assertEqual(update['version'], None)357 self.assertEqual(update['changelog'], None)358 self.assertEqual(update['packageurl'], None)359 self.assertEqual(update['checksumurl'], None)360 @patch('backend.update.CleepGithub')361 @patch('backend.update.CLEEP_VERSION', '0.0.19')362 def test_check_cleep_updates_invalid_package_asset(self, mock_cleepgithub):363 mock_cleepgithub.return_value.get_releases.return_value = GITHUB_SAMPLE364 mock_cleepgithub.return_value.get_release_version.return_value = '0.0.20'365 mock_cleepgithub.return_value.get_release_changelog.return_value = 'hello world'366 mock_cleepgithub.return_value.get_release_assets_infos.return_value = [a for a in GITHUB_SAMPLE[0]['assets'] if a['name'] != 'cleep_0.0.20.deb']367 self.init_session()368 update = self.module.check_cleep_updates()369 logging.debug('update: %s' % update)370 self.assertEqual(update['version'], None)371 self.assertEqual(update['changelog'], None)372 self.assertEqual(update['packageurl'], None)373 self.assertEqual(update['checksumurl'], None)374 @patch('backend.update.CleepGithub')375 @patch('backend.update.CLEEP_VERSION', '0.0.19')376 def test_check_cleep_updates_invalid_checksum_asset(self, mock_cleepgithub):377 mock_cleepgithub.return_value.get_releases.return_value = GITHUB_SAMPLE378 mock_cleepgithub.return_value.get_release_version.return_value = '0.0.20'379 mock_cleepgithub.return_value.get_release_changelog.return_value = 'hello world'380 mock_cleepgithub.return_value.get_release_assets_infos.return_value = [a for a in GITHUB_SAMPLE[0]['assets'] if a['name'] != 'cleep_0.0.20.sha256']381 self.init_session()382 update = self.module.check_cleep_updates()383 logging.debug('update: %s' % update)384 self.assertEqual(update['version'], None)385 self.assertEqual(update['changelog'], None)386 self.assertEqual(update['packageurl'], None)387 self.assertEqual(update['checksumurl'], None)388 @patch('backend.update.CleepGithub')389 @patch('backend.update.CLEEP_VERSION', '0.0.19')390 def test_check_cleep_updates_exception(self, mock_cleepgithub):391 mock_cleepgithub.return_value.get_releases.side_effect = Exception('Test exception')392 mock_cleepgithub.return_value.get_release_version.return_value = '0.0.20'393 mock_cleepgithub.return_value.get_release_changelog.return_value = 'hello world'394 mock_cleepgithub.return_value.get_release_assets_infos.return_value = GITHUB_SAMPLE[0]['assets']395 self.init_session()396 with self.assertRaises(CommandError) as cm:397 self.module.check_cleep_updates()398 self.assertEqual(str(cm.exception), 'Error occured during cleep update check')399 @patch('os.environ', {'GITHUB_TOKEN': 'mysupertoken'})400 @patch('backend.update.CleepGithub')401 @patch('backend.update.CLEEP_VERSION', '0.0.19')402 def test_check_cleep_updates_with_github_token(self, mock_cleepgithub):403 mock_cleepgithub.return_value.get_releases.return_value = GITHUB_SAMPLE404 mock_cleepgithub.return_value.get_release_version.return_value = '0.0.20'405 mock_cleepgithub.return_value.get_release_changelog.return_value = 'hello world'406 mock_cleepgithub.return_value.get_release_assets_infos.return_value = GITHUB_SAMPLE[0]['assets']407 self.init_session()408 update = self.module.check_cleep_updates()409 logging.debug('update: %s' % update)410 mock_cleepgithub.assert_called_with('token mysupertoken')411 def test_fill_modules_updates(self):412 self.init_session()413 self.module._fill_modules_updates()414 modules_updates = self.module.get_modules_updates()415 logging.debug('Modules updates: %s' % modules_updates)416 inventory_keys = list(INVENTORY_GETMODULES.keys())417 inventory_keys.remove('cleepbus')418 self.assertEqual(sorted(inventory_keys), sorted(list(modules_updates.keys())))419 module_name = list(modules_updates.keys())[0]420 module_update = modules_updates[module_name]421 self.assertTrue('updatable' in module_update)422 self.assertTrue('processing' in module_update)423 self.assertTrue('name' in module_update)424 self.assertTrue('version' in module_update)425 self.assertTrue('version' in module_update['update'])426 self.assertTrue('changelog' in module_update['update'])427 self.assertTrue('progress' in module_update['update'])428 self.assertTrue('failed' in module_update['update'])429 self.assertEqual(module_update['name'], module_name)430 def test_fill_modules_updates_exception(self):431 self.init_session()432 self.session.set_mock_command_fail('get_modules')433 with self.assertRaises(Exception) as cm:434 self.module._fill_modules_updates()435 self.assertEqual(str(cm.exception), 'Unable to get modules list from inventory')436 def test_execute_main_action_task_install(self):437 self.init_session()438 self.module._install_main_module = Mock()439 self.module._uninstall_main_module = Mock()440 self.module._update_main_module = Mock()441 action_install = {442 'action': Update.ACTION_MODULE_INSTALL,443 'processing': False,444 'module': 'mod1',445 'extra': None,446 }447 action_update = {448 'action': Update.ACTION_MODULE_UPDATE,449 'processing': False,450 'module': 'mod1',451 'extra': None,452 }453 action_uninstall = {454 'action': Update.ACTION_MODULE_UNINSTALL,455 'processing': False,456 'module': 'mod1',457 'extra': {'force': True},458 }459 infos_mod1 = {460 'loadedby': [],461 'deps': [],462 'version': '1.0.0',463 }464 self.module._get_module_infos_from_modules_json = Mock(side_effect=[infos_mod1])465 with patch.object(self.module, '_Update__sub_actions', []) as mock_subactions:466 with patch.object(self.module, '_Update__main_actions', [action_install]) as mock_main_actions:467 self.module._execute_main_action_task()468 self.assertTrue(action_install['processing'])469 self.assertFalse(action_uninstall['processing'])470 self.assertFalse(action_update['processing'])471 def test_execute_main_action_task_update(self):472 self.init_session()473 self.module._install_main_module = Mock()474 self.module._uninstall_main_module = Mock()475 self.module._update_main_module = Mock()476 action_install = {477 'action': Update.ACTION_MODULE_INSTALL,478 'processing': False,479 'module': 'mod1',480 'extra': None,481 }482 action_update = {483 'action': Update.ACTION_MODULE_UPDATE,484 'processing': False,485 'module': 'mod1',486 'extra': None,487 }488 action_uninstall = {489 'action': Update.ACTION_MODULE_UNINSTALL,490 'processing': False,491 'module': 'mod1',492 'extra': {'force': True},493 }494 infos_mod1 = {495 'loadedby': [],496 'deps': [],497 'version': '1.0.0',498 }499 self.module._get_module_infos_from_modules_json = Mock(side_effect=[infos_mod1])500 with patch.object(self.module, '_Update__sub_actions', []) as mock_subactions:501 with patch.object(self.module, '_Update__main_actions', [action_update]) as mock_main_actions:502 self.module._execute_main_action_task()503 self.assertFalse(action_install['processing'])504 self.assertFalse(action_uninstall['processing'])505 self.assertTrue(action_update['processing'])506 def test_execute_main_action_task_uninstall(self):507 self.init_session()508 self.module._install_main_module = Mock()509 self.module._uninstall_main_module = Mock()510 self.module._update_main_module = Mock()511 action_install = {512 'action': Update.ACTION_MODULE_INSTALL,513 'processing': False,514 'module': 'mod1',515 'extra': None,516 }517 action_update = {518 'action': Update.ACTION_MODULE_UPDATE,519 'processing': False,520 'module': 'mod1',521 'extra': None,522 }523 action_uninstall = {524 'action': Update.ACTION_MODULE_UNINSTALL,525 'processing': False,526 'module': 'mod1',527 'extra': {'force': True},528 }529 infos_mod1 = {530 'loadedby': [],531 'deps': [],532 'version': '1.0.0',533 }534 self.module._get_module_infos_from_modules_json = Mock(side_effect=[infos_mod1])535 with patch.object(self.module, '_Update__sub_actions', []) as mock_subactions:536 with patch.object(self.module, '_Update__main_actions', [action_uninstall]) as mock_main_actions:537 self.module._execute_main_action_task()538 self.assertFalse(action_install['processing'])539 self.assertTrue(action_uninstall['processing'])540 self.assertFalse(action_update['processing'])541 def test_execute_main_action_task_running_action(self):542 self.init_session()543 self.module.logger.debug = Mock()544 with patch.object(self.module, '_Update__sub_actions', ['dummy']) as mock_subactions:545 self.assertIsNone(self.module._execute_main_action_task())546 logging.debug('logs: %s' % self.module.logger.debug.call_args_list)547 self.module.logger.debug.assert_any_call(548 'Main action is processing, stop main action task here.'549 )550 def test_execute_main_action_task_running_subaction(self):551 self.init_session()552 self.module.logger.debug = Mock()553 self.module._Update__processor = 'something'554 with patch.object(self.module, '_Update__sub_actions', []) as mock_subactions:555 self.assertIsNone(self.module._execute_main_action_task())556 logging.debug('logs: %s' % self.module.logger.debug.call_args_list)557 self.module.logger.debug.assert_any_call(558 'Main action is processing, stop main action task here.'559 )560 def test_execute_main_action_task_last_action_terminated_no_more_after(self):561 self.init_session()562 self.module.logger.debug = Mock()563 self.module._need_restart = True564 main_action = {565 'processing': True566 }567 with patch.object(self.module, '_Update__sub_actions', []) as mock_subactions:568 with patch.object(self.module, '_Update__main_actions', [main_action]) as mock_main_actions:569 with patch.object(self.module, '_Update__sub_actions_task') as mock_subactionstask:570 self.assertIsNone(self.module._execute_main_action_task())571 # logging.debug('logs: %s' % self.module.logger.debug.call_args_list)572 self.assertTrue(mock_subactionstask.stop.called)573 self.module.logger.debug.assert_any_call(574 'No more main action to execute, stop all tasks.'575 )576 self.session.assert_event_called('system.cleep.needrestart')577 def test_execute_main_action_task_last_action_terminated_no_more_after_no_needrestart_event(self):578 self.init_session()579 self.module.logger.debug = Mock()580 self.module._need_restart = False581 main_action = {582 'processing': True583 }584 with patch.object(self.module, '_Update__sub_actions', []) as mock_subactions:585 with patch.object(self.module, '_Update__main_actions', [main_action]) as mock_main_actions:586 with patch.object(self.module, '_Update__sub_actions_task') as mock_subactionstask:587 self.assertIsNone(self.module._execute_main_action_task())588 # logging.debug('logs: %s' % self.module.logger.debug.call_args_list)589 self.assertTrue(mock_subactionstask.stop.called)590 self.module.logger.debug.assert_any_call(591 'No more main action to execute, stop all tasks.'592 )593 self.assertFalse(self.session.event_called('system.cleep.needrestart'))594 def test_execute_main_action_task_set_process_step_single_sub_action(self):595 self.init_session()596 action_install = {597 'action': Update.ACTION_MODULE_INSTALL,598 'processing': False,599 'module': 'mod1',600 'extra': None,601 }602 infos_mod1 = {603 'loadedby': [],604 'deps': [],605 'version': '1.0.0',606 }607 self.module._set_module_process = Mock()608 self.module._get_module_infos_from_modules_json = Mock(return_value=infos_mod1)609 with patch.object(self.module, '_Update__main_actions', [action_install]) as mock_mainactions:610 with patch.object(self.module, '_Update__sub_actions', []) as mock_subactions:611 self.module._execute_main_action_task()612 self.module._set_module_process.assert_called_once_with(progress=0)613 self.assertEqual(mock_subactions[0]['progressstep'], 100)614 def test_execute_main_action_task_set_process_step_three_sub_actions(self):615 self.init_session()616 action_install = {617 'action': Update.ACTION_MODULE_INSTALL,618 'processing': False,619 'module': 'mod1',620 'extra': None,621 }622 infos_mod1 = {623 'loadedby': [],624 'deps': ['mod2'],625 'version': '1.0.0',626 }627 infos_mod2 = {628 'loadedy': [],629 'deps': ['mod3'],630 'version': '0.0.0',631 }632 infos_mod3 = {633 'loadedy': [],634 'deps': [],635 'version': '0.0.0',636 }637 self.module._set_module_process = Mock()638 self.module._get_module_infos_from_modules_json = Mock(side_effect=[infos_mod1, infos_mod2, infos_mod3])639 with patch.object(self.module, '_Update__main_actions', [action_install]) as mock_mainactions:640 with patch.object(self.module, '_Update__sub_actions', []) as mock_subactions:641 self.module._execute_main_action_task()642 self.module._set_module_process.assert_called_once_with(progress=0)643 self.assertEqual(mock_subactions[0]['progressstep'], 33)644 self.assertEqual(mock_subactions[1]['progressstep'], 33)645 self.assertEqual(mock_subactions[2]['progressstep'], 33)646 def test_execute_main_action_exception_wo_action(self):647 self.init_session()648 self.module._set_module_process = Mock()649 with patch.object(self.module, '_Update__main_actions', None):650 # cannot pop a None object651 self.module._execute_main_action_task()652 self.module._set_module_process.assert_called_with(failed=True)653 def test_execute_main_action_exception_w_action_install(self):654 self.init_session()655 self.module._set_module_process = Mock()656 self.module._install_main_module = Mock(side_effect=Exception('Test exception'))657 action_install = {658 'action': Update.ACTION_MODULE_INSTALL,659 'processing': False,660 'module': 'mod1',661 'extra': None,662 }663 infos_mod1 = {664 'loadedby': [],665 'deps': [],666 'version': '1.0.0',667 }668 self.module._get_module_infos_from_modules_json = Mock(return_value=[infos_mod1])669 # install670 with patch.object(self.module, '_Update__sub_actions', []) as mock_subactions:671 with patch.object(self.module, '_Update__main_actions', [action_install]) as mock_main_actions:672 self.module._execute_main_action_task()673 self.module._set_module_process.assert_called_with(failed=True)674 self.assertEqual(self.session.event_call_count('update.module.install'), 1)675 self.assertEqual(self.session.event_call_count('update.module.uninstall'), 0)676 self.assertEqual(self.session.event_call_count('update.module.update'), 0)677 def test_execute_main_action_exception_w_action_update(self):678 self.init_session(mock_commands=[679 self.session.make_mock_command('get_module_infos', fail=True)680 ])681 self.module._set_module_process = Mock()682 self.module._install_main_module = Mock(side_effect=Exception('Test exception'))683 action_update = {684 'action': Update.ACTION_MODULE_UPDATE,685 'processing': False,686 'module': 'mod1',687 'extra': None,688 }689 infos_mod1 = {690 'loadedby': [],691 'deps': [],692 'version': '1.0.0',693 }694 self.module._get_module_infos_from_modules_json = Mock(return_value=[infos_mod1])695 #Â update696 with patch.object(self.module, '_Update__sub_actions', []) as mock_subactions:697 with patch.object(self.module, '_Update__main_actions', [action_update]) as mock_main_actions:698 self.module._execute_main_action_task()699 self.module._set_module_process.assert_called_with(failed=True)700 self.assertEqual(self.session.event_call_count('update.module.install'), 0)701 self.assertEqual(self.session.event_call_count('update.module.uninstall'), 0)702 self.assertEqual(self.session.event_call_count('update.module.update'), 1)703 def test_execute_main_action_exception_w_action_uninstall(self):704 self.init_session(mock_commands=[705 self.session.make_mock_command('get_module_infos', fail=True)706 ])707 self.module._set_module_process = Mock()708 self.module._install_main_module = Mock(side_effect=Exception('Test exception'))709 action_uninstall = {710 'action': Update.ACTION_MODULE_UNINSTALL,711 'processing': False,712 'module': 'mod1',713 'extra': { 'force': False },714 }715 infos_mod1 = {716 'loadedby': [],717 'deps': [],718 'version': '1.0.0',719 }720 # uninstall721 with patch.object(self.module, '_Update__sub_actions', []) as mock_subactions:722 with patch.object(self.module, '_Update__main_actions', [action_uninstall]) as mock_main_actions:723 self.module._execute_main_action_task()724 self.module._set_module_process.assert_called_with(failed=True)725 self.assertEqual(self.session.event_call_count('update.module.install'), 0)726 self.assertEqual(self.session.event_call_count('update.module.uninstall'), 1)727 self.assertEqual(self.session.event_call_count('update.module.update'), 0)728 def test_execute_sub_action_task_install(self):729 self.init_session()730 subaction_install = {731 'action': Update.ACTION_MODULE_INSTALL,732 'module': 'mod1',733 'main': 'mod1',734 'infos': {},735 'extra': None,736 'progressstep': 12,737 }738 self.module._is_module_process_failed = Mock(return_value=False)739 self.module._set_module_process = Mock()740 self.module._install_module = Mock()741 self.module._uninstall_module = Mock()742 self.module._update_module = Mock()743 with patch.object(self.module, '_Update__sub_actions', [subaction_install]) as mock_sub_actions:744 self.module._execute_sub_actions_task()745 746 self.assertTrue(self.module._install_module.called)747 self.assertFalse(self.module._uninstall_module.called)748 self.assertFalse(self.module._update_module.called)749 self.assertEqual(len(mock_sub_actions), 0)750 self.module._set_module_process.assert_called_once_with(inc_progress=12)751 def test_execute_sub_action_task_uninstall(self):752 self.init_session()753 subaction_uninstall = {754 'action': Update.ACTION_MODULE_UNINSTALL,755 'module': 'mod1',756 'main': 'mod1',757 'infos': {},758 'extra': {'force': True},759 'progressstep': 12,760 }761 self.module._is_module_process_failed = Mock(return_value=False)762 self.module._set_module_process = Mock()763 self.module._install_module = Mock()764 self.module._uninstall_module = Mock()765 self.module._update_module = Mock()766 with patch.object(self.module, '_Update__sub_actions', [subaction_uninstall]) as mock_sub_actions:767 self.module._execute_sub_actions_task()768 769 self.assertFalse(self.module._install_module.called)770 self.assertTrue(self.module._uninstall_module.called)771 self.assertFalse(self.module._update_module.called)772 self.assertEqual(len(mock_sub_actions), 0)773 self.module._set_module_process.assert_called_once_with(inc_progress=12)774 def test_execute_sub_action_task_update(self):775 self.init_session()776 subaction_update = {777 'action': Update.ACTION_MODULE_UPDATE,778 'module': 'mod1',779 'main': 'mod1',780 'infos': {},781 'extra': None,782 'progressstep': 12,783 }784 self.module._is_module_process_failed = Mock(return_value=False)785 self.module._set_module_process = Mock()786 self.module._install_module = Mock()787 self.module._uninstall_module = Mock()788 self.module._update_module = Mock()789 with patch.object(self.module, '_Update__sub_actions', [subaction_update]) as mock_sub_actions:790 self.module._execute_sub_actions_task()791 792 self.assertFalse(self.module._install_module.called)793 self.assertFalse(self.module._uninstall_module.called)794 self.assertTrue(self.module._update_module.called)795 self.assertEqual(len(mock_sub_actions), 0)796 self.module._set_module_process.assert_called_once_with(inc_progress=12)797 def test_execute_sub_action_task_already_running(self):798 self.init_session()799 subaction_install = {800 'action': Update.ACTION_MODULE_INSTALL,801 'module': 'mod1',802 'main': 'mod1',803 'infos': {},804 'extra': None,805 'progressstep': 100,806 }807 self.module._is_module_process_failed = Mock(return_value=False)808 self.module._set_module_process = Mock()809 self.module._install_module = Mock()810 self.module._uninstall_module = Mock()811 self.module._update_module = Mock()812 with patch.object(self.module, '_Update__sub_actions', [subaction_install]) as mock_sub_actions:813 with patch.object(self.module, '_Update__processor') as mock_processor:814 self.module._execute_sub_actions_task()815 816 self.assertFalse(self.module._install_module.called)817 self.assertFalse(self.module._uninstall_module.called)818 self.assertFalse(self.module._update_module.called)819 self.assertEqual(len(mock_sub_actions), 1)820 def test_execute_sub_action_task_previous_subaction_failed(self):821 self.init_session()822 subaction_install = {823 'action': Update.ACTION_MODULE_INSTALL,824 'module': 'mod1',825 'main': 'mod1',826 'infos': {},827 'extra': None,828 'progressstep': 100,829 }830 self.module._is_module_process_failed = Mock(return_value=True)831 self.module._set_module_process = Mock()832 self.module._install_module = Mock()833 self.module._uninstall_module = Mock()834 self.module._update_module = Mock()835 with patch.object(self.module, '_Update__sub_actions', [subaction_install]) as mock_sub_actions:836 self.module._execute_sub_actions_task()837 838 self.assertFalse(self.module._install_module.called)839 self.assertFalse(self.module._uninstall_module.called)840 self.assertFalse(self.module._update_module.called)841 self.assertEqual(len(mock_sub_actions), 0)842 def test_execute_sub_action_no_more_sub_action(self):843 self.init_session()844 self.module._is_module_process_failed = Mock()845 with patch.object(self.module, '_Update__sub_actions',[]) as mock_sub_actions:846 self.module._execute_sub_actions_task()847 self.assertFalse(self.module._is_module_process_failed.called)848 def test_get_processing_module_name(self):849 self.init_session()850 action_install = {851 'action': Update.ACTION_MODULE_INSTALL,852 'processing': False,853 'module': 'mod1',854 'extra': None,855 }856 action_uninstall = {857 'action': Update.ACTION_MODULE_UNINSTALL,858 'processing': False,859 'module': 'mod2',860 'extra': {'force': True},861 }862 action_update = {863 'action': Update.ACTION_MODULE_UPDATE,864 'processing': True,865 'module': 'mod3',866 'extra': None,867 }868 with patch.object(self.module, '_Update__main_actions', [action_install, action_uninstall, action_update]) as mock_main_actions:869 self.assertEqual(self.module._get_processing_module_name(), 'mod3')870 def test_get_processing_module_name_no_main_action(self):871 self.init_session()872 with patch.object(self.module, '_Update__main_actions', []) as mock_main_actions:873 self.assertEqual(self.module._get_processing_module_name(), None)874 def test_get_processing_module_name_no_main_action_processing(self):875 self.init_session()876 action_install = {877 'action': Update.ACTION_MODULE_INSTALL,878 'processing': False,879 'module': 'mod1',880 'extra': None,881 }882 action_uninstall = {883 'action': Update.ACTION_MODULE_UNINSTALL,884 'processing': False,885 'module': 'mod2',886 'extra': {'force': True},887 }888 action_update = {889 'action': Update.ACTION_MODULE_UPDATE,890 'processing': False,891 'module': 'mod3',892 'extra': None,893 }894 with patch.object(self.module, '_Update__main_actions', [action_install, action_uninstall, action_update]) as mock_main_actions:895 self.assertEqual(self.module._get_processing_module_name(), None)896 def test_set_module_process_update_progress(self):897 self.init_session()898 self.module._get_processing_module_name = Mock(return_value='mod1')899 self.module._modules_updates = {900 'mod1': {901 'processing': False,902 'name': 'mod1',903 'version': '0.0.0',904 'updatable': False,905 'update': {906 'changelog': 'changelog',907 'version': None,908 'progress': 0,909 'failed': False,910 }911 },912 }913 self.module._set_module_process(progress=15)914 self.assertEqual(self.module._modules_updates['mod1']['processing'], True)915 self.assertEqual(self.module._modules_updates['mod1']['update']['progress'], 15)916 def test_set_module_process_update_progress_greater_100(self):917 self.init_session()918 self.module._get_processing_module_name = Mock(return_value='mod1')919 self.module._modules_updates = {920 'mod1': {921 'processing': False,922 'name': 'mod1',923 'version': '0.0.0',924 'updatable': False,925 'update': {926 'changelog': 'changelog',927 'version': None,928 'progress': 0,929 'failed': False,930 }931 },932 }933 self.module._set_module_process(progress=150)934 self.assertEqual(self.module._modules_updates['mod1']['processing'], False)935 self.assertEqual(self.module._modules_updates['mod1']['update']['progress'], 100)936 def test_set_module_process_update_inc_progress(self):937 self.init_session()938 self.module._get_processing_module_name = Mock(return_value='mod1')939 self.module._modules_updates = {940 'mod1': {941 'processing': False,942 'name': 'mod1',943 'version': '0.0.0',944 'updatable': False,945 'update': {946 'changelog': 'changelog',947 'version': None,948 'progress': 10,949 'failed': False,950 }951 },952 }953 self.module._set_module_process(inc_progress=10)954 self.assertEqual(self.module._modules_updates['mod1']['processing'], True)955 self.assertEqual(self.module._modules_updates['mod1']['update']['progress'], 20)956 def test_set_module_process_update_inc_progress_greater_100(self):957 self.init_session()958 self.module._get_processing_module_name = Mock(return_value='mod1')959 self.module._get_module_infos_from_modules_json = Mock(return_value=MODULES_JSON['list']['system'])960 self.module._modules_updates = {961 'mod1': {962 'processing': False,963 'name': 'mod1',964 'version': '0.0.0',965 'updatable': False,966 'update': {967 'changelog': 'changelog',968 'version': None,969 'progress': 90,970 'failed': False,971 }972 },973 }974 self.module._set_module_process(inc_progress=30)975 self.assertEqual(self.module._modules_updates['mod1']['processing'], False)976 self.assertEqual(self.module._modules_updates['mod1']['update']['progress'], 100)977 def test_set_module_process_update_failed(self):978 self.init_session()979 self.module._get_processing_module_name = Mock(return_value='mod1')980 self.module._get_module_infos_from_modules_json = Mock(return_value=MODULES_JSON['list']['system'])981 self.module._modules_updates = {982 'mod1': {983 'processing': False,984 'name': 'mod1',985 'version': '0.0.0',986 'updatable': False,987 'update': {988 'changelog': 'changelog',989 'version': None,990 'progress': 90,991 'failed': False,992 }993 },994 }995 self.module._set_module_process(failed=True)996 logging.debug('_modules_updates[mod1]=%s' % self.module._modules_updates['mod1'])997 self.assertEqual(self.module._modules_updates['mod1']['processing'], False)998 self.assertEqual(self.module._modules_updates['mod1']['update']['progress'], 100)999 self.assertEqual(self.module._modules_updates['mod1']['update']['failed'], True)1000 def test_set_module_process_update_no_action_running(self):1001 self.init_session()1002 self.module._get_processing_module_name = Mock(return_value=None)1003 self.module._modules_updates = {1004 'mod1': {1005 'processing': False,1006 'name': 'mod1',1007 'version': '0.0.0',1008 'updatable': False,1009 'update': {1010 'changelog': 'changelog',1011 'version': None,1012 'progress': 90,1013 'failed': False,1014 }1015 },1016 }1017 self.module._set_module_process(failed=True)1018 self.assertEqual(self.module._modules_updates['mod1']['processing'], False)1019 def test_set_module_process_update_new_module_install(self):1020 self.init_session()1021 self.module._get_processing_module_name = Mock(return_value='mod1')1022 self.module._get_module_infos_from_modules_json = Mock(return_value=MODULES_JSON['list']['system'])1023 self.module._modules_updates = {1024 'mod2': {1025 'processing': False,1026 'name': 'mod1',1027 'version': '0.0.0',1028 'updatable': False,1029 'update': {1030 'changelog': 'changelog',1031 'version': None,1032 'progress': 0,1033 'failed': False,1034 }1035 },1036 }1037 self.module._set_module_process(inc_progress=15)1038 self.assertEqual(self.module._modules_updates['mod1']['processing'], True)1039 self.assertEqual(self.module._modules_updates['mod1']['update']['progress'], 15)1040 self.assertEqual(self.module._modules_updates['mod1']['update']['version'], MODULES_JSON['list']['system']['version'])1041 def test_is_module_process_failed_return_false(self):1042 mock_getmodules = self.session.make_mock_command('get_modules', data=INVENTORY_GETMODULES)1043 self.init_session(mock_commands=[mock_getmodules])1044 self.module._get_processing_module_name = Mock(return_value='system')1045 self.module._modules_updates['system']['update']['failed'] = False1046 self.assertFalse(self.module._is_module_process_failed())1047 def test_is_module_process_failed_return_true(self):1048 self.init_session()1049 self.module._get_processing_module_name = Mock(return_value='system')1050 self.module._modules_updates['system']['update']['failed'] = True1051 self.assertTrue(self.module._is_module_process_failed())1052 def test_is_module_process_failed_no_processing_action(self):1053 self.init_session()1054 self.module._get_processing_module_name = Mock(return_value=None)1055 self.assertTrue(self.module._is_module_process_failed())1056 def test_set_automatic_update(self):1057 self.init_session()1058 # all True1059 self.assertTrue(self.module.set_automatic_update(True, True))1060 config = self.module._get_config()1061 logging.debug('Config: %s' % config)1062 self.assertTrue(config['cleepupdateenabled'])1063 self.assertTrue(config['modulesupdateenabled'])1064 # all False1065 self.assertTrue(self.module.set_automatic_update(False, False))1066 config = self.module._get_config()1067 logging.debug('Config: %s' % config)1068 self.assertFalse(config['cleepupdateenabled'])1069 self.assertFalse(config['modulesupdateenabled'])1070 def test_set_automatic_update_main_task(self):1071 self.init_session()1072 with patch.object(self.module, '_Update__main_actions_task') as mock_task:1073 self.module.set_automatic_update(True, True)1074 self.assertFalse(mock_task.stop.called)1075 with patch.object(self.module, '_Update__main_actions_task') as mock_task:1076 self.module.set_automatic_update(False, False)1077 self.assertTrue(mock_task.stop.called)1078 def test_set_automatic_update_invalid_parameters(self):1079 self.init_session()1080 with self.assertRaises(InvalidParameter) as cm:1081 self.module.set_automatic_update('hello', False)1082 self.assertEqual(str(cm.exception), 'Parameter "cleep_update_enabled" is invalid')1083 with self.assertRaises(InvalidParameter) as cm:1084 self.module.set_automatic_update(666, False)1085 self.assertEqual(str(cm.exception), 'Parameter "cleep_update_enabled" is invalid')1086 with self.assertRaises(InvalidParameter) as cm:1087 self.module.set_automatic_update(True, 'hello')1088 self.assertEqual(str(cm.exception), 'Parameter "modules_update_enabled" is invalid')1089 with self.assertRaises(InvalidParameter) as cm:1090 self.module.set_automatic_update(True, 666)1091 self.assertEqual(str(cm.exception), 'Parameter "modules_update_enabled" is invalid')1092 @patch('backend.update.os.path.exists')1093 @patch('backend.update.json')1094 def test_get_module_infos_from_package(self, json_mock, path_exists_mock):1095 open_mock = mock_open()1096 path_exists_mock.return_value = True1097 json_mock.load.return_value = 'json content'1098 self.init_session()1099 with patch('backend.update.open', open_mock, create=True):1100 with patch('backend.update.ZipFile') as zipfile_mock:1101 data = self.module._get_module_infos_from_package('module')1102 self.assertEqual(data, 'json content')1103 zipfile_mock.return_value.__enter__.return_value.extract.assert_called_with('module.json', path=session.PatternArg('/tmp/.*'))1104 json_mock.load.assert_called()1105 @patch('backend.update.os.path.exists')1106 @patch('backend.update.json')1107 def test_get_module_infos_from_package_file_not_exists(self, json_mock, path_exists_mock):1108 open_mock = mock_open()1109 json_mock.load.return_value = 'json content'1110 path_exists_mock.return_value = True1111 self.init_session()1112 path_exists_mock.return_value = False1113 with patch('backend.update.open', open_mock, create=True):1114 with patch('backend.update.ZipFile') as zipfile_mock:1115 with self.assertRaises(Exception) as cm:1116 data = self.module._get_module_infos_from_package('module')1117 self.assertEqual(str(cm.exception), 'Package "/tmp/module.zip" for module "module" does not exists')1118 @patch('backend.update.os.path.exists')1119 @patch('backend.update.json')1120 def test_get_module_infos_from_package_unzip_error(self, json_mock, path_exists_mock):1121 open_mock = mock_open()1122 path_exists_mock.return_value = True1123 json_mock.load.return_value = 'json content'1124 self.init_session()1125 with patch('backend.update.open', open_mock, create=True):1126 with patch('backend.update.ZipFile') as zipfile_mock:1127 zipfile_mock.return_value.__enter__.return_value.extract.side_effect = Exception('Test exception')1128 with self.assertRaises(Exception) as cm:1129 self.module._get_module_infos_from_package('module')1130 self.assertEqual(str(cm.exception), 'Package "/tmp/module.zip" is not a valid application archive')1131 @patch('backend.update.os.path.exists')1132 @patch('backend.update.json')1133 def test_get_module_infos_from_package_content_error(self, json_mock, path_exists_mock):1134 open_mock = mock_open()1135 path_exists_mock.return_value = True1136 json_mock.load.side_effect = Exception('Test exception')1137 self.init_session()1138 with patch('backend.update.open', open_mock, create=True):1139 with patch('backend.update.ZipFile') as zipfile_mock:1140 with self.assertRaises(Exception) as cm:1141 self.module._get_module_infos_from_package('module')1142 self.assertEqual(str(cm.exception), 'Package "/tmp/module.zip" has invalid content')1143 def test_get_module_infos_from_modules_json(self):1144 self.init_session()1145 self.module.modules_json = Mock()1146 content = {1147 'list': {1148 'dummy': {1149 'hello': 'world'1150 }1151 }1152 }1153 self.module.modules_json.get_json = Mock(return_value=content)1154 infos = self.module._get_module_infos_from_modules_json('dummy')1155 self.assertEqual(infos, content['list']['dummy'])1156 def test_get_module_infos_from_modules_json_unknown_module(self):1157 self.init_session()1158 self.module.modules_json = Mock()1159 content = {1160 'list': {1161 'other': {1162 'hello': 'world'1163 }1164 }1165 }1166 self.module.modules_json.get_json = Mock(return_value=content)1167 infos = self.module._get_module_infos_from_modules_json('dummy')1168 self.assertIsNone(infos)1169 @patch('backend.update.ModulesJson')1170 def test_check_modules_updates_modules_json_updated_with_no_module_update(self, mock_modulesjson):1171 mock_modulesjson.return_value.get_json.return_value = MODULES_JSON1172 mock_modulesjson.return_value.update.return_value = True1173 self.init_session()1174 self.session.add_mock_command(self.session.make_mock_command('reload_modules'))1175 updates = self.module.check_modules_updates()1176 1177 self.assertFalse(updates['modulesupdates'])1178 self.assertTrue(updates['modulesjsonupdated'])1179 self.assertTrue('moduleslastcheck' in updates)1180 self.assertTrue(self.session.command_called('reload_modules'))1181 # make sure modules_updates content is correct1182 for module_name, update in self.module._modules_updates.items():1183 self.assertCountEqual(update.keys(), ['updatable', 'processing', 'pending', 'name', 'version', 'update'])1184 self.assertCountEqual(update['update'].keys(), ['progress', 'failed', 'version', 'changelog'])1185 @patch('backend.update.ModulesJson')1186 def test_check_modules_updates_modules_json_updated_with_module_update(self, mock_modulesjson):1187 modules_json = copy.deepcopy(MODULES_JSON)1188 version = '6.6.6'1189 changelog = 'new version changelog'1190 modules_json['list']['system']['version'] = version1191 modules_json['list']['system']['changelog'] = changelog1192 mock_modulesjson.return_value.get_json.return_value = modules_json1193 mock_modulesjson.return_value.update.return_value = True1194 self.init_session()1195 self.session.add_mock_command(self.session.make_mock_command('reload_modules'))1196 updates = self.module.check_modules_updates()1197 logging.debug('updates: %s' % updates)1198 modules_updates = self.module.get_modules_updates()1199 logging.debug('modules updates: %s' % modules_updates)1200 1201 self.assertTrue(updates['modulesupdates'])1202 self.assertTrue(updates['modulesjsonupdated'])1203 self.assertTrue(modules_updates['system']['updatable'])1204 self.assertFalse(modules_updates['audio']['updatable'])1205 self.assertFalse(modules_updates['sensors']['updatable'])1206 self.assertFalse(modules_updates['network']['updatable'])1207 self.assertFalse(modules_updates['parameters']['updatable'])1208 self.assertEqual(modules_updates['system']['update']['changelog'], changelog)1209 self.assertEqual(modules_updates['system']['update']['version'], version)1210 self.assertTrue(self.session.command_called('reload_modules'))1211 # make sure modules_updates content is correct1212 for module_name, update in self.module._modules_updates.items():1213 self.assertCountEqual(update.keys(), ['updatable', 'processing', 'pending', 'name', 'version', 'update'])1214 self.assertCountEqual(update['update'].keys(), ['progress', 'failed', 'version', 'changelog'])1215 1216 @patch('backend.update.ModulesJson')1217 def test_check_modules_updates_modules_json_exception(self, mock_modulesjson):1218 mock_modulesjson.return_value.get_json.return_value = MODULES_JSON1219 mock_modulesjson.return_value.update.side_effect = Exception('Test exception')1220 self.init_session()1221 self.session.add_mock_command(self.session.make_mock_command('reload_modules'))1222 with self.assertRaises(CommandError) as cm:1223 self.module.check_modules_updates()1224 self.assertEqual(str(cm.exception), 'Unable to refresh modules list from internet')1225 self.assertFalse(self.session.command_called('reload_modules'))1226 @patch('backend.update.ModulesJson')1227 @patch('backend.update.Tools')1228 def test_check_modules_updates_check_module_version_failed(self, mock_tools, mock_modulesjson):1229 mock_modulesjson.return_value.get_json.return_value = MODULES_JSON1230 mock_modulesjson.return_value.update.return_value = True1231 mock_tools.compare_versions.side_effect = Exception('Test exception')1232 self.init_session()1233 self.session.add_mock_command(self.session.make_mock_command('reload_modules'))1234 # should continue event if exception occured during single module check1235 updates = self.module.check_modules_updates()1236 logging.debug('Updates: %s' % updates)1237 self.assertEqual(updates['modulesjsonupdated'], True)1238 self.assertEqual(updates['modulesupdates'], False)1239 self.assertTrue(self.session.command_called('reload_modules'))1240 def test_update_cleep_no_update_available(self):1241 self.init_session()1242 self.module.cleep_filesystem = MagicMock()1243 self.module._get_config_field = Mock(return_value={'version': None, 'changelog': None})1244 with self.assertRaises(CommandInfo) as cm:1245 self.module.update_cleep()1246 self.assertEqual(str(cm.exception), 'No Cleep update available, please launch update check first')1247 self.assertFalse(self.module.cleep_filesystem.enable_write.called)1248 @patch('backend.update.ModulesJson')1249 def test_check_modules_updates_reload_modules_fails(self, mock_modulesjson):1250 modules_json = copy.deepcopy(MODULES_JSON)1251 version = '6.6.6'1252 changelog = 'new version changelog'1253 modules_json['list']['system']['version'] = version1254 modules_json['list']['system']['changelog'] = changelog1255 mock_modulesjson.return_value.get_json.return_value = modules_json1256 mock_modulesjson.return_value.update.return_value = True1257 self.init_session()1258 self.module.logger.error = Mock()1259 self.session.add_mock_command(self.session.make_mock_command('reload_modules', fail=True))1260 updates = self.module.check_modules_updates()1261 self.assertTrue(self.session.command_called('reload_modules'))1262 self.module.logger.error.assert_called_with('Error occured during inventory modules reloading: TEST: command "reload_modules" fails for tests')1263 1264 @patch('backend.update.InstallCleep')1265 def test_update_cleep_update_available(self, mock_installcleep):1266 mock_installcleep.return_value.install = Mock()1267 self.init_session()1268 cleep_filesystem = MagicMock()1269 crash_report = MagicMock()1270 self.module.cleep_filesystem = cleep_filesystem1271 self.module.crash_report = crash_report1272 self.module._cleep_updates = {1273 'updatable': True,1274 'processing': False,1275 'pending': False,1276 'failed': False,1277 'version': '1.0.0',1278 'changelog': 'changelog',1279 'packageurl': 'https://www.cleep.com/packageurl',1280 'checksumurl': 'https://www.cleep.com/checksumurl'1281 }1282 self.module.update_cleep()1283 self.assertTrue(self.module.cleep_filesystem.enable_write.called)1284 mock_installcleep.return_value.install.assert_called_once_with(1285 self.module._cleep_updates['packageurl'],1286 self.module._cleep_updates['checksumurl'],1287 self.module._update_cleep_callback1288 )1289 def test_update_cleep_callback_success(self):1290 self.init_session()1291 self.module.cleep_filesystem = Mock()1292 self.module._store_process_status = Mock()1293 self.module._update_config = Mock()1294 self.module._restart_cleep = Mock()1295 status = {1296 'status': InstallCleep.STATUS_UPDATED,1297 'returncode': 0,1298 'stdout': ['stdout'],1299 'stderr': ['stderr'],1300 }1301 self.module._update_cleep_callback(status)1302 1303 self.assertEqual(self.session.event_call_count('update.cleep.update'), 1)1304 self.assertEqual(self.session.get_last_event_params('update.cleep.update'), {'status': status['status']})1305 self.module._store_process_status.assert_called_with(status, success=True)1306 self.assertTrue(self.module.cleep_filesystem.disable_write.called)1307 self.assertTrue(self.module._restart_cleep.called)1308 def test_update_cleep_callback_failed(self):1309 self.init_session()1310 self.module.cleep_filesystem = Mock()1311 self.module._store_process_status = Mock()1312 self.module._update_config = Mock()1313 self.module._restart_cleep = Mock()1314 status = {1315 'status': InstallCleep.STATUS_ERROR_DOWNLOAD_PACKAGE,1316 'returncode': 1,1317 'stdout': ['stdout'],1318 'stderr': ['stderr'],1319 }1320 self.module._update_cleep_callback(status)1321 1322 self.assertEqual(self.session.event_call_count('update.cleep.update'), 1)1323 self.assertEqual(self.session.get_last_event_params('update.cleep.update'), {'status': status['status']})1324 self.module._store_process_status.assert_called_with(status, success=False)1325 self.assertTrue(self.module.cleep_filesystem.disable_write.called)1326 self.assertFalse(self.module._restart_cleep.called)1327 def test_update_cleep_modules_update_running(self):1328 self.init_session()1329 self.module._cleep_updates = {1330 'updatable': True,1331 }1332 with patch.object(self.module, '_Update__main_actions', [Mock()]):1333 with self.assertRaises(CommandInfo) as cm:1334 self.module.update_cleep()1335 self.assertEqual(str(cm.exception), 'Applications updates are in progress. Please wait for end of it')1336 @patch('backend.update.Task')1337 def test_update_modules(self, mock_task):1338 self.init_session()1339 self.module._cleep_updates = {1340 'processing': False,1341 'pending': False,1342 }1343 mod1 = {1344 'name': 'mod1',1345 'updatable': True,1346 'processing': True,1347 'pending': False,1348 }1349 mod2 = {1350 'name': 'mod2',1351 'updatable': True,1352 'processing': False,1353 'pending': False,1354 }1355 mod3 = {1356 'name': 'mod3',1357 'updatable': False,1358 'processing': False,1359 'pending': False,1360 }1361 mod4 = {1362 'name': 'mod4',1363 'updatable': True,1364 'processing': False,1365 'pending': False,1366 }1367 mod5 = {1368 'name': 'mod5',1369 'updatable': True,1370 'processing': False,1371 'pending': True,1372 }1373 self.module._modules_updates = {1374 'mod1': mod1,1375 'mod2': mod2,1376 'mod3': mod3,1377 'mod4': mod4,1378 'mod5': mod51379 }1380 self.module._postpone_main_action = Mock()1381 self.module.update_modules()1382 logging.debug('Calls: %s' % self.module._postpone_main_action.mock_calls)1383 self.assertEqual(self.module._postpone_main_action.call_count, 2)1384 self.module._postpone_main_action.assert_has_calls([1385 call(Update.ACTION_MODULE_UPDATE, 'mod2'),1386 call(Update.ACTION_MODULE_UPDATE, 'mod4'),1387 ], any_order=True)1388 self.assertTrue(mock_task.return_value.start.called)1389 @patch('backend.update.Task')1390 def test_update_modules_cleep_update_running(self, mock_task):1391 self.init_session()1392 self.module._cleep_updates = {1393 'processing': True,1394 'pending': True1395 }1396 with self.assertRaises(CommandInfo) as cm:1397 self.module.update_modules()1398 self.assertEqual(str(cm.exception), 'Cleep update is in progress. Please wait for end of it')1399 self.assertFalse(mock_task.return_value.start.called)1400 def test_postpone_main_action_install(self):1401 self.init_session()1402 self.module._set_module_process = Mock()1403 with patch.object(self.module, '_Update__main_actions') as mock_main_actions:1404 self.assertTrue(self.module._postpone_main_action(Update.ACTION_MODULE_INSTALL, 'mod1'))1405 self.assertTrue(mock_main_actions.insert.called)1406 self.assertEqual(self.session.event_call_count('update.module.install'), 1)1407 self.assertEqual(self.session.event_call_count('update.module.uninstall'), 0)1408 self.assertEqual(self.session.event_call_count('update.module.update'), 0)1409 def test_postpone_main_action_uninstall(self):1410 self.init_session()1411 self.module._set_module_process = Mock()1412 with patch.object(self.module, '_Update__main_actions') as mock_main_actions:1413 self.assertTrue(self.module._postpone_main_action(Update.ACTION_MODULE_UNINSTALL, 'mod1'))1414 self.assertTrue(mock_main_actions.insert.called)1415 self.assertEqual(self.session.event_call_count('update.module.install'), 0)1416 self.assertEqual(self.session.event_call_count('update.module.uninstall'), 1)1417 self.assertEqual(self.session.event_call_count('update.module.update'), 0)1418 def test_postpone_main_action_update(self):1419 self.init_session()1420 self.module._set_module_process = Mock()1421 with patch.object(self.module, '_Update__main_actions') as mock_main_actions:1422 self.assertTrue(self.module._postpone_main_action(Update.ACTION_MODULE_UPDATE, 'mod1'))1423 self.assertTrue(mock_main_actions.insert.called)1424 self.assertEqual(self.session.event_call_count('update.module.install'), 0)1425 self.assertEqual(self.session.event_call_count('update.module.uninstall'), 0)1426 self.assertEqual(self.session.event_call_count('update.module.update'), 1)1427 def test_postpone_main_action_install_same_module_same_action(self):1428 self.init_session()1429 self.module._set_module_process = Mock()1430 self.assertTrue(self.module._postpone_main_action(Update.ACTION_MODULE_INSTALL, 'mod1'))1431 self.assertFalse(self.module._postpone_main_action(Update.ACTION_MODULE_INSTALL, 'mod1'))1432 self.assertEqual(self.session.event_call_count('update.module.install'), 1)1433 self.assertEqual(self.session.event_call_count('update.module.uninstall'), 0)1434 self.assertEqual(self.session.event_call_count('update.module.update'), 0)1435 def test_postpone_main_action_install_same_module_other_action(self):1436 self.init_session()1437 self.module._set_module_process = Mock()1438 self.assertTrue(self.module._postpone_main_action(Update.ACTION_MODULE_INSTALL, 'mod1'))1439 self.assertTrue(self.module._postpone_main_action(Update.ACTION_MODULE_UNINSTALL, 'mod1'))1440 self.assertEqual(self.session.event_call_count('update.module.install'), 1)1441 self.assertEqual(self.session.event_call_count('update.module.uninstall'), 1)1442 self.assertEqual(self.session.event_call_count('update.module.update'), 0)1443 def test_get_module_infos_from_inventory(self):1444 mock_getmodulesinfos = self.session.make_mock_command(1445 'get_module_infos',1446 data=INVENTORY_GETMODULES['audio'],1447 )1448 self.init_session(mock_commands=[mock_getmodulesinfos])1449 infos = self.module._get_module_infos_from_inventory('audio')1450 logging.debug('Infos: %s' % infos)1451 self.assertEqual(infos, INVENTORY_GETMODULES['audio'])1452 def test_get_module_infos_from_inventory_failed(self):1453 mock_getmodulesinfos = self.session.make_mock_command(1454 'get_module_infos',1455 data=INVENTORY_GETMODULES['audio'],1456 fail=True,1457 )1458 self.init_session(mock_commands=[mock_getmodulesinfos])1459 with self.assertRaises(Exception) as cm:1460 self.module._get_module_infos_from_inventory('audio')1461 self.assertEqual(str(cm.exception), 'Unable to get module "audio" infos')1462 def test_get_module_infos_from_inventory_unknown_module(self):1463 mock_getmodules = self.session.make_mock_command(1464 'get_modules',1465 data={},1466 )1467 mock_getmodulesinfos = self.session.make_mock_command(1468 'get_module_infos',1469 data={},1470 )1471 self.init_session(mock_commands=[mock_getmodulesinfos, mock_getmodules])1472 with self.assertRaises(Exception) as cm:1473 self.module._get_module_infos_from_inventory('audio')1474 self.assertEqual(str(cm.exception), 'Module "audio" not found in installable modules list')1475 def test_extract_compat(self):1476 self.init_session()1477 compat = self.module._Update__extract_compat('cleep<0.1.2')1478 self.assertDictEqual(compat, {1479 'module_name': 'cleep',1480 'operator': '<',1481 'version': '0.1.2',1482 })1483 def test_extract_compat_invalid_string(self):1484 self.init_session()1485 compat = self.module._Update__extract_compat('cleep')1486 self.assertDictEqual(compat, {1487 'module_name': None,1488 'operator': None,1489 'version': None,1490 })1491 def test_extract_compat_invalid_string2(self):1492 self.init_session()1493 compat = self.module._Update__extract_compat('cleep>test')1494 self.assertDictEqual(compat, {1495 'module_name': None,1496 'operator': None,1497 'version': None,1498 })1499 @patch('backend.update.CLEEP_VERSION', '1.2.3')1500 def test_check_dependencies_compatibility(self):1501 self.init_session()1502 try:1503 self.module._Update__check_dependencies_compatibility('charts', ['actions', 'audio', 'charts'], MODULES_JSON['list'])1504 except:1505 self.fail('Should not throw exception')1506 @patch('backend.update.CLEEP_VERSION', '1.2.3')1507 def test_check_dependencies_compatibility_check_equal_operator(self):1508 self.init_session()1509 try:1510 # equal should pass1511 self.module._Update__check_dependencies_compatibility('charts', ['respeaker2mic'], MODULES_JSON['list'])1512 except:1513 self.fail('Should not throw exception for = operator')1514 # equal should not pass1515 with self.assertRaises(Exception) as cm:1516 self.module._Update__extract_compat = Mock(return_value={'module_name': 'cleep', 'operator': '=', 'version': '1.2.2'})1517 self.module._Update__check_dependencies_compatibility('charts', ['respeaker2mic'], MODULES_JSON['list'])1518 # message is not valid due to extract_compat mock1519 self.assertEqual(str(cm.exception), 'Application "charts" is not installable due to version incompatibility of app "respeaker2mic" that requires cleep=1.2.3 to be installed')1520 @patch('backend.update.CLEEP_VERSION', '1.2.2')1521 def test_check_dependencies_compatibility_check_inferior_operator(self):1522 self.init_session()1523 try:1524 # inferior should pass (parameters cleep<1.2.3)1525 self.module._Update__check_dependencies_compatibility('charts', ['parameters'], MODULES_JSON['list'])1526 except:1527 self.fail('Should not throw exception for < operator')1528 # inferior should not pass1529 with self.assertRaises(Exception) as cm:1530 self.module._Update__extract_compat = Mock(return_value={'module_name': 'cleep', 'operator': '<', 'version': '1.2.2'})1531 self.module._Update__check_dependencies_compatibility('charts', ['parameters'], MODULES_JSON['list'])1532 # message is not valid due to extract_compat mock1533 self.assertEqual(str(cm.exception), 'Application "charts" is not installable due to version incompatibility of app "parameters" that requires cleep<1.2.3 to be installed')1534 @patch('backend.update.CLEEP_VERSION', '1.2.3')1535 def test_check_dependencies_compatibility_check_inferior_equal_operator(self):1536 self.init_session()1537 try:1538 # inferior should pass (actions cleep<=1.2.3)1539 self.module._Update__check_dependencies_compatibility('charts', ['actions'], MODULES_JSON['list'])1540 # action cleep<=1.2.4 should pass1541 self.module._Update__extract_compat = Mock(return_value={'module_name': 'cleep', 'operator': '<=', 'version': '1.2.5'})1542 self.module._Update__check_dependencies_compatibility('charts', ['actions'], MODULES_JSON['list'])1543 except:1544 self.fail('Should not throw exception for <= operator')1545 # inferior equal should not pass1546 with self.assertRaises(Exception) as cm:1547 self.module._Update__extract_compat = Mock(return_value={'module_name': 'cleep', 'operator': '<=', 'version': '1.2.2'})1548 self.module._Update__check_dependencies_compatibility('charts', ['actions'], MODULES_JSON['list'])1549 # message is not valid due to extract_compat mock1550 self.assertEqual(str(cm.exception), 'Application "charts" is not installable due to version incompatibility of app "actions" that requires cleep<=1.2.3 to be installed')1551 @patch('backend.update.CLEEP_VERSION', '1.0.0')1552 def test_check_dependencies_compatibility_incompatibility_detected(self):1553 self.init_session()1554 with self.assertRaises(Exception) as cm:1555 self.module._Update__check_dependencies_compatibility('charts', ['actions', 'audio', 'system'], MODULES_JSON['list'])1556 self.assertEqual(str(cm.exception), 'Application "charts" is not installable due to version incompatibility of app "system" that requires cleep<=0.0.1 to be installed')1557 @patch('backend.update.CLEEP_VERSION', '1.0.0')1558 def test_check_dependencies_compatibility_invalid_compat_string(self):1559 self.init_session()1560 # invalid module name1561 self.module._Update__extract_compat = Mock(return_value={'module_name': None, 'operator': '<', 'version': '0.0.0'})1562 with self.assertRaises(Exception) as cm:1563 self.module._Update__check_dependencies_compatibility('charts', ['actions'], MODULES_JSON['list'])1564 self.assertEqual(str(cm.exception), 'Invalid compat string for "actions" application')1565 # invalid operator1566 self.module._Update__extract_compat = Mock(return_value={'module_name': 'test', 'operator': None, 'version': '0.0.0'})1567 with self.assertRaises(Exception) as cm:1568 self.module._Update__check_dependencies_compatibility('charts', ['actions'], MODULES_JSON['list'])1569 self.assertEqual(str(cm.exception), 'Invalid compat string for "actions" application')1570 # invalid version1571 self.module._Update__extract_compat = Mock(return_value={'module_name': 'test', 'operator': '<', 'version': None})1572 with self.assertRaises(Exception) as cm:1573 self.module._Update__check_dependencies_compatibility('charts', ['actions'], MODULES_JSON['list'])1574 self.assertEqual(str(cm.exception), 'Invalid compat string for "actions" application')1575 @patch('backend.update.CLEEP_VERSION', '1.0.0')1576 def test_check_dependencies_compatibility_invalid_module_name(self):1577 self.init_session()1578 self.module._Update__extract_compat = Mock(return_value={'module_name': 'test', 'operator': '<', 'version': '0.0.0'})1579 with self.assertRaises(Exception) as cm:1580 self.module._Update__check_dependencies_compatibility('charts', ['actions'], MODULES_JSON['list'])1581 self.assertEqual(str(cm.exception), 'Invalid compat string (invalid module name) for "actions" application')1582 @patch('backend.update.CLEEP_VERSION', '1.0.0')1583 def test_check_dependencies_compatibility_invalid_operator(self):1584 self.init_session()1585 self.module._Update__extract_compat = Mock(return_value={'module_name': 'cleep', 'operator': '>', 'version': '0.0.0'})1586 with self.assertRaises(Exception) as cm:1587 self.module._Update__check_dependencies_compatibility('charts', ['actions'], MODULES_JSON['list'])1588 self.assertEqual(str(cm.exception), 'Invalid compat string (invalid operator) for "actions" application')1589 def test_store_process_status_module(self):1590 self.init_session()1591 with patch('os.path.exists', return_value=True) as mock_os_path_exists:1592 cleep_filesystem = MagicMock()1593 cleep_filesystem.mkdir = Mock()1594 cleep_filesystem.write_json = Mock()1595 self.module.cleep_filesystem = cleep_filesystem1596 status = {1597 'status': 'testing',1598 'module': 'dummy',1599 'stdout': ['info'],1600 'stderr': ['error'],1601 }1602 self.module._store_process_status(status)1603 self.assertFalse(cleep_filesystem.mkdir.called)1604 cleep_filesystem.write_json.assert_called_with('/opt/cleep/install/dummy/process_success.log', status)1605 self.module._store_process_status(status, success=False)1606 self.assertFalse(cleep_filesystem.mkdir.called)1607 cleep_filesystem.write_json.assert_called_with('/opt/cleep/install/dummy/process_failure.log', status)1608 def test_store_process_status_cleep(self):1609 self.init_session()1610 with patch('os.path.exists', return_value=True) as mock_os_path_exists:1611 cleep_filesystem = MagicMock()1612 cleep_filesystem.mkdir = Mock()1613 cleep_filesystem.write_json = Mock()1614 self.module.cleep_filesystem = cleep_filesystem1615 status = {1616 'status': 'testing',1617 'stdout': ['info'],1618 'stderr': ['error'],1619 }1620 self.module._store_process_status(status)1621 self.assertFalse(cleep_filesystem.mkdir.called)1622 status.update({'module': 'cleep'})1623 cleep_filesystem.write_json.assert_called_with('/opt/cleep/install/cleep/process_success.log', status)1624 self.module._store_process_status(status, success=False)1625 self.assertFalse(cleep_filesystem.mkdir.called)1626 status.update({'module': 'cleep'})1627 cleep_filesystem.write_json.assert_called_with('/opt/cleep/install/cleep/process_failure.log', status)1628 def test_store_process_status_create_log_dir(self):1629 self.init_session()1630 with patch('os.path.exists', return_value=False) as mock_os_path_exists:1631 cleep_filesystem = MagicMock()1632 cleep_filesystem.mkdir = Mock()1633 cleep_filesystem.write_json = Mock()1634 self.module.cleep_filesystem = cleep_filesystem1635 status = {1636 'status': 'testing',1637 'module': 'dummy',1638 'stdout': ['info'],1639 'stderr': ['error'],1640 }1641 self.module._store_process_status(status)1642 mock_os_path_exists.assert_called_with('/opt/cleep/install/dummy')1643 self.assertTrue(cleep_filesystem.mkdir.called)1644 def test_store_process_status_handle_write_error(self):1645 self.init_session()1646 with patch('os.path.exists', return_value=True) as mock_os_path_exists:1647 self.module.logger = Mock()1648 self.module.logger.error = Mock()1649 cleep_filesystem = MagicMock()1650 cleep_filesystem.mkdir = Mock()1651 cleep_filesystem.write_json = Mock(return_value=False)1652 self.module.cleep_filesystem = cleep_filesystem1653 status = {1654 'status': 'testing',1655 'module': 'dummy',1656 'stdout': ['info'],1657 'stderr': ['error'],1658 }1659 self.module._store_process_status(status)1660 self.assertTrue(self.module.logger.error.called)1661 @patch('backend.update.Task')1662 @patch('backend.update.CleepConf')1663 def test_install_module(self, mock_cleepconf, mock_task):1664 self.init_session()1665 self.module._postpone_main_action = Mock(return_value=True)1666 mock_cleepconf.return_value.is_module_installed.return_value = False1667 self.assertTrue(self.module.install_module('dummy'))1668 self.module._postpone_main_action.assert_called_with(1669 self.module.ACTION_MODULE_INSTALL,1670 'dummy',1671 extra={1672 'package': None,1673 'no_compatibility_check': False1674 }1675 )1676 self.assertTrue(mock_task.return_value.start.called)1677 def test_install_module_cleep_update_running(self):1678 self.init_session()1679 self.module._cleep_updates = {1680 'processing': True,1681 'pending': False1682 }1683 with self.assertRaises(CommandInfo) as cm:1684 self.module.install_module('dummy')1685 self.assertEqual(str(cm.exception), 'Cleep update is in progress. Please wait for end of it')1686 @patch('backend.update.Task')1687 @patch('backend.update.CleepConf')1688 def test_install_module_already_installed(self, mock_cleepconf, mock_task):1689 self.init_session()1690 self.module._get_installed_modules_names = Mock(return_value=['dummy'])1691 mock_cleepconf.return_value.is_module_installed.return_value = True1692 with self.assertRaises(InvalidParameter) as cm:1693 self.module.install_module('dummy')1694 self.assertEqual(str(cm.exception), 'Module "dummy" is already installed')1695 self.assertFalse(mock_task.return_value.start.called)1696 @patch('backend.update.Task')1697 @patch('backend.update.CleepConf')1698 def test_install_module_already_installed_as_library(self, mock_cleepconf, mock_task):1699 self.init_session()1700 self.module._get_installed_modules_names = Mock(return_value=['dummy'])1701 mock_cleepconf.return_value.is_module_installed.return_value = False1702 self.module._set_module_process = Mock()1703 self.module.install_module('dummy')1704 mock_cleepconf.return_value.install_module.assert_called_with('dummy')1705 self.module._set_module_process.assert_called_with(progress=100, failed=False, pending=True, forced_module_name='dummy')1706 self.session.assert_event_called_with('update.module.install', {'status': Install.STATUS_DONE, 'module': 'dummy'})1707 self.session.assert_event_called('system.cleep.needrestart')1708 @patch('backend.update.os.path.exists')1709 def test_install_main_module_from_package_file_not_exists(self, pathexists_mock):1710 self.init_session()1711 pathexists_mock.return_value = False1712 with self.assertRaises(Exception) as cm:1713 self.module._install_main_module('dummy', extra={'package': 'dummy.zip'})1714 self.assertEqual(str(cm.exception), 'Specified package "dummy.zip" does not exists')1715 @patch('backend.update.os.path.exists')1716 @patch('backend.update.shutil.copyfile')1717 def test_install_main_module_from_package_without_dependencies(self, shutilcopyfile_mock, pathexists_mock):1718 infos_dummy = {1719 'loadedby': [],1720 'deps': []1721 }1722 self.init_session()1723 pathexists_mock.return_value = True1724 self.module._get_module_infos_from_modules_json = Mock()1725 self.module._get_module_infos_from_package = Mock(return_value=infos_dummy)1726 self.module._install_main_module('dummy', extra={'package': 'dummy.zip'})1727 shutilcopyfile_mock.assert_called_with('dummy.zip', '/tmp/dummy.zip')1728 self.module._get_module_infos_from_package.assert_called()1729 self.module._get_module_infos_from_modules_json.assert_not_called()1730 @patch('backend.update.os.path.exists')1731 @patch('backend.update.shutil.copyfile')1732 def test_install_main_module_from_package_with_dependencies(self, shutilcopyfile_mock, pathexists_mock):1733 infos_dep1 = {1734 'loadedby': [],1735 'deps': []1736 }1737 infos_dummy = {1738 'loadedby': [],1739 'deps': ['dep1']1740 }1741 self.init_session()1742 pathexists_mock.return_value = True1743 self.module._get_module_infos_from_modules_json = Mock(return_value=infos_dep1)1744 self.module._get_module_infos_from_package = Mock(return_value=infos_dummy)1745 self.module._install_main_module('dummy', extra={'package': 'dummy.zip'})1746 shutilcopyfile_mock.assert_called_with('dummy.zip', '/tmp/dummy.zip')1747 self.module._get_module_infos_from_package.assert_called()1748 self.module._get_module_infos_from_modules_json.assert_called()1749 def test_install_main_module_circular_deps(self):1750 self.init_session()1751 infos_dummy = {1752 'loadedby': [],1753 'deps': ['dep1']1754 }1755 infos_dep1 = {1756 'loadedby': [],1757 'deps': ['dep2']1758 }1759 infos_dep2 = {1760 'loadedby': [],1761 'deps': ['dummy']1762 }1763 self.module._get_installed_modules_names = Mock(return_value=[])1764 self.module._get_module_infos_from_modules_json = Mock(side_effect=[infos_dummy, infos_dep1, infos_dep2])1765 self.module._postpone_sub_action = Mock()1766 self.module._install_main_module('dummy')1767 self.module._postpone_sub_action.assert_has_calls([1768 call(self.module.ACTION_MODULE_INSTALL, 'dummy', infos_dummy, 'dummy', extra=None),1769 call(self.module.ACTION_MODULE_INSTALL, 'dep1', infos_dep1, 'dummy', extra=None),1770 call(self.module.ACTION_MODULE_INSTALL, 'dep2', infos_dep2, 'dummy', extra=None),1771 ], any_order=True)1772 self.assertEqual(self.module._postpone_sub_action.call_count, 3)1773 def test_install_main_module_with_deps(self):1774 self.init_session()1775 infos_dummy = {1776 'loadedby': [],1777 'deps': ['dep1']1778 }1779 infos_dep1 = {1780 'loadedby': [],1781 'deps': ['dep2']1782 }1783 infos_dep2 = {1784 'loadedby': [],1785 'deps': []1786 }1787 self.module._get_installed_modules_names = Mock(return_value=[])1788 self.module._get_module_infos_from_modules_json = Mock(side_effect=[infos_dummy, infos_dep1, infos_dep2])1789 self.module._postpone_sub_action = Mock()1790 main_module = 'dummy'1791 self.module._install_main_module(main_module)1792 self.module._postpone_sub_action.assert_has_calls([1793 call(self.module.ACTION_MODULE_INSTALL, 'dummy', infos_dummy, main_module, extra=None),1794 call(self.module.ACTION_MODULE_INSTALL, 'dep1', infos_dep1, main_module, extra=None),1795 call(self.module.ACTION_MODULE_INSTALL, 'dep2', infos_dep2, main_module, extra=None),1796 ], any_order=True)1797 self.assertEqual(self.module._postpone_sub_action.call_count, 3)1798 def test_install_main_module_with_deps_already_installed(self):1799 self.init_session()1800 infos_dummy = {1801 'loadedby': [],1802 'deps': ['dep1'],1803 'version': '0.0.0',1804 }1805 infos_dep1 = {1806 'loadedby': [],1807 'deps': ['dep2'],1808 'version': '0.0.0',1809 }1810 infos_dep2 = {1811 'loadedby': [],1812 'deps': [],1813 'version': '0.0.0',1814 }1815 self.module._get_installed_modules_names = Mock(return_value=['dep2'])1816 self.module._get_module_infos_from_inventory = Mock(side_effect=[infos_dep1])1817 self.module._get_module_infos_from_modules_json = Mock(side_effect=[infos_dummy, infos_dep1, infos_dep2])1818 self.module._postpone_sub_action = Mock()1819 self.module._install_main_module('dummy')1820 self.module._postpone_sub_action.assert_has_calls([1821 call(self.module.ACTION_MODULE_INSTALL, 'dummy', infos_dummy, 'dummy', extra=None),1822 call(self.module.ACTION_MODULE_INSTALL, 'dep1', infos_dep1, 'dummy', extra=None),1823 ], any_order=True)1824 self.assertEqual(self.module._postpone_sub_action.call_count, 2)1825 def test_install_main_module_with_dependency_update(self):1826 self.init_session()1827 infos_dummy = {1828 'loadedby': [],1829 'deps': ['dep1'],1830 'version': '0.0.1',1831 }1832 infos_dep1 = {1833 'loadedby': [],1834 'deps': ['dep2'],1835 'version': '0.0.2',1836 }1837 infos_dep2 = {1838 'loadedby': [],1839 'deps': [],1840 'version': '0.0.3',1841 }1842 self.module._get_installed_modules_names = Mock(return_value=['dep2'])1843 self.module._get_module_infos_from_inventory = Mock(side_effect=[infos_dep1])1844 self.module._get_module_infos_from_modules_json = Mock(side_effect=[infos_dummy, infos_dep1, infos_dep2])1845 self.module._postpone_sub_action = Mock()1846 self.module._install_main_module('dummy')1847 # logging.debug('Calls: %s' % self.module._postpone_sub_action.call_args_list)1848 self.module._postpone_sub_action.assert_has_calls([1849 call(self.module.ACTION_MODULE_INSTALL, 'dummy', infos_dummy, 'dummy', extra=None),1850 call(self.module.ACTION_MODULE_INSTALL, 'dep1', infos_dep1, 'dummy', extra=None),1851 call(self.module.ACTION_MODULE_UPDATE, 'dep2', infos_dep2, 'dummy'),1852 ], any_order=True)1853 self.assertEqual(self.module._postpone_sub_action.call_count, 3)1854 def test_install_module_check_params(self):1855 self.init_session()1856 with self.assertRaises(MissingParameter) as cm:1857 self.module.install_module(None)1858 self.assertEqual(str(cm.exception), 'Parameter "module_name" is missing')1859 with self.assertRaises(MissingParameter) as cm:1860 self.module.install_module('')1861 self.assertEqual(str(cm.exception), 'Parameter "module_name" is missing')1862 @patch('backend.update.CleepConf')1863 def test_install_module_callback_processing(self, mock_cleepconf):1864 status = {1865 'status': Install.STATUS_PROCESSING,1866 'module': 'dummy',1867 'stdout': ['hello'],1868 'stderr': ['world'],1869 }1870 self.init_session()1871 self.module._store_process_status = Mock()1872 self.module._Update__install_module_callback(status)1873 self.assertFalse(self.module._store_process_status.called)1874 self.assertEqual(self.session.event_call_count('update.module.install'), 1)1875 self.assertFalse(self.module._need_restart)1876 self.assertFalse(mock_cleepconf.return_value.install_module.called)1877 @patch('backend.update.CleepConf')1878 def test_install_module_callback_done(self, mock_cleepconf):1879 status = {1880 'status': Install.STATUS_DONE,1881 'module': 'dummy',1882 'stdout': ['hello'],1883 'stderr': ['world'],1884 }1885 self.init_session()1886 self.module._store_process_status = Mock()1887 mod_infos = self.__generate_module_infos([], [], '0.0.1')1888 self.module._get_module_infos_from_modules_json = Mock(side_effect=[mod_infos])1889 self.module._Update__install_module_callback(status)1890 self.module._store_process_status.assert_called_with(status, success=True)1891 self.assertEqual(self.session.event_call_count('update.module.install'), 1)1892 self.assertTrue(self.module._need_restart)1893 mock_cleepconf.return_value.install_module.assert_called_with('dummy')1894 @patch('backend.update.CleepConf')1895 def test_install_module_callback_error(self, mock_cleepconf):1896 status = {1897 'status': Install.STATUS_ERROR,1898 'module': 'dummy',1899 'stdout': ['hello'],1900 'stderr': ['world'],1901 }1902 self.init_session()1903 self.module._store_process_status = Mock()1904 self.module._set_module_process = Mock()1905 self.module._Update__install_module_callback(status)1906 self.module._store_process_status.assert_called_with(status, success=False)1907 self.assertEqual(self.session.event_call_count('update.module.install'), 1)1908 self.assertFalse(self.module._need_restart)1909 self.assertFalse(mock_cleepconf.return_value.install_module.called)1910 self.module._set_module_process.assert_called_once_with(failed=True)1911 @patch('backend.update.Install')1912 def test_final_install_module_is_not_dependency(self, mock_install):1913 mock_install.return_value.install_module = Mock()1914 mock_install.return_value.uninstall_module = Mock()1915 mock_install.return_value.update_module = Mock()1916 self.init_session()1917 infos = {'version': '0.0.0'}1918 module_name = 'dummy'1919 self.module._Update__install_module_callback = Mock()1920 self.module._install_module(module_name, infos, {'isdependency': False})1921 mock_install.return_value.install_module.assert_called_with(module_name, infos, {'isdependency': False})1922 self.assertFalse(mock_install.return_value.uninstall_module.called)1923 self.assertFalse(mock_install.return_value.update_module.called)1924 self.assertFalse(self.module._Update__install_module_callback.called)1925 @patch('backend.update.Install')1926 def test_final_install_module_is_dependency(self, mock_install):1927 mock_install.return_value.install_module = Mock()1928 mock_install.return_value.uninstall_module = Mock()1929 mock_install.return_value.update_module = Mock()1930 self.init_session()1931 infos = {'version': '0.0.0'}1932 module_name = 'dummy'1933 self.module._Update__install_module_callback = Mock()1934 self.module._install_module(module_name, infos, {'isdependency': True})1935 mock_install.return_value.install_module.assert_called_with(module_name, infos, {'isdependency': True})1936 self.assertFalse(mock_install.return_value.uninstall_module.called)1937 self.assertFalse(mock_install.return_value.update_module.called)1938 self.assertFalse(self.module._Update__install_module_callback.called)1939 @patch('backend.update.Install')1940 def test_final_install_module_local_module(self, mock_install):1941 mock_install.return_value.install_module = Mock()1942 mock_install.return_value.uninstall_module = Mock()1943 mock_install.return_value.update_module = Mock()1944 self.init_session()1945 infos = {'version': '0.0.0'}1946 module_name = 'dummy'1947 self.module._Update__install_module_callback = Mock()1948 self.module._install_module(module_name, None, False)1949 self.assertFalse(mock_install.return_value.install_module.called)1950 self.assertFalse(mock_install.return_value.uninstall_module.called)1951 self.assertFalse(mock_install.return_value.update_module.called)1952 self.assertTrue(self.module._Update__install_module_callback.called)1953 @patch('backend.update.Install')1954 def test_final_install_module_exception(self, mock_install):1955 mock_install.return_value.install_module = Mock(side_effect=Exception('Test exception'))1956 self.init_session()1957 infos = {'version': '0.0.0'}1958 module_name = 'dummy'1959 self.module._Update__install_module_callback = Mock()1960 self.module._install_module(module_name, infos, False)1961 self.assertTrue(self.module.crash_report.manual_report.called)1962 self.assertTrue(self.module._Update__install_module_callback.called)1963 @patch('backend.update.CleepConf')1964 def test_get_modules_to_uninstall_with_non_installed_dependencies(self, mock_cleepconf):1965 self.init_session()1966 modules_to_uninstall = [1967 'parent',1968 'child1',1969 'child2',1970 'child3'1971 ]1972 modules_infos = {1973 'parent': {1974 'loadedby': []1975 },1976 'child1': {1977 'loadedby': ['parent', 'dummy']1978 },1979 'child2': {1980 'loadedby': ['parent']1981 },1982 'child3': {1983 'loadedby': ['child2']1984 },1985 }1986 mock_cleepconf.return_value.is_module_installed.return_value = False1987 modules = self.module._get_modules_to_uninstall('parent', modules_to_uninstall, modules_infos)1988 self.assertEqual(modules, ['parent', 'child2', 'child3'])1989 @patch('backend.update.CleepConf')1990 def test_get_modules_to_uninstall_without_dependencies(self, mock_cleepconf):1991 self.init_session()1992 modules_to_uninstall = ['parent']1993 modules_infos = {1994 'parent': {1995 'loadedby': []1996 },1997 'child1': {1998 'loadedby': ['dummy']1999 },2000 'child2': {2001 'loadedby': []2002 },2003 'child3': {2004 'loadedby': []2005 },2006 }2007 mock_cleepconf.return_value.is_module_installed.return_value = False2008 modules = self.module._get_modules_to_uninstall('parent', modules_to_uninstall, modules_infos)2009 self.assertEqual(modules, ['parent'])2010 @patch('backend.update.CleepConf')2011 def test_get_modules_to_uninstall_with_installed_dependency(self, mock_cleepconf):2012 self.init_session()2013 modules_to_uninstall = [2014 'parent',2015 'child1',2016 'child2',2017 'child3'2018 ]2019 modules_infos = {2020 'parent': {2021 'loadedby': []2022 },2023 'child1': {2024 'loadedby': ['parent', 'dummy']2025 },2026 'child2': {2027 'loadedby': ['parent'] # installed by user2028 },2029 'child3': {2030 'loadedby': ['child2']2031 },2032 }2033 mock_cleepconf.return_value.is_module_installed.side_effect = [False, True, False]2034 modules = self.module._get_modules_to_uninstall('parent', modules_to_uninstall, modules_infos)2035 self.assertEqual(modules, ['parent', 'child3'])2036 @patch('backend.update.CleepConf')2037 def test_get_modules_to_uninstall_orphan(self, mock_cleepconf):2038 self.init_session()2039 modules_to_uninstall = [2040 'parent',2041 'child1',2042 'child2',2043 'child3'2044 ]2045 modules_infos = {2046 'parent': {2047 'loadedby': []2048 },2049 'child1': {2050 'loadedby': ['parent', 'dummy']2051 },2052 'child3': {2053 'loadedby': ['child2']2054 },2055 }2056 mock_cleepconf.return_value.is_module_installed.return_value = False2057 modules = self.module._get_modules_to_uninstall('parent', modules_to_uninstall, modules_infos)2058 self.assertEqual(modules, ['parent', 'child3'])2059 @patch('backend.update.importlib')2060 def test_get_local_module_dependencies(self, mock_importlib):2061 self.init_session()2062 dependencies = ['dummy1', 'dummy2']2063 class empty:2064 pass2065 class dummy:2066 class Dummy:2067 MODULE_DEPS = dependencies2068 mock_importlib.import_module.side_effect = [empty(), dummy()]2069 deps = self.module._Update__get_local_module_dependencies('dummy')2070 self.assertCountEqual(deps, dependencies)2071 @patch('backend.update.importlib')2072 def test_get_local_module_dependencies_exception(self, mock_importlib):2073 self.init_session()2074 mock_importlib.import_module.side_effect = Exception('Test exception')2075 deps = self.module._Update__get_local_module_dependencies('dummy')2076 self.assertCountEqual(deps, [])2077 def test_get_module_dependencies(self):2078 callback = Mock(side_effect=[2079 { 'deps': ['dummy2'] }, # dummy1 deps2080 { 'deps': ['dummy3'] }, # dummy2 deps2081 { 'deps': ['dummy4'] }, #Â dummy3 deps2082 { 'deps': [] }, # dummy4 deps2083 ])2084 self.init_session()2085 modules_infos = {}2086 deps = self.module._get_module_dependencies('dummy1', modules_infos, callback)2087 logging.debug('Deps: %s' % deps)2088 self.assertEqual(deps, ['dummy4', 'dummy3', 'dummy2', 'dummy1'])2089 self.assertCountEqual(deps, list(modules_infos.keys()))2090 def test_get_module_dependencies_local_module(self):2091 callback = Mock(side_effect=[2092 { 'deps': ['dummy2'] }, # dummy1 deps2093 None,2094 { 'deps': ['dummy4'] }, #Â dummy3 deps2095 { 'deps': [] }, # dummy4 deps2096 ])2097 self.init_session()2098 self.module._Update__get_local_module_dependencies = Mock(return_value=['dummy3'])2099 modules_infos = {}2100 deps = self.module._get_module_dependencies('dummy1', modules_infos, callback)2101 logging.debug('Deps: %s' % deps)2102 self.assertEqual(deps, ['dummy4', 'dummy3', 'dummy2', 'dummy1'])2103 self.assertCountEqual(deps, list(modules_infos.keys()))2104 def test_get_module_dependencies_complex(self):2105 callback = Mock(side_effect=[2106 { 'deps': ['dummy2'] }, # dummy1 deps2107 { 'deps': ['dummy3', 'dummy4'] }, # dummy2 deps2108 { 'deps': ['dummy5'] }, # dummy3 deps2109 { 'deps': ['dummy5', 'dummy6'] }, # dummy4 deps2110 { 'deps': ['dummy6'] }, # dummy5 deps2111 { 'deps': [] }, # dummy6 deps2112 ])2113 self.init_session()2114 modules_infos = {}2115 deps = self.module._get_module_dependencies('dummy1', modules_infos, callback)2116 logging.debug('Deps: %s' % deps)2117 self.assertEqual(deps, ['dummy6', 'dummy5', 'dummy3', 'dummy4', 'dummy2', 'dummy1'])2118 self.assertCountEqual(deps, list(modules_infos.keys()))2119 def test_get_module_dependencies_circular_deps(self):2120 callback = Mock(side_effect=[2121 { 'deps': ['dummy2'] }, # dummy1 deps2122 { 'deps': ['dummy3'] }, # dummy2 deps2123 { 'deps': ['dummy1'] }, # dummy3 deps2124 ])2125 self.init_session()2126 modules_infos = {}2127 deps = self.module._get_module_dependencies('dummy1', modules_infos, callback)2128 logging.debug('Deps: %s' % deps)2129 self.assertEqual(sorted(deps), ['dummy1', 'dummy2', 'dummy3'])2130 self.assertCountEqual(deps, list(modules_infos.keys()))2131 @patch('backend.update.Task')2132 def test_uninstall_module(self, mock_task):2133 self.init_session()2134 self.module._get_installed_modules_names = Mock(return_value=['dummy'])2135 infos_dummy = {2136 'loadedby': [],2137 'deps': []2138 }2139 extra = {'force': False}2140 self.module._get_module_infos_from_inventory = Mock(side_effect=[infos_dummy])2141 self.module._postpone_main_action = Mock()2142 self.assertTrue(self.module.uninstall_module('dummy'))2143 self.module._postpone_main_action.assert_called_with(self.module.ACTION_MODULE_UNINSTALL, 'dummy', extra=extra)2144 self.assertTrue(mock_task.return_value.start.called)2145 def test_uninstall_module_cleep_update_running(self):2146 self.init_session()2147 self.module._cleep_updates = {2148 'processing': True,2149 'pending': False2150 }2151 with self.assertRaises(CommandInfo) as cm:2152 self.module.uninstall_module('dummy')2153 self.assertEqual(str(cm.exception), 'Cleep update is in progress. Please wait for end of it')2154 @patch('backend.update.Task')2155 def test_uninstall_module_check_params(self, mock_task):2156 self.init_session()2157 infos_dummy = {2158 'loadedby': [],2159 'deps': []2160 }2161 self.module._get_module_infos_from_inventory = Mock(side_effect=[infos_dummy])2162 with self.assertRaises(MissingParameter) as cm:2163 self.module.uninstall_module('')2164 self.assertEqual(str(cm.exception), 'Parameter "module_name" is missing')2165 with self.assertRaises(MissingParameter) as cm:2166 self.module.uninstall_module(None)2167 self.assertEqual(str(cm.exception), 'Parameter "module_name" is missing')2168 self.assertFalse(mock_task.return_value.start.called)2169 @patch('backend.update.Task')2170 def test_uninstall_module_not_installed_module(self, mock_task):2171 self.init_session()2172 with self.assertRaises(InvalidParameter) as cm:2173 self.module.uninstall_module('dummy')2174 self.assertEqual(str(cm.exception), 'Module "dummy" is not installed')2175 self.assertFalse(mock_task.return_value.start.called)2176 @patch('backend.update.Task')2177 def test_uninstall_module_already_postponed(self, mock_task):2178 self.init_session()2179 self.module._get_installed_modules_names = Mock(return_value=['dummy', 'dummy2'])2180 infos_dummy = {2181 'loadedby': [],2182 'deps': []2183 }2184 self.module._get_module_infos_from_inventory = Mock(side_effect=[infos_dummy])2185 infos_dummy_json = self.__generate_module_infos([], ['dep1'], '1.0.0')2186 infos_dep1_json = self.__generate_module_infos([], ['dep2'], '0.0.0')2187 infos_dep2_json = self.__generate_module_infos([], [], '0.0.1')2188 self.module._get_module_infos_from_modules_json = Mock(side_effect=[infos_dummy_json, infos_dep1_json, infos_dep2_json])2189 self.assertTrue(self.module.uninstall_module('dummy'))2190 self.assertFalse(self.module.uninstall_module('dummy'))2191 self.assertEqual(mock_task.return_value.start.call_count, 2) # called twice for main and sub action tasks2192 @patch('backend.update.CleepConf')2193 def test_uninstall_main_module_with_deps(self, mock_cleepconf):2194 self.init_session()2195 self.module._get_installed_modules_names = Mock(return_value=['dummy'])2196 infos_dummy = {2197 'loadedby': [],2198 'deps': ['dep1']2199 }2200 infos_dep1 = {2201 'loadedby': [],2202 'deps': ['dep2']2203 }2204 infos_dep2 = {2205 'loadedby': [],2206 'deps': []2207 }2208 extra = {'force': False}2209 self.module._get_module_infos_from_inventory = Mock(side_effect=[infos_dummy, infos_dep1, infos_dep2])2210 self.module._postpone_sub_action = Mock()2211 mock_cleepconf.return_value.is_module_installed.return_value = False2212 self.module._uninstall_main_module('dummy', extra)2213 self.module._postpone_sub_action.assert_has_calls([2214 call(self.module.ACTION_MODULE_UNINSTALL, 'dummy', infos_dummy, 'dummy', extra),2215 call(self.module.ACTION_MODULE_UNINSTALL, 'dep1', infos_dep1, 'dummy', extra),2216 call(self.module.ACTION_MODULE_UNINSTALL, 'dep2', infos_dep2, 'dummy', extra),2217 ], any_order=True)2218 self.assertEqual(self.module._postpone_sub_action.call_count, 3)2219 @patch('backend.update.CleepConf')2220 def test_uninstall_main_module_with_circular_deps(self, mock_cleepconf):2221 self.init_session()2222 self.module._get_installed_modules_names = Mock(return_value=['dummy'])2223 infos_dummy = {2224 'loadedby': [],2225 'version': '1.2.3',2226 'deps': ['dep1']2227 }2228 infos_dep1 = {2229 'loadedby': [],2230 'version': '1.2.3',2231 'deps': ['dep2']2232 }2233 infos_dep2 = {2234 'loadedby': [],2235 'version': '1.2.3',2236 'deps': ['dummy']2237 }2238 extra = {'force': False}2239 self.module._get_module_infos_from_inventory = Mock(side_effect=[infos_dummy, infos_dep1, infos_dep2])2240 infos_dummy_json = self.__generate_module_infos([], ['dep1'], '1.0.0')2241 infos_dep1_json = self.__generate_module_infos([], ['dep2'], '0.0.0')2242 infos_dep2_json = self.__generate_module_infos([], [], '0.0.1')2243 self.module._get_module_infos_from_modules_json = Mock(side_effect=[infos_dummy_json, infos_dep1_json, infos_dep2_json])2244 self.module._postpone_sub_action = Mock()2245 mock_cleepconf.return_value.is_module_installed.return_value = False2246 self.module.uninstall_module('dummy')2247 self.module._uninstall_main_module('dummy', extra)2248 self.module._postpone_sub_action.assert_has_calls([2249 call(self.module.ACTION_MODULE_UNINSTALL, 'dummy', infos_dummy, 'dummy', extra),2250 call(self.module.ACTION_MODULE_UNINSTALL, 'dep1', infos_dep1, 'dummy', extra),2251 call(self.module.ACTION_MODULE_UNINSTALL, 'dep2', infos_dep2, 'dummy', extra),2252 ], any_order=True)2253 self.assertEqual(self.module._postpone_sub_action.call_count, 3)2254 @patch('backend.update.CleepConf')2255 def test_uninstall_main_module_with_uninstallable_deps(self, mock_cleepconf):2256 self.init_session()2257 self.module._get_installed_modules_names = Mock(return_value=['dummy'])2258 infos_dummy = {2259 'loadedby': [],2260 'deps': ['dep1']2261 }2262 infos_dep1 = {2263 'loadedby': ['system'],2264 'deps': ['dep2']2265 }2266 infos_dep2 = {2267 'loadedby': [],2268 'deps': ['dummy']2269 }2270 extra = {'force': False}2271 self.module._get_module_infos_from_inventory = Mock(side_effect=[infos_dummy, infos_dep1, infos_dep2])2272 infos_dummy_json = self.__generate_module_infos([], ['dep1'], '1.0.0')2273 infos_dep1_json = self.__generate_module_infos([], ['dep2'], '0.0.0')2274 infos_dep2_json = self.__generate_module_infos([], [], '0.0.1')2275 self.module._get_module_infos_from_modules_json = Mock(side_effect=[infos_dummy_json, infos_dep1_json, infos_dep2_json])2276 self.module._postpone_sub_action = Mock()2277 mock_cleepconf.return_value.is_module_installed.return_value = False2278 self.module.uninstall_module('dummy')2279 self.module._uninstall_main_module('dummy', extra)2280 self.module._postpone_sub_action.assert_has_calls([2281 call(self.module.ACTION_MODULE_UNINSTALL, 'dummy', infos_dummy, 'dummy', extra),2282 call(self.module.ACTION_MODULE_UNINSTALL, 'dep2', infos_dep2, 'dummy', extra),2283 ], any_order=True)2284 self.assertEqual(self.module._postpone_sub_action.call_count, 2)2285 @patch('backend.update.CleepConf')2286 def test_uninstall_main_module_forced(self, mock_cleepconf):2287 self.init_session()2288 self.module._get_installed_modules_names = Mock(return_value=['dummy'])2289 infos_dummy = {2290 'loadedby': [],2291 'deps': []2292 }2293 extra = {'force': True}2294 self.module._get_module_infos_from_inventory = Mock(return_value=infos_dummy)2295 self.module._postpone_sub_action = Mock()2296 self.module._postpone_main_action = Mock()2297 mock_cleepconf.return_value.is_module_installed.return_value = False2298 self.module._uninstall_main_module('dummy', extra)2299 self.module._postpone_sub_action.assert_called_once_with(self.module.ACTION_MODULE_UNINSTALL, 'dummy', infos_dummy, 'dummy', extra)2300 self.module.uninstall_module('dummy', force=True)2301 self.module._postpone_main_action.assert_called_once_with(self.module.ACTION_MODULE_UNINSTALL, 'dummy', extra=extra)2302 @patch('backend.update.CleepConf')2303 def test_uninstall_main_module_no_module_to_uninstall(self, mock_cleepconf):2304 self.init_session()2305 self.module._get_module_dependencies = Mock()2306 self.module._get_modules_to_uninstall = Mock(return_value=[])2307 self.module._set_module_process = Mock()2308 self.module._uninstall_main_module('dummy0', extra={'force': False})2309 mock_cleepconf.return_value.uninstall_module.assert_called_with('dummy0')2310 self.module._set_module_process.assert_called_with(progress=100, failed=False, pending=True, forced_module_name='dummy0')2311 self.session.assert_event_called_with('update.module.uninstall', {'status': Install.STATUS_DONE, 'module': 'dummy0'})2312 self.session.assert_event_called('system.cleep.needrestart')2313 @patch('backend.update.CleepConf')2314 def test_uninstall_module_callback_processing(self, mock_cleepconf):2315 status = {2316 'status': Install.STATUS_PROCESSING,2317 'module': 'dummy',2318 'stdout': ['hello'],2319 'stderr': ['world'],2320 }2321 self.init_session()2322 self.module._store_process_status = Mock()2323 self.module._Update__uninstall_module_callback(status)2324 self.assertFalse(self.module._store_process_status.called)2325 self.assertEqual(self.session.event_call_count('update.module.uninstall'), 1)2326 self.assertFalse(self.module._need_restart)2327 self.assertFalse(mock_cleepconf.return_value.uninstall_module.called)2328 @patch('backend.update.CleepConf')2329 def test_uninstall_module_callback_done(self, mock_cleepconf):2330 status = {2331 'status': Install.STATUS_DONE,2332 'module': 'dummy',2333 'stdout': ['hello'],2334 'stderr': ['world'],2335 }2336 self.init_session()2337 self.module._store_process_status = Mock()2338 mod_infos = self.__generate_module_infos([], [], '0.0.1')2339 self.module._get_module_infos_from_modules_json = Mock(side_effect=[mod_infos])2340 self.module._Update__uninstall_module_callback(status)2341 self.module._store_process_status.assert_called_with(status, success=True)2342 self.assertEqual(self.session.event_call_count('update.module.uninstall'), 1)2343 self.assertTrue(self.module._need_restart)2344 mock_cleepconf.return_value.uninstall_module.assert_called_with('dummy')2345 @patch('backend.update.CleepConf')2346 def test_uninstall_module_callback_error(self, mock_cleepconf):2347 status = {2348 'status': Install.STATUS_ERROR,2349 'module': 'dummy',2350 'stdout': ['hello'],2351 'stderr': ['world'],2352 }2353 self.init_session()2354 self.module._store_process_status = Mock()2355 self.module._set_module_process = Mock()2356 self.module._Update__uninstall_module_callback(status)2357 self.module._store_process_status.assert_called_with(status, success=False)2358 self.assertEqual(self.session.event_call_count('update.module.uninstall'), 1)2359 self.assertFalse(self.module._need_restart)2360 self.assertFalse(mock_cleepconf.return_value.uninstall_module.called)2361 self.module._set_module_process.assert_called_once_with(failed=True, pending=True)2362 @patch('backend.update.Install')2363 def test_final_uninstall_module(self, mock_install):2364 mock_install.return_value.install_module = Mock()2365 mock_install.return_value.uninstall_module = Mock()2366 mock_install.return_value.update_module = Mock()2367 self.init_session()2368 infos = {'version': '0.0.0'}2369 module_name = 'dummy'2370 extra = {'force': True}2371 self.module._Update__uninstall_module_callback = Mock()2372 self.module._uninstall_module(module_name, infos, extra)2373 self.assertFalse(mock_install.return_value.install_module.called)2374 mock_install.return_value.uninstall_module.assert_called_with(module_name, infos, extra['force'])2375 self.assertFalse(mock_install.return_value.update_module.called)2376 self.assertFalse(self.module._Update__uninstall_module_callback.called)2377 @patch('backend.update.Install')2378 def test_final_uninstall_module_exception(self, mock_install):2379 mock_install.return_value.uninstall_module = Mock(side_effect=Exception('Test exception'))2380 self.init_session()2381 infos = {'version': '0.0.0'}2382 module_name = 'dummy'2383 extra = {'force': True}2384 self.module._Update__uninstall_module_callback = Mock()2385 self.module._uninstall_module(module_name, infos, extra)2386 self.assertTrue(self.module.crash_report.manual_report.called)2387 self.assertTrue(self.module._Update__uninstall_module_callback.called)2388 @patch('backend.update.Task')2389 def test_update_module(self, mock_task):2390 self.init_session()2391 self.module._get_installed_modules_names = Mock(return_value=['dummy'])2392 self.module._postpone_main_action = Mock(return_value=True)2393 dummy = {2394 'name': 'dummy',2395 'updatable': True,2396 'processing': False,2397 'pending': False,2398 }2399 self.module._modules_updates = {2400 'dummy': dummy2401 }2402 self.assertTrue(self.module.update_module('dummy'))2403 self.module._postpone_main_action.assert_called_with(self.module.ACTION_MODULE_UPDATE, 'dummy')2404 self.assertTrue(mock_task.return_value.start.called)2405 def test_update_module_cleep_update_running(self):2406 self.init_session()2407 self.module._cleep_updates = {2408 'processing': True,2409 'pending': False2410 }2411 with self.assertRaises(CommandInfo) as cm:2412 self.module.update_module('dummy')2413 self.assertEqual(str(cm.exception), 'Cleep update is in progress. Please wait for end of it')2414 def test_update_module_module_already_uptodate(self):2415 self.init_session()2416 mod5 = {2417 'name': 'mod5',2418 'updatable': False,2419 'processing': False,2420 'pending': False,2421 }2422 self.module._modules_updates = {2423 'mod5': mod52424 }2425 self.module._get_installed_modules_names = Mock(return_value=['mod5'])2426 self.assertFalse(self.module.update_module('mod5'))2427 @patch('backend.update.Task')2428 def test_update_module_not_installed(self, mock_task):2429 self.init_session()2430 self.module._get_installed_modules_names = Mock(return_value=[])2431 with self.assertRaises(InvalidParameter) as cm:2432 self.module.update_module('dummy')2433 self.assertEqual(str(cm.exception), 'Module "dummy" is not installed')2434 self.assertFalse(mock_task.return_value.start.called)2435 @patch('backend.update.Task')2436 def test_update_module_check_params(self, mock_task):2437 self.init_session()2438 with self.assertRaises(MissingParameter) as cm:2439 self.module.update_module(None)2440 self.assertEqual(str(cm.exception), 'Parameter "module_name" is missing')2441 with self.assertRaises(MissingParameter) as cm:2442 self.module.update_module('')2443 self.assertEqual(str(cm.exception), 'Parameter "module_name" is missing')2444 self.assertFalse(mock_task.return_value.start.called)2445 def __generate_module_infos(self, loadedby, deps, version):2446 return {2447 'loadedby': loadedby,2448 'deps': deps,2449 'version': version2450 }2451 def test_update_main_module_all_deps_updated_none_uninstalled_none_installed(self):2452 self.init_session()2453 self.module._get_installed_modules_names = Mock(return_value=['dummy', 'dep1', 'dep2'])2454 infos_dummy_inv = self.__generate_module_infos([], ['dep1'], '0.0.0')2455 infos_dep1_inv = self.__generate_module_infos([], ['dep2'], '0.0.0')2456 infos_dep2_inv = self.__generate_module_infos([], [], '0.0.0')2457 infos_dummy_json = self.__generate_module_infos([], ['dep1'], '1.0.0')2458 infos_dep1_json = self.__generate_module_infos([], ['dep2'], '0.1.0')2459 infos_dep2_json = self.__generate_module_infos([], [], '0.0.1')2460 self.module._get_module_infos_from_modules_json = Mock(side_effect=[infos_dummy_json, infos_dep1_json, infos_dep2_json])2461 self.module._get_module_infos_from_inventory = Mock(side_effect=[infos_dummy_inv, infos_dep1_inv, infos_dep2_inv])2462 self.module._postpone_sub_action = Mock()2463 self.module._update_main_module('dummy')2464 self.module._postpone_sub_action.assert_has_calls([2465 call(self.module.ACTION_MODULE_UPDATE, 'dummy', infos_dummy_json, 'dummy'),2466 call(self.module.ACTION_MODULE_UPDATE, 'dep1', infos_dep1_json, 'dummy'),2467 call(self.module.ACTION_MODULE_UPDATE, 'dep2', infos_dep2_json, 'dummy'),2468 ], any_order=True)2469 self.assertEqual(self.module._postpone_sub_action.call_count, 3)2470 def test_update_main_module_some_deps_updated_none_uninstalled_none_installed(self):2471 self.init_session()2472 self.module._get_installed_modules_names = Mock(return_value=['dummy', 'dep1', 'dep2'])2473 infos_dummy_inv = self.__generate_module_infos([], ['dep1'], '0.0.0')2474 infos_dep1_inv = self.__generate_module_infos([], ['dep2'], '0.0.0')2475 infos_dep2_inv = self.__generate_module_infos([], [], '0.0.0')2476 infos_dummy_json = self.__generate_module_infos([], ['dep1'], '1.0.0')2477 infos_dep1_json = self.__generate_module_infos([], ['dep2'], '0.0.0')2478 infos_dep2_json = self.__generate_module_infos([], [], '0.0.1')2479 self.module._get_module_infos_from_modules_json = Mock(side_effect=[infos_dummy_json, infos_dep1_json, infos_dep2_json])2480 self.module._get_module_infos_from_inventory = Mock(side_effect=[infos_dummy_inv, infos_dep1_inv, infos_dep2_inv])2481 self.module._postpone_sub_action = Mock()2482 self.module._update_main_module('dummy')2483 self.module._postpone_sub_action.assert_has_calls([2484 call(self.module.ACTION_MODULE_UPDATE, 'dummy', infos_dummy_json, 'dummy'),2485 call(self.module.ACTION_MODULE_UPDATE, 'dep2', infos_dep2_json, 'dummy'),2486 ], any_order=True)2487 self.assertEqual(self.module._postpone_sub_action.call_count, 2)2488 def test_update_main_module_all_deps_updated_some_uninstalled_none_installed(self):2489 self.init_session()2490 self.module._get_installed_modules_names = Mock(return_value=['dummy', 'dep1', 'dep2'])2491 infos_dummy_inv = self.__generate_module_infos([], ['dep1'], '0.0.0')2492 infos_dep1_inv = self.__generate_module_infos([], ['dep2'], '0.0.0')2493 infos_dep2_inv = self.__generate_module_infos([], [], '0.0.0')2494 infos_dummy_json = self.__generate_module_infos([], ['dep1'], '1.0.0')2495 infos_dep1_json = self.__generate_module_infos([], [], '0.1.0')2496 infos_dep2_json = self.__generate_module_infos([], [], '0.0.1')2497 self.module._get_module_infos_from_modules_json = Mock(side_effect=[infos_dummy_json, infos_dep1_json, infos_dep2_json])2498 self.module._get_module_infos_from_inventory = Mock(side_effect=[infos_dummy_inv, infos_dep1_inv, infos_dep2_inv])2499 self.module._postpone_sub_action = Mock()2500 self.module._update_main_module('dummy')2501 self.module._postpone_sub_action.assert_has_calls([2502 call(self.module.ACTION_MODULE_UPDATE, 'dummy', infos_dummy_json, 'dummy'),2503 call(self.module.ACTION_MODULE_UPDATE, 'dep1', infos_dep1_json, 'dummy'),2504 call(self.module.ACTION_MODULE_UNINSTALL, 'dep2', infos_dep2_inv, 'dummy', extra={'force': True}),2505 ], any_order=True)2506 self.assertEqual(self.module._postpone_sub_action.call_count, 3)2507 def test_update_main_module_some_deps_updated_some_uninstalled_none_installed(self):2508 self.init_session()2509 self.module._get_installed_modules_names = Mock(return_value=['dummy', 'dep1', 'dep2'])2510 infos_dummy_inv = self.__generate_module_infos([], ['dep1'], '0.0.0')2511 infos_dep1_inv = self.__generate_module_infos([], ['dep2'], '0.0.0')2512 infos_dep2_inv = self.__generate_module_infos([], [], '0.0.0')2513 infos_dummy_json = self.__generate_module_infos([], ['dep1'], '0.0.0')2514 infos_dep1_json = self.__generate_module_infos([], [], '0.1.0')2515 infos_dep2_json = self.__generate_module_infos([], [], '0.0.1')2516 self.module._get_module_infos_from_modules_json = Mock(side_effect=[infos_dummy_json, infos_dep1_json, infos_dep2_json])2517 self.module._get_module_infos_from_inventory = Mock(side_effect=[infos_dummy_inv, infos_dep1_inv, infos_dep2_inv])2518 self.module._postpone_sub_action = Mock()2519 self.module._update_main_module('dummy')2520 self.module._postpone_sub_action.assert_has_calls([2521 call(self.module.ACTION_MODULE_UPDATE, 'dep1', infos_dep1_json, 'dummy'),2522 call(self.module.ACTION_MODULE_UNINSTALL, 'dep2', infos_dep2_inv, 'dummy', extra={'force': True}),2523 ], any_order=True)2524 self.assertEqual(self.module._postpone_sub_action.call_count, 2)2525 def test_update_main_module_all_deps_updated_none_uninstalled_some_installed(self):2526 self.init_session()2527 self.module._get_installed_modules_names = Mock(return_value=['dummy', 'dep1', 'dep2'])2528 infos_dummy_inv = self.__generate_module_infos([], ['dep1'], '0.0.0')2529 infos_dep1_inv = self.__generate_module_infos([], [], '0.0.0')2530 infos_dep2_inv = self.__generate_module_infos([], [], '0.0.0')2531 infos_dummy_json = self.__generate_module_infos([], ['dep1'], '1.0.0')2532 infos_dep1_json = self.__generate_module_infos([], ['dep2'], '0.1.0')2533 infos_dep2_json = self.__generate_module_infos([], [], '0.0.1')2534 self.module._get_module_infos_from_modules_json = Mock(side_effect=[infos_dummy_json, infos_dep1_json, infos_dep2_json])2535 self.module._get_module_infos_from_inventory = Mock(side_effect=[infos_dummy_inv, infos_dep1_inv, infos_dep2_inv])2536 self.module._postpone_sub_action = Mock()2537 self.module._update_main_module('dummy')2538 self.module._postpone_sub_action.assert_has_calls([2539 call(self.module.ACTION_MODULE_UPDATE, 'dummy', infos_dummy_json, 'dummy'),2540 call(self.module.ACTION_MODULE_UPDATE, 'dep1', infos_dep1_json, 'dummy'),2541 call(self.module.ACTION_MODULE_INSTALL, 'dep2', infos_dep2_json, 'dummy'),2542 ], any_order=True)2543 self.assertEqual(self.module._postpone_sub_action.call_count, 3)2544 def test_update_main_module_all_deps_updated_some_uninstalled_some_installed(self):2545 self.init_session()2546 self.module._get_installed_modules_names = Mock(return_value=['dummy', 'dep1', 'dep2'])2547 infos_dummy_inv = self.__generate_module_infos([], ['dep1'], '0.0.0')2548 infos_dep1_inv = self.__generate_module_infos([], [], '0.0.0')2549 infos_dep2_inv = self.__generate_module_infos([], [], '0.0.0')2550 infos_dummy_json = self.__generate_module_infos([], ['dep2'], '1.0.0')2551 infos_dep1_json = self.__generate_module_infos([], [], '0.1.0')2552 infos_dep2_json = self.__generate_module_infos([], [], '0.0.1')2553 self.module._get_module_infos_from_modules_json = Mock(side_effect=[infos_dummy_json, infos_dep2_json])2554 self.module._get_module_infos_from_inventory = Mock(side_effect=[infos_dummy_inv, infos_dep1_inv])2555 self.module._postpone_sub_action = Mock()2556 self.module._update_main_module('dummy')2557 self.module._postpone_sub_action.assert_has_calls([2558 call(self.module.ACTION_MODULE_UPDATE, 'dummy', infos_dummy_json, 'dummy'),2559 call(self.module.ACTION_MODULE_UNINSTALL, 'dep1', infos_dep1_inv, 'dummy', extra={'force': True}),2560 call(self.module.ACTION_MODULE_INSTALL, 'dep2', infos_dep2_json, 'dummy'),2561 ], any_order=True)2562 self.assertEqual(self.module._postpone_sub_action.call_count, 3)2563 @patch('backend.update.CleepConf')2564 def test_update_module_callback_processing(self, mock_cleepconf):2565 status = {2566 'status': Install.STATUS_PROCESSING,2567 'module': 'dummy',2568 'stdout': ['hello'],2569 'stderr': ['world'],2570 }2571 self.init_session()2572 self.module._store_process_status = Mock()2573 self.module._Update__update_module_callback(status)2574 self.assertFalse(self.module._store_process_status.called)2575 self.assertEqual(self.session.event_call_count('update.module.update'), 1)2576 self.assertFalse(self.module._need_restart)2577 self.assertFalse(mock_cleepconf.return_value.update_module.called)2578 @patch('backend.update.CleepConf')2579 def test_update_module_callback_done(self, mock_cleepconf):2580 status = {2581 'status': Install.STATUS_DONE,2582 'module': 'dummy',2583 'stdout': ['hello'],2584 'stderr': ['world'],2585 }2586 self.init_session()2587 self.module._store_process_status = Mock()2588 mod_infos = self.__generate_module_infos([], [], '0.0.1')2589 self.module._get_module_infos_from_modules_json = Mock(side_effect=[mod_infos])2590 self.module._Update__update_module_callback(status)2591 self.module._store_process_status.assert_called_with(status, success=True)2592 self.assertEqual(self.session.event_call_count('update.module.update'), 1)2593 self.assertTrue(self.module._need_restart)2594 mock_cleepconf.return_value.update_module.assert_called_with('dummy')2595 @patch('backend.update.CleepConf')2596 def test_update_module_callback_error(self, mock_cleepconf):2597 status = {2598 'status': Install.STATUS_ERROR,2599 'module': 'dummy',2600 'stdout': ['hello'],2601 'stderr': ['world'],2602 }2603 self.init_session()2604 self.module._store_process_status = Mock()2605 self.module._set_module_process = Mock()2606 self.module._Update__update_module_callback(status)2607 self.module._store_process_status.assert_called_with(status, success=False)2608 self.assertEqual(self.session.event_call_count('update.module.update'), 1)2609 self.assertFalse(self.module._need_restart)2610 self.assertFalse(mock_cleepconf.return_value.update_module.called)2611 self.module._set_module_process.assert_called_once_with(failed=True)2612 @patch('backend.update.Install')2613 def test_final_update_module(self, mock_install):2614 mock_install.return_value.install_module = Mock()2615 mock_install.return_value.uninstall_module = Mock()2616 mock_install.return_value.update_module = Mock()2617 self.init_session()2618 infos = {'version': '0.0.0'}2619 module_name = 'dummy'2620 self.module._update_module(module_name, infos)2621 self.assertFalse(mock_install.return_value.install_module.called)2622 self.assertFalse(mock_install.return_value.uninstall_module.called)2623 mock_install.return_value.update_module.assert_called_with(module_name, infos)2624class TestUpdateCleepUpdateEvent(unittest.TestCase):2625 def setUp(self):2626 logging.basicConfig(level=logging.FATAL, format=u'%(asctime)s %(name)s:%(lineno)d %(levelname)s : %(message)s')2627 params = { 2628 'internal_bus': Mock(),2629 'formatters_broker': Mock(),2630 'get_external_bus_name': None,2631 } ...
test_system.py
Source:test_system.py
...45 mock_psutil.Process.return_value.cpu_percent.reset_mock()46 mock_psutil.Process.return_value.memory_info.reset_mock()47 mock_cleepconf.reset_mock()48 self.session.clean()49 def init_session(self, start_module=True):50 self.module = self.session.setup(System)51 if start_module:52 self.session.start_module(self.module)53 def test_configure(self):54 self.init_session(start_module=False)55 self.module.get_module_devices = Mock(return_value={56 '123-123': {'type': 'monitor'},57 '456-456': {'type': 'monitorcpu'},58 '789-789': {'type': 'monitormemory'},59 })60 self.module._add_device = Mock()61 self.module._configure_crash_report = Mock()62 self.module._set_not_renderable_events = Mock()63 self.session.start_module(self.module)64 mock_psutil.Process.assert_called()65 mock_psutil.Process.return_value.cpu_percent.assert_called()66 self.assertEqual(self.module._add_device.call_count, 0)67 self.assertEqual(self.module._System__monitor_memory_uuid, '789-789')68 self.assertEqual(self.module._System__monitor_cpu_uuid, '456-456')69 self.module._configure_crash_report.assert_called_with(True)70 self.module._set_not_renderable_events.assert_called()71 def test_configure_create_all_devices(self):72 self.init_session(start_module=False)73 self.module.get_module_devices = Mock(return_value={})74 self.module._add_device = Mock()75 self.session.start_module(self.module)76 self.assertEqual(self.module._add_device.call_count, 3)77 def test_configure_create_missing_devices(self):78 self.init_session(start_module=False)79 self.module.get_module_devices = Mock(return_value={80 '123-123': {'type': 'monitor'},81 '789-789': {'type': 'monitormemory'},82 })83 self.module._add_device = Mock()84 self.session.start_module(self.module)85 self.assertEqual(self.module._add_device.call_count, 1)86 def test_configure_disable_crash_report_at_startup(self):87 self.init_session(start_module=False)88 self.module.get_module_devices = Mock(return_value={89 '123-123': {'type': 'monitor'},90 '456-456': {'type': 'monitorcpu'},91 '789-789': {'type': 'monitormemory'},92 })93 self.module._configure_crash_report = Mock()94 self.module._get_config_field = Mock(return_value=False)95 self.session.start_module(self.module)96 self.module._configure_crash_report.assert_called_with(False)97 def test_configure_crash_report_enable(self):98 self.init_session()99 self.module._configure_crash_report(True)100 self.assertTrue(self.session.crash_report.enable.called)101 self.assertFalse(self.session.crash_report.disable.called)102 def test_configure_crash_report_disable(self):103 self.init_session()104 self.session.crash_report.is_enabled = Mock(return_value=False)105 self.module._configure_crash_report(False)106 self.assertEqual(self.session.crash_report.enable.call_count, 1) # called during _configure107 self.assertTrue(self.session.crash_report.disable.called)108 def test_on_start(self):109 self.init_session(start_module=False)110 self.module._System__start_monitoring_tasks = Mock()111 self.session.start_module(self.module)112 self.assertTrue(self.module._System__start_monitoring_tasks.called)113 def test_get_module_config(self):114 self.init_session()115 mock_cleepconf.is_system_debugged = Mock(return_value=True)116 mock_cleepconf.is_trace_enabled = Mock(return_value=True)117 config = self.module.get_module_config()118 logging.debug('Config: %s' % config)119 self.assertCountEqual(120 [121 'needrestart',122 'version',123 'eventsnotrenderable',124 'debug',125 'cleepbackupdelay',126 'monitoring',127 'ssl',128 'auth',129 'rpcport',130 'crashreport',131 'needreboot',132 'devices',133 'enablepowerled',134 'enableactivityled'135 ],136 config.keys(),137 )138 def test_get_module_devices(self):139 self.init_session()140 devices = self.module.get_module_devices()141 logging.debug('Devices: %s' % devices)142 self.assertEqual(len(devices), 3)143 for device_uuid, device in devices.items():144 if device['type'] == 'monitor':145 self.assertEqual(146 sorted(['type', 'name', 'uptime', 'memory', 'cpu', 'uuid']),147 sorted(device.keys()),148 )149 break150 def test_on_event_need_restart(self):151 self.init_session()152 self.module.on_event({153 'event': 'system.cleep.needrestart',154 'params': {}155 })156 157 self.assertTrue(self.module._System__need_restart)158 def test_on_event_need_reboot(self):159 self.init_session()160 self.module._set_config_field = Mock()161 self.module.on_event({162 'event': 'system.device.needreboot',163 'params': {}164 })165 166 self.module._set_config_field.assert_called_with('needreboot', True)167 def test_on_event_backup_config(self):168 self.init_session()169 self.module.backup_cleep_config = Mock()170 self.module.on_event({171 'event': 'parameters.time.now',172 'params': {173 'minute': 5174 }175 })176 self.assertFalse(self.module.backup_cleep_config.called)177 self.module.on_event({178 'event': 'parameters.time.now',179 'params': {180 'minute': 15181 }182 })183 self.module.backup_cleep_config.assert_called()184 def test_set_monitoring(self):185 self.init_session()186 self.module._set_config_field = Mock(return_value=True)187 self.module.set_monitoring(True)188 189 self.module._set_config_field.assert_called_with('monitoring', True)190 def test_set_monitoring_failed(self):191 self.init_session()192 self.module._set_config_field = Mock(return_value=False)193 with self.assertRaises(CommandError) as cm:194 self.module.set_monitoring(True)195 self.assertEqual(str(cm.exception), 'Unable to save configuration')196 197 def test_set_monitoring_exception(self):198 self.init_session()199 with self.assertRaises(MissingParameter) as cm:200 self.module.set_monitoring(None)201 self.assertEqual(str(cm.exception), 'Parameter "monitoring" is missing')202 with self.assertRaises(InvalidParameter) as cm:203 self.module.set_monitoring('ola')204 self.assertEqual(str(cm.exception), 'Parameter "monitoring" must be of type "bool"')205 def test_get_monitoring(self):206 self.init_session()207 self.module._get_config_field = Mock(return_value=True)208 self.assertTrue(self.module.get_monitoring())209 @patch('backend.system.Console')210 def test_reboot_device(self, mock_console):211 self.init_session()212 self.module.backup_cleep_config = Mock()213 self.module.reboot_device(delay=10.0)214 215 self.module.backup_cleep_config.assert_called()216 mock_console.return_value.command_delayed.assert_called_with('reboot', 10.0)217 self.assertTrue(self.session.event_called('system.device.reboot'))218 @patch('backend.system.Console')219 def test_poweroff_device(self, mock_console):220 self.init_session()221 self.module.backup_cleep_config = Mock()222 self.module.poweroff_device(delay=10.0)223 224 self.module.backup_cleep_config.assert_called()225 mock_console.return_value.command_delayed.assert_called_with('poweroff', 10.0)226 self.assertTrue(self.session.event_called('system.device.poweroff'))227 @patch('backend.system.Console')228 def test_restart_cleep(self, mock_console):229 self.init_session()230 self.module.backup_cleep_config = Mock()231 self.module.restart_cleep(delay=10.0)232 233 self.module.backup_cleep_config.assert_called()234 mock_console.return_value.command_delayed.assert_called_with('/etc/cleep/cleephelper.sh restart', 10.0)235 self.assertTrue(self.session.event_called('system.cleep.restart'))236 def test_get_memory_usage(self):237 self.init_session()238 usage = self.module.get_memory_usage()239 logging.debug('Usage: %s' % usage)240 self.assertEqual(usage, {241 'total': 512,242 'cleep': 400,243 'available': 256,244 'availablehr': '256B',245 })246 def test_get_cpu_usage(self):247 self.init_session()248 usage = self.module.get_cpu_usage()249 logging.debug('Cpu usage: %s' % usage)250 self.assertEqual(sorted(['system', 'cleep']), sorted(usage.keys()))251 self.assertEqual(usage['system'], 100)252 self.assertEqual(usage['cleep'], 100)253 @patch('time.time', Mock(return_value=1602175845.2728713))254 def test_get_uptime(self):255 self.init_session()256 uptime = self.module.get_uptime()257 logging.debug('Uptime: %s' % uptime)258 self.assertEqual(sorted(['uptime', 'uptimehr']), sorted(uptime.keys()))259 self.assertEqual(uptime['uptime'], 300)260 self.assertEqual(uptime['uptimehr'], '0d 0h 5m')261 def test_monitoring_cpu_task_enabled(self):262 self.init_session()263 self.module._get_config_field = Mock(return_value=True)264 self.module._monitoring_cpu_task()265 266 self.assertTrue(self.session.event_called('system.monitoring.cpu'))267 def test_monitoring_cpu_task_disabled(self):268 self.init_session()269 self.module._get_config_field = Mock(return_value=False)270 self.module._monitoring_cpu_task()271 272 self.assertFalse(self.session.event_called('system.monitoring.cpu'))273 def test_monitoring_memory_task_enabled(self):274 self.init_session()275 self.module._get_config_field = Mock(return_value=True)276 self.module.get_memory_usage = Mock(return_value={277 'total': 512,278 'available': 256,279 })280 self.module._monitoring_memory_task()281 self.assertFalse(self.session.event_called('system.alert.memory'))282 self.assertTrue(self.session.event_called('system.monitoring.memory'))283 def test_monitoring_memory_task_disabled(self):284 self.init_session()285 self.module._get_config_field = Mock(return_value=False)286 self.module.get_memory_usage = Mock(return_value={287 'total': 512,288 'available': 256,289 })290 self.module._monitoring_memory_task()291 self.assertFalse(self.session.event_called('system.alert.memory'))292 self.assertFalse(self.session.event_called('system.monitoring.memory'))293 def test_monitoring_memory_send_alert(self):294 self.init_session()295 self.module._get_config_field = Mock(return_value=True)296 self.module.get_memory_usage = Mock(return_value={297 'total': 500,298 'available': 50,299 })300 self.module._monitoring_memory_task()301 self.assertTrue(self.session.event_called('system.alert.memory'))302 logging.debug('Event params: %s' % self.session.get_last_event_params('system.alert.memory'))303 self.assertTrue(self.session.event_called_with('system.alert.memory', {'percent': 90.0, 'threshold': 80.0}))304 @patch('os.path.exists', Mock(return_value=True))305 @patch('backend.system.datetime')306 @patch('backend.system.ZipFile')307 def test_download_logs(self, mock_zipfile, mock_datetime):308 mock_datetime.now = Mock(return_value=Datetime())309 self.init_session()310 logs = self.module.download_logs()311 logging.debug('Logs: %s' % logs)312 self.assertEqual(logs['filename'], 'cleep_20101010_101010.zip')313 mock_zipfile.return_value.write.assert_called_with(session.AnyArg(), 'cleep.log')314 mock_zipfile.return_value.close.assert_called()315 def test_download_logs_exception(self):316 self.init_session()317 with patch('os.path.exists') as mock_path_exists:318 mock_path_exists.return_value = False319 with self.assertRaises(CommandError) as cm:320 self.module.download_logs()321 self.assertEqual(str(cm.exception), 'Logs file doesn\'t exist')322 def test_get_logs(self):323 self.init_session()324 lines = ['line1', 'line2']325 self.session.cleep_filesystem.read_data = Mock(return_value=lines)326 with patch('os.path.exists') as mock_path_exists:327 mock_path_exists.return_value = True328 logs = self.module.get_logs()329 logging.debug('Logs: %s' % logs)330 331 self.assertEqual(logs, lines)332 def test_get_logs_not_exist(self):333 self.init_session()334 lines = ['line1', 'line2']335 self.session.cleep_filesystem.read_data = Mock(return_value=lines)336 with patch('os.path.exists') as mock_path_exists:337 mock_path_exists.return_value = False338 logs = self.module.get_logs()339 logging.debug('Logs: %s' % logs)340 341 self.assertEqual(logs, [])342 def test_clear_logs(self):343 self.init_session()344 with patch('os.path.exists') as mock_path_exists:345 mock_path_exists.return_value = True346 self.module.clear_logs()347 348 self.session.cleep_filesystem.write_data.assert_called_with('/tmp/cleep.log', '')349 def test_clear_logs_not_exist(self):350 self.init_session()351 with patch('os.path.exists') as mock_path_exists:352 mock_path_exists.return_value = False353 self.module.clear_logs()354 355 self.assertFalse(self.session.cleep_filesystem.write_data.called)356 def test_set_trace_enabled(self):357 self.init_session()358 self.module.set_trace(True)359 self.assertTrue(mock_cleepconf.return_value.enable_trace.called)360 self.assertFalse(mock_cleepconf.return_value.disable_trace.called)361 self.assertTrue(self.module._System__need_restart)362 self.assertTrue(self.session.event_called('system.cleep.needrestart'))363 def test_set_trace_disabled(self):364 self.init_session()365 self.module.set_trace(False)366 self.assertFalse(mock_cleepconf.return_value.enable_trace.called)367 self.assertTrue(mock_cleepconf.return_value.disable_trace.called)368 self.assertTrue(self.module._System__need_restart)369 self.assertTrue(self.session.event_called('system.cleep.needrestart'))370 def test_set_trace_exception(self):371 self.init_session()372 with self.assertRaises(MissingParameter) as cm:373 self.module.set_trace(None)374 self.assertEqual(str(cm.exception), 'Parameter "trace" is missing')375 with self.assertRaises(InvalidParameter) as cm:376 self.module.set_trace('hello')377 self.assertEqual(str(cm.exception), 'Parameter "trace" must be of type "bool"')378 def test_set_core_debug_enabled(self):379 self.init_session()380 self.module.set_core_debug(True)381 self.assertTrue(mock_cleepconf.return_value.enable_core_debug.called)382 self.assertFalse(mock_cleepconf.return_value.disable_core_debug.called)383 def test_set_core_debug_disabled(self):384 self.init_session()385 self.module.set_core_debug(False)386 self.assertFalse(mock_cleepconf.return_value.enable_core_debug.called)387 self.assertTrue(mock_cleepconf.return_value.disable_core_debug.called)388 def test_set_core_debug_exception(self):389 self.init_session()390 with self.assertRaises(MissingParameter) as cm:391 self.module.set_core_debug(None)392 self.assertEqual(str(cm.exception), 'Parameter "debug" is missing')393 with self.assertRaises(InvalidParameter) as cm:394 self.module.set_core_debug('hello')395 self.assertEqual(str(cm.exception), 'Parameter "debug" must be of type "bool"')396 def test_set_module_debug_enable(self):397 self.init_session()398 self.session.add_mock_command(self.session.make_mock_command('set_debug'))399 self.session.add_mock_command(self.session.make_mock_command('set_rpc_debug'))400 self.module.set_module_debug('dummy', True)401 mock_cleepconf.return_value.enable_module_debug.assert_called_with('dummy')402 self.assertFalse(mock_cleepconf.return_value.disable_module_debug.called)403 self.assertTrue(self.session.command_called_with('set_debug', to='dummy', params={'debug': True}))404 self.assertFalse(self.session.command_call_count('set_rpc_debug'), 0)405 def test_set_module_debug_disable(self):406 self.init_session()407 self.session.add_mock_command(self.session.make_mock_command('set_debug'))408 self.session.add_mock_command(self.session.make_mock_command('set_rpc_debug'))409 self.module.set_module_debug('dummy', False)410 self.assertFalse(mock_cleepconf.return_value.enable_module_debug.called)411 mock_cleepconf.return_value.disable_module_debug.assert_called_with('dummy')412 self.assertTrue(self.session.command_called_with('set_debug', to='dummy', params={'debug': False}))413 self.assertFalse(self.session.command_call_count('set_rpc_debug'), 0)414 def test_set_module_debug_rpc_enable(self):415 self.init_session()416 self.session.add_mock_command(self.session.make_mock_command('set_debug'))417 self.session.add_mock_command(self.session.make_mock_command('set_rpc_debug'))418 self.module.set_module_debug('rpc', True)419 mock_cleepconf.return_value.enable_module_debug.assert_called_with('rpc')420 self.assertFalse(mock_cleepconf.return_value.disable_module_debug.called)421 self.assertTrue(self.session.command_called_with('set_rpc_debug', to='inventory', params={'debug': True}))422 self.assertFalse(self.session.command_call_count('set_debug'), 0)423 def test_set_module_debug_rpc_disable(self):424 self.init_session()425 self.session.add_mock_command(self.session.make_mock_command('set_debug'))426 self.session.add_mock_command(self.session.make_mock_command('set_rpc_debug'))427 self.module.set_module_debug('rpc', False)428 self.assertFalse(mock_cleepconf.return_value.enable_module_debug.called)429 mock_cleepconf.return_value.disable_module_debug.assert_called_with('rpc')430 self.assertTrue(self.session.command_called_with('set_rpc_debug', to='inventory', params={'debug': False}))431 self.assertFalse(self.session.command_call_count('set_debug'), 0)432 def test_set_module_debug_exception(self):433 self.init_session()434 self.session.add_mock_command(self.session.make_mock_command('set_debug', fail=True))435 self.session.add_mock_command(self.session.make_mock_command('set_rpc_debug', fail=True))436 437 with self.assertRaises(MissingParameter) as cm:438 self.module.set_module_debug(None, True)439 self.assertEqual(str(cm.exception), 'Parameter "module_name" is missing')440 with self.assertRaises(MissingParameter) as cm:441 self.module.set_module_debug('dummy', None)442 self.assertEqual(str(cm.exception), 'Parameter "debug" is missing')443 with self.assertRaises(InvalidParameter) as cm:444 self.module.set_module_debug(True, True)445 self.assertEqual(str(cm.exception), 'Parameter "module_name" must be of type "str"')446 with self.assertRaises(InvalidParameter) as cm:447 self.module.set_module_debug('dummy', 'hello')448 self.assertEqual(str(cm.exception), 'Parameter "debug" must be of type "bool"')449 with self.assertRaises(CommandError) as cm:450 self.module.set_module_debug('dummy', True)451 self.assertEqual(str(cm.exception), 'Update debug failed')452 with self.assertRaises(CommandError) as cm:453 self.module.set_module_debug('rpc', True)454 self.assertEqual(str(cm.exception), 'Update debug failed')455 #self.session.add_mock_command(self.session.make_mock_command('set_debug', data=None))456 #self.session.add_mock_command(self.session.make_mock_command('set_rpc_debug', data=None))457 self.session.set_mock_command_no_response('set_debug')458 with self.assertRaises(CommandError) as cm:459 self.module.set_module_debug('dummy', True)460 self.assertEqual(str(cm.exception), 'Update debug failed')461 self.session.set_mock_command_no_response('set_rpc_debug')462 with self.assertRaises(CommandError) as cm:463 self.module.set_module_debug('rpc', True)464 self.assertEqual(str(cm.exception), 'Update debug failed')465 def test_set_not_renderable_events(self):466 self.init_session()467 self.module.get_not_renderable_events = Mock(return_value=[{468 'renderer': 'renderer1',469 'event': 'event1'470 }, {471 'renderer': 'renderer2',472 'event': 'event2'473 }])474 mock_event1 = Mock()475 mock_event2 = Mock()476 self.module.events_broker.get_event_instance = Mock(side_effect=[mock_event1, mock_event2])477 self.module._set_not_renderable_events()478 mock_event1.set_renderable.assert_called_with('renderer1', False)479 mock_event2.set_renderable.assert_called_with('renderer2', False)480 def test_set_not_renderable_events_delete_unexisting_event(self):481 self.init_session()482 self.module._get_config_field = Mock(return_value=['renderer1__event1', 'renderer2__event2'])483 self.module._set_config_field = Mock()484 self.module.get_not_renderable_events = Mock(return_value=[{485 'renderer': 'renderer1',486 'event': 'event1'487 }, {488 'renderer': 'renderer2',489 'event': 'event2'490 }])491 mock_event1 = Mock()492 self.module.events_broker.get_event_instance = Mock(side_effect=[mock_event1, Exception('Test exception')])493 self.module._set_not_renderable_events()494 mock_event1.set_renderable.assert_called_with('renderer1', False)495 self.module._set_config_field.assert_called_with('eventsnotrenderable', ['renderer1__event1'])496 def test_set_not_renderable_events_delete_edge_case_duplicated_event_in_conf(self):497 self.init_session()498 self.module._get_config_field = Mock(return_value=['renderer1__event1', 'renderer1__event1'])499 self.module._set_config_field = Mock()500 self.module.get_not_renderable_events = Mock(return_value=[{501 'renderer': 'renderer1',502 'event': 'event1'503 }])504 self.module.events_broker.get_event_instance = Mock(side_effect=Exception('Test exception'))505 self.module._set_not_renderable_events()506 self.module._set_config_field.assert_called_with('eventsnotrenderable', ['renderer1__event1'])507 self.assertEqual(self.module._set_config_field.call_count, 1)508 def test_set_event_renderable(self):509 self.init_session()510 self.module._get_config_field = Mock(return_value=['renderer1%sevent1' % self.module.EVENT_SEPARATOR])511 self.module._set_config_field = Mock(return_value=True)512 self.module.events_broker = Mock()513 514 result = self.module.set_event_renderable('renderer1', 'event1', True)515 logging.debug('Not renderable events: %s' % result)516 self.assertEqual(result, [])517 self.module._get_config_field.assert_called_with('eventsnotrenderable')518 self.module._set_config_field.assert_called_with('eventsnotrenderable', [])519 self.module.events_broker.set_event_renderable.assert_called_with('event1', 'renderer1', True)520 def test_set_event_renderable_not_renderable(self):521 self.init_session()522 self.module._get_config_field = Mock(return_value=[])523 self.module._set_config_field = Mock(return_value=True)524 self.module.events_broker = Mock()525 526 result = self.module.set_event_renderable('renderer1', 'event1', False)527 logging.debug('Not renderable events: %s' % result)528 self.assertEqual(result, [{'renderer': 'renderer1', 'event': 'event1'}])529 self.module._get_config_field.assert_called_with('eventsnotrenderable')530 self.module._set_config_field.assert_called_with('eventsnotrenderable', ['renderer1%sevent1' % self.module.EVENT_SEPARATOR])531 self.module.events_broker.set_event_renderable.assert_called_with('event1', 'renderer1', False)532 def test_set_event_renderable_already_not_renderable(self):533 self.init_session()534 self.module.events_broker = Mock()535 self.module._get_config_field = Mock(return_value=['renderer1%sevent1' % self.module.EVENT_SEPARATOR])536 self.module._set_config_field = Mock(return_value=True)537 538 result = self.module.set_event_renderable('renderer1', 'event1', False)539 logging.debug('Not renderable events: %s' % result)540 self.assertEqual(result, [{'renderer': 'renderer1', 'event': 'event1'}])541 self.module._get_config_field.assert_called_with('eventsnotrenderable')542 self.module._set_config_field.assert_called_with('eventsnotrenderable', ['renderer1%sevent1' % self.module.EVENT_SEPARATOR])543 self.module.events_broker.set_event_renderable.assert_called_with('event1', 'renderer1', False)544 def test_set_event_renderable_unable_to_save_config(self):545 self.init_session()546 mock_event = Mock()547 self.module.events_broker.get_event_instance = Mock(return_value=mock_event)548 self.module._get_config_field = Mock(return_value=[])549 self.module._set_config_field = Mock(return_value=False)550 551 with self.assertRaises(CommandError) as cm:552 self.module.set_event_renderable('renderer1', 'event1', True)553 self.assertEqual(str(cm.exception), 'Unable to save configuration')554 self.assertFalse(mock_event.set_renderable.called)555 def test_set_event_renderable_exception(self):556 self.init_session()557 with self.assertRaises(MissingParameter) as cm:558 self.module.set_event_renderable(None, 'event1', True)559 self.assertEqual(str(cm.exception), 'Parameter "renderer_name" is missing')560 with self.assertRaises(MissingParameter) as cm:561 self.module.set_event_renderable('renderer1', None, True)562 self.assertEqual(str(cm.exception), 'Parameter "event_name" is missing')563 with self.assertRaises(MissingParameter) as cm:564 self.module.set_event_renderable('renderer1', 'event1', None)565 self.assertEqual(str(cm.exception), 'Parameter "renderable" is missing')566 with self.assertRaises(InvalidParameter) as cm:567 self.module.set_event_renderable(123, 'event1', True)568 self.assertEqual(str(cm.exception), 'Parameter "renderer_name" must be of type "str"')569 with self.assertRaises(InvalidParameter) as cm:570 self.module.set_event_renderable('renderer1', True, True)571 self.assertEqual(str(cm.exception), 'Parameter "event_name" must be of type "str"')572 with self.assertRaises(InvalidParameter) as cm:573 self.module.set_event_renderable('renderer1', 'event1', 'true')574 self.assertEqual(str(cm.exception), 'Parameter "renderable" must be of type "bool"')575 def test_get_renderable_events(self):576 self.init_session()577 self.module._get_config_field = Mock(return_value=['renderer1__event1', 'renderer2__event3', 'renderer1__event2'])578 events = self.module.get_not_renderable_events()579 logging.debug('Events: %s' % events)580 581 self.assertEqual(events, [582 { 'renderer': 'renderer1', 'event': 'event1' },583 { 'renderer': 'renderer2', 'event': 'event3' },584 { 'renderer': 'renderer1', 'event': 'event2' },585 ])586 def test_set_crash_report(self):587 self.init_session()588 self.module.crash_report = Mock()589 self.module._set_config_field = Mock()590 591 self.module.set_crash_report(True)592 self.module.crash_report.enable.assert_called()593 self.assertFalse(self.module.crash_report.disable.called)594 self.module._set_config_field.assert_called_with('crashreport', True)595 self.module.crash_report.reset_mock()596 self.module.set_crash_report(False)597 self.module.crash_report.disable.assert_called()598 self.assertFalse(self.module.crash_report.enable.called)599 self.module._set_config_field.assert_called_with('crashreport', False)600 def test_set_crash_report_failed(self):601 self.init_session()602 self.module._set_config_field = Mock(return_value=False)603 604 with self.assertRaises(CommandError) as cm:605 self.module.set_crash_report(True)606 self.assertEqual(str(cm.exception), 'Unable to save crash report value')607 def test_set_crash_report_exception(self):608 self.init_session()609 610 with self.assertRaises(MissingParameter) as cm:611 self.module.set_crash_report(None)612 self.assertEqual(str(cm.exception), 'Parameter "enable" is missing')613 with self.assertRaises(InvalidParameter) as cm:614 self.module.set_crash_report('hello')615 self.assertEqual(str(cm.exception), 'Parameter "enable" must be of type "bool"')616 def test_backup_cleep_config(self):617 self.init_session()618 self.module.cleep_backup = Mock()619 self.module.backup_cleep_config()620 self.module.cleep_backup.backup.assert_called()621 def test_set_cleep_backup_delay(self):622 self.init_session()623 self.module._set_config_field = Mock(return_value=True)624 self.module.set_cleep_backup_delay(5)625 self.assertEqual(self.module.cleep_backup_delay, 5)626 self.module.set_cleep_backup_delay(120)627 self.assertEqual(self.module.cleep_backup_delay, 120)628 self.module._set_config_field = Mock(return_value=False)629 self.module.set_cleep_backup_delay(15)630 self.assertEqual(self.module.cleep_backup_delay, 120)631 def test_set_cleep_backup_delay_exception(self):632 self.init_session()633 with self.assertRaises(MissingParameter) as cm:634 self.module.set_cleep_backup_delay(None)635 self.assertEqual(str(cm.exception), 'Parameter "delay" is missing')636 with self.assertRaises(InvalidParameter) as cm:637 self.module.set_cleep_backup_delay(True)638 self.assertEqual(str(cm.exception), 'Parameter "delay" is invalid (specified="True")')639 with self.assertRaises(InvalidParameter) as cm:640 self.module.set_cleep_backup_delay(4)641 self.assertEqual(str(cm.exception), 'Parameter "delay" is invalid (specified="4")')642 with self.assertRaises(InvalidParameter) as cm:643 self.module.set_cleep_backup_delay(121)644 self.assertEqual(str(cm.exception), 'Parameter "delay" is invalid (specified="121")')645 def test_install_driver_terminated_success_no_reboot_required(self):646 self.init_session()647 self.module.reboot_device = Mock()648 self.module.drivers = Mock()649 self.module.drivers.get_driver.return_value = DummyDriver(False)650 self.module._install_driver_terminated('dummy', 'dummy-driver', True, '')651 self.assertTrue(self.session.event_called_with('system.driver.install', {652 'drivertype': 'dummy',653 'drivername': 'dummy-driver',654 'installing': False,655 'success': True,656 'message': '',657 }))658 self.assertFalse(self.module.reboot_device.called)659 self.assertTrue(self.module.drivers.get_driver.called)660 def test_install_driver_terminated_success_reboot_required(self):661 self.init_session()662 self.module.reboot_device = Mock()663 self.module.drivers = Mock()664 self.module.drivers.get_driver.return_value = DummyDriver(True)665 self.module._install_driver_terminated('dummy', 'dummy-driver', True, '')666 self.assertTrue(self.session.event_called_with('system.driver.install', {667 'drivertype': 'dummy',668 'drivername': 'dummy-driver',669 'installing': False,670 'success': True,671 'message': '',672 }))673 self.assertTrue(self.module.reboot_device.called)674 self.assertTrue(self.module.drivers.get_driver.called)675 def test_install_driver_terminated_failure(self):676 self.init_session()677 self.module.reboot_device = Mock()678 self.module.drivers = Mock()679 self.module._install_driver_terminated('dummy', 'dummy-driver', False, 'error occured')680 self.assertTrue(self.session.event_called_with('system.driver.install', {681 'drivertype': 'dummy',682 'drivername': 'dummy-driver',683 'installing': False,684 'success': False,685 'message': 'error occured',686 }))687 self.assertFalse(self.module.reboot_device.called)688 self.assertFalse(self.module.drivers.get_driver.called)689 def test_install_driver(self):690 self.init_session()691 driver = Mock()692 driver.is_installed = Mock(return_value=False)693 self.module.drivers.get_driver = Mock(return_value=driver)694 self.module.install_driver('dummy', 'dummy-driver')695 driver.install.assert_called()696 self.session.event_called_with('system.driver.install', {697 'drivertype': 'dummy',698 'drivername': 'dummy-driver',699 'installing': True,700 'success': None,701 'message': None,702 })703 def test_install_driver_already_installed(self):704 self.init_session()705 driver = Mock()706 driver.is_installed = Mock(return_value=True)707 self.module.drivers.get_driver = Mock(return_value=driver)708 with self.assertRaises(CommandInfo) as cm:709 self.module.install_driver('dummy', 'dummy-driver')710 self.assertEqual(str(cm.exception), 'Driver is already installed')711 def test_install_driver_exception(self):712 self.init_session()713 self.module.drivers.get_driver = Mock(return_value=None)714 with self.assertRaises(InvalidParameter) as cm:715 self.module.install_driver('dummy', 'dummy-driver')716 self.assertEqual(str(cm.exception), 'No driver found for specified parameters')717 with self.assertRaises(MissingParameter) as cm:718 self.module.install_driver(None, 'dummy-driver')719 self.assertEqual(str(cm.exception), 'Parameter "driver_type" is missing')720 with self.assertRaises(InvalidParameter) as cm:721 self.module.install_driver(123, 'dummy-driver')722 self.assertEqual(str(cm.exception), 'Parameter "driver_type" must be of type "str"')723 with self.assertRaises(InvalidParameter) as cm:724 self.module.install_driver('', 'dummy-driver')725 self.assertEqual(str(cm.exception), 'Parameter "driver_type" is invalid (specified="")')726 with self.assertRaises(MissingParameter) as cm:727 self.module.install_driver('dummy', None)728 self.assertEqual(str(cm.exception), 'Parameter "driver_name" is missing')729 with self.assertRaises(InvalidParameter) as cm:730 self.module.install_driver('dummy', 123)731 self.assertEqual(str(cm.exception), 'Parameter "driver_name" must be of type "str"')732 with self.assertRaises(InvalidParameter) as cm:733 self.module.install_driver('dummy', '')734 self.assertEqual(str(cm.exception), 'Parameter "driver_name" is invalid (specified="")')735 def test_uninstall_driver_terminated_success_no_reboot_required(self):736 self.init_session()737 self.module.reboot_device = Mock()738 self.module.drivers = Mock()739 self.module.drivers.get_driver.return_value = DummyDriver(False)740 self.module._uninstall_driver_terminated('dummy', 'dummy-driver', True, '')741 self.assertTrue(self.session.event_called_with('system.driver.uninstall', {742 'drivertype': 'dummy',743 'drivername': 'dummy-driver',744 'uninstalling': False,745 'success': True,746 'message': '',747 }))748 self.assertFalse(self.module.reboot_device.called)749 self.assertTrue(self.module.drivers.get_driver.called)750 def test_uninstall_driver_terminated_success_reboot_required(self):751 self.init_session()752 self.module.reboot_device = Mock()753 self.module.drivers = Mock()754 self.module.drivers.get_driver.return_value = DummyDriver(True)755 self.module._uninstall_driver_terminated('dummy', 'dummy-driver', True, '')756 self.assertTrue(self.session.event_called_with('system.driver.uninstall', {757 'drivertype': 'dummy',758 'drivername': 'dummy-driver',759 'uninstalling': False,760 'success': True,761 'message': '',762 }))763 self.assertTrue(self.module.reboot_device.called)764 self.assertTrue(self.module.drivers.get_driver.called)765 def test_uninstall_driver_terminated_failure(self):766 self.init_session()767 self.module.reboot_device = Mock()768 self.module._uninstall_driver_terminated('dummy', 'dummy-driver', False, 'error occured')769 self.assertTrue(self.session.event_called_with('system.driver.uninstall', {770 'drivertype': 'dummy',771 'drivername': 'dummy-driver',772 'uninstalling': False,773 'success': False,774 'message': 'error occured',775 }))776 self.assertFalse(self.module.reboot_device.called)777 def test_uninstall_driver(self):778 self.init_session()779 driver = Mock()780 driver.is_installed = Mock(return_value=True)781 self.module.drivers.get_driver = Mock(return_value=driver)782 self.module.uninstall_driver('dummy', 'dummy-driver')783 driver.uninstall.assert_called()784 self.session.event_called_with('system.driver.uninstall', {785 'drivertype': 'dummy',786 'drivername': 'dummy-driver',787 'uninstalling': True,788 'success': None,789 'message': None,790 })791 def test_uninstall_driver_already_uninstalled(self):792 self.init_session()793 driver = Mock()794 driver.is_installed = Mock(return_value=False)795 self.module.drivers.get_driver = Mock(return_value=driver)796 with self.assertRaises(CommandInfo) as cm:797 self.module.uninstall_driver('dummy', 'dummy-driver')798 self.assertEqual(str(cm.exception), 'Driver is not installed')799 def test_uninstall_driver_exception(self):800 self.init_session()801 self.module.drivers.get_driver = Mock(return_value=None)802 with self.assertRaises(InvalidParameter) as cm:803 self.module.uninstall_driver('dummy', 'dummy-driver')804 self.assertEqual(str(cm.exception), 'No driver found for specified parameters')805 with self.assertRaises(MissingParameter) as cm:806 self.module.uninstall_driver(None, 'dummy-driver')807 self.assertEqual(str(cm.exception), 'Parameter "driver_type" is missing')808 with self.assertRaises(InvalidParameter) as cm:809 self.module.uninstall_driver(123, 'dummy-driver')810 self.assertEqual(str(cm.exception), 'Parameter "driver_type" must be of type "str"')811 with self.assertRaises(InvalidParameter) as cm:812 self.module.uninstall_driver('', 'dummy-driver')813 self.assertEqual(str(cm.exception), 'Parameter "driver_type" is invalid (specified="")')814 with self.assertRaises(MissingParameter) as cm:815 self.module.uninstall_driver('dummy', None)816 self.assertEqual(str(cm.exception), 'Parameter "driver_name" is missing')817 with self.assertRaises(InvalidParameter) as cm:818 self.module.uninstall_driver('dummy', 123)819 self.assertEqual(str(cm.exception), 'Parameter "driver_name" must be of type "str"')820 with self.assertRaises(InvalidParameter) as cm:821 self.module.uninstall_driver('dummy', '')822 self.assertEqual(str(cm.exception), 'Parameter "driver_name" is invalid (specified="")')823 def test_apply_tweaks(self):824 self.init_session()825 self.module.tweak_power_led = Mock()826 self.module.tweak_activity_led = Mock()827 self.module._get_config_field = Mock(side_effect=[True, True])828 self.module._System__apply_tweaks()829 self.module.tweak_power_led.assert_called()830 self.module.tweak_activity_led.assert_called()831 @patch('backend.system.Console')832 def test_tweak_power_led_turn_on(self, mock_console):833 self.init_session()834 self.module._set_config_field = Mock()835 mock_console.return_value.command.return_value = { 'returncode': 0 }836 self.module.tweak_power_led(True)837 self.module._set_config_field.assert_called_with('enablepowerled', True)838 mock_console.return_value.command.assert_called_with(session.PatternArg('.*echo 1.*'))839 @patch('backend.system.Console')840 def test_tweak_power_led_turn_off(self, mock_console):841 self.init_session()842 self.module._set_config_field = Mock()843 mock_console.return_value.command.return_value = { 'returncode': 0 }844 self.module.tweak_power_led(False)845 self.module._set_config_field.assert_called_with('enablepowerled', False)846 mock_console.return_value.command.assert_called_with(session.PatternArg('.*echo 0.*'))847 @patch('backend.system.Console')848 def test_tweak_power_led_failed(self, mock_console):849 self.init_session()850 self.module._set_config_field = Mock()851 mock_console.return_value.command.return_value = { 'returncode': 1 }852 with self.assertRaises(CommandError) as cm:853 self.module.tweak_power_led(True)854 self.assertEqual(str(cm.exception), 'Error tweaking power led')855 self.assertFalse(self.module._set_config_field.called)856 def test_tweak_power_led_no_file(self):857 self.init_session()858 self.module._set_config_field = Mock()859 with patch('backend.system.Console') as mock_console:860 with patch('os.path.exists', Mock(return_value=False)):861 self.module.tweak_power_led(True)862 self.assertFalse(self.module._set_config_field.called)863 self.assertFalse(mock_console.return_value.command.called)864 @patch('backend.system.Console')865 def test_tweak_activity_led_turn_on(self, mock_console):866 self.init_session()867 self.module._set_config_field = Mock()868 mock_console.return_value.command.return_value = { 'returncode': 0 }869 self.module.tweak_activity_led(True)870 self.module._set_config_field.assert_called_with('enableactivityled', True)871 mock_console.return_value.command.assert_called_with(session.PatternArg('.*echo 1.*'))872 @patch('backend.system.Console')873 def test_tweak_activity_led_turn_off(self, mock_console):874 self.init_session()875 self.module._set_config_field = Mock()876 mock_console.return_value.command.return_value = { 'returncode': 0 }877 self.module.tweak_activity_led(False)878 self.module._set_config_field.assert_called_with('enableactivityled', False)879 mock_console.return_value.command.assert_called_with(session.PatternArg('.*echo 0.*'))880 @patch('backend.system.Console')881 def test_tweak_activity_led_failed(self, mock_console):882 self.init_session()883 self.module._set_config_field = Mock()884 mock_console.return_value.command.return_value = { 'returncode': 1 }885 with self.assertRaises(CommandError) as cm:886 self.module.tweak_activity_led(True)887 self.assertEqual(str(cm.exception), 'Error tweaking activity led')888 self.assertFalse(self.module._set_config_field.called)889 def test_tweak_activity_led_no_file(self):890 self.init_session()891 self.module._set_config_field = Mock()892 with patch('backend.system.Console') as mock_console:893 with patch('os.path.exists', Mock(return_value=False)):894 self.module.tweak_activity_led(True)895 self.assertFalse(self.module._set_config_field.called)896 self.assertFalse(mock_console.return_value.command.called)897if __name__ == '__main__':898 # coverage run --omit="*lib/python*/*","test_*" --concurrency=thread test_system.py; coverage report -m -i899 unittest.main()...
test_core.py
Source:test_core.py
1import os2from loguru import logger3from mytest_api.httpbin import *4from .conftest import *5logger.add('../log/log_{time}.log', rotation='500 MB')6logger.debug('this is the debug message')7def test_version():8 from mytest_api import __version__9 assert isinstance(__version__, str)10def test_httpbin_get(init_session):11 TestHttpbinGet().run(init_session) \12 .validate("status_code", 200) \13 .validate("headers.server", "gunicorn/19.9.0") \14 .validate("json().headers.Host", "www.httpbin.org")15def test_httpbin_get_with_params(init_session):16 TestHttpbinGet() \17 .set_params(abc=123, xyz=456) \18 .run(init_session) \19 .validate("status_code", 200)20def test_httpbin_post(init_session):21 TestHttpbinPost() \22 .set_data({"abc": 123}) \23 .run(init_session) \24 .validate("status_code", 200)25def test_httpbin_with_params_share(init_session):26 user_id = "my123"27 TestHttpbinGet() \28 .set_params(user_id=user_id) \29 .run(init_session) \30 .validate("status_code", 200) \31 .validate("headers.server", "gunicorn/19.9.0") \32 .validate("json().headers.Host", "www.httpbin.org") \33 .validate("json().url",34 "http://www.httpbin.org/get?user_id={}".format(user_id))35 TestHttpbinPost() \36 .set_json({"user_id": user_id}) \37 .run(init_session) \38 .validate("status_code", 200) \39 .validate("headers.server", "gunicorn/19.9.0") \40 .validate("json().url", "http://www.httpbin.org/post?abc=123") \41 .validate("json().headers.Accept", 'application/json') \42 .validate("json().json.user_id", "my123")43def test_httpbin_extract(init_session):44 api_run = TestHttpbinGet().run(init_session)45 status_code = api_run.extract("status_code")46 assert status_code == 20047 server = api_run.extract("headers.server")48 assert server == "gunicorn/19.9.0"49 accept_type = api_run.extract("json().headers.Accept")50 assert accept_type == "application/json"51def test_httpbin_setcookies(init_session):52 api_run = TestHttpBinGetCookies() \53 .set_cookies("freeform1", "123") \54 .set_cookies("freeform2", "456") \55 .run(init_session)56 freeform1 = api_run.extract("json().cookies.freeform1")57 freeform2 = api_run.extract("json().cookies.freeform2")58 assert freeform1 == "123"59 assert freeform2 == "456"60def test_httpbin_extract_cookies(init_session):61 freeform = TestHttpBinGetCookies() \62 .set_cookies("freeform", "123") \63 .run(init_session) \64 .extract("json().cookies.freeform")65 TestHttpbinPost() \66 .set_json({"freeform": freeform}) \67 .run(init_session) \68 .validate("status_code", 200) \69 .validate("json().json.freeform", freeform)70def test_httpbin_login_status(init_session):71 logger.debug(init_session)72 73 # step1: login and get the cookies74 TestHttpBinSetCookies().set_params(freeform='567').run(init_session)75 # step2:76 resp = TestHttpbinPost() \77 .set_json({"abc": 123}) \78 .run(init_session) \79 .get_response()80 request_headers = resp.request.headers...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!