def testDownloadAuthUrlFallback(self, mock_get_metadata, mock_download_url, mock_tempfile): auth_url = 'https://storage.googleapis.com/fake/url' metadata_prefix = 'http://metadata.google.internal/computeMetadata/v1/' token_url = metadata_prefix + 'instance/service-accounts/default/token' mock_tempfile.return_value = mock_tempfile mock_tempfile.name = self.dest self.retriever.token = None mock_get_metadata.return_value = None mock_download_url.return_value = None self.assertIsNone( self.retriever._DownloadAuthUrl(auth_url, self.dest_dir)) mock_get_metadata.return_value = mock_get_metadata # GetMetadata includes a prefix, so remove it. prefix = 'http://metadata.google.internal/computeMetadata/v1/' stripped_url = token_url.replace(prefix, '') mock_get_metadata.assert_called_once_with(stripped_url, recursive=False, retry=False) mock_download_url.assert_called_once_with(auth_url, self.dest_dir) self.assertIsNone(self.retriever.token) expected_calls = [ mock.call(mock.ANY, auth_url, self.dest), mock.call(mock.ANY), ] self.assertEqual(self.mock_logger.info.mock_calls, expected_calls)
def testUpdateAuthorizedKeysNoHomeDir( self, mock_islink, mock_exists, mock_tempfile, mock_copy, mock_permissions): user = '******' ssh_keys = ['Google key 1'] temp_dest = '/tmp/dest' pw_uid = 1 pw_gid = 2 pw_dir = '/home/user' ssh_dir = '/home/user/.ssh' authorized_keys_file = '/home/user/.ssh/authorized_keys' pw_entry = accounts_utils.pwd.struct_passwd( ('', '', pw_uid, pw_gid, '', pw_dir, '')) self.mock_utils._GetUser.return_value = pw_entry mock_islink.return_value = False mock_exists.side_effect = [False, False] mock_tempfile.return_value = mock_tempfile mock_tempfile.__enter__.return_value.name = temp_dest self.mock_logger.name = 'test' accounts_utils.AccountsUtils._UpdateAuthorizedKeys( self.mock_utils, user, ssh_keys) expected_calls = [ mock.call(pw_dir, mode=0o755, uid=pw_uid, gid=pw_gid, mkdir=True), mock.call(ssh_dir, mode=0o700, uid=pw_uid, gid=pw_gid, mkdir=True), mock.call(authorized_keys_file, mode=0o600, uid=pw_uid, gid=pw_gid), ] self.assertEqual(mock_permissions.mock_calls, expected_calls)
def testUpdateUsers(self): update_users = { 'a': '1', 'b': '2', 'c': '3', 'invalid': '4', 'valid': '5', 'unchanged': ['1', '2', '3'], } self.mock_setup.user_ssh_keys = { 'unchanged': ['3', '2', '1'], } self.mock_setup.invalid_users = set(['invalid']) # Make UpdateUser succeed for fake names longer than one character. self.mock_utils.UpdateUser.side_effect = lambda user, _: len(user) > 1 accounts_daemon.AccountsDaemon._UpdateUsers(self.mock_setup, update_users) expected_calls = [ mock.call('a', '1'), mock.call('b', '2'), mock.call('c', '3'), mock.call('valid', '5'), ] self.mock_utils.UpdateUser.assert_has_calls(expected_calls, any_order=True) self.assertEqual(self.mock_utils.UpdateUser.call_count, len(expected_calls)) self.assertEqual(self.mock_setup.invalid_users, set(['invalid', 'a', 'b', 'c'])) self.assertEqual(self.mock_setup.user_ssh_keys, { 'valid': '5', 'unchanged': ['3', '2', '1'] })
def testSetSshHostKeysFirstBoot(self, mock_listdir): self.mock_instance_config.GetOptionString.return_value = None mock_instance_id = mock.Mock() mock_instance_id.return_value = '123' self.mock_setup._GetInstanceId = mock_instance_id mock_generate_key = mock.Mock() self.mock_setup._GenerateSshKey = mock_generate_key mock_listdir.return_value = [ 'ssh_config', 'ssh_host_dsa_key', 'ssh_host_dsa_key.pub', 'ssh_host_ed25519_key', 'ssh_host_ed25519_key.pub', 'ssh_host_rsa_key', 'ssh_host_rsa_key.pub', ] instance_setup.InstanceSetup._SetSshHostKeys( self.mock_setup, host_key_types='rsa,dsa,abc') expected_calls = [ mock.call('abc', '/etc/ssh/ssh_host_abc_key'), mock.call('dsa', '/etc/ssh/ssh_host_dsa_key'), mock.call('ed25519', '/etc/ssh/ssh_host_ed25519_key'), mock.call('rsa', '/etc/ssh/ssh_host_rsa_key'), ] self.assertEqual(sorted(mock_generate_key.mock_calls), expected_calls) self.mock_instance_config.SetOption.assert_called_once_with( 'Instance', 'instance_id', '123')
def testSetSshHostKeysFirstBoot(self, mock_listdir): self.mock_instance_config.GetOptionString.return_value = None mock_instance_id = mock.Mock() mock_instance_id.return_value = '123' self.mock_setup._GetInstanceId = mock_instance_id mock_generate_key = mock.Mock() mock_generate_key.return_value = ('ssh-rsa', 'asdfasdf') self.mock_setup._GenerateSshKey = mock_generate_key mock_listdir.return_value = [ 'ssh_config', 'ssh_host_dsa_key', 'ssh_host_dsa_key.pub', 'ssh_host_ed25519_key', 'ssh_host_ed25519_key.pub', 'ssh_host_rsa_key', 'ssh_host_rsa_key.pub', ] instance_setup.InstanceSetup._SetSshHostKeys( self.mock_setup, host_key_types='rsa,dsa,abc') expected_calls = [ mock.call('abc', '/etc/ssh/ssh_host_abc_key'), mock.call('dsa', '/etc/ssh/ssh_host_dsa_key'), mock.call('ed25519', '/etc/ssh/ssh_host_ed25519_key'), mock.call('rsa', '/etc/ssh/ssh_host_rsa_key'), ] self.assertEqual(sorted(mock_generate_key.mock_calls), expected_calls) self.mock_instance_config.SetOption.assert_called_once_with( 'Instance', 'instance_id', '123')
def testRunScript(self, mock_subprocess): mock_readline = mock.Mock() mock_readline.side_effect = [bytes(b'a\n'), bytes(b'b\n'), bytes(b'')] mock_stdout = mock.Mock() mock_stdout.readline = mock_readline mock_process = mock.Mock() mock_process.poll.return_value = 0 mock_process.stdout = mock_stdout mock_process.returncode = 1 mock_subprocess.Popen.return_value = mock_process metadata_key = '%s-script' % self.script_type self.executor._RunScript(metadata_key, self.metadata_script) expected_calls = [ mock.call('%s: %s', metadata_key, 'a'), mock.call('%s: %s', metadata_key, 'b'), mock.call('%s: Return code %s.', metadata_key, 1), ] self.assertEqual(self.mock_logger.info.mock_calls, expected_calls) mock_subprocess.Popen.assert_called_once_with( self.metadata_script, shell=True, executable='/bin/bash', stderr=mock_subprocess.STDOUT, stdout=mock_subprocess.PIPE) mock_process.poll.assert_called_once_with()
def testDownloadAuthUrlFallback( self, mock_get_metadata, mock_download_url, mock_tempfile): auth_url = 'https://storage.googleapis.com/fake/url' metadata_prefix = 'http://metadata.google.internal/computeMetadata/v1/' token_url = metadata_prefix + 'instance/service-accounts/default/token' mock_tempfile.return_value = mock_tempfile mock_tempfile.name = self.dest self.retriever.token = None mock_get_metadata.return_value = None mock_download_url.return_value = None self.assertIsNone(self.retriever._DownloadAuthUrl(auth_url, self.dest_dir)) mock_get_metadata.return_value = mock_get_metadata # GetMetadata includes a prefix, so remove it. prefix = 'http://metadata.google.internal/computeMetadata/v1/' stripped_url = token_url.replace(prefix, '') mock_get_metadata.assert_called_once_with( stripped_url, recursive=False, retry=False) mock_download_url.assert_called_once_with(auth_url, self.dest_dir) self.assertIsNone(self.retriever.token) expected_calls = [ mock.call(mock.ANY, auth_url, self.dest), mock.call(mock.ANY), ] self.assertEqual(self.mock_logger.info.mock_calls, expected_calls)
def testAddHeader(self): mock_fp = mock.Mock() self.mock_config_manager._AddHeader(mock_fp) expected_calls = [ mock.call('# %s' % self.config_header), mock.call('\n\n'), ] self.assertEqual(mock_fp.write.mock_calls, expected_calls)
def testWriteConfig(self): mock_open = mock.mock_open() with mock.patch('%s.open' % builtin, mock_open, create=False): self.mock_config_manager.WriteConfig() expected_calls = [ mock.call('# %s' % self.config_header), mock.call('\n\n'), ] self.assertEqual(mock_open().write.mock_calls, expected_calls)
def testUpdateAuthorizedKeys( self, mock_islink, mock_exists, mock_tempfile, mock_copy, mock_permissions): mock_open = mock.mock_open() user = '******' ssh_keys = ['Google key 1', 'Google key 2'] temp_dest = '/tmp/dest' pw_uid = 1 pw_gid = 2 pw_dir = '/home' ssh_dir = '/home/.ssh' authorized_keys_file = '/home/.ssh/authorized_keys' pw_entry = accounts_utils.pwd.struct_passwd( ('', '', pw_uid, pw_gid, '', pw_dir, '')) self.mock_utils._GetUser.return_value = pw_entry mock_islink.return_value = False mock_exists.return_value = True mock_tempfile.return_value = mock_tempfile mock_tempfile.__enter__.return_value.name = temp_dest self.mock_logger.name = 'test' with mock.patch('%s.open' % builtin, mock_open, create=False): mock_open().readlines.return_value = [ 'User key a\n', 'User key b\n', '\n', self.mock_utils.google_comment + '\n', 'Google key a\n', self.mock_utils.google_comment + '\n', 'Google key b\n', 'User key c\n', ] accounts_utils.AccountsUtils._UpdateAuthorizedKeys( self.mock_utils, user, ssh_keys) expected_calls = [ mock.call(mode='w', prefix='test-', delete=True), mock.call.__enter__(), mock.call.__enter__().write('User key a\n'), mock.call.__enter__().write('User key b\n'), mock.call.__enter__().write('\n'), mock.call.__enter__().write('User key c\n'), mock.call.__enter__().write(self.mock_utils.google_comment + '\n'), mock.call.__enter__().write('Google key 1\n'), mock.call.__enter__().write(self.mock_utils.google_comment + '\n'), mock.call.__enter__().write('Google key 2\n'), mock.call.__enter__().flush(), mock.call.__exit__(None, None, None), ] self.assertEqual(mock_tempfile.mock_calls, expected_calls) mock_copy.assert_called_once_with(temp_dest, authorized_keys_file) expected_calls = [ mock.call(ssh_dir, mode=0o700, uid=pw_uid, gid=pw_gid, mkdir=True), mock.call(authorized_keys_file, mode=0o600, uid=pw_uid, gid=pw_gid), ] self.assertEqual(mock_permissions.mock_calls, expected_calls) self.mock_logger.warning.assert_not_called()
def testUpdateAuthorizedKeys(self, mock_islink, mock_exists, mock_tempfile, mock_copy, mock_permissions): mock_open = mock.mock_open() user = '******' ssh_keys = ['Google key 1', 'Google key 2'] temp_dest = '/tmp/dest' pw_uid = 1 pw_gid = 2 pw_dir = '/home' ssh_dir = '/home/.ssh' authorized_keys_file = '/home/.ssh/authorized_keys' pw_entry = accounts_utils.pwd.struct_passwd( ('', '', pw_uid, pw_gid, '', pw_dir, '')) self.mock_utils._GetUser.return_value = pw_entry mock_islink.return_value = False mock_exists.return_value = True mock_tempfile.return_value = mock_tempfile mock_tempfile.__enter__.return_value.name = temp_dest self.mock_logger.name = 'test' with mock.patch('%s.open' % builtin, mock_open, create=False): mock_open().readlines.return_value = [ 'User key a\n', 'User key b\n', '\n', self.mock_utils.google_comment + '\n', 'Google key a\n', self.mock_utils.google_comment + '\n', 'Google key b\n', 'User key c\n', ] accounts_utils.AccountsUtils._UpdateAuthorizedKeys( self.mock_utils, user, ssh_keys) expected_calls = [ mock.call(mode='w', prefix='test-', delete=True), mock.call.__enter__(), mock.call.__enter__().write('User key a\n'), mock.call.__enter__().write('User key b\n'), mock.call.__enter__().write('\n'), mock.call.__enter__().write('User key c\n'), mock.call.__enter__().write(self.mock_utils.google_comment + '\n'), mock.call.__enter__().write('Google key 1\n'), mock.call.__enter__().write(self.mock_utils.google_comment + '\n'), mock.call.__enter__().write('Google key 2\n'), mock.call.__enter__().flush(), mock.call.__exit__(None, None, None), ] self.assertEqual(mock_tempfile.mock_calls, expected_calls) mock_copy.assert_called_once_with(temp_dest, authorized_keys_file) expected_calls = [ mock.call(ssh_dir, mode=0o700, uid=pw_uid, gid=pw_gid, mkdir=True), mock.call(authorized_keys_file, mode=0o600, uid=pw_uid, gid=pw_gid), ] self.assertEqual(mock_permissions.mock_calls, expected_calls) self.mock_logger.warning.assert_not_called()
def testRemoveUsers(self): remove_users = ['a', 'b', 'c', 'valid'] self.mock_setup.invalid_users = set(['invalid', 'a', 'b', 'c']) accounts_daemon.AccountsDaemon._RemoveUsers(self.mock_setup, remove_users) expected_calls = [ mock.call('a'), mock.call('b'), mock.call('c'), mock.call('valid'), ] self.mock_utils.RemoveUser.assert_has_calls(expected_calls) self.assertEqual(self.mock_setup.invalid_users, set(['invalid']))
def testHandleMetadataUpdateException(self): mock_response = mock.Mock() first = metadata_watcher.socket.timeout() second = metadata_watcher.urlerror.URLError('Test') mock_response.side_effect = [first, first, second, {}] self.mock_watcher._GetMetadataUpdate = mock_response metadata_key = 'instance/id' recursive = False wait = False retries = 5 self.assertEqual( self.mock_watcher._HandleMetadataUpdate(metadata_key=metadata_key, recursive=recursive, wait=wait, timeout=None, retries=retries), {}) expected_calls = [ mock.call(metadata_key=metadata_key, recursive=recursive, wait=wait, timeout=None), ] * 4 self.assertEqual(mock_response.mock_calls, expected_calls) expected_calls = [mock.call.error(mock.ANY, mock.ANY)] * 2 self.assertEqual(self.mock_logger.mock_calls, expected_calls)
def testSetConfiguredUsers(self, mock_tempfile, mock_copy, mock_permissions, mock_exists, mock_makedirs): temp_dest = '/temp/dest' users = ['a', 'b', 'c'] mock_tempfile.return_value = mock_tempfile mock_tempfile.__enter__.return_value.name = temp_dest mock_exists.return_value = False self.mock_logger.name = 'test' accounts_utils.AccountsUtils.SetConfiguredUsers(self.mock_utils, users) expected_calls = [ mock.call(mode='w', prefix='test-', delete=True), mock.call.__enter__(), mock.call.__enter__().write('a\n'), mock.call.__enter__().write('b\n'), mock.call.__enter__().write('c\n'), mock.call.__enter__().flush(), mock.call.__exit__(None, None, None), ] self.assertEqual(mock_tempfile.mock_calls, expected_calls) mock_makedirs.assert_called_once_with(self.users_dir) mock_copy.assert_called_once_with(temp_dest, self.users_file) mock_permissions.assert_called_once_with( self.users_file, mode=0o600, uid=0, gid=0)
def testAddIpAlias(self, mock_netaddr): mock_netaddr.IPNetwork.return_value = [ '1.1.1.0', '1.1.1.1', '1.1.1.2', '1.1.1.3' ] mock_run = mock.Mock() self.mock_utils._RunIfconfig = mock_run self.mock_utils.AddForwardedIp('1.1.1.1/30', 'interface') mock_netaddr.IPNetwork.assert_called_once_with('1.1.1.1/30') expected_calls = [ mock.call(args=['interface', 'alias', '1.1.1.0/32']), mock.call(args=['interface', 'alias', '1.1.1.1/32']), mock.call(args=['interface', 'alias', '1.1.1.2/32']), mock.call(args=['interface', 'alias', '1.1.1.3/32']) ] self.assertEqual(mock_run.mock_calls, expected_calls)
def testSetConfiguredUsers(self, mock_tempfile, mock_copy, mock_permissions, mock_exists, mock_makedirs): temp_dest = '/temp/dest' users = ['a', 'b', 'c'] mock_tempfile.return_value = mock_tempfile mock_tempfile.__enter__.return_value.name = temp_dest mock_exists.return_value = False self.mock_logger.name = 'test' accounts_utils.AccountsUtils.SetConfiguredUsers(self.mock_utils, users) expected_calls = [ mock.call(mode='w', prefix='test-', delete=True), mock.call.__enter__(), mock.call.__enter__().write('a\n'), mock.call.__enter__().write('b\n'), mock.call.__enter__().write('c\n'), mock.call.__enter__().flush(), mock.call.__exit__(None, None, None), ] self.assertEqual(mock_tempfile.mock_calls, expected_calls) mock_makedirs.assert_called_once_with(self.users_dir) mock_copy.assert_called_once_with(temp_dest, self.users_file) mock_permissions.assert_called_once_with(self.users_file, mode=0o600, uid=0, gid=0)
def testRunScript(self, mock_subprocess): mock_readline = mock.Mock() mock_readline.side_effect = [bytes(b'a\n'), bytes(b'b\n'), bytes(b'')] mock_stdout = mock.Mock() mock_stdout.readline = mock_readline mock_process = mock.Mock() mock_process.poll.return_value = 0 mock_process.stdout = mock_stdout mock_subprocess.Popen.return_value = mock_process script = '/tmp/script.py' instance_setup.InstanceSetup._RunScript(self.mock_setup, script) expected_calls = [mock.call('a'), mock.call('b')] self.assertEqual(self.mock_logger.info.mock_calls, expected_calls) mock_subprocess.Popen.assert_called_once_with( script, shell=True, stderr=mock_subprocess.STDOUT, stdout=mock_subprocess.PIPE) mock_process.poll.assert_called_once_with()
def testRemoveUsers(self): remove_users = ['a', 'b', 'c', 'valid'] self.mock_setup.user_ssh_keys = { 'a': ['1'], 'b': ['2'], 'c': ['3'], 'invalid': ['key'], } self.mock_setup.invalid_users = set(['invalid', 'a', 'b', 'c']) accounts_daemon.AccountsDaemon._RemoveUsers(self.mock_setup, remove_users) expected_calls = [ mock.call('a'), mock.call('b'), mock.call('c'), mock.call('valid'), ] self.mock_utils.RemoveUser.assert_has_calls(expected_calls) self.assertEqual(self.mock_setup.invalid_users, set(['invalid'])) self.assertEqual(self.mock_setup.user_ssh_keys, {'invalid': ['key']})
def testUpdateAuthorizedKeysSymlink(self, mock_islink, mock_permissions): user = '******' ssh_keys = ['Google key 1'] pw_uid = 1 pw_gid = 2 pw_dir = '/home' ssh_dir = '/home/.ssh' authorized_keys_file = '/home/.ssh/authorized_keys' pw_entry = accounts_utils.pwd.struct_passwd( ('', '', pw_uid, pw_gid, '', pw_dir, '')) self.mock_utils._GetUser.return_value = pw_entry mock_islink.side_effect = [False, True] accounts_utils.AccountsUtils._UpdateAuthorizedKeys( self.mock_utils, user, ssh_keys) expected_calls = [mock.call(ssh_dir), mock.call(authorized_keys_file)] self.assertEqual(mock_islink.mock_calls, expected_calls) self.mock_logger.warning.assert_called_once_with(mock.ANY, user) mock_permissions.assert_not_called()
def testCallNtpdateActive(self, mock_call, mock_check_call): command_status = ['service', 'ntpd', 'status'] command_stop = ['service', 'ntpd', 'stop'] command_start = ['service', 'ntpd', 'start'] command_ntpdate = 'ntpdate `awk \'$1=="server" {print $2}\' /etc/ntp.conf`' mock_logger = mock.Mock() mock_call.return_value = 0 mock_check_call.return_value = True helpers.CallNtpdate(mock_logger) mock_call.assert_called_once_with(command_status) expected_calls = [ mock.call(command_stop), mock.call(command_ntpdate, shell=True), mock.call(command_start), ] self.assertEqual(mock_check_call.mock_calls, expected_calls) expected_calls = [mock.call.info(mock.ANY)] self.assertEqual(mock_logger.mock_calls, expected_calls)
def testGetAccessToken(self, mock_watcher): mock_watcher.MetadataWatcher.return_value = mock_watcher mock_watcher.GetMetadata.side_effect = [ list(compute_auth.GS_SCOPES), # The Google Storage scopes. {'access_token': 'token'}, # The access token. {}, # The access token second query. ] mock_compute_auth = compute_auth.ComputeAuth( None, self.mock_config, self.mock_provider) self.assertEqual(mock_compute_auth._GetAccessToken(), 'token') self.assertEqual(mock_compute_auth._GetAccessToken(), None) token_key = 'instance/service-accounts/%s/token' % self.service_account expected_calls = [ mock.ANY, mock.call(metadata_key=token_key, recursive=False), mock.call(metadata_key=token_key, recursive=False), ] self.assertEqual(mock_watcher.GetMetadata.mock_calls, expected_calls)
def testEnableRouteAdvertisements(self, mock_call): mock_logger = mock.Mock() interfaces = ['foo', 'bar', 'baz'] helpers.CallEnableRouteAdvertisements(interfaces, mock_logger) mock_call.assert_has_calls([ mock.call([ 'sysctl', '-w', 'net.ipv6.conf.%s.accept_ra_rt_info_max_plen=128' % interface, ]) for interface in interfaces ])
def testGetAccessToken(self, mock_watcher): mock_watcher.MetadataWatcher.return_value = mock_watcher mock_watcher.GetMetadata.side_effect = [ list(compute_auth.GS_SCOPES), # The Google Storage scopes. { 'access_token': 'token' }, # The access token. {}, # The access token second query. ] mock_compute_auth = compute_auth.ComputeAuth(None, self.mock_config, self.mock_provider) self.assertEqual(mock_compute_auth._GetAccessToken(), 'token') self.assertEqual(mock_compute_auth._GetAccessToken(), None) token_key = 'instance/service-accounts/%s/token' % self.service_account expected_calls = [ mock.ANY, mock.call(metadata_key=token_key, recursive=False), mock.call(metadata_key=token_key, recursive=False), ] self.assertEqual(mock_watcher.GetMetadata.mock_calls, expected_calls)
def testUpdateAuthorizedKeysNoKeys(self, mock_islink, mock_exists, mock_tempfile, mock_copy, mock_permissions): user = '******' ssh_keys = ['Google key 1'] temp_dest = '/tmp/dest' pw_uid = 1 pw_gid = 2 pw_dir = '/home' ssh_dir = '/home/.ssh' authorized_keys_file = '/home/.ssh/authorized_keys' pw_entry = accounts_utils.pwd.struct_passwd( ('', '', pw_uid, pw_gid, '', pw_dir, '')) self.mock_utils._GetUser.return_value = pw_entry mock_islink.return_value = False mock_exists.side_effect = [True, False] mock_tempfile.return_value = mock_tempfile mock_tempfile.__enter__.return_value.name = temp_dest self.mock_logger.name = 'test' # The authorized keys file does not exist so write a new one. accounts_utils.AccountsUtils._UpdateAuthorizedKeys( self.mock_utils, user, ssh_keys) expected_calls = [ mock.call(mode='w', prefix='test-', delete=True), mock.call.__enter__(), mock.call.__enter__().write(self.mock_utils.google_comment + '\n'), mock.call.__enter__().write('Google key 1\n'), mock.call.__enter__().flush(), mock.call.__exit__(None, None, None), ] self.assertEqual(mock_tempfile.mock_calls, expected_calls) mock_copy.assert_called_once_with(temp_dest, authorized_keys_file) expected_calls = [ mock.call(ssh_dir, mode=0o700, uid=pw_uid, gid=pw_gid, mkdir=True), mock.call(authorized_keys_file, mode=0o600, uid=pw_uid, gid=pw_gid), ] self.assertEqual(mock_permissions.mock_calls, expected_calls) self.mock_logger.warning.assert_not_called()
def testUpdateAuthorizedKeysNoKeys( self, mock_islink, mock_exists, mock_tempfile, mock_copy, mock_permissions): user = '******' ssh_keys = ['Google key 1'] temp_dest = '/tmp/dest' pw_uid = 1 pw_gid = 2 pw_dir = '/home' ssh_dir = '/home/.ssh' authorized_keys_file = '/home/.ssh/authorized_keys' pw_entry = accounts_utils.pwd.struct_passwd( ('', '', pw_uid, pw_gid, '', pw_dir, '')) self.mock_utils._GetUser.return_value = pw_entry mock_islink.return_value = False mock_exists.side_effect = [True, False] mock_tempfile.return_value = mock_tempfile mock_tempfile.__enter__.return_value.name = temp_dest self.mock_logger.name = 'test' # The authorized keys file does not exist so write a new one. accounts_utils.AccountsUtils._UpdateAuthorizedKeys( self.mock_utils, user, ssh_keys) expected_calls = [ mock.call(mode='w', prefix='test-', delete=True), mock.call.__enter__(), mock.call.__enter__().write(self.mock_utils.google_comment + '\n'), mock.call.__enter__().write('Google key 1\n'), mock.call.__enter__().flush(), mock.call.__exit__(None, None, None), ] self.assertEqual(mock_tempfile.mock_calls, expected_calls) mock_copy.assert_called_once_with(temp_dest, authorized_keys_file) expected_calls = [ mock.call(ssh_dir, mode=0o700, uid=pw_uid, gid=pw_gid, mkdir=True), mock.call(authorized_keys_file, mode=0o600, uid=pw_uid, gid=pw_gid), ] self.assertEqual(mock_permissions.mock_calls, expected_calls) self.mock_logger.warning.assert_not_called()
def testUpdateUsers(self): update_users = { 'a': '1', 'b': '2', 'c': '3', 'invalid': '4', 'valid': '5', } self.mock_setup.invalid_users = set(['invalid']) # Make UpdateUser succeed for fake names longer than one character. self.mock_utils.UpdateUser.side_effect = lambda user, _: len(user) > 1 accounts_daemon.AccountsDaemon._UpdateUsers(self.mock_setup, update_users) expected_calls = [ mock.call('a', '1'), mock.call('b', '2'), mock.call('c', '3'), mock.call('valid', '5'), ] self.mock_utils.UpdateUser.assert_has_calls(expected_calls, any_order=True) self.assertEqual( self.mock_utils.UpdateUser.call_count, len(expected_calls)) self.assertEqual( self.mock_setup.invalid_users, set(['invalid', 'a', 'b', 'c']))
def testCreateConfigProjectId(self, mock_config, mock_watcher): mock_config_instance = mock.Mock() mock_config.ConfigManager.return_value = mock_config_instance mock_watcher_instance = mock.Mock() mock_watcher.MetadataWatcher.return_value = mock_watcher_instance mock_watcher_instance.GetMetadata.return_value = self.project_id boto_config.BotoConfig() mock_watcher_instance.GetMetadata.assert_called_once_with( metadata_key='project/numeric-project-id', recursive=False) expected_calls = [ mock.call('GSUtil', 'default_project_id', self.project_id), ] mock_config_instance.SetOption.assert_has_calls(expected_calls)
def testRunScript(self, mock_subprocess): mock_readline = mock.Mock() mock_readline.side_effect = [bytes(b'a\n'), bytes(b'b\n'), bytes(b'')] mock_stdout = mock.Mock() mock_stdout.readline = mock_readline mock_process = mock.Mock() mock_process.poll.return_value = 0 mock_process.stdout = mock_stdout mock_process.returncode = 1 mock_subprocess.Popen.return_value = mock_process metadata_key = '%s-script' % self.script_type self.executor._RunScript(metadata_key, self.metadata_script) expected_calls = [ mock.call('%s: %s', metadata_key, 'a'), mock.call('%s: %s', metadata_key, 'b'), mock.call('%s: Return code %s.', metadata_key, 1), ] self.assertEqual(self.mock_logger.info.mock_calls, expected_calls) mock_subprocess.Popen.assert_called_once_with( self.metadata_script, shell=True, stderr=mock_subprocess.STDOUT, stdout=mock_subprocess.PIPE) mock_process.poll.assert_called_once_with()
def testGetAccessToken(self, mock_watcher): mock_auth = mock.create_autospec(compute_auth.ComputeAuth) mock_auth.watcher = mock_watcher mock_auth.metadata_key = self.metadata_key mock_auth.service_account = self.service_account mock_watcher.GetMetadata.side_effect = [ {self.service_account: {'token': {'access_token': 'test'}}}, {}, ] self.assertEqual( compute_auth.ComputeAuth._GetAccessToken(mock_auth), 'test') self.assertEqual( compute_auth.ComputeAuth._GetAccessToken(mock_auth), None) expected_calls = [mock.call(metadata_key=self.metadata_key)] * 2 self.assertEqual(mock_watcher.GetMetadata.mock_calls, expected_calls)
def testGetMetadataUpdateWait(self): self.params['last_etag'] = 1 self.mock_watcher.etag = 1 mock_unchanged = mock.Mock() mock_unchanged.headers = {'etag': 1} mock_unchanged.read.return_value = bytes(b'{}') mock_changed = mock.Mock() mock_changed.headers = {'etag': 2} mock_changed.read.return_value = bytes(b'{}') mock_response = mock.Mock() mock_response.side_effect = [mock_unchanged, mock_unchanged, mock_changed] self.mock_watcher._GetMetadataRequest = mock_response request_url = os.path.join(self.url, '') self.mock_watcher._GetMetadataUpdate() self.assertEqual(self.mock_watcher.etag, 2) expected_calls = [mock.call(request_url, params=self.params)] * 3 self.assertEqual(mock_response.mock_calls, expected_calls)
def testGetMetadataUpdateWait(self): self.params['last_etag'] = 1 self.mock_watcher.etag = 1 mock_unchanged = mock.Mock() mock_unchanged.headers = {'etag': 1} mock_unchanged.read.return_value = bytes(b'{}') mock_changed = mock.Mock() mock_changed.headers = {'etag': 2} mock_changed.read.return_value = bytes(b'{}') mock_response = mock.Mock() mock_response.side_effect = [mock_unchanged, mock_unchanged, mock_changed] self.mock_watcher._GetMetadataRequest = mock_response request_url = os.path.join(self.url, '') self.mock_watcher._GetMetadataUpdate() self.assertEqual(self.mock_watcher.etag, 2) expected_calls = [ mock.call(request_url, params=self.params, timeout=None), ] * 3 self.assertEqual(mock_response.mock_calls, expected_calls)
def testHandleMetadataUpdateException(self): mock_response = mock.Mock() first = metadata_watcher.socket.timeout() second = metadata_watcher.urlerror.URLError('Test') mock_response.side_effect = [first, first, second, {}] self.mock_watcher._GetMetadataUpdate = mock_response metadata_key = 'instance/id' recursive = False wait = False self.assertEqual( self.mock_watcher._HandleMetadataUpdate( metadata_key=metadata_key, recursive=recursive, wait=wait), {}) expected_calls = [ mock.call(metadata_key=metadata_key, recursive=recursive, wait=wait), ] * 4 self.assertEqual(mock_response.mock_calls, expected_calls) expected_calls = [mock.call.exception(mock.ANY)] * 2 self.assertEqual(self.mock_logger.mock_calls, expected_calls)
def testHandleMetadataUpdateExceptionNoRetry(self): mock_response = mock.Mock() mock_response.side_effect = metadata_watcher.socket.timeout() self.mock_watcher._GetMetadataUpdate = mock_response metadata_key = 'instance/id' recursive = False wait = False retry = False self.assertIsNone( self.mock_watcher._HandleMetadataUpdate( metadata_key=metadata_key, recursive=recursive, wait=wait, timeout=None, retry=retry)) expected_calls = [ mock.call( metadata_key=metadata_key, recursive=recursive, wait=wait, timeout=None), ] self.assertEqual(mock_response.mock_calls, expected_calls) expected_calls = [mock.call.error(mock.ANY, mock.ANY)] self.assertEqual(self.mock_logger.mock_calls, expected_calls)
def testGetAccessToken(self, mock_watcher): mock_auth = mock.create_autospec(compute_auth.ComputeAuth) mock_auth.watcher = mock_watcher mock_auth.metadata_key = self.metadata_key mock_auth.service_account = self.service_account mock_watcher.GetMetadata.side_effect = [ { self.service_account: { 'token': { 'access_token': 'test' } } }, {}, ] self.assertEqual(compute_auth.ComputeAuth._GetAccessToken(mock_auth), 'test') self.assertEqual(compute_auth.ComputeAuth._GetAccessToken(mock_auth), None) expected_calls = [mock.call(metadata_key=self.metadata_key)] * 2 self.assertEqual(mock_watcher.GetMetadata.mock_calls, expected_calls)