def test_users_with_ssh_redirect_user_default_str(self, m_user, m_group): """When ssh_redirect_user is 'default' pass default username.""" cfg = { 'users': ['default', { 'name': 'me2', 'ssh_redirect_user': '******' }] } # System config defines a default user for the distro. sys_cfg = { 'default_user': { 'name': 'ubuntu', 'lock_passwd': True, 'groups': ['lxd', 'sudo'], 'shell': '/bin/bash' } } metadata = {'public-keys': ['key1']} cloud = self.tmp_cloud(distro='ubuntu', sys_cfg=sys_cfg, metadata=metadata) cc_users_groups.handle('modulename', cfg, cloud, None, None) self.assertItemsEqual(m_user.call_args_list, [ mock.call('ubuntu', groups='lxd,sudo', lock_passwd=True, shell='/bin/bash'), mock.call('me2', cloud_public_ssh_keys=['key1'], default=False, ssh_redirect_user='******') ]) m_group.assert_not_called()
def test_handle_users_in_cfg_calls_create_users_on_bsd( self, m_fbsd_user, m_fbsd_group, m_linux_user, m_linux_group, ): """When users in config, create users with freebsd.create_user.""" cfg = {'users': ['default', {'name': 'me2'}]} # merged cloud-config # System config defines a default user for the distro. sys_cfg = { 'default_user': { 'name': 'freebsd', 'lock_passwd': True, 'groups': ['wheel'], 'shell': '/bin/tcsh' } } metadata = {} cloud = self.tmp_cloud(distro='freebsd', sys_cfg=sys_cfg, metadata=metadata) cc_users_groups.handle('modulename', cfg, cloud, None, None) self.assertCountEqual(m_fbsd_user.call_args_list, [ mock.call( 'freebsd', groups='wheel', lock_passwd=True, shell='/bin/tcsh'), mock.call('me2', default=False) ]) m_fbsd_group.assert_not_called() m_linux_group.assert_not_called() m_linux_user.assert_not_called()
def test_install_drivers_handles_old_ubuntu_drivers_gracefully( self, m_which, m_subp, m_tmp): """Older ubuntu-drivers versions should emit message and raise error""" tdir = self.tmp_dir() debconf_file = os.path.join(tdir, 'nvidia.template') m_tmp.return_value = tdir myCloud = mock.MagicMock() def fake_subp(cmd): if cmd[0].startswith(tdir): return raise ProcessExecutionError( stderr=OLD_UBUNTU_DRIVERS_ERROR_STDERR, exit_code=2) m_subp.side_effect = fake_subp with self.assertRaises(Exception): drivers.handle( 'ubuntu_drivers', self.cfg_accepted, myCloud, None, None) self.assertEqual([mock.call(['ubuntu-drivers-common'])], myCloud.distro.install_packages.call_args_list) self.assertEqual( [mock.call(AnyTempScriptAndDebconfFile(tdir, debconf_file)), mock.call(self.install_gpgpu)], m_subp.call_args_list) self.assertIn('WARNING: the available version of ubuntu-drivers is' ' too old to perform requested driver installation', self.logs.getvalue())
def test_handle_skips_squashfuse_when_unconfigured(self, m_squash, m_add, m_run): """When squashfuse_in_container is unset, don't attempt to install.""" handle('snap', cfg={'snap': {}}, cloud=None, log=self.logger, args=None) handle('snap', cfg={'snap': { 'squashfuse_in_container': None }}, cloud=None, log=self.logger, args=None) handle('snap', cfg={'snap': { 'squashfuse_in_container': False }}, cloud=None, log=self.logger, args=None) self.assertEqual([], m_squash.call_args_list) # No calls # snap configuration missing assertions and commands will default to [] self.assertIn(mock.call([]), m_add.call_args_list) self.assertIn(mock.call([]), m_run.call_args_list)
def test_handle_users_in_cfg_calls_create_users(self, m_user, m_group): """When users in config, create users with distro.create_user.""" cfg = {'users': ['default', {'name': 'me2'}]} # merged cloud-config # System config defines a default user for the distro. sys_cfg = { 'default_user': { 'name': 'ubuntu', 'lock_passwd': True, 'groups': ['lxd', 'sudo'], 'shell': '/bin/bash' } } metadata = {} cloud = self.tmp_cloud(distro='ubuntu', sys_cfg=sys_cfg, metadata=metadata) cc_users_groups.handle('modulename', cfg, cloud, None, None) self.assertItemsEqual(m_user.call_args_list, [ mock.call('ubuntu', groups='lxd,sudo', lock_passwd=True, shell='/bin/bash'), mock.call('me2', default=False) ]) m_group.assert_not_called()
def test_disable_no_tool(self, m_subp, m_which): """Log error when neither route nor ip commands are available""" m_which.return_value = None # Find neither ifconfig nor ip ec2_meta.handle('foo', DISABLE_CFG, None, LOG, None) self.assertEqual( [mock.call('ip'), mock.call('ifconfig')], m_which.call_args_list) m_subp.assert_not_called()
def test_configure_ua_attach_on_service_error(self, m_subp): """all services should be enabled and then any failures raised""" def fake_subp(cmd, capture=None): fail_cmds = [['ua', 'enable', svc] for svc in ['esm', 'cc']] if cmd in fail_cmds and capture: svc = cmd[-1] raise util.ProcessExecutionError( 'Invalid {} credentials'.format(svc.upper())) m_subp.side_effect = fake_subp with self.assertRaises(RuntimeError) as context_manager: configure_ua(token='SomeToken', enable=['esm', 'cc', 'fips']) self.assertEqual(m_subp.call_args_list, [ mock.call(['ua', 'attach', 'SomeToken']), mock.call(['ua', 'enable', 'esm'], capture=True), mock.call(['ua', 'enable', 'cc'], capture=True), mock.call(['ua', 'enable', 'fips'], capture=True) ]) self.assertIn( 'WARNING: Failure enabling "esm":\nUnexpected error' ' while running command.\nCommand: -\nExit code: -\nReason: -\n' 'Stdout: Invalid ESM credentials\nStderr: -\n', self.logs.getvalue()) self.assertIn( 'WARNING: Failure enabling "cc":\nUnexpected error' ' while running command.\nCommand: -\nExit code: -\nReason: -\n' 'Stdout: Invalid CC credentials\nStderr: -\n', self.logs.getvalue()) self.assertEqual( 'Failure enabling Ubuntu Advantage service(s): "esm", "cc"', str(context_manager.exception))
def test_disable_no_tool(self, m_subp, m_which): """Log error when neither route nor ip commands are available""" m_which.return_value = None # Find neither ifconfig nor ip ec2_meta.handle('foo', DISABLE_CFG, None, LOG, None) self.assertEqual( [mock.call('ip'), mock.call('ifconfig')], m_which.call_args_list) m_subp.assert_not_called()
def test_configure_ua_attach_on_service_error(self, m_subp): """all services should be enabled and then any failures raised""" def fake_subp(cmd, capture=None): fail_cmds = [['ua', 'enable', svc] for svc in ['esm', 'cc']] if cmd in fail_cmds and capture: svc = cmd[-1] raise util.ProcessExecutionError( 'Invalid {} credentials'.format(svc.upper())) m_subp.side_effect = fake_subp with self.assertRaises(RuntimeError) as context_manager: configure_ua(token='SomeToken', enable=['esm', 'cc', 'fips']) self.assertEqual( m_subp.call_args_list, [mock.call(['ua', 'attach', 'SomeToken']), mock.call(['ua', 'enable', 'esm'], capture=True), mock.call(['ua', 'enable', 'cc'], capture=True), mock.call(['ua', 'enable', 'fips'], capture=True)]) self.assertIn( 'WARNING: Failure enabling "esm":\nUnexpected error' ' while running command.\nCommand: -\nExit code: -\nReason: -\n' 'Stdout: Invalid ESM credentials\nStderr: -\n', self.logs.getvalue()) self.assertIn( 'WARNING: Failure enabling "cc":\nUnexpected error' ' while running command.\nCommand: -\nExit code: -\nReason: -\n' 'Stdout: Invalid CC credentials\nStderr: -\n', self.logs.getvalue()) self.assertEqual( 'Failure enabling Ubuntu Advantage service(s): "esm", "cc"', str(context_manager.exception))
def test_handle_raises_error_if_no_drivers_found( self, m_which, m_subp, m_tmp): """If ubuntu-drivers doesn't install any drivers, raise an error.""" tdir = self.tmp_dir() debconf_file = os.path.join(tdir, 'nvidia.template') m_tmp.return_value = tdir myCloud = mock.MagicMock() def fake_subp(cmd): if cmd[0].startswith(tdir): return raise ProcessExecutionError( stdout='No drivers found for installation.\n', exit_code=1) m_subp.side_effect = fake_subp with self.assertRaises(Exception): drivers.handle( 'ubuntu_drivers', self.cfg_accepted, myCloud, None, None) self.assertEqual([mock.call(['ubuntu-drivers-common'])], myCloud.distro.install_packages.call_args_list) self.assertEqual( [mock.call(AnyTempScriptAndDebconfFile(tdir, debconf_file)), mock.call(self.install_gpgpu)], m_subp.call_args_list) self.assertIn('ubuntu-drivers found no drivers for installation', self.logs.getvalue())
def _assert_happy_path_taken(self, config, m_which, m_subp): """Positive path test through handle. Package should be installed.""" myCloud = mock.MagicMock() drivers.handle('ubuntu_drivers', config, myCloud, None, None) self.assertEqual([mock.call(['ubuntu-drivers-common'])], myCloud.distro.install_packages.call_args_list) self.assertEqual([mock.call(self.install_gpgpu)], m_subp.call_args_list)
def _assert_happy_path_taken(self, config, m_which, m_subp): """Positive path test through handle. Package should be installed.""" myCloud = mock.MagicMock() drivers.handle('ubuntu_drivers', config, myCloud, None, None) self.assertEqual([mock.call(['ubuntu-drivers-common'])], myCloud.distro.install_packages.call_args_list) self.assertEqual([mock.call(self.install_gpgpu)], m_subp.call_args_list)
def test_apply_credentials_with_user(self, m_setup_keys): """Apply keys for the given user and root.""" keys = ["key1"] user = "******" cc_ssh.apply_credentials(keys, user, False, ssh_util.DISABLE_USER_OPTS) self.assertEqual([mock.call(set(keys), user), mock.call(set(keys), "root", options="")], m_setup_keys.call_args_list)
def test_install_drivers_no_install_if_present(self, m_which, m_subp): """If 'ubuntu-drivers' is present, no package install should occur.""" pkg_install = mock.MagicMock() drivers.install_drivers(self.cfg_accepted['drivers'], pkg_install_func=pkg_install) self.assertEqual(0, pkg_install.call_count) self.assertEqual([mock.call('ubuntu-drivers')], m_which.call_args_list) self.assertEqual([mock.call(self.install_gpgpu)], m_subp.call_args_list)
def test_group_added(self, m_is_group, m_subp, m_is_snappy): m_is_group.return_value = False user = '******' self.dist.create_user(user, groups=['group1']) expected = [ mock.call(['groupadd', 'group1']), self._useradd2call([user, '--groups', 'group1', '-m']), mock.call(['passwd', '-l', user])] self.assertEqual(m_subp.call_args_list, expected)
def test_maybe_install_squashfuse_happy_path(self, m_container): """maybe_install_squashfuse logs and raises package install errors.""" m_container.return_value = True distro = mock.MagicMock() # No errors raised maybe_install_squashfuse(cloud=FakeCloud(distro)) self.assertEqual([mock.call()], distro.update_package_sources.call_args_list) self.assertEqual([mock.call(['squashfuse'])], distro.install_packages.call_args_list)
def test_group_added(self, m_is_group, m_subp, m_is_snappy): m_is_group.return_value = False user = '******' self.dist.create_user(user, groups=['group1']) expected = [ mock.call(['groupadd', 'group1']), self._useradd2call([user, '--groups', 'group1', '-m']), mock.call(['passwd', '-l', user])] self.assertEqual(m_subp.call_args_list, expected)
def test_configure_ua_attach_with_specific_services(self, m_subp): """When services a list, only enable specific services.""" configure_ua(token='SomeToken', enable=['fips']) self.assertEqual( m_subp.call_args_list, [mock.call(['ua', 'attach', 'SomeToken']), mock.call(['ua', 'enable', 'fips'], capture=True)]) self.assertEqual( 'DEBUG: Attaching to Ubuntu Advantage. ua attach SomeToken\n', self.logs.getvalue())
def test_preexec_fn_sets_group_id_if_adm_group_present( self, _m_os_umask, m_setgid, m_getgrnam, preexec_fn): """We should setgrp to adm if present, so files are owned by them.""" fake_group = mock.Mock(gr_gid=mock.sentinel.gr_gid) m_getgrnam.return_value = fake_group preexec_fn() assert [mock.call("adm")] == m_getgrnam.call_args_list assert [mock.call(mock.sentinel.gr_gid)] == m_setgid.call_args_list
def test_install_drivers_no_install_if_present(self, m_which, m_subp): """If 'ubuntu-drivers' is present, no package install should occur.""" pkg_install = mock.MagicMock() drivers.install_drivers(self.cfg_accepted['drivers'], pkg_install_func=pkg_install) self.assertEqual(0, pkg_install.call_count) self.assertEqual([mock.call('ubuntu-drivers')], m_which.call_args_list) self.assertEqual([mock.call(self.install_gpgpu)], m_subp.call_args_list)
def test_configure_ua_attach_with_specific_services(self, m_subp): """When services a list, only enable specific services.""" configure_ua(token='SomeToken', enable=['fips']) self.assertEqual(m_subp.call_args_list, [ mock.call(['ua', 'attach', 'SomeToken']), mock.call(['ua', 'enable', 'fips'], capture=True) ]) self.assertEqual( 'DEBUG: Attaching to Ubuntu Advantage. ua attach SomeToken\n', self.logs.getvalue())
def test_maybe_install_squashfuse_happy_path(self, m_container): """maybe_install_squashfuse logs and raises package install errors.""" m_container.return_value = True distro = mock.MagicMock() # No errors raised maybe_install_squashfuse(cloud=FakeCloud(distro)) self.assertEqual( [mock.call()], distro.update_package_sources.call_args_list) self.assertEqual( [mock.call(['squashfuse'])], distro.install_packages.call_args_list)
def test_apply_credentials_with_user_disable_root(self, m_setup_keys): """Apply keys for the given user and disable root ssh.""" keys = ["key1"] user = "******" options = ssh_util.DISABLE_USER_OPTS cc_ssh.apply_credentials(keys, user, True, options) options = options.replace("$USER", user) options = options.replace("$DISABLE_USER", "root") self.assertEqual([mock.call(set(keys), user), mock.call(set(keys), "root", options=options)], m_setup_keys.call_args_list)
def test_apply_network_allowed_when_default_boot(self, m_ubuntu, m_macs): """Apply network if datasource permits BOOT event.""" net_cfg = self._apply_network_setup(m_macs) self.init.apply_network_config(True) assert mock.call( net_cfg ) == self.init.distro.apply_network_config_names.call_args_list[-1] assert mock.call( net_cfg, bring_up=True ) == self.init.distro.apply_network_config.call_args_list[-1]
def test_only_new_group_added(self, m_is_group, m_subp, m_is_snappy): ex_groups = ['existing_group'] groups = ['group1', ex_groups[0]] m_is_group.side_effect = lambda m: m in ex_groups user = '******' self.dist.create_user(user, groups=groups) expected = [ mock.call(['groupadd', 'group1']), self._useradd2call([user, '--groups', ','.join(groups), '-m']), mock.call(['passwd', '-l', user])] self.assertEqual(m_subp.call_args_list, expected)
def test_only_new_group_added(self, m_is_group, m_subp, m_is_snappy): ex_groups = ['existing_group'] groups = ['group1', ex_groups[0]] m_is_group.side_effect = lambda m: m in ex_groups user = '******' self.dist.create_user(user, groups=groups) expected = [ mock.call(['groupadd', 'group1']), self._useradd2call([user, '--groups', ','.join(groups), '-m']), mock.call(['passwd', '-l', user])] self.assertEqual(m_subp.call_args_list, expected)
def test_handle_raises_error_if_no_drivers_found(self, m_which, m_subp): """If ubuntu-drivers doesn't install any drivers, raise an error.""" myCloud = mock.MagicMock() with self.assertRaises(Exception): drivers.handle('ubuntu_drivers', self.cfg_accepted, myCloud, None, None) self.assertEqual([mock.call(['ubuntu-drivers-common'])], myCloud.distro.install_packages.call_args_list) self.assertEqual([mock.call(self.install_gpgpu)], m_subp.call_args_list) self.assertIn('ubuntu-drivers found no drivers for installation', self.logs.getvalue())
def test_handle_raises_error_if_no_drivers_found(self, m_which, m_subp): """If ubuntu-drivers doesn't install any drivers, raise an error.""" myCloud = mock.MagicMock() with self.assertRaises(Exception): drivers.handle( 'ubuntu_drivers', self.cfg_accepted, myCloud, None, None) self.assertEqual([mock.call(['ubuntu-drivers-common'])], myCloud.distro.install_packages.call_args_list) self.assertEqual([mock.call(self.install_gpgpu)], m_subp.call_args_list) self.assertIn('ubuntu-drivers found no drivers for installation', self.logs.getvalue())
def test_correct_url_used_for_goalstate(self): self.find_endpoint.return_value = 'test_endpoint' shim = wa_shim() shim.register_with_azure_and_fetch_data() get = self.AzureEndpointHttpClient.return_value.get self.assertEqual( [mock.call('http://test_endpoint/machine/?comp=goalstate')], get.call_args_list) self.assertEqual( [mock.call(get.return_value.contents, self.AzureEndpointHttpClient.return_value)], self.GoalState.call_args_list)
def test_configure_ua_attach_with_string_services(self, m_subp): """When services a string, treat as singleton list and warn""" configure_ua(token='SomeToken', enable='fips') self.assertEqual(m_subp.call_args_list, [ mock.call(['ua', 'attach', 'SomeToken']), mock.call(['ua', 'enable', 'fips'], capture=True) ]) self.assertEqual( 'WARNING: ubuntu_advantage: enable should be a list, not a' ' string; treating as a single enable\n' 'DEBUG: Attaching to Ubuntu Advantage. ua attach SomeToken\n', self.logs.getvalue())
def test_correct_url_used_for_goalstate(self): self.find_endpoint.return_value = 'test_endpoint' shim = azure_helper.WALinuxAgentShim() shim.register_with_azure_and_fetch_data() get = self.AzureEndpointHttpClient.return_value.get self.assertEqual( [mock.call('http://test_endpoint/machine/?comp=goalstate')], get.call_args_list) self.assertEqual([ mock.call(get.return_value.contents, self.AzureEndpointHttpClient.return_value) ], self.GoalState.call_args_list)
def test_create_groups_with_whitespace_string( self, m_is_group, m_subp, m_is_snappy): # groups supported as a comma delimeted string even with white space m_is_group.return_value = False user = '******' self.dist.create_user(user, groups='group1, group2') expected = [ mock.call(['groupadd', 'group1']), mock.call(['groupadd', 'group2']), self._useradd2call([user, '--groups', 'group1,group2', '-m']), mock.call(['passwd', '-l', user])] self.assertEqual(m_subp.call_args_list, expected)
def test_configure_ua_attach_with_string_services(self, m_subp): """When services a string, treat as singleton list and warn""" configure_ua(token='SomeToken', enable='fips') self.assertEqual( m_subp.call_args_list, [mock.call(['ua', 'attach', 'SomeToken']), mock.call(['ua', 'enable', 'fips'], capture=True)]) self.assertEqual( 'WARNING: ubuntu_advantage: enable should be a list, not a' ' string; treating as a single enable\n' 'DEBUG: Attaching to Ubuntu Advantage. ua attach SomeToken\n', self.logs.getvalue())
def test_create_groups_with_whitespace_string( self, m_is_group, m_subp, m_is_snappy): # groups supported as a comma delimeted string even with white space m_is_group.return_value = False user = '******' self.dist.create_user(user, groups='group1, group2') expected = [ mock.call(['groupadd', 'group1']), mock.call(['groupadd', 'group2']), self._useradd2call([user, '--groups', 'group1,group2', '-m']), mock.call(['passwd', '-l', user])] self.assertEqual(m_subp.call_args_list, expected)
def _assert_happy_path_taken(self, config, m_which, m_subp, m_tmp): """Positive path test through handle. Package should be installed.""" tdir = self.tmp_dir() debconf_file = os.path.join(tdir, 'nvidia.template') m_tmp.return_value = tdir myCloud = mock.MagicMock() drivers.handle('ubuntu_drivers', config, myCloud, None, None) self.assertEqual([mock.call(['ubuntu-drivers-common'])], myCloud.distro.install_packages.call_args_list) self.assertEqual([ mock.call(AnyTempScriptAndDebconfFile(tdir, debconf_file)), mock.call(self.install_gpgpu) ], m_subp.call_args_list)
def test_version_none_uses_latest(self, m_which, m_subp, m_tmp): tdir = self.tmp_dir() debconf_file = os.path.join(tdir, 'nvidia.template') m_tmp.return_value = tdir myCloud = mock.MagicMock() version_none_cfg = { 'drivers': {'nvidia': {'license-accepted': True, 'version': None}}} drivers.handle( 'ubuntu_drivers', version_none_cfg, myCloud, None, None) self.assertEqual( [mock.call(AnyTempScriptAndDebconfFile(tdir, debconf_file)), mock.call(['ubuntu-drivers', 'install', '--gpgpu', 'nvidia'])], m_subp.call_args_list)
def test_create_user_with_ssh_redirect_user_does_not_disable_auth_keys( self, m_setup_user_keys, m_subp, m_is_snappy): """Do not disable ssh_authorized_keys when ssh_redirect_user is set.""" user = '******' self.dist.create_user( user, ssh_authorized_keys='auth1', ssh_redirect_user='******', cloud_public_ssh_keys=['key1']) disable_prefix = ssh_util.DISABLE_USER_OPTS disable_prefix = disable_prefix.replace('$USER', 'someuser') disable_prefix = disable_prefix.replace('$DISABLE_USER', user) self.assertEqual( m_setup_user_keys.call_args_list, [mock.call(set(['auth1']), user), # not disabled mock.call(set(['key1']), 'foouser', options=disable_prefix)])
def test_install_drivers_handles_old_ubuntu_drivers_gracefully( self, m_which, m_subp): """Older ubuntu-drivers versions should emit message and raise error""" myCloud = mock.MagicMock() with self.assertRaises(Exception): drivers.handle( 'ubuntu_drivers', self.cfg_accepted, myCloud, None, None) self.assertEqual([mock.call(['ubuntu-drivers-common'])], myCloud.distro.install_packages.call_args_list) self.assertEqual([mock.call(self.install_gpgpu)], m_subp.call_args_list) self.assertIn('WARNING: the available version of ubuntu-drivers is' ' too old to perform requested driver installation', self.logs.getvalue())
def test_create_user_with_ssh_redirect_user_does_not_disable_auth_keys( self, m_setup_user_keys, m_subp, m_is_snappy): """Do not disable ssh_authorized_keys when ssh_redirect_user is set.""" user = '******' self.dist.create_user( user, ssh_authorized_keys='auth1', ssh_redirect_user='******', cloud_public_ssh_keys=['key1']) disable_prefix = ssh_util.DISABLE_USER_OPTS disable_prefix = disable_prefix.replace('$USER', 'someuser') disable_prefix = disable_prefix.replace('$DISABLE_USER', user) self.assertEqual( m_setup_user_keys.call_args_list, [mock.call(set(['auth1']), user), # not disabled mock.call(set(['key1']), 'foouser', options=disable_prefix)])
def test_mkswap(self, m_which, subp, *args): """mkfs observes extra_opts and overwrite settings when cmd is not present.""" m_which.side_effect = iter([None, '/sbin/mkswap']) cc_disk_setup.mkfs({ 'filesystem': 'swap', 'device': '/dev/xdb1', 'label': 'swap', 'overwrite': True, }) self.assertEqual([mock.call('mkfs.swap'), mock.call('mkswap')], m_which.call_args_list) subp.assert_called_once_with( ['/sbin/mkswap', '/dev/xdb1', '-L', 'swap', '-f'], shell=False)
def test_install_drivers_handles_old_ubuntu_drivers_gracefully( self, m_which, m_subp): """Older ubuntu-drivers versions should emit message and raise error""" myCloud = mock.MagicMock() with self.assertRaises(Exception): drivers.handle('ubuntu_drivers', self.cfg_accepted, myCloud, None, None) self.assertEqual([mock.call(['ubuntu-drivers-common'])], myCloud.distro.install_packages.call_args_list) self.assertEqual([mock.call(self.install_gpgpu)], m_subp.call_args_list) self.assertIn( 'WARNING: the available version of ubuntu-drivers is' ' too old to perform requested driver installation', self.logs.getvalue())
def test_handle_skips_squashfuse_when_unconfigured(self, m_squash, m_add, m_run): """When squashfuse_in_container is unset, don't attempt to install.""" handle( 'snap', cfg={'snap': {}}, cloud=None, log=self.logger, args=None) handle( 'snap', cfg={'snap': {'squashfuse_in_container': None}}, cloud=None, log=self.logger, args=None) handle( 'snap', cfg={'snap': {'squashfuse_in_container': False}}, cloud=None, log=self.logger, args=None) self.assertEqual([], m_squash.call_args_list) # No calls # snap configuration missing assertions and commands will default to [] self.assertIn(mock.call([]), m_add.call_args_list) self.assertIn(mock.call([]), m_run.call_args_list)
def test_install_drivers_no_install_if_present(self, m_which, m_subp, m_tmp): """If 'ubuntu-drivers' is present, no package install should occur.""" tdir = self.tmp_dir() debconf_file = os.path.join(tdir, 'nvidia.template') m_tmp.return_value = tdir pkg_install = mock.MagicMock() drivers.install_drivers(self.cfg_accepted['drivers'], pkg_install_func=pkg_install) self.assertEqual(0, pkg_install.call_count) self.assertEqual([mock.call('ubuntu-drivers')], m_which.call_args_list) self.assertEqual([ mock.call(AnyTempScriptAndDebconfFile(tdir, debconf_file)), mock.call(self.install_gpgpu) ], m_subp.call_args_list)
def test_dhcp_discovery_outside_sandbox(self, m_subp, m_kill, m_getppid): """dhcp_discovery brings up the interface and runs dhclient. It also returns the parsed dhcp.leases file generated in the sandbox. """ m_subp.return_value = ('', '') tmpdir = self.tmp_dir() dhclient_script = os.path.join(tmpdir, 'dhclient.orig') script_content = '#!/bin/bash\necho fake-dhclient' write_file(dhclient_script, script_content, mode=0o755) lease_content = dedent(""" lease { interface "eth9"; fixed-address 192.168.2.74; option subnet-mask 255.255.255.0; option routers 192.168.2.1; } """) lease_file = os.path.join(tmpdir, 'dhcp.leases') write_file(lease_file, lease_content) pid_file = os.path.join(tmpdir, 'dhclient.pid') my_pid = 1 write_file(pid_file, "%d\n" % my_pid) m_getppid.return_value = 1 # Indicate that dhclient has daemonized with mock.patch('os.access', return_value=False): self.assertCountEqual([{ 'interface': 'eth9', 'fixed-address': '192.168.2.74', 'subnet-mask': '255.255.255.0', 'routers': '192.168.2.1' }], dhcp_discovery(dhclient_script, 'eth9', tmpdir)) # dhclient script got copied with open(os.path.join(tmpdir, 'dhclient.orig')) as stream: self.assertEqual(script_content, stream.read()) # Interface was brought up before dhclient called from sandbox m_subp.assert_has_calls([ mock.call(['ip', 'link', 'set', 'dev', 'eth9', 'up'], capture=True), mock.call([ os.path.join(tmpdir, 'dhclient.orig'), '-1', '-v', '-lf', lease_file, '-pf', os.path.join(tmpdir, 'dhclient.pid'), 'eth9', '-sf', '/bin/true' ], capture=True) ]) m_kill.assert_has_calls([mock.call(my_pid, signal.SIGKILL)])
def test_basic(self, m_subp, m_is_snappy): user = '******' self.dist.create_user(user) self.assertEqual( m_subp.call_args_list, [self._useradd2call([user, '-m']), mock.call(['passwd', '-l', user])])
def test_explicit_no_home_false(self, m_subp, m_is_snappy): user = '******' self.dist.create_user(user, no_create_home=False) self.assertEqual( m_subp.call_args_list, [self._useradd2call([user, '-m']), mock.call(['passwd', '-l', user])])
def test_dump_events_with_cisource(self, m_parse_from_date): """Cisource file is read and parsed into a tuple of events and data.""" tmpfile = self.tmp_path('logfile') write_file(tmpfile, SAMPLE_LOGS) m_parse_from_date.return_value = 1472594005.972 events, data = dump_events(cisource=open(tmpfile)) year = datetime.now().year dt1 = datetime.strptime( 'Nov 03 06:51:06.074410 %d' % year, '%b %d %H:%M:%S.%f %Y') timestamp1 = float(dt1.strftime('%s.%f')) expected_events = [{ 'description': 'starting search for local datasources', 'event_type': 'start', 'name': 'init-local', 'origin': 'cloudinit', 'timestamp': timestamp1}, { 'description': 'running modules for final', 'event_type': 'finish', 'name': 'modules-final', 'origin': 'cloudinit', 'result': 'SUCCESS', 'timestamp': 1472594005.972}] self.assertEqual(expected_events, events) self.assertEqual(SAMPLE_LOGS.splitlines(), [d.strip() for d in data]) m_parse_from_date.assert_has_calls( [mock.call("2016-08-30 21:53:25.972325+00:00")])
def test_dump_events_with_rawdata(self, m_parse_from_date): """Rawdata is split and parsed into a tuple of events and data""" m_parse_from_date.return_value = "1472594005.972" events, data = dump_events(rawdata=SAMPLE_LOGS) expected_data = SAMPLE_LOGS.splitlines() self.assertEqual( [mock.call("2016-08-30 21:53:25.972325+00:00")], m_parse_from_date.call_args_list) self.assertEqual(expected_data, data) year = datetime.now().year dt1 = datetime.strptime( 'Nov 03 06:51:06.074410 %d' % year, '%b %d %H:%M:%S.%f %Y') timestamp1 = float(dt1.strftime('%s.%f')) expected_events = [{ 'description': 'starting search for local datasources', 'event_type': 'start', 'name': 'init-local', 'origin': 'cloudinit', 'timestamp': timestamp1}, { 'description': 'running modules for final', 'event_type': 'finish', 'name': 'modules-final', 'origin': 'cloudinit', 'result': 'SUCCESS', 'timestamp': 1472594005.972}] self.assertEqual(expected_events, events)
def test_full_registration(self, m_sman_cli): ''' Registration with auto-attach, service-level, adding pools, and enabling and disabling yum repos ''' call_lists = [] call_lists.append(['attach', '--pool=pool1', '--pool=pool3']) call_lists.append(['repos', '--disable=repo5', '--enable=repo2', '--enable=repo3']) call_lists.append(['attach', '--auto', '--servicelevel=self-support']) reg = "The system has been registered with ID:" \ " 12345678-abde-abcde-1234-1234567890abc" m_sman_cli.side_effect = [ util.ProcessExecutionError, (reg, 'bar'), ('Service level set to: self-support', ''), ('pool1\npool3\n', ''), ('pool2\n', ''), ('', ''), ('Repo ID: repo1\nRepo ID: repo5\n', ''), ('Repo ID: repo2\nRepo ID: repo3\nRepo ID: repo4', ''), ('', '')] self.handle(self.name, self.config_full, self.cloud_init, self.log, self.args) self.assertEqual(m_sman_cli.call_count, 9) for call in call_lists: self.assertIn(mock.call(call), m_sman_cli.call_args_list) self.assertIn("rh_subscription plugin completed successfully", self.logs.getvalue())
def test_add_assertions_adds_assertions_as_dict(self, m_subp): """When provided with a dict, add_assertions adds all assertions.""" self.assertEqual( ASSERTIONS_FILE, '/var/lib/cloud/instance/snapd.assertions') assert_file = self.tmp_path('snapd.assertions', dir=self.tmp) assertions = {'00': SYSTEM_USER_ASSERTION, '01': ACCOUNT_ASSERTION} wrap_and_call( 'cloudinit.config.cc_snap', {'ASSERTIONS_FILE': {'new': assert_file}}, add_assertions, assertions) self.assertIn( 'Importing user-provided snap assertions', self.logs.getvalue()) self.assertIn( "DEBUG: Snap acking: ['type: system-user', 'authority-id: Lqv", self.logs.getvalue()) self.assertIn( "DEBUG: Snap acking: ['type: account-key', 'authority-id: canonic", self.logs.getvalue()) self.assertEqual( [mock.call(['snap', 'ack', assert_file], capture=True)], m_subp.call_args_list) compare_file = self.tmp_path('comparison', dir=self.tmp) combined = '\n'.join(assertions.values()) util.write_file(compare_file, combined.encode('utf-8')) self.assertEqual( util.load_file(compare_file), util.load_file(assert_file))
def test_handle_tries_to_install_squashfuse(self, m_squash): """If squashfuse_in_container is True, try installing squashfuse.""" cfg = {'snap': {'squashfuse_in_container': True}} mycloud = FakeCloud(None) handle('snap', cfg=cfg, cloud=mycloud, log=self.logger, args=None) self.assertEqual( [mock.call(mycloud)], m_squash.call_args_list)
def test_handle_tries_to_install_squashfuse(self, m_squash): """If squashfuse_in_container is True, try installing squashfuse.""" cfg = {'snap': {'squashfuse_in_container': True}} mycloud = FakeCloud(None) handle('snap', cfg=cfg, cloud=mycloud, log=self.logger, args=None) self.assertEqual( [mock.call(mycloud)], m_squash.call_args_list)
def test_correct_url_used_for_report_ready(self): self.find_endpoint.return_value = 'test_endpoint' shim = wa_shim() shim.register_with_azure_and_fetch_data() expected_url = 'http://test_endpoint/machine?comp=health' self.assertEqual( [mock.call(expected_url, data=mock.ANY, extra_headers=mock.ANY)], self.AzureEndpointHttpClient.return_value.post.call_args_list)
def test_lock_with_passwd_if_available(self, m_which, m_subp, m_is_snappy): """Lock with only passwd will use passwd.""" m_which.side_effect = lambda m: m in ('passwd',) self.dist.lock_passwd("bob") self.assertEqual( [mock.call(['passwd', '-l', 'bob'])], m_subp.call_args_list)
def test_system_user(self, m_subp, m_is_snappy): # system user should have no home and get --system user = '******' self.dist.create_user(user, system=True) self.assertEqual( m_subp.call_args_list, [self._useradd2call([user, '--system', '-M']), mock.call(['passwd', '-l', user])])
def test_set_password(self, m_subp, m_is_snappy): user = '******' password = '******' self.dist.create_user(user, passwd=password) self.assertEqual( m_subp.call_args_list, [self._useradd2call([user, '--password', password, '-m']), mock.call(['passwd', '-l', user])])
def test_handle_users_in_cfg_calls_create_users(self, m_user, m_group): """When users in config, create users with distro.create_user.""" cfg = {'users': ['default', {'name': 'me2'}]} # merged cloud-config # System config defines a default user for the distro. sys_cfg = {'default_user': {'name': 'ubuntu', 'lock_passwd': True, 'groups': ['lxd', 'sudo'], 'shell': '/bin/bash'}} metadata = {} cloud = self.tmp_cloud( distro='ubuntu', sys_cfg=sys_cfg, metadata=metadata) cc_users_groups.handle('modulename', cfg, cloud, None, None) self.assertItemsEqual( m_user.call_args_list, [mock.call('ubuntu', groups='lxd,sudo', lock_passwd=True, shell='/bin/bash'), mock.call('me2', default=False)]) m_group.assert_not_called()
def test_non_secure_get(self): client = azure_helper.AzureEndpointHttpClient(mock.MagicMock()) url = 'MyTestUrl' response = client.get(url, secure=False) self.assertEqual(1, self.read_file_or_url.call_count) self.assertEqual(self.read_file_or_url.return_value, response) self.assertEqual(mock.call(url, headers=self.regular_headers), self.read_file_or_url.call_args)
def test_lock_with_usermod_if_no_passwd(self, m_which, m_subp, m_is_snappy): """Lock uses usermod --lock if no 'passwd' cmd available.""" m_which.side_effect = lambda m: m in ('usermod',) self.dist.lock_passwd("bob") self.assertEqual( [mock.call(['usermod', '--lock', 'bob'])], m_subp.call_args_list)
def test_users_with_ssh_redirect_user_default_false(self, m_user, m_group): """When unspecified ssh_redirect_user is false and not set up.""" cfg = {'users': ['default', {'name': 'me2'}]} # System config defines a default user for the distro. sys_cfg = {'default_user': {'name': 'ubuntu', 'lock_passwd': True, 'groups': ['lxd', 'sudo'], 'shell': '/bin/bash'}} metadata = {'public-keys': ['key1']} cloud = self.tmp_cloud( distro='ubuntu', sys_cfg=sys_cfg, metadata=metadata) cc_users_groups.handle('modulename', cfg, cloud, None, None) self.assertItemsEqual( m_user.call_args_list, [mock.call('ubuntu', groups='lxd,sudo', lock_passwd=True, shell='/bin/bash'), mock.call('me2', default=False)]) m_group.assert_not_called()