desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Should be a bool or converted to one'
@assert_bool def test_oom_kill_disable(self):
pass
'Should be an int or converted to one'
@assert_int def test_oom_score_adj(self):
pass
'Should be a string or converted to one'
@assert_string def test_pid_mode(self):
pass
'Should be an int or converted to one'
@assert_int def test_pids_limit(self):
pass
'This has several potential formats and can include port ranges. It needs its own test.'
def test_port_bindings(self):
expected = ({'port_bindings': {80: [('10.1.2.3', 8080), ('10.1.2.3', 8888)], 3333: ('10.4.5.6', 3333), 4505: ('10.7.8.9', 14505), 4506: ('10.7.8.9', 14506), '81/udp': [('10.1.2.3', 8080), ('10.1.2.3', 8888)], '3334/udp': ('10.4.5.6', 3334), '5505/udp': ('10.7.8.9', 15505), '5506/udp': ('10.7.8.9', 15506)}, 'ports': [80, '81/udp', 3333, '3334/udp', 4505, 4506, '5505/udp', '5506/udp']}, {}, []) translated_input = docker_utils.translate_input(port_bindings='10.1.2.3:8080:80,10.1.2.3:8888:80,10.4.5.6:3333:3333,10.7.8.9:14505-14506:4505-4506,10.1.2.3:8080:81/udp,10.1.2.3:8888:81/udp,10.4.5.6:3334:3334/udp,10.7.8.9:15505-15506:5505-5506/udp') self.assertEqual(translated_input, expected) self.assertEqual(docker_utils.translate_input(port_bindings=['10.1.2.3:8080:80', '10.1.2.3:8888:80', '10.4.5.6:3333:3333', '10.7.8.9:14505-14506:4505-4506', '10.1.2.3:8080:81/udp', '10.1.2.3:8888:81/udp', '10.4.5.6:3334:3334/udp', '10.7.8.9:15505-15506:5505-5506/udp']), expected) expected = ({'port_bindings': {80: [('10.1.2.3',), ('10.1.2.3',)], 3333: ('10.4.5.6',), 4505: ('10.7.8.9',), 4506: ('10.7.8.9',), '81/udp': [('10.1.2.3',), ('10.1.2.3',)], '3334/udp': ('10.4.5.6',), '5505/udp': ('10.7.8.9',), '5506/udp': ('10.7.8.9',)}, 'ports': [80, '81/udp', 3333, '3334/udp', 4505, 4506, '5505/udp', '5506/udp']}, {}, []) self.assertEqual(docker_utils.translate_input(port_bindings='10.1.2.3::80,10.1.2.3::80,10.4.5.6::3333,10.7.8.9::4505-4506,10.1.2.3::81/udp,10.1.2.3::81/udp,10.4.5.6::3334/udp,10.7.8.9::5505-5506/udp'), expected) self.assertEqual(docker_utils.translate_input(port_bindings=['10.1.2.3::80', '10.1.2.3::80', '10.4.5.6::3333', '10.7.8.9::4505-4506', '10.1.2.3::81/udp', '10.1.2.3::81/udp', '10.4.5.6::3334/udp', '10.7.8.9::5505-5506/udp']), expected) expected = ({'port_bindings': {80: [8080, 8888], 3333: 3333, 4505: 14505, 4506: 14506, '81/udp': [8080, 8888], '3334/udp': 3334, '5505/udp': 15505, '5506/udp': 15506}, 'ports': [80, '81/udp', 3333, '3334/udp', 4505, 4506, '5505/udp', '5506/udp']}, {}, []) self.assertEqual(docker_utils.translate_input(port_bindings='8080:80,8888:80,3333:3333,14505-14506:4505-4506,8080:81/udp,8888:81/udp,3334:3334/udp,15505-15506:5505-5506/udp'), expected) self.assertEqual(docker_utils.translate_input(port_bindings=['8080:80', '8888:80', '3333:3333', '14505-14506:4505-4506', '8080:81/udp', '8888:81/udp', '3334:3334/udp', '15505-15506:5505-5506/udp']), expected) expected = ({'port_bindings': {80: None, 3333: None, 4505: None, 4506: None, '81/udp': None, '3334/udp': None, '5505/udp': None, '5506/udp': None}, 'ports': [80, '81/udp', 3333, '3334/udp', 4505, 4506, '5505/udp', '5506/udp']}, {}, []) self.assertEqual(docker_utils.translate_input(port_bindings='80,3333,4505-4506,81/udp,3334/udp,5505-5506/udp'), expected) self.assertEqual(docker_utils.translate_input(port_bindings=['80', '3333', '4505-4506', '81/udp', '3334/udp', '5505-5506/udp']), expected) expected = ({'port_bindings': {80: ('10.1.2.3', 8080), 3333: ('10.4.5.6',), 4505: 14505, 4506: 14506, 9999: None, 10000: None, 10001: None, '81/udp': ('10.1.2.3', 8080), '3334/udp': ('10.4.5.6',), '5505/udp': 15505, '5506/udp': 15506, '19999/udp': None, '20000/udp': None, '20001/udp': None}, 'ports': [80, '81/udp', 3333, '3334/udp', 4505, 4506, '5505/udp', '5506/udp', 9999, 10000, 10001, '19999/udp', '20000/udp', '20001/udp']}, {}, []) self.assertEqual(docker_utils.translate_input(port_bindings='10.1.2.3:8080:80,10.4.5.6::3333,14505-14506:4505-4506,9999-10001,10.1.2.3:8080:81/udp,10.4.5.6::3334/udp,15505-15506:5505-5506/udp,19999-20001/udp'), expected) self.assertEqual(docker_utils.translate_input(port_bindings=['10.1.2.3:8080:80', '10.4.5.6::3333', '14505-14506:4505-4506', '9999-10001', '10.1.2.3:8080:81/udp', '10.4.5.6::3334/udp', '15505-15506:5505-5506/udp', '19999-20001/udp']), expected) self.assertEqual(docker_utils.translate_input(port_bindings='10.1.2.3:8080:80:123'), ({}, {'port_bindings': "'10.1.2.3:8080:80:123' is an invalid port binding definition (at most 3 components are allowed, found 4)"}, [])) expected = ({}, {'port_bindings': 'Start of port range (5555) cannot be greater than end of port range (5554)'}, []) self.assertEqual(docker_utils.translate_input(port_bindings='10.1.2.3:5555-5554:1111-1112'), expected) self.assertEqual(docker_utils.translate_input(port_bindings='10.1.2.3:1111-1112:5555-5554'), expected) self.assertEqual(docker_utils.translate_input(port_bindings='10.1.2.3::5555-5554'), expected) self.assertEqual(docker_utils.translate_input(port_bindings='5555-5554:1111-1112'), expected) self.assertEqual(docker_utils.translate_input(port_bindings='1111-1112:5555-5554'), expected) self.assertEqual(docker_utils.translate_input(port_bindings='5555-5554'), expected) expected = ({}, {'port_bindings': "'foo' is non-numeric or an invalid port range"}, []) self.assertEqual(docker_utils.translate_input(port_bindings='10.1.2.3:foo:1111-1112'), expected) self.assertEqual(docker_utils.translate_input(port_bindings='10.1.2.3:1111-1112:foo'), expected) self.assertEqual(docker_utils.translate_input(port_bindings='10.1.2.3::foo'), expected) self.assertEqual(docker_utils.translate_input(port_bindings='foo:1111-1112'), expected) self.assertEqual(docker_utils.translate_input(port_bindings='1111-1112:foo'), expected) self.assertEqual(docker_utils.translate_input(port_bindings='foo'), expected) self.assertEqual(docker_utils.translate_input(port_bindings='10.1.2.3:1111-1113:1111-1112'), ({}, {'port_bindings': 'Host port range (1111-1113) does not have the same number of ports as the container port range (1111-1112)'}, [])) self.assertEqual(docker_utils.translate_input(port_bindings='10.1.2.3:1111-1112:1111-1113'), ({}, {'port_bindings': 'Host port range (1111-1112) does not have the same number of ports as the container port range (1111-1113)'}, [])) self.assertEqual(docker_utils.translate_input(port_bindings='1111-1113:1111-1112'), ({}, {'port_bindings': 'Host port range (1111-1113) does not have the same number of ports as the container port range (1111-1112)'}, [])) self.assertEqual(docker_utils.translate_input(port_bindings='1111-1112:1111-1113'), ({}, {'port_bindings': 'Host port range (1111-1112) does not have the same number of ports as the container port range (1111-1113)'}, [])) self.assertEqual(docker_utils.translate_input(port_bindings=':1111'), ({}, {'port_bindings': "Empty host port in port binding definition ':1111'"}, [])) self.assertEqual(docker_utils.translate_input(port_bindings='1111:'), ({}, {'port_bindings': "Empty container port in port binding definition '1111:'"}, [])) self.assertEqual(docker_utils.translate_input(port_bindings=''), ({}, {'port_bindings': 'Empty port binding definition found'}, []))
'Ports can be passed as a comma-separated or Python list of port numbers, with \'/tcp\' being optional for TCP ports. They must ultimately be a list of port definitions, in which an integer denotes a TCP port, and a tuple in the format (port_num, \'udp\') denotes a UDP port. Also, the port numbers must end up as integers. None of the decorators will suffice so this one must be tested specially.'
def test_ports(self):
expected = ({'ports': [1111, 2222, (3333, 'udp'), 4505, 4506]}, {}, []) self.assertEqual(docker_utils.translate_input(ports='1111,2222/tcp,3333/udp,4505-4506'), expected) self.assertEqual(docker_utils.translate_input(ports=[1111, '2222/tcp', '3333/udp', '4505-4506']), expected) self.assertEqual(docker_utils.translate_input(ports=['1111', '2222/tcp', '3333/udp', '4505-4506']), expected) self.assertEqual(docker_utils.translate_input(ports=1.0), ({}, {'ports': "'1.0' is not a valid port definition"}, [])) self.assertEqual(docker_utils.translate_input(ports=[1.0]), ({}, {'ports': "'1.0' is not a valid port definition"}, [])) self.assertEqual(docker_utils.translate_input(ports='5555-5554'), ({}, {'ports': 'Start of port range (5555) cannot be greater than end of port range (5554)'}, []))
'Should be a bool or converted to one'
@assert_bool def test_privileged(self):
pass
'Should be a bool or converted to one'
@assert_bool def test_publish_all_ports(self):
pass
'Should be a bool or converted to one'
@assert_bool def test_read_only(self):
pass
'Input is in the format "name[:retry_count]", but the API wants it in the format {\'Name\': name, \'MaximumRetryCount\': retry_count}'
def test_restart_policy(self):
for item in ('restart_policy', 'restart'): self.assertEqual(docker_utils.translate_input(**{item: 'on-failure:5'}), ({'restart_policy': {'Name': 'on-failure', 'MaximumRetryCount': 5}}, {}, [])) self.assertEqual(docker_utils.translate_input(**{item: 'on-failure'}), ({'restart_policy': {'Name': 'on-failure', 'MaximumRetryCount': 0}}, {}, [])) self.assertEqual(docker_utils.translate_input(restart_policy='on-failure:5', restart='always'), ({'restart_policy': {'Name': 'on-failure', 'MaximumRetryCount': 5}}, {}, ['restart_policy'])) self.assertEqual(docker_utils.translate_input(**{item: 'on-failure,always'}), ({}, {item: 'Only one policy is permitted'}, []))
'Should be a list of strings or converted to one'
@assert_stringlist def test_security_opt(self):
pass
'Should be a string or converted to one'
@assert_int_or_string def test_shm_size(self):
pass
'Should be a bool or converted to one'
@assert_bool def test_stdin_open(self):
pass
'Should be a string or converted to one'
@assert_string def test_stop_signal(self):
pass
'Should be an int or converted to one'
@assert_int def test_stop_timeout(self):
pass
'Can be passed in several formats but must end up as a dictionary mapping keys to values'
@assert_key_equals_value def test_storage_opt(self):
pass
'Can be passed in several formats but must end up as a dictionary mapping keys to values'
@assert_key_equals_value def test_sysctls(self):
pass
'Can be passed in several formats but must end up as a dictionary mapping keys to values'
@assert_dict def test_tmpfs(self):
pass
'Should be a bool or converted to one'
@assert_bool def test_tty(self):
pass
'Input is in the format "name=soft_limit[:hard_limit]", but the API wants it in the format {\'Name\': name, \'Soft\': soft_limit, \'Hard\': hard_limit}'
def test_ulimits(self):
self.assertEqual(docker_utils.translate_input(ulimits='nofile=1024:2048,nproc=50'), ({'ulimits': [{'Name': 'nofile', 'Soft': 1024, 'Hard': 2048}, {'Name': 'nproc', 'Soft': 50, 'Hard': 50}]}, {}, [])) self.assertEqual(docker_utils.translate_input(ulimits=['nofile=1024:2048', 'nproc=50:50']), ({'ulimits': [{'Name': 'nofile', 'Soft': 1024, 'Hard': 2048}, {'Name': 'nproc', 'Soft': 50, 'Hard': 50}]}, {}, [])) self.assertEqual(docker_utils.translate_input(ulimits='nofile:1024:2048'), ({}, {'ulimits': "Ulimit definition 'nofile:1024:2048' is not in the format type=soft_limit[:hard_limit]"}, [])) self.assertEqual(docker_utils.translate_input(ulimits='nofile=foo:2048'), ({}, {'ulimits': "Limit 'nofile=foo:2048' contains non-numeric value(s)"}, []))
'Must be either username (string) or uid (int). An int passed as a string (e.g. \'0\') should be converted to an int.'
def test_user(self):
self.assertEqual(docker_utils.translate_input(user='foo'), ({'user': 'foo'}, {}, [])) self.assertEqual(docker_utils.translate_input(user=0), ({'user': 0}, {}, [])) self.assertEqual(docker_utils.translate_input(user='0'), ({'user': 0}, {}, [])) self.assertEqual(docker_utils.translate_input(user=['foo']), ({}, {'user': 'Value must be a username or uid'}, [])) self.assertEqual(docker_utils.translate_input(user=(-1)), ({}, {'user': "'-1' is an invalid uid"}, []))
'Should be a bool or converted to one'
@assert_string def test_userns_mode(self):
pass
'Should be a bool or converted to one'
@assert_string def test_volume_driver(self):
pass
'Should be a list of absolute paths'
@assert_stringlist def test_volumes(self):
if salt.utils.platform.is_windows(): path = 'foo\\bar\\baz' else: path = 'foo/bar/baz' self.assertEqual(docker_utils.translate_input(volumes=path), ({}, {'volumes': "'{0}' is not an absolute path".format(path)}, []))
'Should be a list of strings or converted to one'
@assert_stringlist def test_volumes_from(self):
pass
'Should be a single absolute path'
@assert_string def test_working_dir(self):
if salt.utils.platform.is_windows(): path = 'foo\\bar\\baz' else: path = 'foo/bar/baz' self.assertEqual(docker_utils.translate_input(volumes=path), ({}, {'volumes': "'{0}' is not an absolute path".format(path)}, []))
'Test translation of port definition (1234, \'1234/tcp\', \'1234/udp\', etc.) into the format which docker-py uses (integer for TCP ports, \'port_num/udp\' for UDP ports).'
def test_get_port_def(self):
self.assertEqual(translate_funcs._get_port_def(2222), 2222) self.assertEqual(translate_funcs._get_port_def('2222'), 2222) self.assertEqual(translate_funcs._get_port_def('2222', 'tcp'), 2222) self.assertEqual(translate_funcs._get_port_def('2222/tcp', 'udp'), 2222) self.assertEqual(translate_funcs._get_port_def(2222, 'udp'), (2222, 'udp')) self.assertEqual(translate_funcs._get_port_def('2222', 'udp'), (2222, 'udp')) self.assertEqual(translate_funcs._get_port_def('2222/udp'), (2222, 'udp'))
'Test extracting the start and end of a port range from a port range expression (e.g. 4505-4506)'
def test_get_port_range(self):
self.assertEqual(translate_funcs._get_port_range(2222), (2222, 2222)) self.assertEqual(translate_funcs._get_port_range('2222'), (2222, 2222)) self.assertEqual(translate_funcs._get_port_range('2222-2223'), (2222, 2223)) with self.assertRaisesRegex(ValueError, 'Start of port range \\(2222\\) cannot be greater than end of port range \\(2221\\)'): translate_funcs._get_port_range('2222-2221') with self.assertRaisesRegex(ValueError, "'2222-bar' is non-numeric or an invalid port range"): translate_funcs._get_port_range('2222-bar')
'init'
def __init__(self):
self.msg = None
'Capture error message'
def error(self, msg):
self.msg = msg
'init'
def __init__(self):
self.log_level = None self.log_file = None self.log_level_logfile = None self.config = {} self.temp_log_level = None
'Set console loglevel'
def setup_console_logger(self, log_level='error', **kwargs):
self.log_level = log_level
'Set opts'
def setup_extended_logging(self, opts):
self.config = opts
'Set logfile and loglevel'
def setup_logfile_logger(self, logfile, loglevel, **kwargs):
self.log_file = logfile self.log_level_logfile = loglevel
'Mock'
@staticmethod def get_multiprocessing_logging_queue():
return None
'Set opts'
def setup_multiprocessing_logging_listener(self, opts, *args):
self.config = opts
'Set temp loglevel'
def setup_temp_logger(self, log_level='error'):
self.temp_log_level = log_level
'Mock logger functions'
def setup_log(self):
self.log_setup = LogSetupMock() patcher = patch.multiple(log, setup_console_logger=self.log_setup.setup_console_logger, setup_extended_logging=self.log_setup.setup_extended_logging, setup_logfile_logger=self.log_setup.setup_logfile_logger, get_multiprocessing_logging_queue=self.log_setup.get_multiprocessing_logging_queue, setup_multiprocessing_logging_listener=self.log_setup.setup_multiprocessing_logging_listener, setup_temp_logger=self.log_setup.setup_temp_logger) patcher.start() self.addCleanup(patcher.stop) self.addCleanup(setattr, self, 'log_setup', None)
'Tests that log level match command-line specified value'
def test_get_log_level_cli(self):
default_log_level = self.default_config[self.loglevel_config_setting_name] log_level = 'critical' args = (['--log-level', log_level] + self.args) parser = self.parser() with patch(self.config_func, MagicMock(return_value=self.default_config)): parser.parse_args(args) with patch('salt.utils.parsers.is_writeable', MagicMock(return_value=True)): parser.setup_logfile_logger() console_log_level = getattr(parser.options, self.loglevel_config_setting_name) self.assertEqual(console_log_level, log_level) self.assertEqual(self.log_setup.log_level, log_level) self.assertEqual(self.log_setup.config[self.loglevel_config_setting_name], log_level) self.assertEqual(self.log_setup.temp_log_level, log_level) self.assertEqual(self.log_setup.log_level_logfile, default_log_level)
'Tests that log level match the configured value'
def test_get_log_level_config(self):
args = self.args log_level = 'info' opts = self.default_config.copy() opts.update({self.loglevel_config_setting_name: log_level}) parser = self.parser() with patch(self.config_func, MagicMock(return_value=opts)): parser.parse_args(args) with patch('salt.utils.parsers.is_writeable', MagicMock(return_value=True)): parser.setup_logfile_logger() console_log_level = getattr(parser.options, self.loglevel_config_setting_name) self.assertEqual(console_log_level, log_level) self.assertEqual(self.log_setup.log_level, log_level) self.assertEqual(self.log_setup.config[self.loglevel_config_setting_name], log_level) self.assertEqual(self.log_setup.temp_log_level, 'error') self.assertEqual(self.log_setup.log_level_logfile, log_level)
'Tests that log level match the default value'
def test_get_log_level_default(self):
log_level = default_log_level = self.default_config[self.loglevel_config_setting_name] args = self.args parser = self.parser() with patch(self.config_func, MagicMock(return_value=self.default_config)): parser.parse_args(args) with patch('salt.utils.parsers.is_writeable', MagicMock(return_value=True)): parser.setup_logfile_logger() console_log_level = getattr(parser.options, self.loglevel_config_setting_name) self.assertEqual(console_log_level, log_level) self.assertEqual(self.log_setup.log_level, log_level) self.assertEqual(self.log_setup.config[self.loglevel_config_setting_name], log_level) self.assertEqual(self.log_setup.temp_log_level, 'error') self.assertEqual(self.log_setup.log_level_logfile, default_log_level) self.assertIn("Default: '{0}'.".format(default_log_level), parser.get_option('--log-level').help)
'Tests that log file match command-line specified value'
def test_get_log_file_cli(self):
log_level = self.default_config[self.loglevel_config_setting_name] log_file = '{0}_cli.log'.format(self.log_file) args = (['--log-file', log_file] + self.args) parser = self.parser() with patch(self.config_func, MagicMock(return_value=self.default_config)): parser.parse_args(args) with patch('salt.utils.parsers.is_writeable', MagicMock(return_value=True)): parser.setup_logfile_logger() log_file_option = getattr(parser.options, self.logfile_config_setting_name) if (not self.skip_console_logging_config): self.assertEqual(self.log_setup.log_level, log_level) self.assertEqual(self.log_setup.config[self.loglevel_config_setting_name], log_level) self.assertEqual(self.log_setup.config[self.logfile_config_setting_name], log_file) self.assertEqual(self.log_setup.temp_log_level, 'error') self.assertEqual(log_file_option, log_file) self.assertEqual(self.log_setup.log_file, log_file)
'Tests that log file match the configured value'
def test_get_log_file_config(self):
log_level = self.default_config[self.loglevel_config_setting_name] args = self.args log_file = '{0}_config.log'.format(self.log_file) opts = self.default_config.copy() opts.update({self.logfile_config_setting_name: log_file}) parser = self.parser() with patch(self.config_func, MagicMock(return_value=opts)): parser.parse_args(args) with patch('salt.utils.parsers.is_writeable', MagicMock(return_value=True)): parser.setup_logfile_logger() log_file_option = getattr(parser.options, self.logfile_config_setting_name) if (not self.skip_console_logging_config): self.assertEqual(self.log_setup.log_level, log_level) self.assertEqual(self.log_setup.config[self.loglevel_config_setting_name], log_level) self.assertEqual(self.log_setup.config[self.logfile_config_setting_name], log_file) self.assertEqual(self.log_setup.temp_log_level, 'error') self.assertEqual(log_file_option, log_file) self.assertEqual(self.log_setup.log_file, log_file)
'Tests that log file match the default value'
def test_get_log_file_default(self):
log_level = self.default_config[self.loglevel_config_setting_name] log_file = default_log_file = self.default_config[self.logfile_config_setting_name] args = self.args parser = self.parser() with patch(self.config_func, MagicMock(return_value=self.default_config)): parser.parse_args(args) with patch('salt.utils.parsers.is_writeable', MagicMock(return_value=True)): parser.setup_logfile_logger() log_file_option = getattr(parser.options, self.logfile_config_setting_name) if (not self.skip_console_logging_config): self.assertEqual(self.log_setup.log_level, log_level) self.assertEqual(self.log_setup.config[self.loglevel_config_setting_name], log_level) self.assertEqual(self.log_setup.config[self.logfile_config_setting_name], log_file) self.assertEqual(self.log_setup.temp_log_level, 'error') self.assertEqual(log_file_option, log_file) self.assertEqual(self.log_setup.log_file, log_file) self.assertIn("Default: '{0}'.".format(default_log_file), parser.get_option('--log-file').help)
'Tests that file log level match command-line specified value'
def test_get_log_file_level_cli(self):
default_log_level = self.default_config[self.loglevel_config_setting_name] log_level_logfile = 'error' args = (['--log-file-level', log_level_logfile] + self.args) parser = self.parser() with patch(self.config_func, MagicMock(return_value=self.default_config)): parser.parse_args(args) with patch('salt.utils.parsers.is_writeable', MagicMock(return_value=True)): parser.setup_logfile_logger() log_level_logfile_option = getattr(parser.options, self.logfile_loglevel_config_setting_name) if (not self.skip_console_logging_config): self.assertEqual(self.log_setup.log_level, default_log_level) self.assertEqual(self.log_setup.config[self.loglevel_config_setting_name], default_log_level) self.assertEqual(self.log_setup.config[self.logfile_loglevel_config_setting_name], log_level_logfile) self.assertEqual(self.log_setup.temp_log_level, 'error') self.assertEqual(log_level_logfile_option, log_level_logfile) self.assertEqual(self.log_setup.log_level_logfile, log_level_logfile)
'Tests that log file level match the configured value'
def test_get_log_file_level_config(self):
log_level = self.default_config[self.loglevel_config_setting_name] args = self.args log_level_logfile = 'info' opts = self.default_config.copy() opts.update({self.logfile_loglevel_config_setting_name: log_level_logfile}) parser = self.parser() with patch(self.config_func, MagicMock(return_value=opts)): parser.parse_args(args) with patch('salt.utils.parsers.is_writeable', MagicMock(return_value=True)): parser.setup_logfile_logger() log_level_logfile_option = getattr(parser.options, self.logfile_loglevel_config_setting_name) if (not self.skip_console_logging_config): self.assertEqual(self.log_setup.log_level, log_level) self.assertEqual(self.log_setup.config[self.loglevel_config_setting_name], log_level) self.assertEqual(self.log_setup.config[self.logfile_loglevel_config_setting_name], log_level_logfile) self.assertEqual(self.log_setup.temp_log_level, 'error') self.assertEqual(log_level_logfile_option, log_level_logfile) self.assertEqual(self.log_setup.log_level_logfile, log_level_logfile)
'Tests that log file level match the default value'
def test_get_log_file_level_default(self):
default_log_level = self.default_config[self.loglevel_config_setting_name] log_level = default_log_level log_level_logfile = default_log_level args = self.args parser = self.parser() with patch(self.config_func, MagicMock(return_value=self.default_config)): parser.parse_args(args) with patch('salt.utils.parsers.is_writeable', MagicMock(return_value=True)): parser.setup_logfile_logger() log_level_logfile_option = getattr(parser.options, self.logfile_loglevel_config_setting_name) if (not self.skip_console_logging_config): self.assertEqual(self.log_setup.log_level, log_level) self.assertEqual(self.log_setup.config[self.loglevel_config_setting_name], log_level) self.assertEqual(self.log_setup.config[self.logfile_loglevel_config_setting_name], log_level_logfile) self.assertEqual(self.log_setup.temp_log_level, 'error') self.assertEqual(log_level_logfile_option, log_level_logfile) self.assertEqual(self.log_setup.log_level_logfile, log_level_logfile) self.assertIn("Default: '{0}'.".format(default_log_level), parser.get_option('--log-file-level').help)
'Tests that both console log level and log file level setting are working together'
def test_get_console_log_level_with_file_log_level(self):
log_level = 'critical' log_level_logfile = 'debug' args = (['--log-file-level', log_level_logfile] + self.args) opts = self.default_config.copy() opts.update({self.loglevel_config_setting_name: log_level}) parser = self.parser() with patch(self.config_func, MagicMock(return_value=opts)): parser.parse_args(args) with patch('salt.utils.parsers.is_writeable', MagicMock(return_value=True)): parser.setup_logfile_logger() log_level_logfile_option = getattr(parser.options, self.logfile_loglevel_config_setting_name) if (not self.skip_console_logging_config): self.assertEqual(self.log_setup.log_level, log_level) self.assertEqual(self.log_setup.config[self.loglevel_config_setting_name], log_level) self.assertEqual(self.log_setup.config[self.logfile_loglevel_config_setting_name], log_level_logfile) self.assertEqual(self.log_setup.temp_log_level, 'error') self.assertEqual(log_level_logfile_option, log_level_logfile) self.assertEqual(self.log_setup.log_level_logfile, log_level_logfile)
'Setting up'
def setUp(self):
self.default_config = salt.config.DEFAULT_MASTER_OPTS self.addCleanup(delattr, self, 'default_config') self.log_file = '/tmp/salt_master_parser_test' self.config_func = 'salt.config.master_config' self.setup_log() self.parser = salt.utils.parsers.MasterOptionParser self.addCleanup(delattr, self, 'parser')
'Setting up'
def setUp(self):
self.default_config = salt.config.DEFAULT_MINION_OPTS self.addCleanup(delattr, self, 'default_config') self.log_file = '/tmp/salt_minion_parser_test' self.config_func = 'salt.config.minion_config' self.setup_log() self.parser = salt.utils.parsers.MinionOptionParser self.addCleanup(delattr, self, 'parser')
'Setting up'
def setUp(self):
self.default_config = salt.config.DEFAULT_MINION_OPTS.copy() self.default_config.update(salt.config.DEFAULT_PROXY_MINION_OPTS) self.addCleanup(delattr, self, 'default_config') self.log_file = '/tmp/salt_proxy_minion_parser_test' self.config_func = 'salt.config.proxy_config' self.setup_log() self.parser = salt.utils.parsers.ProxyMinionOptionParser self.addCleanup(delattr, self, 'parser')
'Setting up'
def setUp(self):
self.logfile_config_setting_name = 'syndic_log_file' self.default_config = salt.config.DEFAULT_MASTER_OPTS self.addCleanup(delattr, self, 'default_config') self.log_file = '/tmp/salt_syndic_parser_test' self.config_func = 'salt.config.syndic_config' self.setup_log() self.parser = salt.utils.parsers.SyndicOptionParser self.addCleanup(delattr, self, 'parser')
'Setting up'
def setUp(self):
self.args = ['foo', 'bar.baz'] self.default_config = salt.config.DEFAULT_MASTER_OPTS self.addCleanup(delattr, self, 'default_config') self.log_file = '/tmp/salt_cmd_parser_test' self.config_func = 'salt.config.client_config' self.setup_log() self.parser = salt.utils.parsers.SaltCMDOptionParser self.addCleanup(delattr, self, 'parser')
'Setting up'
def setUp(self):
self.args = ['foo', 'bar', 'baz'] self.default_config = salt.config.DEFAULT_MASTER_OPTS self.addCleanup(delattr, self, 'default_config') self.log_file = '/tmp/salt_cp_parser_test' self.config_func = 'salt.config.master_config' self.setup_log() self.parser = salt.utils.parsers.SaltCPOptionParser self.addCleanup(delattr, self, 'parser')
'Setting up'
def setUp(self):
self.skip_console_logging_config = True self.logfile_config_setting_name = 'key_logfile' self.default_config = salt.config.DEFAULT_MASTER_OPTS self.addCleanup(delattr, self, 'default_config') self.log_file = '/tmp/salt_key_parser_test' self.config_func = 'salt.config.master_config' self.setup_log() self.parser = salt.utils.parsers.SaltKeyOptionParser self.addCleanup(delattr, self, 'parser')
'Tests that console log level option is not recognized'
def test_get_log_level_cli(self):
log_level = default_log_level = None option = '--log-level' args = (self.args + [option, 'error']) parser = self.parser() mock_err = ErrorMock() with patch('salt.utils.parsers.OptionParser.error', mock_err.error): parser.parse_args(args) self.assertEqual(mock_err.msg, 'no such option: {0}'.format(option)) self.assertEqual(self.log_setup.log_level, log_level) self.assertNotIn(self.loglevel_config_setting_name, self.log_setup.config) self.assertEqual(self.log_setup.temp_log_level, 'error') self.assertEqual(self.log_setup.log_level_logfile, default_log_level)
'Tests that log level set in config is ignored'
def test_get_log_level_config(self):
log_level = 'info' args = self.args opts = {self.loglevel_config_setting_name: log_level, self.logfile_config_setting_name: 'key_logfile', 'log_fmt_logfile': None, 'log_datefmt_logfile': None, 'log_rotate_max_bytes': None, 'log_rotate_backup_count': None} parser = self.parser() with patch(self.config_func, MagicMock(return_value=opts)): parser.parse_args(args) with patch('salt.utils.parsers.is_writeable', MagicMock(return_value=True)): parser.setup_logfile_logger() self.assertNotIn(self.loglevel_config_setting_name, parser.options.__dict__) self.assertEqual(self.log_setup.log_level, None) self.assertNotIn(self.loglevel_config_setting_name, self.log_setup.config) self.assertEqual(self.log_setup.temp_log_level, 'error') self.assertEqual(self.log_setup.log_level_logfile, log_level)
'Tests that log level default value is ignored'
def test_get_log_level_default(self):
default_log_level = self.default_config[self.loglevel_config_setting_name] log_level = None args = self.args parser = self.parser() parser.parse_args(args) with patch('salt.utils.parsers.is_writeable', MagicMock(return_value=True)): parser.setup_logfile_logger() self.assertNotIn(self.loglevel_config_setting_name, parser.options.__dict__) self.assertEqual(self.log_setup.log_level, log_level) self.assertNotIn(self.loglevel_config_setting_name, self.log_setup.config) self.assertEqual(self.log_setup.temp_log_level, 'error') self.assertEqual(self.log_setup.log_level_logfile, default_log_level)
'Setting up'
def setUp(self):
self.args = ['foo.bar'] self.default_config = salt.config.DEFAULT_MINION_OPTS self.addCleanup(delattr, self, 'default_config') self.log_file = '/tmp/salt_call_parser_test' self.config_func = 'salt.config.minion_config' self.setup_log() self.parser = salt.utils.parsers.SaltCallOptionParser self.addCleanup(delattr, self, 'parser')
'Setting up'
def setUp(self):
self.args = ['foo.bar'] self.default_config = salt.config.DEFAULT_MASTER_OPTS self.addCleanup(delattr, self, 'default_config') self.log_file = '/tmp/salt_run_parser_test' self.config_func = 'salt.config.master_config' self.setup_log() self.parser = salt.utils.parsers.SaltRunOptionParser self.addCleanup(delattr, self, 'parser')
'Setting up'
def setUp(self):
self.args = ['foo', 'bar.baz'] self.logfile_config_setting_name = 'ssh_log_file' self.default_config = salt.config.DEFAULT_MASTER_OPTS self.addCleanup(delattr, self, 'default_config') self.log_file = '/tmp/salt_ssh_parser_test' self.config_func = 'salt.config.master_config' self.setup_log() self.parser = salt.utils.parsers.SaltSSHOptionParser self.addCleanup(delattr, self, 'parser')
'Setting up'
def setUp(self):
self.args = ['-p', 'foo', 'bar'] self.default_config = salt.config.DEFAULT_MASTER_OPTS.copy() self.default_config.update(salt.config.DEFAULT_CLOUD_OPTS) self.addCleanup(delattr, self, 'default_config') self.log_file = '/tmp/salt_cloud_parser_test' self.config_func = 'salt.config.cloud_config' self.setup_log() self.parser = salt.utils.parsers.SaltCloudParser self.addCleanup(delattr, self, 'parser')
'Setting up'
def setUp(self):
self.args = ['foo', 'bar'] self.logfile_config_setting_name = 'spm_logfile' self.default_config = salt.config.DEFAULT_MASTER_OPTS.copy() self.default_config.update(salt.config.DEFAULT_SPM_OPTS) self.addCleanup(delattr, self, 'default_config') self.log_file = '/tmp/spm_parser_test' self.config_func = 'salt.config.spm_config' self.setup_log() self.parser = salt.utils.parsers.SPMParser self.addCleanup(delattr, self, 'parser')
'Setting up'
def setUp(self):
self.args = [] self.logfile_config_setting_name = 'api_logfile' self.default_config = salt.config.DEFAULT_MASTER_OPTS.copy() self.default_config.update(salt.config.DEFAULT_API_OPTS) self.addCleanup(delattr, self, 'default_config') self.log_file = '/tmp/salt_api_parser_test' self.config_func = 'salt.config.api_config' self.setup_log() self.parser = salt.utils.parsers.SaltAPIParser self.addCleanup(delattr, self, 'parser')
'Make sure you can instantiate etc.'
def test_sanity(self):
cd = cache.CacheDict(5) self.assertIsInstance(cd, cache.CacheDict) self.assertNotIn('foo', cd) cd['foo'] = 'bar' self.assertEqual(cd['foo'], 'bar') del cd['foo'] self.assertNotIn('foo', cd)
'Smoke test the context cache'
def test_smoke_context(self):
if os.path.exists(os.path.join(tempfile.gettempdir(), 'context')): self.skipTest('Context dir already exists') else: opts = salt.config.DEFAULT_MINION_OPTS opts['cachedir'] = tempfile.gettempdir() context_cache = cache.ContextCache(opts, 'cache_test') context_cache.cache_context({'a': 'b'}) ret = context_cache.get_cache_context() self.assertDictEqual({'a': 'b'}, ret)
'Test to ensure that a module which decorates itself with a context cache can store and retreive its contextual data'
def test_context_wrapper(self):
opts = salt.config.DEFAULT_MINION_OPTS opts['cachedir'] = tempfile.gettempdir() ll_ = salt.loader.LazyLoader([os.path.join(os.path.dirname(os.path.realpath(__file__)), 'cache_mods')], tag='rawmodule', virtual_enable=False, opts=opts) cache_test_func = ll_['cache_mod.test_context_module'] self.assertEqual(cache_test_func()['called'], 0) self.assertEqual(cache_test_func()['called'], 1)
'Ensure we throw an exception if we have a too-long IPC URI'
@skipIf(NO_MOCK, NO_MOCK_REASON) @skipIf((not hasattr(zmq, 'IPC_PATH_MAX_LEN')), 'ZMQ does not have max length support.') def test_check_ipc_length(self):
with patch('zmq.IPC_PATH_MAX_LEN', 1): self.assertRaises(SaltSystemExit, salt.utils.zeromq.check_ipc_path_max_len, ('1' * 1024))
'Take CMD_RET and update it w/(a list of ) delta_res Mock cmd.run_all w/it :param delta_res: list or dict :return: patched cmd.run_all'
def _mock_cmd_ret(self, delta_res):
if isinstance(delta_res, (list, tuple)): test_res = [] for dres in delta_res: tres = self.CMD_RET.copy() tres.update(dres) test_res.append(tres) cmd_mock = MagicMock(side_effect=test_res) else: test_res = self.CMD_RET.copy() test_res.update(delta_res) cmd_mock = MagicMock(return_value=test_res) return patch.dict(salt.utils.dns.__salt__, {'cmd.run_all': cmd_mock}, clear=True)
'Perform a given battery of tests against a given lookup utilizing cmd.run_all :param wrong_type: delta cmd.run_all output for an incorrect DNS type :param wrong: delta cmd.run_all output for any error :param right: delta cmd.run_all output for outputs in RESULTS :param empty: delta cmd.run_all output for anything that won\'t return matches :param secure: delta cmd.run_all output for secured RESULTS'
def _test_cmd_lookup(self, lookup_cb, wrong_type, wrong, right, empty=None, secure=None):
for wrong in wrong: with self._mock_cmd_ret(wrong): self.assertEqual(lookup_cb('mockq', 'A'), False) if (empty is None): empty = {} with self._mock_cmd_ret(empty): self.assertEqual(lookup_cb('mockq', 'AAAA'), []) with self._mock_cmd_ret(wrong_type): self.assertRaises(ValueError, lookup_cb, 'mockq', 'WRONG') for (rec_t, tests) in right.items(): with self._mock_cmd_ret([dict([('stdout', dres)]) for dres in tests]): for test_res in self.RESULTS[rec_t]: if (rec_t in ('A', 'AAAA', 'CNAME')): rec = 'mocksrvr.example.com' else: rec = 'example.com' self.assertEqual(lookup_cb(rec, rec_t), test_res) if (not secure): return for (rec_t, tests) in right.items(): with self._mock_cmd_ret([dict([('stdout', dres)]) for dres in tests]): for _ in self.RESULTS[rec_t]: self.assertEqual(lookup_cb('mocksrvr.example.com', rec_t, secure=True), False, msg='Insecure {0} returns should not be returned'.format(rec_t)) for (rec_t, tests) in secure.items(): with self._mock_cmd_ret([dict([('stdout', dres)]) for dres in tests]): for test_res in self.RESULTS[rec_t]: self.assertEqual(lookup_cb('mocksrvr.example.com', rec_t, secure=True), test_res, msg="Error parsing DNSSEC'd {0} returns".format(rec_t))
'Make sure all test modules conform to the test_*.py naming scheme'
def test_module_name(self):
excluded_dirs = tuple(EXCLUDED_DIRS) tests_dir = os.path.join(CODE_DIR, 'tests') bad_names = [] for (root, dirs, files) in os.walk(tests_dir): reldir = os.path.relpath(root, CODE_DIR) if (reldir.startswith(excluded_dirs) or reldir.endswith('__pycache__')): continue for fname in files: if ((fname == '__init__.py') or (not fname.endswith('.py'))): continue relpath = os.path.join(reldir, fname) if (relpath in EXCLUDED_FILES): continue if (not fname.startswith('test_')): bad_names.append(relpath) error_msg = '\n\nPlease rename the following files:\n' for path in bad_names: (directory, filename) = path.rsplit(os.sep, 1) (filename, ext) = os.path.splitext(filename) error_msg += ' {} -> {}/test_{}.py\n'.format(path, directory, filename.split('_test')[0]) error_msg += '\nIf you believe one of the entries above should be ignored, please add it to either\n' error_msg += "'EXCLUDED_DIRS' or 'EXCLUDED_FILES' in 'tests/unit/test_module_names.py'.\n" error_msg += 'If it is a tests module, then please rename as suggested.' self.assertEqual([], bad_names, error_msg)
'Return the path to a testing runtime script'
def get_script_path(self, script_name):
if (not os.path.isdir(RUNTIME_VARS.TMP_SCRIPT_DIR)): os.makedirs(RUNTIME_VARS.TMP_SCRIPT_DIR) script_path = os.path.join(RUNTIME_VARS.TMP_SCRIPT_DIR, script_name) if (not os.path.isfile(script_path)): log.debug('Generating {0}'.format(script_path)) import salt.utils.files with salt.utils.files.fopen(script_path, 'w') as sfh: script_template = SCRIPT_TEMPLATES.get(script_name, None) if (script_template is None): script_template = SCRIPT_TEMPLATES.get('common', None) if (script_template is None): raise RuntimeError('{0} does not know how to handle the {1} script'.format(self.__class__.__name__, script_name)) sfh.write(('#!{0}\n'.format(sys.executable) + '\n'.join(script_template).format(script_name.replace('salt-', '')))) st = os.stat(script_path) os.chmod(script_path, (st.st_mode | stat.S_IEXEC)) return script_path
'Run the ``salt`` CLI tool with the provided arguments .. code-block:: python class MatchTest(ShellTestCase): def test_list(self): test salt -L matcher data = self.run_salt(\'-L minion test.ping\') data = \'\n\'.join(data) self.assertIn(\'minion\', data)'
def run_salt(self, arg_str, with_retcode=False, catch_stderr=False, timeout=15):
arg_str = '-c {0} {1}'.format(self.get_config_dir(), arg_str) return self.run_script('salt', arg_str, with_retcode=with_retcode, catch_stderr=catch_stderr)
'Execute salt-ssh'
def run_ssh(self, arg_str, with_retcode=False, timeout=25, catch_stderr=False):
arg_str = '-c {0} -i --priv {1} --roster-file {2} localhost {3} --out=json'.format(self.get_config_dir(), os.path.join(RUNTIME_VARS.TMP_CONF_DIR, 'key_test'), os.path.join(RUNTIME_VARS.TMP_CONF_DIR, 'roster'), arg_str) return self.run_script('salt-ssh', arg_str, with_retcode=with_retcode, catch_stderr=catch_stderr, raw=True)
'Execute salt-run'
def run_run(self, arg_str, with_retcode=False, catch_stderr=False, async=False, timeout=60, config_dir=None):
arg_str = '-c {0}{async_flag} -t {timeout} {1}'.format((config_dir or self.get_config_dir()), arg_str, timeout=timeout, async_flag=(' --async' if async else '')) return self.run_script('salt-run', arg_str, with_retcode=with_retcode, catch_stderr=catch_stderr)
'Execute the runner function and return the return data and output in a dict'
def run_run_plus(self, fun, *arg, **kwargs):
ret = {'fun': fun} import salt.config import salt.output import salt.runner from salt.ext.six.moves import cStringIO opts = salt.config.master_config(self.get_config_file_path('master')) opts_arg = list(arg) if kwargs: opts_arg.append({'__kwarg__': True}) opts_arg[(-1)].update(kwargs) opts.update({'doc': False, 'fun': fun, 'arg': opts_arg}) with RedirectStdStreams(): runner = salt.runner.Runner(opts) ret['return'] = runner.run() try: ret['jid'] = runner.jid except AttributeError: ret['jid'] = None opts['color'] = False opts['output_file'] = cStringIO() try: salt.output.display_output(ret['return'], opts=opts) ret['out'] = opts['output_file'].getvalue() finally: opts['output_file'].close() return ret
'Execute salt-key'
def run_key(self, arg_str, catch_stderr=False, with_retcode=False):
arg_str = '-c {0} {1}'.format(self.get_config_dir(), arg_str) return self.run_script('salt-key', arg_str, catch_stderr=catch_stderr, with_retcode=with_retcode)
'Execute salt-cp'
def run_cp(self, arg_str, with_retcode=False, catch_stderr=False):
arg_str = '--config-dir {0} {1}'.format(self.get_config_dir(), arg_str) return self.run_script('salt-cp', arg_str, with_retcode=with_retcode, catch_stderr=catch_stderr)
'Execute salt-cloud'
def run_cloud(self, arg_str, catch_stderr=False, timeout=None):
arg_str = '-c {0} {1}'.format(self.get_config_dir(), arg_str) return self.run_script('salt-cloud', arg_str, catch_stderr, timeout)
'Execute a script with the given argument string'
def run_script(self, script, arg_str, catch_stderr=False, with_retcode=False, timeout=15, raw=False):
script_path = self.get_script_path(script) if (not os.path.isfile(script_path)): return False python_path = os.environ.get('PYTHONPATH', None) if sys.platform.startswith('win'): cmd = 'set PYTHONPATH=' else: cmd = 'PYTHONPATH=' if (python_path is not None): cmd += '{0}:'.format(python_path) if (sys.version_info[0] < 3): cmd += '{0} '.format(':'.join(sys.path[1:])) else: cmd += '{0} '.format(':'.join(sys.path[0:])) cmd += 'python{0}.{1} '.format(*sys.version_info) cmd += '{0} '.format(script_path) cmd += '{0} '.format(arg_str) tmp_file = tempfile.SpooledTemporaryFile() popen_kwargs = {'shell': True, 'stdout': tmp_file, 'universal_newlines': True} if (catch_stderr is True): popen_kwargs['stderr'] = subprocess.PIPE if (not sys.platform.lower().startswith('win')): popen_kwargs['close_fds'] = True def detach_from_parent_group(): os.setpgrp() popen_kwargs['preexec_fn'] = detach_from_parent_group elif (sys.platform.lower().startswith('win') and (timeout is not None)): raise RuntimeError('Timeout is not supported under windows') process = subprocess.Popen(cmd, **popen_kwargs) if (timeout is not None): stop_at = (datetime.now() + timedelta(seconds=timeout)) term_sent = False while True: process.poll() time.sleep(0.1) if (datetime.now() > stop_at): if (term_sent is False): os.killpg(os.getpgid(process.pid), signal.SIGINT) term_sent = True continue try: os.killpg(os.getpgid(process.pid), signal.SIGKILL) except OSError as exc: if (exc.errno != errno.ESRCH): raise out = ['Process took more than {0} seconds to complete. Process Killed!'.format(timeout)] if catch_stderr: err = ['Process killed, unable to catch stderr output'] if with_retcode: return (out, err, process.returncode) else: return (out, err) if with_retcode: return (out, process.returncode) else: return out if (process.returncode is not None): break tmp_file.seek(0) if (sys.version_info >= (3,)): try: out = tmp_file.read().decode(__salt_system_encoding__) except (NameError, UnicodeDecodeError): out = tmp_file.read().decode('utf-8') else: out = tmp_file.read() if catch_stderr: if (sys.version_info < (2, 7)): process.wait() err = process.stderr.read() else: (_, err) = process.communicate() if (process.stdout is not None): process.stdout.close() if (process.stderr is not None): process.stderr.close() try: if with_retcode: if ((out is not None) and (err is not None)): if (not raw): return (out.splitlines(), err.splitlines(), process.returncode) else: return (out, err, process.returncode) return (out.splitlines(), [], process.returncode) else: if ((out is not None) and (err is not None)): if (not raw): return (out.splitlines(), err.splitlines()) else: return (out, err) if (not raw): return (out.splitlines(), []) else: return (out, []) finally: try: if os.path.exists(tmp_file.name): if isinstance(tmp_file.name, six.string_types): os.remove(tmp_file.name) else: tmp_file.close() process.terminate() except OSError as err: pass process.communicate() if (process.stdout is not None): process.stdout.close() try: if with_retcode: if (not raw): return (out.splitlines(), process.returncode) else: return (out, process.returncode) elif (not raw): return out.splitlines() else: return out finally: try: if os.path.exists(tmp_file.name): if isinstance(tmp_file.name, six.string_types): os.remove(tmp_file.name) else: tmp_file.close() process.terminate() except OSError as err: pass
'Execute salt'
def run_salt(self, arg_str, with_retcode=False, catch_stderr=False, timeout=60):
arg_str = '-c {0} {1}'.format(self.get_config_dir(), arg_str) return self.run_script('salt', arg_str, with_retcode=with_retcode, catch_stderr=catch_stderr, timeout=timeout)
'Execute salt-ssh'
def run_ssh(self, arg_str, with_retcode=False, catch_stderr=False, timeout=60):
arg_str = '-ldebug -W -c {0} -i --priv {1} --roster-file {2} --out=json localhost {3}'.format(self.get_config_dir(), os.path.join(RUNTIME_VARS.TMP_CONF_DIR, 'key_test'), os.path.join(RUNTIME_VARS.TMP_CONF_DIR, 'roster'), arg_str) return self.run_script('salt-ssh', arg_str, with_retcode=with_retcode, catch_stderr=catch_stderr, timeout=timeout, raw=True)
'Execute salt-run'
def run_run(self, arg_str, with_retcode=False, catch_stderr=False, async=False, timeout=60, config_dir=None):
arg_str = '-c {0}{async_flag} -t {timeout} {1}'.format((config_dir or self.get_config_dir()), arg_str, timeout=timeout, async_flag=(' --async' if async else '')) return self.run_script('salt-run', arg_str, with_retcode=with_retcode, catch_stderr=catch_stderr, timeout=60)
'Execute the runner function and return the return data and output in a dict'
def run_run_plus(self, fun, *arg, **kwargs):
import salt.runner import salt.output ret = {'fun': fun} from_scratch = bool(kwargs.pop('__reload_config', False)) opts = {} opts.update(self.get_config('client_config', from_scratch=from_scratch)) opts_arg = list(arg) if kwargs: opts_arg.append({'__kwarg__': True}) opts_arg[(-1)].update(kwargs) opts.update({'doc': False, 'fun': fun, 'arg': opts_arg}) with RedirectStdStreams(): runner = salt.runner.Runner(opts) ret['return'] = runner.run() try: ret['jid'] = runner.jid except AttributeError: ret['jid'] = None opts['color'] = False opts['output_file'] = cStringIO() try: salt.output.display_output(ret['return'], opts=opts) ret['out'] = opts['output_file'].getvalue().splitlines() finally: opts['output_file'].close() return ret
'Execute salt-key'
def run_key(self, arg_str, catch_stderr=False, with_retcode=False):
arg_str = '-c {0} {1}'.format(self.get_config_dir(), arg_str) return self.run_script('salt-key', arg_str, catch_stderr=catch_stderr, with_retcode=with_retcode, timeout=60)
'Execute salt-cp'
def run_cp(self, arg_str, with_retcode=False, catch_stderr=False):
arg_str = '--config-dir {0} {1}'.format(self.get_config_dir(), arg_str) return self.run_script('salt-cp', arg_str, with_retcode=with_retcode, catch_stderr=catch_stderr, timeout=60)
'Execute salt-call.'
def run_call(self, arg_str, with_retcode=False, catch_stderr=False):
arg_str = '--config-dir {0} {1}'.format(self.get_config_dir(), arg_str) return self.run_script('salt-call', arg_str, with_retcode=with_retcode, catch_stderr=catch_stderr, timeout=60)
'Execute salt-cloud'
def run_cloud(self, arg_str, catch_stderr=False, timeout=30):
arg_str = '-c {0} {1}'.format(self.get_config_dir(), arg_str) return self.run_script('salt-cloud', arg_str, catch_stderr, timeout=timeout)
'Run a single salt function on the \'minion\' target and condition the return down to match the behavior of the raw function call'
def minion_run(self, _function, *args, **kw):
return self.run_function(_function, args, **kw)
'Run a single salt function and condition the return down to match the behavior of the raw function call'
def run_function(self, function, arg=(), minion_tgt='minion', timeout=90, **kwargs):
know_to_return_none = ('file.chown', 'file.chgrp', 'ssh.recv_known_host') if ('f_arg' in kwargs): kwargs['arg'] = kwargs.pop('f_arg') if ('f_timeout' in kwargs): kwargs['timeout'] = kwargs.pop('f_timeout') orig = self.client.cmd(minion_tgt, function, arg, timeout=timeout, kwarg=kwargs) if (minion_tgt not in orig): self.skipTest("WARNING(SHOULD NOT HAPPEN #1935): Failed to get a reply from the minion '{0}'. Command output: {1}".format(minion_tgt, orig)) elif ((orig[minion_tgt] is None) and (function not in know_to_return_none)): self.skipTest("WARNING(SHOULD NOT HAPPEN #1935): Failed to get '{0}' from the minion '{1}'. Command output: {2}".format(function, minion_tgt, orig)) orig[minion_tgt] = self._check_state_return(orig[minion_tgt]) return orig[minion_tgt]
'Run the state.single command and return the state return structure'
def run_state(self, function, **kwargs):
ret = self.run_function('state.single', [function], **kwargs) return self._check_state_return(ret)
'Run a single salt function and condition the return down to match the behavior of the raw function call'
def run_function(self, function, arg=()):
orig = self.client.cmd('minion', function, arg, timeout=25) if ('minion' not in orig): self.skipTest('WARNING(SHOULD NOT HAPPEN #1935): Failed to get a reply from the minion. Command output: {0}'.format(orig)) return orig['minion']
'We use a 90s timeout here, which some slower systems do end up needing'
def run_function(self, function, arg=(), timeout=90, **kwargs):
ret = self.run_ssh(self._arg_str(function, arg), timeout=timeout) try: return json.loads(ret)['localhost'] except Exception: return ret
'Return the options used for the master'
@property def master_opts(self):
return self.get_config('master')
'Return the options used for the minion'
@property def minion_opts(self):
return self.get_config('minion')
'Return the options used for the sub_minion'
@property def sub_minion_opts(self):
return self.get_config('sub_minion')
'Collect events and store them'
@staticmethod def _fetch(q):
def _clean_queue(): print('Cleaning queue!') while (not q.empty()): queue_item = q.get() queue_item.task_done() atexit.register(_clean_queue) a_config = AdaptedConfigurationTestCaseMixin() event = salt.utils.event.get_event('minion', sock_dir=a_config.get_config('minion')['sock_dir'], opts=a_config.get_config('minion')) while True: try: events = event.get_event(full=False) except Exception: pass q.put(events)
'mock.assert_called_once only exists in PY3 in 3.6 and newer'
@staticmethod def assert_called_once(mock):
try: mock.assert_called_once() except AttributeError: log.warning('assert_called_once invoked, but not available')
'Set up all the webserver paths. Designed to be run once in a setUpClass function.'
@classmethod def prep_server(cls):
cls.root_dir = tempfile.mkdtemp(dir=TMP) cls.config_dir = os.path.join(cls.root_dir, 'config') cls.nginx_conf = os.path.join(cls.config_dir, 'nginx.conf') cls.uwsgi_conf = os.path.join(cls.config_dir, 'uwsgi.yml') cls.git_dir = os.path.join(cls.root_dir, 'git') cls.repo_dir = os.path.join(cls.git_dir, 'repos') cls.venv_dir = os.path.join(cls.root_dir, 'venv') cls.uwsgi_bin = os.path.join(cls.venv_dir, 'bin', 'uwsgi') cls.nginx_port = cls.uwsgi_port = get_unused_localhost_port() while (cls.uwsgi_port == cls.nginx_port): cls.uwsgi_port = get_unused_localhost_port() cls.url = 'http://127.0.0.1:{port}/repo.git'.format(port=cls.nginx_port) cls.ext_opts = {'url': cls.url} for credential_param in ('user', 'password'): if hasattr(cls, credential_param): cls.ext_opts[credential_param] = getattr(cls, credential_param)
'Make the test class available to the tearDownClass. Note that this cannot be defined in a parent class and inherited, as this will cause the parent class to be modified.'
@classmethod def update_class(cls, case):
if (getattr(cls, 'case') is None): setattr(cls, 'case', case)