desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'test pam auth mechanism errors for an invalid user'
def test_pam_auth_invalid_user(self):
cmd = '-a pam "*" test.ping --username nouser --password {0}'.format('abcd1234') resp = self.run_salt(cmd) self.assertTrue(('Failed to authenticate' in ''.join(resp)))
'test that pam auth mechanism works for a valid group'
def test_pam_auth_valid_group(self):
(password, hashed_pwd) = gen_password() set_pw_cmd = "shadow.set_password {0} '{1}'".format(self.userB, (password if salt.utils.platform.is_darwin() else hashed_pwd)) self.run_call(set_pw_cmd) cmd = '-a pam "*" test.ping --username {0} --password {1}'.format(self.userB, password) resp = self.run_salt(cmd) self.assertTrue(('minion:' in resp))
'Test passing a non-supported keyword argument. The relevant code that checks for invalid kwargs is located in salt/minion.py, within the \'load_args_and_kwargs\' function.'
def test_unsupported_kwarg(self):
self.assertIn("ERROR executing 'test.ping': The following keyword arguments", self.run_function('test.ping', foo='bar'))
'Tests the arg parser to ensure that kwargs with dashes in the arg name are properly identified as kwargs. If this fails, then the KWARG_REGEX variable in salt/utils/__init__.py needs to be fixed.'
def test_kwarg_name_containing_dashes(self):
self.assertEqual(self.run_function('test.arg', salt.utils.args.parse_input(['foo-bar=baz'])).get('kwargs', {}).get('foo-bar'), 'baz')
'Tests the argument parsing to ensure that a CLI argument with a pound sign doesn\'t have the pound sign interpreted as a comment and removed. See https://github.com/saltstack/salt/issues/8585 for more info.'
def test_argument_containing_pound_sign(self):
arg = 'foo bar #baz' self.assertEqual(self.run_function('test.echo', [arg]), arg)
'Ensure correct exit status when --proxyid argument is missing.'
def test_exit_status_no_proxyid(self):
proxy = testprogram.TestDaemonSaltProxy(name='proxy-no_proxyid', parent_dir=self._test_dir) proxy.setup() (stdout, stderr, status) = proxy.run(args=['--config-dir', proxy.abs_path(proxy.config_dir), '-d'], verbatim_args=True, catch_stderr=True, with_retcode=True, timeout=60) try: self.assert_exit_status(status, 'EX_USAGE', message='no --proxyid specified', stdout=stdout, stderr=tests.integration.utils.decode_byte_list(stderr)) finally: proxy.shutdown()
'Ensure correct exit status when the proxy is configured to run as an unknown user.'
def test_exit_status_unknown_user(self):
proxy = testprogram.TestDaemonSaltProxy(name='proxy-unknown_user', config_base={'user': 'some_unknown_user_xyz'}, parent_dir=self._test_dir) proxy.setup() (stdout, stderr, status) = proxy.run(args=['-d'], catch_stderr=True, with_retcode=True) try: self.assert_exit_status(status, 'EX_NOUSER', message='unknown user not on system', stdout=stdout, stderr=tests.integration.utils.decode_byte_list(stderr)) finally: proxy.shutdown()
'Ensure correct exit status when an unknown argument is passed to salt-proxy.'
def test_exit_status_unknown_argument(self):
proxy = testprogram.TestDaemonSaltProxy(name='proxy-unknown_argument', parent_dir=self._test_dir) proxy.setup() (stdout, stderr, status) = proxy.run(args=['-d', '--unknown-argument'], catch_stderr=True, with_retcode=True) try: self.assert_exit_status(status, 'EX_USAGE', message='unknown argument', stdout=stdout, stderr=stderr) finally: proxy.shutdown()
'Ensure correct exit status when salt-proxy starts correctly.'
def test_exit_status_correct_usage(self):
proxy = testprogram.TestDaemonSaltProxy(name='proxy-correct_usage', parent_dir=self._test_dir) proxy.setup() (stdout, stderr, status) = proxy.run(args=['-d'], catch_stderr=True, with_retcode=True) try: self.assert_exit_status(status, 'EX_OK', message='correct usage', stdout=stdout, stderr=tests.integration.utils.decode_byte_list(stderr)) finally: proxy.shutdown(wait_for_orphans=3)
'Wrapper that runs the initscript for the configured minions and verifies the results.'
def _run_initscript(self, init_script, minions, minion_running, action, exitstatus=None, message=''):
user = getpass.getuser() ret = init_script.run([action], catch_stderr=True, with_retcode=True, env={'SALTMINION_CONFIGS': '\n'.join(['{0} {1}'.format(user, minion.abs_path(minion.config_dir)) for minion in minions])}, timeout=90) for line in ret[0]: log.debug('script: salt-minion: stdout: {0}'.format(line)) for line in ret[1]: log.debug('script: salt-minion: stderr: {0}'.format(line)) log.debug('exit status: {0}'.format(ret[2])) if six.PY3: std_out = '\nSTDOUT:'.join(ret[0]) std_err = '\nSTDERR:'.join(ret[1]) else: std_out = '\nSTDOUT:'.join(ret[0]) std_err = '\nSTDERR:'.join(ret[1]) for minion in minions: self.assertEqual(minion.is_running(), minion_running, 'script action "{0}" should result in minion "{1}" {2} and is not.\nSTDOUT:{3}\nSTDERR:{4}'.format(action, minion.name, ['stopped', 'running'][minion_running], std_out, std_err)) if (exitstatus is not None): self.assertEqual(ret[2], exitstatus, 'script action "{0}" {1} exited {2}, must be {3}\nSTDOUT:{4}\nSTDERR:{5}'.format(action, message, ret[2], exitstatus, std_out, std_err)) return ret
'Re-usable setup for running salt-minion tests'
def _initscript_setup(self, minions):
_minions = [] for mname in minions: pid_file = 'salt-{0}.pid'.format(mname) minion = testprogram.TestDaemonSaltMinion(name=mname, root_dir='init_script', config_dir=os.path.join('etc', mname), parent_dir=self._test_dir, pid_file=pid_file, configs={'minion': {'map': {'pidfile': os.path.join('var', 'run', pid_file), 'sock_dir': os.path.join('var', 'run', 'salt', mname), 'log_file': os.path.join('var', 'log', 'salt', mname)}}}) minion.setup() _minions.append(minion) salt_call = testprogram.TestProgramSaltCall(root_dir='init_script', parent_dir=self._test_dir) salt_call.setup() sysconf_dir = os.path.dirname(_minions[0].abs_path(_minions[0].config_dir)) cmd_env = {'PATH': ':'.join([salt_call.abs_path(salt_call.script_dir), os.getenv('PATH')]), 'SALTMINION_DEBUG': ('1' if DEBUG else ''), 'SALTMINION_PYTHON': sys.executable, 'SALTMINION_SYSCONFDIR': sysconf_dir, 'SALTMINION_BINDIR': _minions[0].abs_path(_minions[0].script_dir)} default_dir = os.path.join(sysconf_dir, 'default') if (not os.path.exists(default_dir)): os.makedirs(default_dir) with salt.utils.files.fopen(os.path.join(default_dir, 'salt'), 'w') as defaults: defaults.write('TIMEOUT=60\nTICK=1\n') init_script = testprogram.TestProgram(name='init:salt-minion', program=os.path.join(CODE_DIR, 'pkg', 'rpm', 'salt-minion'), env=cmd_env) return (_minions, salt_call, init_script)
'Various tests of the init script to verify that it properly controls a salt minion.'
@skipIf(True, 'Disabled. Test suite hanging') def test_linux_initscript(self):
pform = platform.uname()[0].lower() if (pform not in ('linux',)): self.skipTest('salt-minion init script is unavailable on {1}'.format(platform)) (minions, _, init_script) = self._initscript_setup(self._test_minions) try: ret = self._run_initscript(init_script, minions[:1], False, 'bogusaction', 2) ret = self._run_initscript(init_script, minions[:1], False, 'reload', 3) ret = self._run_initscript(init_script, minions[:1], False, 'stop', 0, 'when not running') ret = self._run_initscript(init_script, minions[:1], False, 'status', 3, 'when not running') ret = self._run_initscript(init_script, minions[:1], False, 'condrestart', 7, 'when not running') ret = self._run_initscript(init_script, minions[:1], False, 'try-restart', 7, 'when not running') ret = self._run_initscript(init_script, minions, True, 'start', 0, 'when not running') ret = self._run_initscript(init_script, minions, True, 'status', 0, 'when running') mpids = {} for line in ret[0]: segs = line.decode(__salt_system_encoding__).split() minfo = segs[0].split(':') mpids[minfo[(-1)]] = (int(segs[(-1)]) if segs[(-1)].isdigit() else None) for minion in minions: self.assertEqual(minion.daemon_pid, mpids[minion.name], 'PID in "{0}" is {1} and does not match status PID {2}'.format(minion.abs_path(minion.pid_path), minion.daemon_pid, mpids[minion.name])) ret = self._run_initscript(init_script, minions, True, 'start', 0, 'when running') ret = self._run_initscript(init_script, minions, True, 'condrestart', 0, 'when running') ret = self._run_initscript(init_script, minions, True, 'try-restart', 0, 'when running') ret = self._run_initscript(init_script, minions, False, 'stop', 0, 'when running') finally: for minion in minions: minion.shutdown()
'Ensure correct exit status when the minion is configured to run as an unknown user.'
def test_exit_status_unknown_user(self):
minion = testprogram.TestDaemonSaltMinion(name='unknown_user', configs={'minion': {'map': {'user': 'some_unknown_user_xyz'}}}, parent_dir=self._test_dir) minion.setup() (stdout, stderr, status) = minion.run(args=['-d'], catch_stderr=True, with_retcode=True) try: self.assert_exit_status(status, 'EX_NOUSER', message='unknown user not on system', stdout=stdout, stderr=tests.integration.utils.decode_byte_list(stderr)) finally: minion.shutdown()
'Ensure correct exit status when an unknown argument is passed to salt-minion.'
def test_exit_status_unknown_argument(self):
minion = testprogram.TestDaemonSaltMinion(name='unknown_argument', parent_dir=self._test_dir) minion.setup() (stdout, stderr, status) = minion.run(args=['-d', '--unknown-argument'], catch_stderr=True, with_retcode=True) try: self.assert_exit_status(status, 'EX_USAGE', message='unknown argument', stdout=stdout, stderr=tests.integration.utils.decode_byte_list(stderr)) finally: minion.shutdown()
'Ensure correct exit status when salt-minion starts correctly.'
def test_exit_status_correct_usage(self):
minion = testprogram.TestDaemonSaltMinion(name='correct_usage', parent_dir=self._test_dir) minion.setup() (stdout, stderr, status) = minion.run(args=['-d'], catch_stderr=True, with_retcode=True) self.assert_exit_status(status, 'EX_OK', message='correct usage', stdout=stdout, stderr=stderr) minion.shutdown(wait_for_orphans=3)
'helper method to add user'
def _add_user(self):
try: add_user = self.run_call('user.add {0} createhome=False'.format(USERA)) add_pwd = self.run_call("shadow.set_password {0} '{1}'".format(USERA, (USERA_PWD if salt.utils.platform.is_darwin() else HASHED_USERA_PWD))) self.assertTrue(add_user) self.assertTrue(add_pwd) user_list = self.run_call('user.list_users') self.assertIn(USERA, str(user_list)) except AssertionError: self.run_call('user.delete {0} remove=True'.format(USERA)) self.skipTest('Could not add user or password, skipping test')
'helper method to remove user'
def _remove_user(self):
user_list = self.run_call('user.list_users') for user in user_list: if (USERA in user): self.run_call('user.delete {0} remove=True'.format(USERA))
'test salt-key -l for accepted arguments'
def test_list_accepted_args(self):
for key in ('acc', 'pre', 'den', 'un', 'rej'): data = self.run_key('-l {0}'.format(key), catch_stderr=True) self.assertNotIn('error:', '\n'.join(data[1])) data = self.run_key('-l foo-{0}'.format(key), catch_stderr=True) self.assertIn('error:', '\n'.join(data[1]))
'test salt-key -L'
def test_list_all(self):
data = self.run_key('-L') expect = None if (self.master_opts['transport'] in ('zeromq', 'tcp')): expect = ['Accepted Keys:', 'minion', 'sub_minion', 'Denied Keys:', 'Unaccepted Keys:', 'Rejected Keys:'] elif (self.master_opts['transport'] == 'raet'): expect = ['Accepted Keys:', 'minion', 'sub_minion', 'Unaccepted Keys:', 'Rejected Keys:'] self.assertEqual(data, expect)
'test salt-key -L --json-out'
def test_list_json_out(self):
data = self.run_key('-L --out json') ret = {} try: import json ret = json.loads('\n'.join(data)) except ValueError: pass expect = None if (self.master_opts['transport'] in ('zeromq', 'tcp')): expect = {'minions_rejected': [], 'minions_denied': [], 'minions_pre': [], 'minions': ['minion', 'sub_minion']} elif (self.master_opts['transport'] == 'raet'): expect = {'accepted': ['minion', 'sub_minion'], 'rejected': [], 'pending': []} self.assertEqual(ret, expect)
'test salt-key -L --yaml-out'
def test_list_yaml_out(self):
data = self.run_key('-L --out yaml') ret = {} try: import yaml ret = yaml.load('\n'.join(data)) except Exception: pass expect = [] if (self.master_opts['transport'] in ('zeromq', 'tcp')): expect = {'minions_rejected': [], 'minions_denied': [], 'minions_pre': [], 'minions': ['minion', 'sub_minion']} elif (self.master_opts['transport'] == 'raet'): expect = {'accepted': ['minion', 'sub_minion'], 'rejected': [], 'pending': []} self.assertEqual(ret, expect)
'test salt-key -L --raw-out'
def test_list_raw_out(self):
data = self.run_key('-L --out raw') self.assertEqual(len(data), 1) ret = {} try: import ast ret = ast.literal_eval(data[0]) except ValueError: pass expect = None if (self.master_opts['transport'] in ('zeromq', 'tcp')): expect = {'minions_rejected': [], 'minions_denied': [], 'minions_pre': [], 'minions': ['minion', 'sub_minion']} elif (self.master_opts['transport'] == 'raet'): expect = {'accepted': ['minion', 'sub_minion'], 'rejected': [], 'pending': []} self.assertEqual(ret, expect)
'test salt-key -l'
def test_list_acc(self):
data = self.run_key('-l acc') expect = ['Accepted Keys:', 'minion', 'sub_minion'] self.assertEqual(data, expect)
'test salt-key -l with eauth'
def test_list_acc_eauth(self):
self._add_user() data = self.run_key('-l acc --eauth pam --username {0} --password {1}'.format(USERA, USERA_PWD)) expect = ['Accepted Keys:', 'minion', 'sub_minion'] self.assertEqual(data, expect) self._remove_user()
'test salt-key -l with eauth and bad creds'
def test_list_acc_eauth_bad_creds(self):
self._add_user() data = self.run_key('-l acc --eauth pam --username {0} --password wrongpassword'.format(USERA)) expect = ['Authentication failure of type "eauth" occurred for user {0}.'.format(USERA)] self.assertEqual(data, expect) self._remove_user()
'test salt-key -l with wrong eauth'
def test_list_acc_wrong_eauth(self):
data = self.run_key('-l acc --eauth wrongeauth --username {0} --password {1}'.format(USERA, USERA_PWD)) expect = ['The specified external authentication system "wrongeauth" is not available'] self.assertEqual(data, expect)
'test salt-key -l'
def test_list_un(self):
data = self.run_key('-l un') expect = ['Unaccepted Keys:'] self.assertEqual(data, expect)
'ensure that python_shell defaults to True for cmd.run'
def test_shell_default_enabled(self):
enabled_ret = '3\nsaltines' ret = self.run_function('cmd.run', [self.cmd]) self.assertEqual(ret.strip(), enabled_ret)
'test shell disabled output for cmd.run'
def test_shell_disabled(self):
disabled_ret = 'first\nsecond\nthird\n|\nwc\n-l\n;\nexport\nSALTY_VARIABLE=saltines\n&&\necho\n$SALTY_VARIABLE\n;\necho\nduh\n&>\n/dev/null' ret = self.run_function('cmd.run', [self.cmd], python_shell=False) self.assertEqual(ret, disabled_ret)
'Test cmd.shell works correctly when using a template. Note: This test used to test that python_shell defaulted to True for templates in releases before 2017.7.0. The cmd.run --> cmd.shell aliasing was removed in 2017.7.0. Templates should now be using cmd.shell.'
def test_template_shell(self):
state_name = 'template_shell_enabled' state_filename = (state_name + '.sls') state_file = os.path.join(STATE_DIR, state_filename) enabled_ret = '3 saltines' ret_key = 'test_|-shell_enabled_|-{0}_|-configurable_test_state'.format(enabled_ret) try: with salt.utils.files.fopen(state_file, 'w') as fp_: fp_.write(textwrap.dedent(' {{% set shell_enabled = salt[\'cmd.shell\']("{0}").strip() %}}\n\n shell_enabled:\n test.configurable_test_state:\n - name: \'{{{{ shell_enabled }}}}\'\n '.format(self.cmd))) ret = self.run_function('state.sls', [state_name]) self.assertEqual(ret[ret_key]['name'], enabled_ret) finally: os.remove(state_file)
'test shell disabled output for templates (python_shell=False is the default beginning with the 2017.7.0 release).'
def test_template_default_disabled(self):
state_name = 'template_shell_disabled' state_filename = (state_name + '.sls') state_file = os.path.join(STATE_DIR, state_filename) disabled_ret = 'first second third | wc -l ; export SALTY_VARIABLE=saltines && echo $SALTY_VARIABLE ; echo duh &> /dev/null' ret_key = 'test_|-shell_enabled_|-{0}_|-configurable_test_state'.format(disabled_ret) try: with salt.utils.files.fopen(state_file, 'w') as fp_: fp_.write(textwrap.dedent(' {{% set shell_disabled = salt[\'cmd.run\']("{0}") %}}\n\n shell_enabled:\n test.configurable_test_state:\n - name: \'{{{{ shell_disabled }}}}\'\n '.format(self.cmd))) ret = self.run_function('state.sls', [state_name]) self.assertEqual(ret[ret_key]['name'], disabled_ret) finally: os.remove(state_file)
'helper method to add user'
def _add_user(self):
try: add_user = self.run_call('user.add {0} createhome=False'.format(USERA)) add_pwd = self.run_call("shadow.set_password {0} '{1}'".format(USERA, (USERA_PWD if salt.utils.platform.is_darwin() else HASHED_USERA_PWD))) self.assertTrue(add_user) self.assertTrue(add_pwd) user_list = self.run_call('user.list_users') self.assertIn(USERA, str(user_list)) except AssertionError: self.run_call('user.delete {0} remove=True'.format(USERA)) self.skipTest('Could not add user or password, skipping test')
'helper method to remove user'
def _remove_user(self):
user_list = self.run_call('user.list_users') for user in user_list: if (USERA in user): self.run_call('user.delete {0} remove=True'.format(USERA))
'test the salt-run docs system'
def test_in_docs(self):
data = self.run_run('-d') data = '\n'.join(data) self.assertIn('jobs.active:', data) self.assertIn('jobs.list_jobs:', data) self.assertIn('jobs.lookup_jid:', data) self.assertIn('manage.down:', data) self.assertIn('manage.up:', data) self.assertIn('network.wol:', data) self.assertIn('network.wollist:', data)
'Verify that hidden methods are not in run docs'
def test_notin_docs(self):
data = self.run_run('-d') data = '\n'.join(data) self.assertNotIn('jobs.SaltException:', data)
'Test to see if passing additional arguments shows an error'
def test_salt_documentation_too_many_arguments(self):
data = self.run_run('-d virt.list foo', catch_stderr=True) self.assertIn('You can only get documentation for one method at one time', '\n'.join(data[1]))
'Ensure correct exit status when an unknown argument is passed to salt-run.'
def test_exit_status_unknown_argument(self):
runner = testprogram.TestProgramSaltRun(name='run-unknown_argument', parent_dir=self._test_dir) runner.setup() (stdout, stderr, status) = runner.run(args=['--unknown-argument'], catch_stderr=True, with_retcode=True) self.assert_exit_status(status, 'EX_USAGE', message='unknown argument', stdout=stdout, stderr=stderr)
'Ensure correct exit status when salt-run starts correctly.'
def test_exit_status_correct_usage(self):
runner = testprogram.TestProgramSaltRun(name='run-correct_usage', parent_dir=self._test_dir) runner.setup() (stdout, stderr, status) = runner.run(catch_stderr=True, with_retcode=True) self.assert_exit_status(status, 'EX_OK', message='correct usage', stdout=stdout, stderr=stderr)
'test salt-run with eauth tests all eauth args'
@skip_if_not_root def test_salt_run_with_eauth_all_args(self):
args = ['--auth', '--eauth', '--external-auth', '-a'] self._add_user() for arg in args: run_cmd = self.run_run('{0} pam --username {1} --password {2} test.arg arg kwarg=kwarg1'.format(arg, USERA, USERA_PWD)) expect = ['args:', ' - arg', 'kwargs:', ' ----------', ' kwarg:', ' kwarg1'] self.assertEqual(expect, run_cmd) self._remove_user()
'test salt-run with eauth and bad password'
@skip_if_not_root def test_salt_run_with_eauth_bad_passwd(self):
self._add_user() run_cmd = self.run_run('-a pam --username {0} --password wrongpassword test.arg arg kwarg=kwarg1'.format(USERA)) expect = ['Authentication failure of type "eauth" occurred for user saltdev.'] self.assertEqual(expect, run_cmd) self._remove_user()
'test salt-run with wrong eauth parameter'
def test_salt_run_with_wrong_eauth(self):
run_cmd = self.run_run('-a wrongeauth --username {0} --password {1} test.arg arg kwarg=kwarg1'.format(USERA, USERA_PWD)) expect = ['The specified external authentication system "wrongeauth" is not available'] self.assertEqual(expect, run_cmd)
'test salt -L matcher'
def test_list(self):
data = self.run_salt('-L minion test.ping') data = '\n'.join(data) self.assertIn('minion', data) self.assertNotIn('sub_minion', data) data = self.run_salt('-L minion,sub_minion test.ping') data = '\n'.join(data) self.assertIn('minion', data) self.assertIn('sub_minion', data)
'test salt compound matcher'
def test_compound(self):
data = self.run_salt('-C "min* and G@test_grain:cheese" test.ping') self.assertTrue(minion_in_returns('minion', data)) self.assertFalse(minion_in_returns('sub_minion', data)) time.sleep(2) data = self.run_salt('-C "min* and not G@test_grain:foo" test.ping') self.assertTrue(minion_in_returns('minion', data)) self.assertFalse(minion_in_returns('sub_minion', data)) time.sleep(2) data = self.run_salt('-C "min* not G@test_grain:foo" test.ping') self.assertTrue(minion_in_returns('minion', data)) self.assertFalse(minion_in_returns('sub_minion', data)) time.sleep(2) match = 'P@test_grain:^cheese$ and * and G@test_grain:cheese' data = self.run_salt("-t 1 -C '{0}' test.ping".format(match)) self.assertTrue(minion_in_returns('minion', data)) self.assertFalse(minion_in_returns('sub_minion', data)) time.sleep(2) match = 'L@sub_minion and E@.*' data = self.run_salt('-t 1 -C "{0}" test.ping'.format(match)) self.assertTrue(minion_in_returns('sub_minion', data)) self.assertFalse(minion_in_returns('minion', data)) time.sleep(2) data = self.run_salt("-C 'not sub_minion' test.ping") self.assertTrue(minion_in_returns('minion', data)) self.assertFalse(minion_in_returns('sub_minion', data)) time.sleep(2) data = self.run_salt("-C '* and ( not G@test_grain:cheese )' test.ping") self.assertFalse(minion_in_returns('minion', data)) self.assertTrue(minion_in_returns('sub_minion', data)) time.sleep(2) data = self.run_salt("-C 'G%@planets%merc*' test.ping") self.assertTrue(minion_in_returns('minion', data)) self.assertFalse(minion_in_returns('sub_minion', data)) time.sleep(2) data = self.run_salt("-C 'P%@planets%^(mercury|saturn)$' test.ping") self.assertTrue(minion_in_returns('minion', data)) self.assertTrue(minion_in_returns('sub_minion', data)) time.sleep(2) data = self.run_salt("-C 'I%@companions%three%sarah*' test.ping") self.assertTrue(minion_in_returns('minion', data)) self.assertTrue(minion_in_returns('sub_minion', data)) time.sleep(2) data = self.run_salt("-C 'J%@knights%^(Lancelot|Galahad)$' test.ping") self.assertTrue(minion_in_returns('minion', data)) self.assertTrue(minion_in_returns('sub_minion', data))
'test salt nodegroup matcher'
def test_nodegroup(self):
data = self.run_salt('-N min test.ping') self.assertTrue(minion_in_returns('minion', data)) self.assertFalse(minion_in_returns('sub_minion', data)) time.sleep(2) data = self.run_salt('-N sub_min test.ping') self.assertFalse(minion_in_returns('minion', data)) self.assertTrue(minion_in_returns('sub_minion', data)) time.sleep(2) data = self.run_salt('-N mins test.ping') self.assertTrue(minion_in_returns('minion', data)) self.assertTrue(minion_in_returns('sub_minion', data)) time.sleep(2) data = self.run_salt('-N unknown_nodegroup test.ping') self.assertFalse(minion_in_returns('minion', data)) self.assertFalse(minion_in_returns('sub_minion', data)) time.sleep(2) data = self.run_salt('-N redundant_minions test.ping') self.assertTrue(minion_in_returns('minion', data)) self.assertTrue(minion_in_returns('sub_minion', data)) time.sleep(2) data = '\n'.join(self.run_salt('-N nodegroup_loop_a test.ping')) self.assertIn('No minions matched', data) time.sleep(2) data = self.run_salt('-N multiline_nodegroup test.ping') self.assertTrue(minion_in_returns('minion', data)) self.assertTrue(minion_in_returns('sub_minion', data))
'test salt glob matcher'
def test_glob(self):
data = self.run_salt('minion test.ping') data = '\n'.join(data) self.assertIn('minion', data) self.assertNotIn('sub_minion', data) data = self.run_salt('"*" test.ping') data = '\n'.join(data) self.assertIn('minion', data) self.assertIn('sub_minion', data)
'test salt regex matcher'
def test_regex(self):
data = self.run_salt('-E "^minion$" test.ping') data = '\n'.join(data) self.assertIn('minion', data) self.assertNotIn('sub_minion', data) data = self.run_salt('-E ".*" test.ping') data = '\n'.join(data) self.assertIn('minion', data) self.assertIn('sub_minion', data)
'test salt grain matcher'
def test_grain(self):
self.run_salt('-t1 "*" saltutil.sync_grains') data = self.run_salt('-t 1 -G "test_grain:cheese" test.ping') data = '\n'.join(data) self.assertIn('minion', data) self.assertNotIn('sub_minion', data) data = self.run_salt('-G "test_grain:spam" test.ping') data = '\n'.join(data) self.assertIn('sub_minion', data) self.assertNotIn('minion', data.replace('sub_minion', 'stub')) data = self.run_salt('-t 1 -G "match:maker" test.ping') data = '\n'.join(data) self.assertIn('minion', data) self.assertIn('sub_minion', data) data = self.run_salt('-t 1 -G "planets:earth" test.ping') data = '\n'.join(data) self.assertIn('minion', data) self.assertNotIn('sub_minion', data) data = self.run_salt('-G "planets:saturn" test.ping') data = '\n'.join(data) self.assertIn('sub_minion', data) self.assertNotIn('minion', data.replace('sub_minion', 'stub')) data = self.run_salt('-G "planets:pluto" test.ping') expect = None if (self.master_opts['transport'] in ('zeromq', 'tcp')): expect = 'No minions matched the target. No command was sent, no jid was assigned.' elif (self.master_opts['transport'] == 'raet'): expect = '' self.assertEqual(''.join(data), expect) data = self.run_salt('-t 1 -G "level1:level2:foo" test.ping') data = '\n'.join(data) self.assertIn('minion', data) self.assertNotIn('sub_minion', data) data = self.run_salt('-G "level1:level2:bar" test.ping') data = '\n'.join(data) self.assertIn('sub_minion', data) self.assertNotIn('minion', data.replace('sub_minion', 'stub')) data = self.run_salt('-t 1 -G "companions:one:ian" test.ping') data = '\n'.join(data) self.assertIn('minion', data) self.assertNotIn('sub_minion', data) data = self.run_salt('-G "companions:two:jamie" test.ping') data = '\n'.join(data) self.assertIn('sub_minion', data) self.assertNotIn('minion', data.replace('sub_minion', 'stub')) data = self.run_salt('-G "companions:*:susan" test.ping') data = '\n'.join(data) self.assertIn('minion:', data) self.assertNotIn('sub_minion', data) data = self.run_salt('-G "companions:one:*" test.ping') data = '\n'.join(data) self.assertIn('minion:', data) self.assertNotIn('sub_minion', data) data = self.run_salt('-G "companions:*:*" test.ping') data = '\n'.join(data) self.assertIn('minion:', data) self.assertIn('sub_minion', data)
'test salt grain matcher'
def test_regrain(self):
data = self.run_salt('-t 1 --grain-pcre "test_grain:^cheese$" test.ping') data = '\n'.join(data) self.assertIn('minion', data) self.assertNotIn('sub_minion', data) data = self.run_salt('--grain-pcre "test_grain:.*am$" test.ping') data = '\n'.join(data) self.assertIn('sub_minion', data) self.assertNotIn('minion', data.replace('sub_minion', 'stub'))
'test pillar matcher'
def test_pillar(self):
data = self.run_salt('-I "monty:python" test.ping') data = '\n'.join(data) self.assertIn('minion', data) self.assertIn('sub_minion', data) data = self.run_salt('-I "sub:sub_minion" test.ping') data = '\n'.join(data) self.assertIn('sub_minion', data) self.assertNotIn('minion', data.replace('sub_minion', 'stub')) data = self.run_salt('-I "knights:Bedevere" test.ping') data = '\n'.join(data) self.assertIn('minion', data) self.assertIn('sub_minion', data) data = self.run_salt('-I "level1:level2:foo" test.ping') data = '\n'.join(data) self.assertIn('minion', data) self.assertIn('sub_minion', data) data = self.run_salt('-I "companions:three:sarah jane" test.ping') data = '\n'.join(data) self.assertIn('minion', data) self.assertIn('sub_minion', data)
'test salt pillar PCRE matcher'
def test_repillar(self):
data = self.run_salt('-J "monty:^(python|hall)$" test.ping') data = '\n'.join(data) self.assertIn('minion', data) self.assertIn('sub_minion', data) data = self.run_salt('--pillar-pcre "knights:^(Robin|Lancelot)$" test.ping') data = '\n'.join(data) self.assertIn('sub_minion', data) self.assertIn('minion', data.replace('sub_minion', 'stub'))
'test salt static call'
def test_static(self):
data = self.run_salt('minion test.ping --static') data = '\n'.join(data) self.assertIn('minion', data)
'Test to see if we\'re supporting --doc'
def test_salt_documentation(self):
data = self.run_salt('-d "*" user') self.assertIn('user.add:', data)
'Test to see if we\'re not auto-adding \'*\' and \'sys.doc\' to the call'
def test_salt_documentation_arguments_not_assumed(self):
os_family = self.run_call('--local grains.get os_family')[1].strip() if (os_family == 'Arch'): self.skipTest('This test is failing in Arch due to a bug in salt-testing. Skipping until salt-testing can be upgraded. For more information, see https://github.com/saltstack/salt-jenkins/issues/324.') data = self.run_salt('-d -t 20') if data: self.assertIn('user.add:', data) data = self.run_salt('"*" -d -t 20') if data: self.assertIn('user.add:', data) data = self.run_salt('"*" -d user -t 20') self.assertIn('user.add:', data) data = self.run_salt('"*" sys.doc -d user -t 20') self.assertIn('user.add:', data) data = self.run_salt('"*" sys.doc user -t 20') self.assertIn('user.add:', data)
'Test to see if passing additional arguments shows an error'
def test_salt_documentation_too_many_arguments(self):
data = self.run_salt('-d minion salt ldap.search "filter=ou=People"', catch_stderr=True) self.assertIn('You can only get documentation for one method at one time', '\n'.join(data[1]))
'Ensure correct exit status when the syndic is configured to run as an unknown user.'
def test_exit_status_unknown_user(self):
syndic = testprogram.TestDaemonSaltSyndic(name='unknown_user', config_base={'user': 'some_unknown_user_xyz'}, parent_dir=self._test_dir) syndic.setup() (stdout, stderr, status) = syndic.run(args=['-d'], catch_stderr=True, with_retcode=True) try: self.assert_exit_status(status, 'EX_NOUSER', message='unknown user not on system', stdout=stdout, stderr=stderr) finally: syndic.shutdown()
'Ensure correct exit status when an unknown argument is passed to salt-syndic.'
def test_exit_status_unknown_argument(self):
syndic = testprogram.TestDaemonSaltSyndic(name='unknown_argument', parent_dir=self._test_dir) syndic.setup() (stdout, stderr, status) = syndic.run(args=['-d', '--unknown-argument'], catch_stderr=True, with_retcode=True) try: self.assert_exit_status(status, 'EX_USAGE', message='unknown argument', stdout=stdout, stderr=stderr) finally: syndic.shutdown()
'Ensure correct exit status when salt-syndic starts correctly.'
def test_exit_status_correct_usage(self):
syndic = testprogram.TestDaemonSaltSyndic(name='correct_usage', parent_dir=self._test_dir) syndic.setup() (stdout, stderr, status) = syndic.run(args=['-d', '-l', 'debug'], catch_stderr=True, with_retcode=True) try: self.assert_exit_status(status, 'EX_OK', message='correct usage', stdout=stdout, stderr=stderr) finally: syndic.shutdown(wait_for_orphans=3)
'Ensure correct exit status when an unknown argument is passed to salt-run.'
def test_exit_status_unknown_argument(self):
runner = testprogram.TestProgramSalt(name='run-unknown_argument', parent_dir=self._test_dir) runner.setup() (stdout, stderr, status) = runner.run(args=['--unknown-argument'], catch_stderr=True, with_retcode=True) self.assert_exit_status(status, 'EX_USAGE', message='unknown argument', stdout=stdout, stderr=stderr)
'Ensure correct exit status when salt-run starts correctly.'
def test_exit_status_correct_usage(self):
runner = testprogram.TestProgramSalt(name='run-correct_usage', parent_dir=self._test_dir) runner.setup() (stdout, stderr, status) = runner.run(args=['*', '-h'], catch_stderr=True, with_retcode=True) self.assert_exit_status(status, 'EX_OK', message='correct usage', stdout=stdout, stderr=stderr)
'test salt-cp'
def test_cp_testfile(self):
minions = [] for line in self.run_salt('--out yaml "*" test.ping'): if (not line): continue data = yaml.load(line) minions.extend(data.keys()) self.assertNotEqual(minions, []) testfile = os.path.abspath(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'files', 'file', 'base', 'testfile')) with salt.utils.files.fopen(testfile, 'r') as fh_: testfile_contents = fh_.read() for (idx, minion) in enumerate(minions): ret = self.run_salt('--out yaml {0} file.directory_exists {1}'.format(pipes.quote(minion), TMP)) data = yaml.load('\n'.join(ret)) if (data[minion] is False): ret = self.run_salt('--out yaml {0} file.makedirs {1}'.format(pipes.quote(minion), TMP)) data = yaml.load('\n'.join(ret)) self.assertTrue(data[minion]) minion_testfile = os.path.join(TMP, 'cp_{0}_testfile'.format(idx)) ret = self.run_cp('--out pprint {0} {1} {2}'.format(pipes.quote(minion), pipes.quote(testfile), pipes.quote(minion_testfile))) data = yaml.load('\n'.join(ret)) for part in six.itervalues(data): self.assertTrue(part[minion_testfile]) ret = self.run_salt('--out yaml {0} file.file_exists {1}'.format(pipes.quote(minion), pipes.quote(minion_testfile))) data = yaml.load('\n'.join(ret)) self.assertTrue(data[minion]) ret = self.run_salt('--out yaml {0} file.contains {1} {2}'.format(pipes.quote(minion), pipes.quote(minion_testfile), pipes.quote(testfile_contents))) data = yaml.load('\n'.join(ret)) self.assertTrue(data[minion]) ret = self.run_salt('--out yaml {0} file.remove {1}'.format(pipes.quote(minion), pipes.quote(minion_testfile))) data = yaml.load('\n'.join(ret)) self.assertTrue(data[minion])
'Test to ensure correct output when installing package'
@destructiveTest @skipIf(True, "Skipping due to off the wall failures and hangs on most os's. Will re-enable when fixed.") @skipIf(sys.platform.startswith('win'), 'This test does not apply on Win') @skipIf((getpass.getuser() == 'root'), 'Requires root to test pkg.install') def test_local_pkg_install(self):
get_os_family = self.run_call('--local grains.get os_family') pkg_targets = _PKG_TARGETS.get(get_os_family[1].strip(), []) check_pkg = self.run_call('--local pkg.list_pkgs') for pkg in pkg_targets: if (pkg not in str(check_pkg)): out = self.run_call('--local pkg.install {0}'.format(pkg)) self.assertIn('local: ----------', ''.join(out)) self.assertIn('{0}: ----------'.format(pkg), ''.join(out)) self.assertIn('new:', ''.join(out)) self.assertIn('old:', ''.join(out)) _PKGS_INSTALLED.add(pkg) else: log.debug('The pkg: {0} is already installed on the machine'.format(pkg))
'Test to see if passing additional arguments shows an error'
def test_salt_documentation_too_many_arguments(self):
data = self.run_call('-d virtualenv.create /tmp/ve', catch_stderr=True) self.assertIn('You can only get documentation for one method at one time', '\n'.join(data[1]))
'If there is no tops/master_tops or state file matches for this minion, salt-call should exit non-zero if invoked with option --retcode-passthrough'
def test_issue_6973_state_highstate_exit_code(self):
src = os.path.join(FILES, 'file/base/top.sls') dst = os.path.join(FILES, 'file/base/top.sls.bak') shutil.move(src, dst) expected_comment = 'No states found for this minion' try: (stdout, retcode) = self.run_call('-l quiet --retcode-passthrough state.highstate', with_retcode=True) finally: shutil.move(dst, src) self.assertIn(expected_comment, ''.join(stdout)) self.assertNotEqual(0, retcode)
'Teardown method to remove installed packages'
def tearDown(self):
user = '' user_info = self.run_call('--local grains.get username') if (user_info and isinstance(user_info, (list, tuple)) and isinstance(user_info[(-1)], six.string_types)): user = user_info[(-1)].strip() if (user == 'root'): for pkg in _PKGS_INSTALLED: _ = self.run_call('--local pkg.remove {0}'.format(pkg)) super(CallTest, self).tearDown()
'Ensure correct exit status when an unknown argument is passed to salt-call.'
def test_exit_status_unknown_argument(self):
call = testprogram.TestProgramSaltCall(name='unknown_argument', parent_dir=self._test_dir) call.setup() (stdout, stderr, status) = call.run(args=['--unknown-argument'], catch_stderr=True, with_retcode=True) self.assert_exit_status(status, 'EX_USAGE', message='unknown argument', stdout=stdout, stderr=stderr)
'Ensure correct exit status when salt-call starts correctly.'
def test_exit_status_correct_usage(self):
call = testprogram.TestProgramSaltCall(name='correct_usage', parent_dir=self._test_dir) call.setup() (stdout, stderr, status) = call.run(args=['--local', 'test.true'], catch_stderr=True, with_retcode=True) self.assert_exit_status(status, 'EX_OK', message='correct usage', stdout=stdout, stderr=stderr)
'Tests that a VM is created successfully when calling salt.cloud.CloudClient.create(), which does not require a profile configuration. Also checks that salt.cloud.CloudClient.destroy() works correctly since this test needs to remove the VM after creating it. This test was created as a regression check against Issue #41971.'
def test_cloud_client_create_and_delete(self):
cloud_client = salt.cloud.CloudClient(self.config_file) created = cloud_client.create(provider=self.provider_name, names=[INSTANCE_NAME], image=self.image_name, location='sfo1', size='512mb', vm_size='512mb') self.assertIn(INSTANCE_NAME, created) deleted = cloud_client.destroy(names=[INSTANCE_NAME]) self.assertIn(INSTANCE_NAME, deleted)
'Sets up the test requirements'
@expensiveTest def setUp(self):
super(JoyentTest, self).setUp() profile_str = 'joyent-config' providers = self.run_cloud('--list-providers') if ((profile_str + ':') not in providers): self.skipTest('Configuration file for {0} was not found. Check {0}.conf files in tests/integration/files/conf/cloud.*.d/ to run these tests.'.format(PROVIDER_NAME)) config = cloud_providers_config(os.path.join(FILES, 'conf', 'cloud.providers.d', (PROVIDER_NAME + '.conf'))) user = config[profile_str][PROVIDER_NAME]['user'] password = config[profile_str][PROVIDER_NAME]['password'] private_key = config[profile_str][PROVIDER_NAME]['private_key'] keyname = config[profile_str][PROVIDER_NAME]['keyname'] if ((user == '') or (password == '') or (private_key == '') or (keyname == '')): self.skipTest('A user name, password, private_key file path, and a key name must be provided to run these tests. Check tests/integration/files/conf/cloud.providers.d/{0}.conf'.format(PROVIDER_NAME))
'Test creating and deleting instance on Joyent'
def test_instance(self):
try: self.assertIn(INSTANCE_NAME, [i.strip() for i in self.run_cloud('-p joyent-test {0}'.format(INSTANCE_NAME), timeout=500)]) except AssertionError: self.run_cloud('-d {0} --assume-yes'.format(INSTANCE_NAME), timeout=500) raise try: self.assertIn((INSTANCE_NAME + ':'), [i.strip() for i in self.run_cloud('-d {0} --assume-yes'.format(INSTANCE_NAME), timeout=500)]) except AssertionError: raise
'Clean up after tests'
def tearDown(self):
query = self.run_cloud('--query') ret_str = ' {0}:'.format(INSTANCE_NAME) if (ret_str in query): self.run_cloud('-d {0} --assume-yes'.format(INSTANCE_NAME), timeout=500)
'Sets up the test requirements'
@expensiveTest def setUp(self):
super(DigitalOceanTest, self).setUp() profile_str = 'digitalocean-config' providers = self.run_cloud('--list-providers') if ((profile_str + ':') not in providers): self.skipTest('Configuration file for {0} was not found. Check {0}.conf files in tests/integration/files/conf/cloud.*.d/ to run these tests.'.format(PROVIDER_NAME)) config = cloud_providers_config(os.path.join(FILES, 'conf', 'cloud.providers.d', (PROVIDER_NAME + '.conf'))) personal_token = config[profile_str][PROVIDER_NAME]['personal_access_token'] ssh_file = config[profile_str][PROVIDER_NAME]['ssh_key_file'] ssh_name = config[profile_str][PROVIDER_NAME]['ssh_key_name'] if ((personal_token == '') or (ssh_file == '') or (ssh_name == '')): self.skipTest('A personal access token, an ssh key file, and an ssh key name must be provided to run these tests. Check tests/integration/files/conf/cloud.providers.d/{0}.conf'.format(PROVIDER_NAME))
'Tests the return of running the --list-images command for digital ocean'
def test_list_images(self):
image_list = self.run_cloud('--list-images {0}'.format(PROVIDER_NAME)) self.assertIn('14.04.5 x64', [i.strip() for i in image_list])
'Tests the return of running the --list-locations command for digital ocean'
def test_list_locations(self):
_list_locations = self.run_cloud('--list-locations {0}'.format(PROVIDER_NAME)) self.assertIn('San Francisco 1', [i.strip() for i in _list_locations])
'Tests the return of running the --list-sizes command for digital ocean'
def test_list_sizes(self):
_list_sizes = self.run_cloud('--list-sizes {0}'.format(PROVIDER_NAME)) self.assertIn('16gb', [i.strip() for i in _list_sizes])
'Test key management'
def test_key_management(self):
pub = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAQQDDHr/jh2Jy4yALcK4JyWbVkPRaWmhck3IgCoeOO3z1e2dBowLh64QAM+Qb72pxekALga2oi4GvT+TlWNhzPH4V example' finger_print = '3b:16:bf:e4:8b:00:8b:b8:59:8c:a9:d3:f0:19:45:fa' _key = self.run_cloud('-f create_key {0} name="MyPubKey" public_key="{1}"'.format(PROVIDER_NAME, pub)) self.assertIn(finger_print, [i.strip() for i in _key]) try: list_keypairs = self.run_cloud('-f list_keypairs {0}'.format(PROVIDER_NAME)) self.assertIn(finger_print, [i.strip() for i in list_keypairs]) show_keypair = self.run_cloud('-f show_keypair {0} keyname={1}'.format(PROVIDER_NAME, 'MyPubKey')) self.assertIn(finger_print, [i.strip() for i in show_keypair]) except AssertionError: self.run_cloud('-f remove_key {0} id={1}'.format(PROVIDER_NAME, finger_print)) raise self.assertTrue(self.run_cloud('-f remove_key {0} id={1}'.format(PROVIDER_NAME, finger_print)))
'Test creating an instance on DigitalOcean'
def test_instance(self):
try: self.assertIn(INSTANCE_NAME, [i.strip() for i in self.run_cloud('-p digitalocean-test {0}'.format(INSTANCE_NAME), timeout=500)]) except AssertionError: self.run_cloud('-d {0} --assume-yes'.format(INSTANCE_NAME), timeout=500) raise try: self.assertIn('True', [i.strip() for i in self.run_cloud('-d {0} --assume-yes'.format(INSTANCE_NAME), timeout=500)]) except AssertionError: raise if (INSTANCE_NAME in [i.strip() for i in self.run_cloud('--query')]): self.run_cloud('-d {0} --assume-yes'.format(INSTANCE_NAME), timeout=500)
'Sets up the test requirements'
@expensiveTest def setUp(self):
super(LinodeTest, self).setUp() profile_str = 'linode-config' providers = self.run_cloud('--list-providers') if ((profile_str + ':') not in providers): self.skipTest('Configuration file for {0} was not found. Check {0}.conf files in tests/integration/files/conf/cloud.*.d/ to run these tests.'.format(PROVIDER_NAME)) config = cloud_providers_config(os.path.join(FILES, 'conf', 'cloud.providers.d', (PROVIDER_NAME + '.conf'))) api = config[profile_str][PROVIDER_NAME]['apikey'] password = config[profile_str][PROVIDER_NAME]['password'] if ((api == '') or (password == '')): self.skipTest('An api key and password must be provided to run these tests. Check tests/integration/files/conf/cloud.providers.d/{0}.conf'.format(PROVIDER_NAME))
'Test creating an instance on Linode'
def test_instance(self):
try: self.assertIn(INSTANCE_NAME, [i.strip() for i in self.run_cloud('-p linode-test {0}'.format(INSTANCE_NAME), timeout=500)]) except AssertionError: self.run_cloud('-d {0} --assume-yes'.format(INSTANCE_NAME), timeout=500) raise try: self.assertIn((INSTANCE_NAME + ':'), [i.strip() for i in self.run_cloud('-d {0} --assume-yes'.format(INSTANCE_NAME), timeout=500)]) except AssertionError: raise
'Clean up after tests'
def tearDown(self):
query = self.run_cloud('--query') ret_str = ' {0}:'.format(INSTANCE_NAME) if (ret_str in query): self.run_cloud('-d {0} --assume-yes'.format(INSTANCE_NAME), timeout=500)
'Sets up the test requirements'
@expensiveTest def setUp(self):
super(GoGridTest, self).setUp() profile_str = 'gogrid-config' providers = self.run_cloud('--list-providers') if ((profile_str + ':') not in providers): self.skipTest('Configuration file for {0} was not found. Check {0}.conf files in tests/integration/files/conf/cloud.*.d/ to run these tests.'.format(PROVIDER_NAME)) config = cloud_providers_config(os.path.join(FILES, 'conf', 'cloud.providers.d', (PROVIDER_NAME + '.conf'))) api = config[profile_str][PROVIDER_NAME]['apikey'] shared_secret = config[profile_str][PROVIDER_NAME]['sharedsecret'] if ((api == '') or (shared_secret == '')): self.skipTest('An api key and shared secret must be provided to run these tests. Check tests/integration/files/conf/cloud.providers.d/{0}.conf'.format(PROVIDER_NAME))
'Test creating an instance on GoGrid'
def test_instance(self):
try: self.assertIn(INSTANCE_NAME, [i.strip() for i in self.run_cloud('-p gogrid-test {0}'.format(INSTANCE_NAME), timeout=500)]) except AssertionError: self.run_cloud('-d {0} --assume-yes'.format(INSTANCE_NAME), timeout=500) raise try: self.assertIn((INSTANCE_NAME + ':'), [i.strip() for i in self.run_cloud('-d {0} --assume-yes'.format(INSTANCE_NAME), timeout=500)]) except AssertionError: raise
'Clean up after tests'
def tearDown(self):
query = self.run_cloud('--query') ret_str = ' {0}:'.format(INSTANCE_NAME) if (ret_str in query): self.run_cloud('-d {0} --assume-yes'.format(INSTANCE_NAME), timeout=500)
'Calls salt-cloud to destroy a machine and returns the destroyed machine object (should be None) @param machine_name: @type str: @return: @rtype: dict'
def run_cloud_destroy(self, machine_name):
output = self.run_cloud('-d {0} --assume-yes --log-level=debug'.format(machine_name)) return output.get(CONFIG_NAME, {}).get(PROVIDER_NAME, {})
'Sets up the test requirements'
def setUp(self):
super(VirtualboxProviderTest, self).setUp() profile_str = 'virtualbox-config' providers = self.run_cloud('--list-providers') log.debug('providers: %s', providers) if (profile_str not in providers): self.skipTest('Configuration file for {0} was not found. Check {0}.conf files in tests/integration/files/conf/cloud.*.d/ to run these tests.'.format(PROVIDER_NAME)) config_path = os.path.join(integration.FILES, 'conf', 'cloud.providers.d', (PROVIDER_NAME + '.conf')) log.debug('config_path: %s', config_path) providers = cloud_providers_config(config_path) log.debug('config: %s', providers) config_path = os.path.join(integration.FILES, 'conf', 'cloud.profiles.d', (PROVIDER_NAME + '.conf')) profiles = vm_profiles_config(config_path, providers) profile = profiles.get(PROFILE_NAME) if (not profile): self.skipTest('Profile {0} was not found. Check {1}.conf files in tests/integration/files/conf/cloud.profiles.d/ to run these tests.'.format(PROFILE_NAME, PROVIDER_NAME)) base_box_name = profile.get('clonefrom') if (base_box_name != BASE_BOX_NAME): self.skipTest('Profile {0} does not have a base box to clone from. Check {1}.conf files in tests/integration/files/conf/cloud.profiles.d/ to run these tests.And add a "clone_from: {2}" to the profile'.format(PROFILE_NAME, PROVIDER_NAME, BASE_BOX_NAME))
'Simply create a machine and make sure it was created'
def test_cloud_create(self):
machines = self.run_cloud('-p {0} {1} --log-level=debug'.format(PROFILE_NAME, INSTANCE_NAME)) self.assertIn(INSTANCE_NAME, machines.keys())
'List all machines in virtualbox and make sure the requested attributes are included'
def test_cloud_list(self):
machines = self.run_cloud_function('list_nodes') expected_attributes = MINIMAL_MACHINE_ATTRIBUTES names = machines.keys() self.assertGreaterEqual(len(names), 1, 'No machines found') for (name, machine) in six.iteritems(machines): if six.PY3: self.assertCountEqual(expected_attributes, machine.keys()) else: self.assertItemsEqual(expected_attributes, machine.keys()) self.assertIn(BASE_BOX_NAME, names)
'List all machines and make sure full information in included'
def test_cloud_list_full(self):
machines = self.run_cloud_function('list_nodes_full') expected_minimal_attribute_count = len(MINIMAL_MACHINE_ATTRIBUTES) names = machines.keys() self.assertGreaterEqual(len(names), 1, 'No machines found') for (name, machine) in six.iteritems(machines): self.assertGreaterEqual(len(machine.keys()), expected_minimal_attribute_count) self.assertIn(BASE_BOX_NAME, names)
'List selected attributes of all machines'
def test_cloud_list_select(self):
machines = self.run_cloud_function('list_nodes_select') expected_attributes = ['id'] names = machines.keys() self.assertGreaterEqual(len(names), 1, 'No machines found') for (name, machine) in six.iteritems(machines): if six.PY3: self.assertCountEqual(expected_attributes, machine.keys()) else: self.assertItemsEqual(expected_attributes, machine.keys()) self.assertIn(BASE_BOX_NAME, names)
'Test creating an instance on virtualbox with the virtualbox driver'
def test_cloud_destroy(self):
self.test_cloud_create() ret = self.run_cloud_destroy(INSTANCE_NAME) self.assertIn(INSTANCE_NAME, ret.keys())
'Clean up after tests'
def tearDown(self):
if vb_machine_exists(INSTANCE_NAME): vb_destroy_machine(INSTANCE_NAME)
'Is it either a IPv4 or IPv6 address @param ip_str: @type ip_str: str @raise AssertionError'
def assertIsIpAddress(self, ip_str):
try: socket.inet_aton(ip_str) except Exception: try: socket.inet_pton(socket.AF_INET6, ip_str) except Exception: self.fail('{0} is not a valid IP address'.format(ip_str))
'Sets up the test requirements'
def setUp(self):
provider_str = CONFIG_NAME providers = self.run_cloud('--list-providers') log.debug('providers: %s', providers) if (provider_str not in providers): self.skipTest('Configuration file for {0} was not found. Check {0}.conf files in tests/integration/files/conf/cloud.*.d/ to run these tests.'.format(PROVIDER_NAME)) config_path = os.path.join(integration.FILES, 'conf', 'cloud.providers.d', (PROVIDER_NAME + '.conf')) log.debug('config_path: %s', config_path) providers = cloud_providers_config(config_path) log.debug('config: %s', providers) config_path = os.path.join(integration.FILES, 'conf', 'cloud.profiles.d', (PROVIDER_NAME + '.conf')) profiles = vm_profiles_config(config_path, providers) profile = profiles.get(DEPLOY_PROFILE_NAME) if (not profile): self.skipTest('Profile {0} was not found. Check {1}.conf files in tests/integration/files/conf/cloud.profiles.d/ to run these tests.'.format(DEPLOY_PROFILE_NAME, PROVIDER_NAME)) base_box_name = profile.get('clonefrom') if (base_box_name != BOOTABLE_BASE_BOX_NAME): self.skipTest('Profile {0} does not have a base box to clone from. Check {1}.conf files in tests/integration/files/conf/cloud.profiles.d/ to run these tests.And add a "clone_from: {2}" to the profile'.format(PROFILE_NAME, PROVIDER_NAME, BOOTABLE_BASE_BOX_NAME))
'Sets up the test requirements'
@expensiveTest def setUp(self):
super(EC2Test, self).setUp() profile_str = 'ec2-config' providers = self.run_cloud('--list-providers') if ((profile_str + ':') not in providers): self.skipTest('Configuration file for {0} was not found. Check {0}.conf files in tests/integration/files/conf/cloud.*.d/ to run these tests.'.format(PROVIDER_NAME)) config = cloud_providers_config(os.path.join(FILES, 'conf', 'cloud.providers.d', (PROVIDER_NAME + '.conf'))) id_ = config[profile_str][PROVIDER_NAME]['id'] key = config[profile_str][PROVIDER_NAME]['key'] key_name = config[profile_str][PROVIDER_NAME]['keyname'] sec_group = config[profile_str][PROVIDER_NAME]['securitygroup'] private_key = config[profile_str][PROVIDER_NAME]['private_key'] location = config[profile_str][PROVIDER_NAME]['location'] conf_items = [id_, key, key_name, sec_group, private_key, location] missing_conf_item = [] for item in conf_items: if (item == ''): missing_conf_item.append(item) if missing_conf_item: self.skipTest('An id, key, keyname, security group, private key, and location must be provided to run these tests. One or more of these elements is missing. Check tests/integration/files/conf/cloud.providers.d/{0}.conf'.format(PROVIDER_NAME))
'Tests creating and deleting an instance on EC2 (classic)'
def test_instance(self):
instance = self.run_cloud('-p ec2-test {0}'.format(INSTANCE_NAME), timeout=500) ret_str = '{0}:'.format(INSTANCE_NAME) try: self.assertIn(ret_str, instance) except AssertionError: self.run_cloud('-d {0} --assume-yes'.format(INSTANCE_NAME), timeout=500) raise delete = self.run_cloud('-d {0} --assume-yes'.format(INSTANCE_NAME), timeout=500) ret_str = ' shutting-down' try: self.assertIn(ret_str, delete) except AssertionError: raise
'Clean up after tests'
def tearDown(self):
query = self.run_cloud('--query') ret_str = ' {0}:'.format(INSTANCE_NAME) if (ret_str in query): self.run_cloud('-d {0} --assume-yes'.format(INSTANCE_NAME), timeout=500)
'Sets up the test requirements'
@expensiveTest def setUp(self):
super(RackspaceTest, self).setUp() profile_str = 'rackspace-config' providers = self.run_cloud('--list-providers') if ((profile_str + ':') not in providers): self.skipTest('Configuration file for {0} was not found. Check {0}.conf files in tests/integration/files/conf/cloud.*.d/ to run these tests.'.format(PROVIDER_NAME)) config = cloud_providers_config(os.path.join(FILES, 'conf', 'cloud.providers.d', (PROVIDER_NAME + '.conf'))) user = config[profile_str][DRIVER_NAME]['user'] tenant = config[profile_str][DRIVER_NAME]['tenant'] api = config[profile_str][DRIVER_NAME]['apikey'] if ((api == '') or (tenant == '') or (user == '')): self.skipTest('A user, tenant, and an api key must be provided to run these tests. Check tests/integration/files/conf/cloud.providers.d/{0}.conf'.format(PROVIDER_NAME))
'Test creating an instance on rackspace with the openstack driver'
def test_instance(self):
try: self.assertIn(INSTANCE_NAME, [i.strip() for i in self.run_cloud('-p rackspace-test {0}'.format(INSTANCE_NAME), timeout=500)]) except AssertionError: self.run_cloud('-d {0} --assume-yes'.format(INSTANCE_NAME), timeout=500) raise try: self.assertIn((INSTANCE_NAME + ':'), [i.strip() for i in self.run_cloud('-d {0} --assume-yes'.format(INSTANCE_NAME), timeout=500)]) except AssertionError: raise
'Clean up after tests'
def tearDown(self):
query = self.run_cloud('--query') ret = ' {0}:'.format(INSTANCE_NAME) if (ret in query): self.run_cloud('-d {0} --assume-yes'.format(INSTANCE_NAME), timeout=500)
'Sets up the test requirements'
@expensiveTest def setUp(self):
super(ProfitBricksTest, self).setUp() profile_str = 'profitbricks-config' providers = self.run_cloud('--list-providers') if ((profile_str + ':') not in providers): self.skipTest('Configuration file for {0} was not found. Check {0}.conf files in tests/integration/files/conf/cloud.*.d/ to run these tests.'.format(PROVIDER_NAME)) config = cloud_providers_config(os.path.join(FILES, 'conf', 'cloud.providers.d', (PROVIDER_NAME + '.conf'))) username = config[profile_str][DRIVER_NAME]['username'] password = config[profile_str][DRIVER_NAME]['password'] datacenter_id = config[profile_str][DRIVER_NAME]['datacenter_id'] if ((username == '') or (password == '') or (datacenter_id == '')): self.skipTest('A username, password, and an datacenter must be provided to run these tests. Check tests/integration/files/conf/cloud.providers.d/{0}.conf'.format(PROVIDER_NAME))
'Tests the return of running the --list-images command for ProfitBricks'
def test_list_images(self):
image_list = self.run_cloud('--list-images {0}'.format(PROVIDER_NAME)) self.assertIn('Ubuntu-16.04-LTS-server-2016-10-06', [i.strip() for i in image_list])