コード例 #1
0
    def _test_get_winrm_listeners_config(self,
                                         listeners_config=None,
                                         http_listener=None,
                                         https_listener=None):
        winrmconfig = importlib.import_module('cloudbaseinit.utils.'
                                              'windows.winrmconfig')
        mock_service = mock.MagicMock()
        mock_service.get_winrm_listeners_configuration.return_value = \
            listeners_config
        expected_result = listeners_config
        if listeners_config is None:
            expected_result = []
            if http_listener:
                expected_result.append(
                    {"protocol": winrmconfig.LISTENER_PROTOCOL_HTTP})
            if https_listener:
                expected_result.append(
                    {"protocol": winrmconfig.LISTENER_PROTOCOL_HTTPS})

        with testutils.ConfPatcher("winrm_configure_http_listener",
                                   http_listener):
            with testutils.ConfPatcher("winrm_configure_https_listener",
                                       https_listener):
                result = self._winrmlistener._get_winrm_listeners_config(
                    mock_service)

        self.assertEqual(result, expected_result)
コード例 #2
0
    def _test_preprocess_options(self, fail=False):
        if fail:
            with testutils.ConfPatcher("types", ["vfat", "ntfs"],
                                       group="config_drive"):
                with self.assertRaises(exception.CloudbaseInitException):
                    self._config_drive._preprocess_options()
            with testutils.ConfPatcher("locations", ["device"],
                                       group="config_drive"):
                with self.assertRaises(exception.CloudbaseInitException):
                    self._config_drive._preprocess_options()
            return

        options = {
            "raw_hdd": False,
            "cdrom": False,
            "vfat": True,
            # Deprecated options above.
            "types": ["vfat", "iso"],
            "locations": ["partition"]
        }
        contexts = [testutils.ConfPatcher(key, value, group="config_drive")
                    for key, value in options.items()]
        with contexts[0], contexts[1], contexts[2], \
                contexts[3], contexts[4]:
            self._config_drive._preprocess_options()
            self.assertEqual({"vfat", "iso"},
                             self._config_drive._searched_types)
            self.assertEqual({"hdd", "partition"},
                             self._config_drive._searched_locations)
コード例 #3
0
    def _test_get_ephemeral_disk_volume_by_mount_point(self, mount_point,
                                                       paths, exception_raise):
        mock_osutils = mock.MagicMock()
        eclass = exception.ItemNotFoundException
        if exception_raise:
            mock_osutils.get_volume_path_names_by_mount_point.side_effect = \
                eclass()
        else:
            mock_osutils.get_volume_path_names_by_mount_point.return_value = \
                paths

        with testutils.ConfPatcher('ephemeral_disk_volume_mount_point',
                                   mount_point):
            if exception_raise:
                with testutils.LogSnatcher(MODULE_PATH) as snatcher:
                    self._disk._get_ephemeral_disk_volume_by_mount_point(
                        mock_osutils)
                expected_logging = [
                    "Ephemeral disk mount point not found: %s" % mount_point
                ]
            else:
                result = None
                result = self._disk._get_ephemeral_disk_volume_by_mount_point(
                    mock_osutils)
        if mount_point:
            (mock_osutils.get_volume_path_names_by_mount_point.
             assert_called_once_with(str(mount_point)))
            if not exception_raise:
                if paths:
                    self.assertEqual(result, paths[0])
                else:
                    self.assertEqual(result, None)
            else:
                self.assertEqual(snatcher.output, expected_logging)
コード例 #4
0
    def _test_get_password(self, inject_password, generate_password):
        shared_data = {}
        reuse_password = not generate_password and not inject_password
        expected_password = '******'
        if reuse_password:
            # The password should be the one created by
            # CreateUser plugin.
            shared_data[constants.SHARED_DATA_PASSWORD] = (
                mock.sentinel.create_user_password)

        mock_service = mock.MagicMock()
        mock_osutils = mock.MagicMock()
        mock_service.get_admin_password.return_value = expected_password
        mock_osutils.generate_random_password.return_value = expected_password

        with testutils.ConfPatcher('inject_user_password', inject_password):
            response = self._setpassword_plugin._get_password(
                mock_service, mock_osutils, shared_data)
        if inject_password:
            mock_service.get_admin_password.assert_called_with()
        elif reuse_password:
            self.assertFalse(mock_service.get_admin_password.called)
            self.assertFalse(mock_osutils.generate_random_password.called)
            expected_password = mock.sentinel.create_user_password
        else:
            mock_osutils.get_maximum_password_length.assert_called_once_with()
            mock_osutils.generate_random_password.assert_called_once_with(
                mock_osutils.get_maximum_password_length())
        self.assertEqual(expected_password, response)
コード例 #5
0
    def _test_get_password(self, inject_password):
        shared_data = {}
        expected_password = '******'
        if not inject_password:
            # The password should be the one created by
            # CreateUser plugin.
            shared_data[constants.SHARED_DATA_PASSWORD] = (
                mock.sentinel.create_user_password)

        mock_service = mock.MagicMock()
        mock_service.get_admin_password.return_value = expected_password

        with testutils.LogSnatcher('cloudbaseinit.plugins.common.'
                                   'setuserpassword') as snatcher:
            with testutils.ConfPatcher('inject_user_password',
                                       inject_password):
                response = self._setpassword_plugin._get_password(
                    mock_service, shared_data)

        expected_logging = [
            'Using admin_pass metadata user password. '
            'Consider changing it as soon as possible'
        ]
        if inject_password:
            self.assertEqual(expected_logging, snatcher.output)
            mock_service.get_admin_password.assert_called_with()
            expected_password = (expected_password, True)
        else:
            self.assertFalse(mock_service.get_admin_password.called)
            expected_password = (mock.sentinel.create_user_password, False)

        self.assertEqual(expected_password, response)
コード例 #6
0
 def _test_get_page_file_volumes_by_mount_point(
         self,
         mount_points=None,
         paths=None,
         get_endpoint_side_effect=False):
     mock_osutils = mock.MagicMock()
     mock_get_volume = mock_osutils.get_volume_path_names_by_mount_point
     if get_endpoint_side_effect:
         mock_get_volume.side_effect = exception.ItemNotFoundException
     else:
         mock_get_volume.return_value = paths
     if not mount_points:
         res = self._pagefiles._get_page_file_volumes_by_mount_point(
             mock_osutils)
         self.assertEqual(res, [])
         return
     with testutils.ConfPatcher("page_file_volume_mount_points",
                                mount_points):
         if not paths:
             expected_logging = ("Mount point not found: %s" %
                                 mount_points[0])
             with self._logsnatcher:
                 res = (self._pagefiles.
                        _get_page_file_volumes_by_mount_point(mock_osutils))
             self.assertEqual(self._logsnatcher.output[0], expected_logging)
             return
         res = self._pagefiles._get_page_file_volumes_by_mount_point(
             mock_osutils)
         self.assertEqual(res, paths)
コード例 #7
0
    def _test_execute(self,
                      mock_create_cert,
                      mock_WinRMConfig,
                      mock_check_winrm_service,
                      mock_get_os_utils,
                      mock_get_winrm_listeners,
                      mock_check_restrictions,
                      mock_configure_listener,
                      service_status=True,
                      protocol=None,
                      listeners_config=True,
                      certificate_thumbprint=None):
        mock_winrm_config = mock.MagicMock()
        mock_WinRMConfig.return_value = mock_winrm_config
        mock_osutils = mock.MagicMock()
        mock_get_os_utils.return_value = mock_osutils
        mock_check_winrm_service.return_value = service_status
        if not service_status:
            expected_result = (base.PLUGIN_EXECUTE_ON_NEXT_BOOT, False)
        elif not listeners_config:
            mock_get_winrm_listeners.return_value = None
            expected_result = (base.PLUGIN_EXECUTION_DONE, False)
        else:
            expected_result = (base.PLUGIN_EXECUTION_DONE, False)
            if certificate_thumbprint is not None:
                certificate_thumbprint = \
                    str(mock.sentinel.certificate_thumbprint)
            listener_config = {
                "protocol": protocol,
                "certificate_thumbprint": certificate_thumbprint
            }
            mock_get_winrm_listeners.return_value = [listener_config]
        winrm_enable_basic_auth = mock.Mock(spec=bool)
        with testutils.ConfPatcher('winrm_enable_basic_auth',
                                   winrm_enable_basic_auth):
            result = self._winrmlistener.execute(mock.sentinel.service,
                                                 mock.sentinel.shared_data)

        self.assertEqual(result, expected_result)
        mock_get_os_utils.assert_called_once_with()
        mock_check_winrm_service.assert_called_once_with(mock_osutils)
        if service_status:
            mock_get_winrm_listeners.assert_called_once_with(
                mock.sentinel.service)
            if listeners_config:
                mock_check_restrictions.assert_called_once_with(mock_osutils)
                mock_WinRMConfig.assert_called_once_with()
                mock_winrm_config.set_auth_config.assert_called_once_with(
                    basic=winrm_enable_basic_auth)
                winrmconfig = importlib.import_module('cloudbaseinit.utils.'
                                                      'windows.winrmconfig')
                if (protocol == winrmconfig.LISTENER_PROTOCOL_HTTPS
                        and not certificate_thumbprint):
                    certificate_thumbprint = mock_create_cert.return_value
                    mock_create_cert.assert_called_once_with()
                mock_configure_listener.assert_called_once_with(
                    mock_osutils, mock_winrm_config, protocol.upper(),
                    certificate_thumbprint)
コード例 #8
0
    def _test_trim(self, mock_get_os_utils, status):
        shared_data = 'fake_shared_data'
        mock_os_utils = mock.Mock()
        mock_get_os_utils.return_value = mock_os_utils

        with testutils.ConfPatcher('trim_enabled', status):
            response = self._trim_plugin.execute(mock.Mock(), shared_data)

        mock_os_utils.enable_trim.assert_called_once_with(status)
        self.assertEqual(response, (base.PLUGIN_EXECUTION_DONE, False))
コード例 #9
0
    def _test_set_policy_already_set(self, policy, mock_storage_factory):
        mock_storage_manager = mock.MagicMock()
        san_policy = self._san_policy_map[policy]
        mock_storage_manager.get_san_policy.return_value = san_policy
        mock_storage_factory.return_value = mock_storage_manager

        with testutils.ConfPatcher('san_policy', policy):
            self._san_policy.execute(None, "")

            self.assertEqual(mock_storage_manager.call_count, 0)
コード例 #10
0
    def _test_set_policy(self, policy, mock_storage_factory):
        mock_storage_manager = mock.MagicMock()
        mock_storage_manager.get_san_policy.return_value = "fake policy"
        mock_storage_factory.return_value = mock_storage_manager

        with testutils.ConfPatcher('san_policy', policy):
            self._san_policy.execute(None, "")

            mock_storage_manager.set_san_policy.assert_called_once_with(
                self._san_policy_map[policy])
コード例 #11
0
 def test_get_data(self, mock_get_response, mock_Request,
                   mock_get_oauth_headers):
     with testutils.ConfPatcher('maas_metadata_url', '196.254.196.254'):
         fake_path = os.path.join('fake', 'path')
         mock_get_oauth_headers.return_value = 'fake headers'
         response = self._maasservice._get_data(path=fake_path)
         norm_path = posixpath.join(CONF.maas_metadata_url, fake_path)
         mock_get_oauth_headers.assert_called_once_with(norm_path)
         mock_Request.assert_called_once_with(norm_path,
                                              headers='fake headers')
         mock_get_response.assert_called_once_with(mock_Request())
         self.assertEqual(mock_get_response.return_value.read.return_value,
                          response)
コード例 #12
0
 def _test_get_page_file_volumes_by_label(self,
                                          drives=None,
                                          labels=None,
                                          conf_labels=None):
     mock_osutils = mock.MagicMock()
     mock_osutils.get_logical_drives.return_value = drives
     mock_osutils.get_volume_label.return_value = labels
     if not labels:
         res = self._pagefiles._get_page_file_volumes_by_label(mock_osutils)
         self.assertEqual(res, [])
         return
     with testutils.ConfPatcher("page_file_volume_labels", conf_labels):
         res = self._pagefiles._get_page_file_volumes_by_label(mock_osutils)
         self.assertEqual(res, drives)
コード例 #13
0
 def test_activate_windows(self):
     activate_result = mock.Mock()
     mock_service = mock.Mock()
     mock_manager = mock.Mock()
     mock_manager.activate_windows.return_value = activate_result
     expected_logs = [
         "Activating Windows",
         "Activation result:\n%s" % activate_result
     ]
     with testutils.ConfPatcher('activate_windows', True):
         with self.snatcher:
             self._licensing._activate_windows(mock_service, mock_manager)
     self.assertEqual(self.snatcher.output, expected_logs)
     mock_manager.activate_windows.assert_called_once_with()
コード例 #14
0
    def _test_execute(self, mock_run_slmgr, mock_get_os_utils,
                      activate_windows):
        mock_osutils = mock.MagicMock()
        run_slmgr_calls = [mock.call(mock_osutils, ['/dlv'])]
        mock_get_os_utils.return_value = mock_osutils

        with testutils.ConfPatcher('activate_windows', activate_windows):
            response = self._licensing.execute(service=None, shared_data=None)

        mock_get_os_utils.assert_called_once_with()
        if activate_windows:
            run_slmgr_calls.append(mock.call(mock_osutils, ['/ato']))

        self.assertEqual(run_slmgr_calls, mock_run_slmgr.call_args_list)
        self.assertEqual((base.PLUGIN_EXECUTION_DONE, False), response)
コード例 #15
0
    def _test_set_password(self,
                           mock_get_password,
                           mock_change_logon_behaviour,
                           password,
                           can_update_password,
                           is_password_changed,
                           max_password_length=20,
                           injected=False):
        expected_password = password
        expected_logging = []
        user = '******'

        mock_get_password.return_value = (password, injected)

        mock_service = mock.MagicMock()
        mock_osutils = mock.MagicMock()
        if not password:
            expected_password = "******" * CONF.user_password_length

        mock_osutils.generate_random_password.return_value = expected_password
        mock_service.can_update_password = can_update_password
        mock_service.is_password_changed.return_value = is_password_changed

        with testutils.ConfPatcher('user_password_length',
                                   max_password_length):
            with testutils.LogSnatcher('cloudbaseinit.plugins.common.'
                                       'setuserpassword') as snatcher:
                response = self._setpassword_plugin._set_password(
                    mock_service, mock_osutils, user,
                    mock.sentinel.shared_data)

        if can_update_password and not is_password_changed:
            expected_logging.append('Updating password is not required.')
            expected_password = None

        if not password:
            expected_logging.append('Generating a random user password')

        if not can_update_password or is_password_changed:
            mock_get_password.assert_called_once_with(
                mock_service, mock.sentinel.shared_data)

        self.assertEqual(expected_password, response)
        self.assertEqual(expected_logging, snatcher.output)
        if password and can_update_password and is_password_changed:
            mock_change_logon_behaviour.assert_called_once_with(
                user, password_injected=injected)
コード例 #16
0
    def test_execute(self, mock_extend_volumes, mock_query_packs,
                     mock_query_providers, mock_load_vds_service):
        mock_svc = mock.MagicMock()
        fake_providers = ['fake providers']
        fake_packs = ['fake packs']
        mock_service = mock.MagicMock()
        fake_data = 'fake data'
        mock_load_vds_service.return_value = mock_svc
        mock_query_providers.return_value = fake_providers
        mock_query_packs.return_value = fake_packs

        with testutils.ConfPatcher('volumes_to_extend', '1'):
            self._extend_volumes.execute(mock_service, fake_data)

        mock_query_providers.assert_called_once_with(mock_svc)
        mock_query_packs.assert_called_once_with('fake providers')
        mock_extend_volumes.assert_called_with('fake packs', [1])
コード例 #17
0
    def test__create_transport_cert(self):
        mock_cert_mgr = mock.Mock()
        expected_certs = (mock.sentinel.thumbprint, mock.sentinel.cert)

        mock_cert_mgr.create_self_signed_cert.return_value = (
            mock.sentinel.thumbprint, mock.sentinel.cert)
        with testutils.ConfPatcher(key='transport_cert_store_name',
                                   value='fake_name',
                                   group="azure"):
            with self._azureservice._create_transport_cert(mock_cert_mgr) as r:
                self.assertEqual(r, expected_certs)
        (mock_cert_mgr.create_self_signed_cert.assert_called_once_with(
            "CN=Cloudbase-Init AzureService Transport",
            machine_keyset=True,
            store_name="fake_name"))
        (mock_cert_mgr.delete_certificate_from_store.assert_called_once_with(
            mock.sentinel.thumbprint,
            machine_keyset=True,
            store_name="fake_name"))
コード例 #18
0
    def _test_load(self, mock_get_cache_data, ip, cache_data_fails=False):
        if cache_data_fails:
            mock_get_cache_data.side_effect = Exception

        with testutils.ConfPatcher('metadata_base_url', ip, "maas"):
            with testutils.LogSnatcher('cloudbaseinit.metadata.services.'
                                       'maasservice') as snatcher:
                response = self._maasservice.load()

            if ip is not None:
                if not cache_data_fails:
                    mock_get_cache_data.assert_called_once_with(
                        '%s/meta-data/' % self._maasservice._metadata_version)
                    self.assertTrue(response)
                else:
                    expected_logging = 'Metadata not found at URL \'%s\'' % ip
                    self.assertEqual(expected_logging, snatcher.output[-1])
            else:
                self.assertFalse(response)
コード例 #19
0
    def _test_is_vfat_drive(self, execute_process_value, expected_logging,
                            expected_response):

        mock_osutils = mock.Mock()
        mock_osutils.execute_process.return_value = execute_process_value

        with testutils.LogSnatcher('cloudbaseinit.utils.windows.'
                                   'vfat') as snatcher:
            with testutils.ConfPatcher('mtools_path', 'mtools_path'):

                response = vfat.is_vfat_drive(mock_osutils,
                                              mock.sentinel.drive)

                mdir = os.path.join(CONF.mtools_path, "mlabel.exe")
                mock_osutils.execute_process.assert_called_once_with(
                    [mdir, "-i", mock.sentinel.drive, "-s"], shell=False)

        self.assertEqual(expected_logging, snatcher.output)
        self.assertEqual(expected_response, response)
コード例 #20
0
    def _test_execute(self,
                      mock_get_licensing_manager,
                      mock_get_os_utils,
                      mock_set_product_key,
                      mock_set_kms_host,
                      mock_activate_windows,
                      nano=False):
        mock_service = mock.Mock()
        mock_manager = mock.Mock()
        mock_get_licensing_manager.return_value = mock_manager
        mock_osutils = mock.MagicMock()
        mock_osutils.is_nano_server.return_value = nano
        mock_get_os_utils.return_value = mock_osutils
        mock_manager.get_licensing_info.return_value = "fake"
        expected_logs = []
        with testutils.ConfPatcher('activate_windows', True):
            with self.snatcher:
                response = self._licensing.execute(service=mock_service,
                                                   shared_data=None)

        mock_get_os_utils.assert_called_once_with()
        if nano:
            expected_logs = [
                "Licensing info and activation are "
                "not available on Nano Server"
            ]
            self.assertEqual(self.snatcher.output, expected_logs)
            return
        else:
            mock_set_product_key.assert_called_once_with(
                mock_service, mock_manager)
            mock_set_kms_host.assert_called_once_with(mock_service,
                                                      mock_manager)
            mock_activate_windows.assert_called_once_with(
                mock_service, mock_manager)
            expected_logs.append('Microsoft Windows license info:\nfake')
            mock_manager.get_licensing_info.assert_called_once_with()

        self.assertEqual((base.PLUGIN_EXECUTION_DONE, False), response)
        self.assertEqual(self.snatcher.output, expected_logs)
コード例 #21
0
    def _test_execute(self, mock_get_osutils, mock_get_volume_path,
                      mock_set_volume_path, mock_join, not_existing_exception,
                      disk_volume_path, disk_warning_path):
        mock_service = mock.MagicMock()
        shared_data = mock.sentinel.shared_data
        eclass = metadata_services_base.NotExistingMetadataException
        expected_result = base.PLUGIN_EXECUTION_DONE, False
        expected_logging = []
        if not_existing_exception:
            mock_service.get_ephemeral_disk_data_loss_warning.side_effect = \
                eclass()

        else:
            mock_osutils = mock.MagicMock()
            mock_get_osutils.return_value = mock_osutils
            mock_get_volume_path.return_value = disk_volume_path
            if not disk_volume_path:
                expected_logging += ["Ephemeral disk volume not found"]
            else:
                mock_join.return_value = disk_warning_path
        with testutils.ConfPatcher('ephemeral_disk_data_loss_warning_path',
                                   disk_warning_path):
            with testutils.LogSnatcher(MODULE_PATH) as snatcher:
                result = self._disk.execute(mock_service, shared_data)
        self.assertEqual(result, expected_result)
        self.assertEqual(snatcher.output, expected_logging)
        (mock_service.get_ephemeral_disk_data_loss_warning.
         assert_called_once_with())
        if not not_existing_exception:
            mock_get_osutils.assert_called_once_with()
            mock_get_volume_path.assert_called_once_with(mock_osutils)
            if disk_volume_path and disk_warning_path:
                mock_join.assert_called_once_with(disk_volume_path,
                                                  disk_warning_path)
                mock_set_volume_path.assert_called_once_with(
                    mock_service, disk_warning_path)
コード例 #22
0
 def _test_get_ephemeral_disk_volume_by_label(self, label,
                                              ephemeral_disk_volume_label):
     expected_result = None
     mock_osutils = mock.MagicMock()
     if ephemeral_disk_volume_label:
         labels = [None, str(mock.sentinel.label)] * 2
         labels += [label] + [None, str(mock.sentinel.label)]
         mock_osutils.get_logical_drives.return_value = range(len(labels))
         mock_osutils.get_volume_label.side_effect = labels
         if label.upper() == ephemeral_disk_volume_label.upper():
             expected_result = labels.index(label)
     with testutils.ConfPatcher('ephemeral_disk_volume_label',
                                ephemeral_disk_volume_label):
         result = self._disk._get_ephemeral_disk_volume_by_label(
             mock_osutils)
     self.assertEqual(result, expected_result)
     if ephemeral_disk_volume_label:
         mock_osutils.get_logical_drives.assert_called_once_with()
         if expected_result is not None:
             self.assertEqual(mock_osutils.get_volume_label.call_count,
                              expected_result + 1)
         else:
             self.assertEqual(mock_osutils.get_volume_label.call_count,
                              len(labels))
コード例 #23
0
 def test_get_volumes_to_extend(self):
     with testutils.ConfPatcher('volumes_to_extend', '1'):
         response = self._extend_volumes._get_volumes_to_extend()
         self.assertEqual([1], response)
コード例 #24
0
    def _test_execute(self,
                      mock_unpack_ntp_hosts,
                      mock_verify_time_service,
                      mock_get_dhcp_options,
                      mock_get_os_utils,
                      original_unpack_hosts,
                      ntp_data,
                      expected_hosts,
                      is_real_time=True,
                      enable_service=False,
                      use_dhcp_config=False):
        # Set the side effect to the actual function, in order to
        # see the expected result.
        mock_unpack_ntp_hosts.side_effect = original_unpack_hosts

        mock_service = mock.MagicMock()
        mock_osutils = mock.MagicMock()
        mock_options_data = mock.MagicMock()

        mock_get_os_utils.return_value = mock_osutils
        mock_osutils.get_dhcp_hosts_in_use.return_value = [
            ('fake friendly name', 'fake mac address', 'fake dhcp host')
        ]
        mock_get_dhcp_options.return_value = mock_options_data
        mock_options_data.get.return_value = ntp_data

        expected_logging = []
        reboot_required = not is_real_time

        mock_osutils.is_real_time_clock_utc.return_value = is_real_time

        with self.snatcher:
            with testutils.ConfPatcher('ntp_enable_service', enable_service):
                with testutils.ConfPatcher('ntp_use_dhcp_config',
                                           use_dhcp_config):
                    response = self._ntpclient.execute(
                        service=mock_service,
                        shared_data=mock.sentinel.shared_data)

        mock_get_os_utils.assert_called_once_with()
        mock_osutils.is_real_time_clock_utc.assert_called_once_with()
        if not is_real_time:
            mock_osutils.set_real_time_clock_utc.assert_called_once_with(True)
            expected_logging.append('RTC set to UTC: %s' % is_real_time)
        if enable_service:
            mock_verify_time_service.assert_called_once_with(mock_osutils)
            expected_logging.append('NTP client service enabled')
        if use_dhcp_config:
            mock_osutils.get_dhcp_hosts_in_use.assert_called_once_with()
            mock_get_dhcp_options.assert_called_once_with(
                'fake dhcp host', [dhcp.OPTION_NTP_SERVERS])
            mock_options_data.get.assert_called_once_with(
                dhcp.OPTION_NTP_SERVERS)
            if ntp_data:
                mock_unpack_ntp_hosts.assert_called_once_with(ntp_data)
                self.assertEqual(response,
                                 (base.PLUGIN_EXECUTION_DONE, reboot_required))
                mock_osutils.set_ntp_client_config.assert_called_once_with(
                    expected_hosts)
            else:
                expected_logging.append(
                    "Could not obtain the NTP configuration via DHCP")
                self.assertEqual(
                    response,
                    (base.PLUGIN_EXECUTE_ON_NEXT_BOOT, reboot_required))
        else:
            self.assertEqual(response,
                             (base.PLUGIN_EXECUTION_DONE, reboot_required))
コード例 #25
0
    def _test_execute(self,
                      mock_post_create_user,
                      mock_create_user,
                      mock_get_password,
                      mock_get_os_utils,
                      user_exists=False,
                      group_adding_works=True,
                      rename_admin_user=False,
                      rename_admin_taken=False):
        shared_data = {}
        mock_osutils = mock.MagicMock()
        mock_service = mock.MagicMock()
        mock_service.get_admin_username.return_value = CONF.username
        mock_get_password.return_value = 'password'
        mock_get_os_utils.return_value = mock_osutils
        mock_osutils.user_exists.return_value = user_exists
        if rename_admin_user:
            mock_osutils.is_builtin_admin.return_value = True
            if rename_admin_taken:
                mock_osutils.enum_users.return_value = [CONF.username]
            else:
                mock_osutils.enum_users.return_value = ["fake user name"]
        if not group_adding_works:
            mock_osutils.add_user_to_local_group.side_effect = Exception

        with testutils.ConfPatcher('rename_admin_user', rename_admin_user):
            with testutils.LogSnatcher("cloudbaseinit.plugins.common."
                                       "createuser") as snatcher:
                response = self._create_user.execute(mock_service, shared_data)

        mock_get_os_utils.assert_called_once_with()
        mock_get_password.assert_called_once_with(mock_osutils)

        if user_exists:
            mock_osutils.user_exists.assert_called_once_with(CONF.username)
            mock_osutils.set_user_password.assert_called_once_with(
                CONF.username, 'password')
            expected_logging = [
                "Setting password for existing user \"%s\"" % CONF.username
            ]
        elif rename_admin_user:
            if rename_admin_taken:
                expected_logging = [
                    '"%s" is already the name of the builtin admin '
                    'user, skipping renaming' % CONF.username
                ]
            else:
                expected_logging = [
                    'Renaming builtin admin user "{admin_user_name}" '
                    'to {new_user_name} and setting password'.format(
                        admin_user_name="fake user name",
                        new_user_name=CONF.username)
                ]
        else:
            mock_create_user.assert_called_once_with(CONF.username, 'password',
                                                     mock_osutils)
            expected_logging = [
                "Creating user \"%s\" and setting password" % CONF.username
            ]

        mock_post_create_user.assert_called_once_with(CONF.username,
                                                      'password', mock_osutils)

        self.assertEqual(expected_logging, snatcher.output[:1])
        if not group_adding_works:
            failed = snatcher.output[1].startswith(
                "Cannot add user to group \"Admins\"")
            self.assertTrue(failed)

        mock_osutils.add_user_to_local_group.assert_called_once_with(
            CONF.username, CONF.groups[0])
        self.assertEqual((base.PLUGIN_EXECUTION_DONE, False), response)