desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'tests True when remove targets succeeds'
def test_that_when_removing_targets_succeeds_the_remove_targets_method_returns_true(self):
self.conn.remove_targets.return_value = {'FailedEntryCount': 0} result = boto_cloudwatch_event.remove_targets(Rule=rule_name, Ids=[], **conn_parameters) self.assertIsNone(result['failures']) self.assertEqual(result.get('error'), None)
'tests False when remove targets fails'
def test_that_when_removing_targets_fails_the_remove_targets_method_returns_error(self):
self.conn.remove_targets.side_effect = ClientError(error_content, 'remove_targets') result = boto_cloudwatch_event.remove_targets(Rule=rule_name, Ids=[], **conn_parameters) self.assertEqual(result.get('error', {}).get('message'), error_message.format('remove_targets'))
'Test to Reloads systemctl'
def test_systemctl_reload(self):
mock = MagicMock(side_effect=[{'stdout': 'Who knows why?', 'stderr': '', 'retcode': 1, 'pid': 12345}, {'stdout': '', 'stderr': '', 'retcode': 0, 'pid': 54321}]) with patch.dict(systemd.__salt__, {'cmd.run_all': mock}): self.assertRaisesRegex(CommandExecutionError, 'Problem performing systemctl daemon-reload: Who knows why?', systemd.systemctl_reload) self.assertTrue(systemd.systemctl_reload())
'Test to return a list of all enabled services'
def test_get_enabled(self):
cmd_mock = MagicMock(return_value=_LIST_UNIT_FILES) listdir_mock = MagicMock(return_value=['foo', 'bar', 'baz', 'README']) sd_mock = MagicMock(return_value=set([x.replace('.service', '') for x in _SYSTEMCTL_STATUS])) access_mock = MagicMock(side_effect=(lambda x, y: (x != os.path.join(systemd.INITSCRIPT_PATH, 'README')))) sysv_enabled_mock = MagicMock(side_effect=(lambda x: (x == 'baz'))) with patch.dict(systemd.__salt__, {'cmd.run': cmd_mock}): with patch.object(os, 'listdir', listdir_mock): with patch.object(systemd, '_get_systemd_services', sd_mock): with patch.object(os, 'access', side_effect=access_mock): with patch.object(systemd, '_sysv_enabled', sysv_enabled_mock): self.assertListEqual(systemd.get_enabled(), ['baz', 'service1', 'timer1.timer'])
'Test to return a list of all disabled services'
def test_get_disabled(self):
cmd_mock = MagicMock(return_value=_LIST_UNIT_FILES) listdir_mock = MagicMock(return_value=['foo', 'bar', 'baz', 'README']) sd_mock = MagicMock(return_value=set([x.replace('.service', '') for x in _SYSTEMCTL_STATUS])) access_mock = MagicMock(side_effect=(lambda x, y: (x != os.path.join(systemd.INITSCRIPT_PATH, 'README')))) sysv_enabled_mock = MagicMock(side_effect=(lambda x: (x == 'baz'))) with patch.dict(systemd.__salt__, {'cmd.run': cmd_mock}): with patch.object(os, 'listdir', listdir_mock): with patch.object(systemd, '_get_systemd_services', sd_mock): with patch.object(os, 'access', side_effect=access_mock): with patch.object(systemd, '_sysv_enabled', sysv_enabled_mock): self.assertListEqual(systemd.get_disabled(), ['bar', 'service2', 'timer2.timer'])
'Test to return a list of all available services'
def test_get_all(self):
listdir_mock = MagicMock(side_effect=[['foo.service', 'multi-user.target.wants', 'mytimer.timer'], [], ['foo.service', 'multi-user.target.wants', 'bar.service'], ['mysql', 'nginx', 'README']]) access_mock = MagicMock(side_effect=(lambda x, y: (x != os.path.join(systemd.INITSCRIPT_PATH, 'README')))) with patch.object(os, 'listdir', listdir_mock): with patch.object(os, 'access', side_effect=access_mock): self.assertListEqual(systemd.get_all(), ['bar', 'foo', 'mysql', 'mytimer.timer', 'nginx'])
'Test to check that the given service is available'
def test_available(self):
mock = MagicMock(side_effect=(lambda x: _SYSTEMCTL_STATUS[x])) with patch.dict(systemd.__context__, {'salt.utils.systemd.version': 230}): with patch.object(systemd, '_systemctl_status', mock): self.assertTrue(systemd.available('sshd.service')) self.assertFalse(systemd.available('foo.service')) with patch.dict(systemd.__context__, {'salt.utils.systemd.version': 231}): with patch.dict(_SYSTEMCTL_STATUS, _SYSTEMCTL_STATUS_GTE_231): with patch.object(systemd, '_systemctl_status', mock): self.assertTrue(systemd.available('sshd.service')) self.assertFalse(systemd.available('bar.service')) with patch.dict(systemd.__context__, {'salt.utils.systemd.version': 219}): with patch.dict(_SYSTEMCTL_STATUS, _SYSTEMCTL_STATUS_GTE_231): with patch.object(systemd, '_systemctl_status', mock): self.assertTrue(systemd.available('sshd.service')) self.assertFalse(systemd.available('bar.service'))
'Test to the inverse of service.available.'
def test_missing(self):
mock = MagicMock(side_effect=(lambda x: _SYSTEMCTL_STATUS[x])) with patch.dict(systemd.__context__, {'salt.utils.systemd.version': 230}): with patch.object(systemd, '_systemctl_status', mock): self.assertFalse(systemd.missing('sshd.service')) self.assertTrue(systemd.missing('foo.service')) with patch.dict(systemd.__context__, {'salt.utils.systemd.version': 231}): with patch.dict(_SYSTEMCTL_STATUS, _SYSTEMCTL_STATUS_GTE_231): with patch.object(systemd, '_systemctl_status', mock): self.assertFalse(systemd.missing('sshd.service')) self.assertTrue(systemd.missing('bar.service')) with patch.dict(systemd.__context__, {'salt.utils.systemd.version': 219}): with patch.dict(_SYSTEMCTL_STATUS, _SYSTEMCTL_STATUS_GTE_231): with patch.object(systemd, '_systemctl_status', mock): self.assertFalse(systemd.missing('sshd.service')) self.assertTrue(systemd.missing('bar.service'))
'Test to show properties of one or more units/jobs or the manager'
def test_show(self):
show_output = 'a=b\nc=d\ne={ f=g ; h=i }\nWants=foo.service bar.service\n' mock = MagicMock(return_value=show_output) with patch.dict(systemd.__salt__, {'cmd.run': mock}): self.assertDictEqual(systemd.show('sshd'), {'a': 'b', 'c': 'd', 'e': {'f': 'g', 'h': 'i'}, 'Wants': ['foo.service', 'bar.service']})
'Test to return a list of all files specified as ``ExecStart`` for all services'
def test_execs(self):
mock = MagicMock(return_value=['a', 'b']) with patch.object(systemd, 'get_all', mock): mock = MagicMock(return_value={'ExecStart': {'path': 'c'}}) with patch.object(systemd, 'show', mock): self.assertDictEqual(systemd.execs(), {'a': 'c', 'b': 'c'})
'Common code for start/stop/restart/reload/force_reload tests'
def _change_state(self, action, no_block=False):
func = getattr(systemd, action) action = action.rstrip('_').replace('_', '-') systemctl_command = ['systemctl'] if no_block: systemctl_command.append('--no-block') systemctl_command.extend([action, (self.unit_name + '.service')]) scope_prefix = ['systemd-run', '--scope'] assert_kwargs = {'python_shell': False} if (action in ('enable', 'disable')): assert_kwargs['ignore_retcode'] = True with patch.object(systemd, '_check_for_unit_changes', self.mock_none): with patch.object(systemd, '_unit_file_changed', self.mock_none): with patch.object(systemd, '_check_unmask', self.mock_none): with patch.object(systemd, '_get_sysv_services', self.mock_empty_list): with patch.object(salt.utils.systemd, 'has_scope', self.mock_true): with patch.dict(systemd.__salt__, {'config.get': self.mock_true, 'cmd.run_all': self.mock_run_all_success}): ret = func(self.unit_name, no_block=no_block) self.assertTrue(ret) self.mock_run_all_success.assert_called_with((scope_prefix + systemctl_command), **assert_kwargs) with patch.dict(systemd.__salt__, {'config.get': self.mock_true, 'cmd.run_all': self.mock_run_all_failure}): if (action in ('stop', 'disable')): ret = func(self.unit_name, no_block=no_block) self.assertFalse(ret) else: self.assertRaises(CommandExecutionError, func, self.unit_name, no_block=no_block) self.mock_run_all_failure.assert_called_with((scope_prefix + systemctl_command), **assert_kwargs) with patch.dict(systemd.__salt__, {'config.get': self.mock_false, 'cmd.run_all': self.mock_run_all_success}): ret = func(self.unit_name, no_block=no_block) self.assertTrue(ret) self.mock_run_all_success.assert_called_with(systemctl_command, **assert_kwargs) with patch.dict(systemd.__salt__, {'config.get': self.mock_false, 'cmd.run_all': self.mock_run_all_failure}): if (action in ('stop', 'disable')): ret = func(self.unit_name, no_block=no_block) self.assertFalse(ret) else: self.assertRaises(CommandExecutionError, func, self.unit_name, no_block=no_block) self.mock_run_all_failure.assert_called_with(systemctl_command, **assert_kwargs) with patch.object(salt.utils.systemd, 'has_scope', self.mock_false): for scope_mock in (self.mock_true, self.mock_false): with patch.dict(systemd.__salt__, {'config.get': scope_mock, 'cmd.run_all': self.mock_run_all_success}): ret = func(self.unit_name, no_block=no_block) self.assertTrue(ret) self.mock_run_all_success.assert_called_with(systemctl_command, **assert_kwargs) with patch.dict(systemd.__salt__, {'config.get': scope_mock, 'cmd.run_all': self.mock_run_all_failure}): if (action in ('stop', 'disable')): ret = func(self.unit_name, no_block=no_block) self.assertFalse(ret) else: self.assertRaises(CommandExecutionError, func, self.unit_name, no_block=no_block) self.mock_run_all_failure.assert_called_with(systemctl_command, **assert_kwargs)
'Common code for mask/unmask tests'
def _mask_unmask(self, action, runtime):
func = getattr(systemd, action) action = action.rstrip('_').replace('_', '-') systemctl_command = ['systemctl', action] if runtime: systemctl_command.append('--runtime') systemctl_command.append((self.unit_name + '.service')) scope_prefix = ['systemd-run', '--scope'] args = [self.unit_name, runtime] masked_mock = (self.mock_true if (action == 'unmask') else self.mock_false) with patch.object(systemd, '_check_for_unit_changes', self.mock_none): if (action == 'unmask'): mock_not_run = MagicMock(return_value={'retcode': 0, 'stdout': '', 'stderr': '', 'pid': 12345}) with patch.dict(systemd.__salt__, {'cmd.run_all': mock_not_run}): with patch.object(systemd, 'masked', self.mock_false): self.assertTrue(systemd.unmask_(self.unit_name)) self.assertTrue((mock_not_run.call_count == 0)) with patch.object(systemd, 'masked', masked_mock): with patch.object(salt.utils.systemd, 'has_scope', self.mock_true): with patch.dict(systemd.__salt__, {'config.get': self.mock_true, 'cmd.run_all': self.mock_run_all_success}): ret = func(*args) self.assertTrue(ret) self.mock_run_all_success.assert_called_with((scope_prefix + systemctl_command), python_shell=False, redirect_stderr=True) with patch.dict(systemd.__salt__, {'config.get': self.mock_true, 'cmd.run_all': self.mock_run_all_failure}): self.assertRaises(CommandExecutionError, func, *args) self.mock_run_all_failure.assert_called_with((scope_prefix + systemctl_command), python_shell=False, redirect_stderr=True) with patch.dict(systemd.__salt__, {'config.get': self.mock_false, 'cmd.run_all': self.mock_run_all_success}): ret = func(*args) self.assertTrue(ret) self.mock_run_all_success.assert_called_with(systemctl_command, python_shell=False, redirect_stderr=True) with patch.dict(systemd.__salt__, {'config.get': self.mock_false, 'cmd.run_all': self.mock_run_all_failure}): self.assertRaises(CommandExecutionError, func, *args) self.mock_run_all_failure.assert_called_with(systemctl_command, python_shell=False, redirect_stderr=True) with patch.object(salt.utils.systemd, 'has_scope', self.mock_false): for scope_mock in (self.mock_true, self.mock_false): with patch.dict(systemd.__salt__, {'config.get': scope_mock, 'cmd.run_all': self.mock_run_all_success}): ret = func(*args) self.assertTrue(ret) self.mock_run_all_success.assert_called_with(systemctl_command, python_shell=False, redirect_stderr=True) with patch.dict(systemd.__salt__, {'config.get': scope_mock, 'cmd.run_all': self.mock_run_all_failure}): self.assertRaises(CommandExecutionError, func, *args) self.mock_run_all_failure.assert_called_with(systemctl_command, python_shell=False, redirect_stderr=True)
'Tests the at.atq not available for any type of os_family.'
def test_atq_not_available(self):
with patch('salt.modules.at._cmd', MagicMock(return_value=None)): with patch.dict(at.__grains__, {'os_family': 'RedHat'}): self.assertEqual(at.atq(), "'at.atq' is not available.") with patch.dict(at.__grains__, {'os_family': ''}): self.assertEqual(at.atq(), "'at.atq' is not available.")
'Tests the no jobs available for any type of os_family.'
def test_atq_no_jobs_available(self):
with patch('salt.modules.at._cmd', MagicMock(return_value='')): with patch.dict(at.__grains__, {'os_family': 'RedHat'}): self.assertDictEqual(at.atq(), {'jobs': []}) with patch.dict(at.__grains__, {'os_family': ''}): self.assertDictEqual(at.atq(), {'jobs': []})
'Tests the list all queued and running jobs.'
def test_atq_list(self):
with patch('salt.modules.at._cmd') as salt_modules_at__cmd_mock: salt_modules_at__cmd_mock.return_value = '101 DCTB Thu Dec 11 19:48:47 2014 A B' with patch.dict(at.__grains__, {'os_family': '', 'os': ''}): self.assertDictEqual(at.atq(), {'jobs': [{'date': '2014-12-11', 'job': 101, 'queue': 'A', 'tag': '', 'time': '19:48:00', 'user': 'B'}]}) salt_modules_at__cmd_mock.return_value = '101 DCTB 2014-12-11 19:48:47 A B' with patch.dict(at.__grains__, {'os_family': 'RedHat', 'os': ''}): self.assertDictEqual(at.atq(), {'jobs': [{'date': '2014-12-11', 'job': 101, 'queue': 'A', 'tag': '', 'time': '19:48:47', 'user': 'B'}]}) salt_modules_at__cmd_mock.return_value = 'SALT: Dec 11, 2014 19:48 A 101 B' with patch.dict(at.__grains__, {'os_family': '', 'os': 'OpenBSD'}): self.assertDictEqual(at.atq(), {'jobs': [{'date': '2014-12-11', 'job': '101', 'queue': 'B', 'tag': '', 'time': '19:48:00', 'user': 'A'}]})
'Tests for remove jobs from the queue.'
def test_atrm(self):
with patch('salt.modules.at.atq', MagicMock(return_value=self.atq_output)): with patch.object(salt.utils.path, 'which', return_value=None): self.assertEqual(at.atrm(), "'at.atrm' is not available.") with patch.object(salt.utils.path, 'which', return_value=True): self.assertDictEqual(at.atrm(), {'jobs': {'removed': [], 'tag': None}}) with patch.object(at, '_cmd', return_value=True): with patch.object(salt.utils.path, 'which', return_value=True): self.assertDictEqual(at.atrm('all'), {'jobs': {'removed': ['101'], 'tag': None}}) with patch.object(at, '_cmd', return_value=True): with patch.object(salt.utils.path, 'which', return_value=True): self.assertDictEqual(at.atrm(101), {'jobs': {'removed': ['101'], 'tag': None}}) with patch.object(at, '_cmd', return_value=None): self.assertEqual(at.atrm(101), "'at.atrm' is not available.")
'Tests for check the job from queue.'
def test_jobcheck(self):
with patch('salt.modules.at.atq', MagicMock(return_value=self.atq_output)): self.assertDictEqual(at.jobcheck(), {'error': 'You have given a condition'}) self.assertDictEqual(at.jobcheck(runas='foo'), {'note': 'No match jobs or time format error', 'jobs': []}) self.assertDictEqual(at.jobcheck(runas='B', tag='', hour=19, minute=48, day=11, month=12, Year=2014), {'jobs': [{'date': '2014-12-11', 'job': 101, 'queue': 'A', 'tag': '', 'time': '19:48:47', 'user': 'B'}]})
'Tests for add a job to the queue.'
def test_at(self):
with patch('salt.modules.at.atq', MagicMock(return_value=self.atq_output)): self.assertDictEqual(at.at(), {'jobs': []}) with patch.object(salt.utils.path, 'which', return_value=None): self.assertEqual(at.at('12:05am', '/sbin/reboot', tag='reboot'), "'at.at' is not available.") with patch.object(salt.utils.path, 'which', return_value=True): with patch.dict(at.__grains__, {'os_family': 'RedHat'}): mock = MagicMock(return_value=None) with patch.dict(at.__salt__, {'cmd.run': mock}): self.assertEqual(at.at('12:05am', '/sbin/reboot', tag='reboot'), "'at.at' is not available.") mock = MagicMock(return_value='Garbled time') with patch.dict(at.__salt__, {'cmd.run': mock}): self.assertDictEqual(at.at('12:05am', '/sbin/reboot', tag='reboot'), {'jobs': [], 'error': 'invalid timespec'}) mock = MagicMock(return_value='warning: commands\nA B') with patch.dict(at.__salt__, {'cmd.run': mock}): with patch.dict(at.__grains__, {'os': 'OpenBSD'}): self.assertDictEqual(at.at('12:05am', '/sbin/reboot', tag='reboot'), {'jobs': [{'date': '2014-12-11', 'job': 101, 'queue': 'A', 'tag': '', 'time': '19:48:47', 'user': 'B'}]}) with patch.dict(at.__grains__, {'os_family': ''}): mock = MagicMock(return_value=None) with patch.dict(at.__salt__, {'cmd.run': mock}): self.assertEqual(at.at('12:05am', '/sbin/reboot', tag='reboot'), "'at.at' is not available.")
'Tests for atc'
def test_atc(self):
with patch.object(at, '_cmd', return_value=None): self.assertEqual(at.atc(101), "'at.atc' is not available.") with patch.object(at, '_cmd', return_value=''): self.assertDictEqual(at.atc(101), {'error': "invalid job id '101'"}) with patch.object(at, '_cmd', return_value='101 DCTB Thu Dec 11 19:48:47 2014 A B'): self.assertEqual(at.atc(101), '101 DCTB Thu Dec 11 19:48:47 2014 A B')
'Test to gather lm-sensors data from a given chip'
def test_sense(self):
with patch.dict(sensors.__salt__, {'cmd.run': MagicMock(return_value='A:a B:b C:c D:d')}): self.assertDictEqual(sensors.sense('chip'), {'A': 'a B'})
'Test if it install an NPM package.'
def test_install(self):
mock = MagicMock(return_value={'retcode': 1, 'stderr': 'error'}) with patch.dict(npm.__salt__, {'cmd.run_all': mock}): self.assertRaises(CommandExecutionError, npm.install, 'coffee-script') mock = MagicMock(return_value={'retcode': 0, 'stderr': 'error', 'stdout': '{"salt": ["SALT"]}'}) with patch.dict(npm.__salt__, {'cmd.run_all': mock}): mock_err = MagicMock(return_value='SALT') with patch.object(json, 'loads', mock_err): self.assertEqual(npm.install('coffee-script'), 'SALT') mock = MagicMock(return_value={'retcode': 0, 'stderr': 'error', 'stdout': '{"salt": ["SALT"]}'}) with patch.dict(npm.__salt__, {'cmd.run_all': mock}): mock_err = MagicMock(side_effect=ValueError()) with patch.object(json, 'loads', mock_err): self.assertEqual(npm.install('coffee-script'), '{"salt": ["SALT"]}')
'Test if it uninstall an NPM package.'
def test_uninstall(self):
mock = MagicMock(return_value={'retcode': 1, 'stderr': 'error'}) with patch.dict(npm.__salt__, {'cmd.run_all': mock}): self.assertFalse(npm.uninstall('coffee-script')) mock = MagicMock(return_value={'retcode': 0, 'stderr': 'error'}) with patch.dict(npm.__salt__, {'cmd.run_all': mock}): self.assertTrue(npm.uninstall('coffee-script'))
'Test if it list installed NPM packages.'
def test_list(self):
mock = MagicMock(return_value={'retcode': 1, 'stderr': 'error'}) with patch.dict(npm.__salt__, {'cmd.run_all': mock}): self.assertRaises(CommandExecutionError, npm.list_, 'coffee-script') mock = MagicMock(return_value={'retcode': 0, 'stderr': 'error', 'stdout': '{"salt": ["SALT"]}'}) with patch.dict(npm.__salt__, {'cmd.run_all': mock}): mock_err = MagicMock(return_value={'dependencies': 'SALT'}) with patch.object(json, 'loads', mock_err): self.assertEqual(npm.list_('coffee-script'), 'SALT')
'Test if it cleans the cached NPM packages.'
def test_cache_clean(self):
mock = MagicMock(return_value={'retcode': 1, 'stderr': 'error'}) with patch.dict(npm.__salt__, {'cmd.run_all': mock}): self.assertFalse(npm.cache_clean()) mock = MagicMock(return_value={'retcode': 0}) with patch.dict(npm.__salt__, {'cmd.run_all': mock}): self.assertTrue(npm.cache_clean()) mock = MagicMock(return_value={'retcode': 0}) with patch.dict(npm.__salt__, {'cmd.run_all': mock}): self.assertTrue(npm.cache_clean('coffee-script'))
'Test if it lists the NPM cache.'
def test_cache_list(self):
mock = MagicMock(return_value={'retcode': 1, 'stderr': 'error'}) with patch.dict(npm.__salt__, {'cmd.run_all': mock}): self.assertRaises(CommandExecutionError, npm.cache_list) mock = MagicMock(return_value={'retcode': 0, 'stderr': 'error', 'stdout': ['~/.npm']}) with patch.dict(npm.__salt__, {'cmd.run_all': mock}): self.assertEqual(npm.cache_list(), ['~/.npm']) mock = MagicMock(return_value={'retcode': 0, 'stderr': 'error', 'stdout': ''}) with patch.dict(npm.__salt__, {'cmd.run_all': mock}): self.assertEqual(npm.cache_list('coffee-script'), '')
'Test if it prints the NPM cache path.'
def test_cache_path(self):
mock = MagicMock(return_value={'retcode': 1, 'stderr': 'error'}) with patch.dict(npm.__salt__, {'cmd.run_all': mock}): self.assertEqual(npm.cache_path(), 'error') mock = MagicMock(return_value={'retcode': 0, 'stderr': 'error', 'stdout': '/User/salt/.npm'}) with patch.dict(npm.__salt__, {'cmd.run_all': mock}): self.assertEqual(npm.cache_path(), '/User/salt/.npm')
'Test opening the database. :return:'
def test_open(self):
with patch('os.listdir', MagicMock(return_value=['test_db'])): with patch('gzip.open', mock_open('foo:int,bar:str')): csvdb = CsvDB('/foobar') csvdb.open() assert (list(csvdb.list_tables()) == ['test_db']) assert (csvdb.is_closed() is False)
'Test closing the database. :return:'
def test_close(self):
with patch('os.listdir', MagicMock(return_value=['test_db'])): with patch('gzip.open', mock_open('foo:int,bar:str')): csvdb = CsvDB('/foobar') csvdb.open() csvdb.close() assert (csvdb.is_closed() is True)
'Test creating table. :return:'
def test_create_table(self):
with patch('os.path.exists', MagicMock(return_value=False)): with patch('os.listdir', MagicMock(return_value=['some_table'])): writable = Writable() with patch('gzip.open', MagicMock(return_value=writable)): csvdb = CsvDB('/foobar') csvdb.open() csvdb.create_table_from_object(FoobarEntity()) if six.PY2: assert (writable.data[0].strip() == 'foo:int,bar:str,spam:float') else: writable_data = writable.data[0].strip() assert_order_options = ['bar:str,foo:int,spam:float', 'bar:str,spam:float,foo:int', 'foo:int,spam:float,bar:str', 'foo:int,bar:str,spam:float', 'spam:float,foo:int,bar:str', 'spam:float,bar:str,foo:int'] while assert_order_options: assert_option = assert_order_options.pop() try: assert (writable_data == assert_option) break except AssertionError: if (not assert_order_options): raise continue
'Test list databases. :return:'
def test_list_databases(self):
with patch('os.listdir', MagicMock(return_value=['test_db'])): csvdb = CsvDB('/foobar') assert (csvdb.list() == ['test_db'])
'Test storing object into the database. :return:'
def test_add_object(self):
with patch('os.path.exists', MagicMock(return_value=False)): with patch('os.listdir', MagicMock(return_value=['some_table'])): writable = Writable() with patch('gzip.open', MagicMock(return_value=writable)): obj = FoobarEntity() obj.foo = 123 obj.bar = 'test entity' obj.spam = 0.123 csvdb = CsvDB('/foobar') csvdb.open() csvdb._tables = {'some_table': OrderedDict([tuple(elm.split(':')) for elm in ['foo:int', 'bar:str', 'spam:float']])} csvdb.store(obj) assert (writable.data[0].strip() == '123,test entity,0.123')
'Deleting an object from the store. :return:'
def test_delete_object(self):
with patch('gzip.open', MagicMock()): with patch('os.listdir', MagicMock(return_value=['test_db'])): with patch('csv.reader', MagicMock(return_value=iter([[], ['foo:int', 'bar:str', 'spam:float'], ['123', 'test', '0.123'], ['234', 'another', '0.456']]))): class InterceptedCsvDB(CsvDB, ): def __init__(self, path): CsvDB.__init__(self, path) self._remained = list() def store(self, obj, distinct=False): self._remained.append(obj) csvdb = InterceptedCsvDB('/foobar') csvdb.open() csvdb.create_table_from_object = MagicMock() csvdb.flush = MagicMock() assert (csvdb.delete(FoobarEntity, eq={'foo': 123}) is True) assert (len(csvdb._remained) == 1) assert (csvdb._remained[0].foo == 234) assert (csvdb._remained[0].bar == 'another') assert (csvdb._remained[0].spam == 0.456)
'Updating an object from the store. :return:'
def test_update_object(self):
with patch('gzip.open', MagicMock()): with patch('os.listdir', MagicMock(return_value=['test_db'])): with patch('csv.reader', MagicMock(return_value=iter([[], ['foo:int', 'bar:str', 'spam:float'], ['123', 'test', '0.123'], ['234', 'another', '0.456']]))): obj = FoobarEntity() obj.foo = 123 obj.bar = 'updated' obj.spam = 0.5 class InterceptedCsvDB(CsvDB, ): def __init__(self, path): CsvDB.__init__(self, path) self._remained = list() def store(self, obj, distinct=False): self._remained.append(obj) csvdb = InterceptedCsvDB('/foobar') csvdb.open() csvdb.create_table_from_object = MagicMock() csvdb.flush = MagicMock() assert (csvdb.update(obj, eq={'foo': 123}) is True) assert (len(csvdb._remained) == 2) assert (csvdb._remained[0].foo == 123) assert (csvdb._remained[0].bar == 'updated') assert (csvdb._remained[0].spam == 0.5) assert (csvdb._remained[1].foo == 234) assert (csvdb._remained[1].bar == 'another') assert (csvdb._remained[1].spam == 0.456)
'Getting an object from the store. :return:'
def test_get_object(self):
with patch('os.listdir', MagicMock(return_value=['test_db'])): with patch('gzip.open', MagicMock()): with patch('csv.reader', MagicMock(return_value=iter([[], ['foo:int', 'bar:str', 'spam:float'], ['123', 'test', '0.123'], ['234', 'another', '0.456']]))): csvdb = CsvDB('/foobar') csvdb.open() entities = csvdb.get(FoobarEntity) assert (list == type(entities)) assert (len(entities) == 2) assert (entities[0].foo == 123) assert (entities[0].bar == 'test') assert (entities[0].spam == 0.123) assert (entities[1].foo == 234) assert (entities[1].bar == 'another') assert (entities[1].spam == 0.456)
'Getting an object from the store with conditions :return:'
def test_get_obj_equals(self):
with patch('os.listdir', MagicMock(return_value=['test_db'])): with patch('gzip.open', MagicMock()): with patch('csv.reader', MagicMock(return_value=iter([[], ['foo:int', 'bar:str', 'spam:float'], ['123', 'test', '0.123'], ['234', 'another', '0.456']]))): csvdb = CsvDB('/foobar') csvdb.open() entities = csvdb.get(FoobarEntity, eq={'foo': 123}) assert (list == type(entities)) assert (len(entities) == 1) assert (entities[0].foo == 123) assert (entities[0].bar == 'test') assert (entities[0].spam == 0.123)
'Getting an object from the store with conditions :return:'
def test_get_obj_more_than(self):
with patch('gzip.open', MagicMock()): with patch('os.listdir', MagicMock(return_value=['test_db'])): with patch('csv.reader', MagicMock(return_value=iter([[], ['foo:int', 'bar:str', 'spam:float'], ['123', 'test', '0.123'], ['234', 'another', '0.456']]))): csvdb = CsvDB('/foobar') csvdb.open() entities = csvdb.get(FoobarEntity, mt={'foo': 123}) assert (list == type(entities)) assert (len(entities) == 1) assert (entities[0].foo == 234) assert (entities[0].bar == 'another') assert (entities[0].spam == 0.456)
'Getting an object from the store with conditions :return:'
def test_get_obj_less_than(self):
with patch('gzip.open', MagicMock()): with patch('os.listdir', MagicMock(return_value=['test_db'])): with patch('csv.reader', MagicMock(return_value=iter([[], ['foo:int', 'bar:str', 'spam:float'], ['123', 'test', '0.123'], ['234', 'another', '0.456']]))): csvdb = CsvDB('/foobar') csvdb.open() entities = csvdb.get(FoobarEntity, lt={'foo': 234}) assert (list == type(entities)) assert (len(entities) == 1) assert (entities[0].foo == 123) assert (entities[0].bar == 'test') assert (entities[0].spam == 0.123)
'Getting an object from the store with conditions :return:'
def test_get_obj_matching(self):
with patch('gzip.open', MagicMock()): with patch('os.listdir', MagicMock(return_value=['test_db'])): with patch('csv.reader', MagicMock(return_value=iter([[], ['foo:int', 'bar:str', 'spam:float'], ['123', 'this is test of something', '0.123'], ['234', 'another test of stuff', '0.456']]))): csvdb = CsvDB('/foobar') csvdb.open() entities = csvdb.get(FoobarEntity, matches={'bar': 'is\\stest'}) assert (list == type(entities)) assert (len(entities) == 1) assert (entities[0].foo == 123) assert (entities[0].bar == 'this is test of something') assert (entities[0].spam == 0.123)
'Test object serialization. :return:'
def test_obj_serialization(self):
obj = FoobarEntity() obj.foo = 123 obj.bar = 'test entity' obj.spam = 0.123 descr = OrderedDict([tuple(elm.split(':')) for elm in ['foo:int', 'bar:str', 'spam:float']]) assert (obj._serialize(descr) == [123, 'test entity', 0.123])
'Test object validation. :return:'
def test_obj_validation(self):
with patch('os.path.exists', MagicMock(return_value=False)): with patch('os.listdir', MagicMock(return_value=['some_table'])): obj = FoobarEntity() obj.foo = 123 obj.bar = 'test entity' obj.spam = 0.123 csvdb = CsvDB('/foobar') csvdb._tables = {'some_table': OrderedDict([tuple(elm.split(':')) for elm in ['foo:int', 'bar:str', 'spam:float']])} assert (csvdb._validate_object(obj) == [123, 'test entity', 0.123])
'Test criteria selector. :return:'
def test_criteria(self):
with patch('os.path.exists', MagicMock(return_value=False)): with patch('os.listdir', MagicMock(return_value=['some_table'])): obj = FoobarEntity() obj.foo = 123 obj.bar = 'test entity' obj.spam = 0.123 obj.pi = 3.14 cmp = CsvDB('/foobar')._CsvDB__criteria assert (cmp(obj, eq={'foo': 123}) is True) assert (cmp(obj, lt={'foo': 124}) is True) assert (cmp(obj, mt={'foo': 122}) is True) assert (cmp(obj, eq={'foo': 0}) is False) assert (cmp(obj, lt={'foo': 123}) is False) assert (cmp(obj, mt={'foo': 123}) is False) assert (cmp(obj, matches={'bar': 't\\se.*?'}) is True) assert (cmp(obj, matches={'bar': '\\s\\sentity'}) is False) assert (cmp(obj, eq={'foo': 123, 'bar': 'test entity', 'spam': 0.123}) is True) assert (cmp(obj, eq={'foo': 123, 'bar': 'test', 'spam': 0.123}) is False) assert (cmp(obj, lt={'foo': 124, 'spam': 0.124}) is True) assert (cmp(obj, lt={'foo': 124, 'spam': 0.123}) is False) assert (cmp(obj, mt={'foo': 122, 'spam': 0.122}) is True) assert (cmp(obj, mt={'foo': 122, 'spam': 0.123}) is False) assert (cmp(obj, matches={'bar': 'test'}, mt={'foo': 122}, lt={'spam': 0.124}, eq={'pi': 3.14}) is True) assert (cmp(obj, matches={'bar': '^test.*?y$'}, mt={'foo': 122}, lt={'spam': 0.124}, eq={'pi': 3.14}) is True) assert (cmp(obj, matches={'bar': '^ent'}, mt={'foo': 122}, lt={'spam': 0.124}, eq={'pi': 3.14}) is False) assert (cmp(obj, matches={'bar': '^test.*?y$'}, mt={'foo': 123}, lt={'spam': 0.124}, eq={'pi': 3.14}) is False)
'tests network.wol with bad mac'
def test_wol_bad_mac(self):
bad_mac = '31337' self.assertRaises(ValueError, network.wol, bad_mac)
'tests network.wol success'
def test_wol_success(self):
mac = '080027136977' bcast = '255.255.255.255 7' class MockSocket(object, ): def __init__(self, *args, **kwargs): pass def __call__(self, *args, **kwargs): pass def setsockopt(self, *args, **kwargs): pass def sendto(self, *args, **kwargs): pass with patch('socket.socket', MockSocket): self.assertTrue(network.wol(mac, bcast))
'Test for Performs a ping to a host'
def test_ping(self):
with patch.object(salt.utils.network, 'sanitize_host', return_value='A'): mock_all = MagicMock(side_effect=[{'retcode': 1}, {'retcode': 0}]) with patch.dict(network.__salt__, {'cmd.run_all': mock_all}): self.assertFalse(network.ping('host', return_boolean=True)) self.assertTrue(network.ping('host', return_boolean=True)) with patch.dict(network.__salt__, {'cmd.run': MagicMock(return_value='A')}): self.assertEqual(network.ping('host'), 'A')
'Test for return information on open ports and states'
def test_netstat(self):
with patch.dict(network.__grains__, {'kernel': 'Linux'}): with patch.object(network, '_netstat_linux', return_value='A'): with patch.object(network, '_ss_linux', return_value='A'): self.assertEqual(network.netstat(), 'A') with patch.dict(network.__grains__, {'kernel': 'OpenBSD'}): with patch.object(network, '_netstat_bsd', return_value='A'): self.assertEqual(network.netstat(), 'A') with patch.dict(network.__grains__, {'kernel': 'A'}): self.assertRaises(CommandExecutionError, network.netstat)
'Test for return a dict containing information on all of the running TCP connections'
def test_active_tcp(self):
with patch.object(salt.utils.network, 'active_tcp', return_value='A'): with patch.dict(network.__grains__, {'kernel': 'Linux'}): self.assertEqual(network.active_tcp(), 'A')
'Test for Performs a traceroute to a 3rd party host'
def test_traceroute(self):
with patch.object(salt.utils.path, 'which', side_effect=[False, True]): self.assertListEqual(network.traceroute('host'), []) with patch.object(salt.utils.network, 'sanitize_host', return_value='A'): with patch.dict(network.__salt__, {'cmd.run': MagicMock(return_value='')}): self.assertListEqual(network.traceroute('host'), [])
'Test for Performs a DNS lookup with dig'
def test_dig(self):
with patch('salt.utils.path.which', MagicMock(return_value='dig')): with patch.object(salt.utils.network, 'sanitize_host', return_value='A'): with patch.dict(network.__salt__, {'cmd.run': MagicMock(return_value='A')}): self.assertEqual(network.dig('host'), 'A')
'Test for return the arp table from the minion'
def test_arp(self):
with patch.dict(network.__salt__, {'cmd.run': MagicMock(return_value='A,B,C,D\nE,F,G,H\n')}): with patch('salt.utils.path.which', MagicMock(return_value='')): self.assertDictEqual(network.arp(), {})
'Test for return a dictionary of information about all the interfaces on the minion'
def test_interfaces(self):
with patch.object(salt.utils.network, 'interfaces', return_value={}): self.assertDictEqual(network.interfaces(), {})
'Test for return the hardware address (a.k.a. MAC address) for a given interface'
def test_hw_addr(self):
with patch.object(salt.utils.network, 'hw_addr', return_value={}): self.assertDictEqual(network.hw_addr('iface'), {})
'Test for return the inet address for a given interface'
def test_interface(self):
with patch.object(salt.utils.network, 'interface', return_value={}): self.assertDictEqual(network.interface('iface'), {})
'Test for return the inet address for a given interface'
def test_interface_ip(self):
with patch.object(salt.utils.network, 'interface_ip', return_value={}): self.assertDictEqual(network.interface_ip('iface'), {})
'Test for returns a list of subnets to which the host belongs'
def test_subnets(self):
with patch.object(salt.utils.network, 'subnets', return_value={}): self.assertDictEqual(network.subnets(), {})
'Test for returns True if host is within specified subnet, otherwise False.'
def test_in_subnet(self):
with patch.object(salt.utils.network, 'in_subnet', return_value={}): self.assertDictEqual(network.in_subnet('iface'), {})
'Test for returns a list of IPv4 addresses assigned to the host.'
def test_ip_addrs(self):
with patch.object(salt.utils.network, 'ip_addrs', return_value=['0.0.0.0']): with patch.object(salt.utils.network, 'in_subnet', return_value=True): self.assertListEqual(network.ip_addrs('interface', 'include_loopback', 'cidr'), ['0.0.0.0']) self.assertListEqual(network.ip_addrs('interface', 'include_loopback'), ['0.0.0.0'])
'Test for returns a list of IPv6 addresses assigned to the host.'
def test_ip_addrs6(self):
with patch.object(salt.utils.network, 'ip_addrs6', return_value=['A']): self.assertListEqual(network.ip_addrs6('int', 'include'), ['A'])
'Test for Get hostname'
def test_get_hostname(self):
with patch.object(network.socket, 'gethostname', return_value='A'): self.assertEqual(network.get_hostname(), 'A')
'Test for Modify hostname'
def test_mod_hostname(self):
self.assertFalse(network.mod_hostname(None)) with patch.object(salt.utils.path, 'which', return_value='hostname'): with patch.dict(network.__salt__, {'cmd.run': MagicMock(return_value=None)}): file_d = '\n'.join(['#', 'A B C D,E,F G H']) with patch('salt.utils.files.fopen', mock_open(read_data=file_d), create=True) as mfi: mfi.return_value.__iter__.return_value = file_d.splitlines() with patch.dict(network.__grains__, {'os_family': 'A'}): self.assertTrue(network.mod_hostname('hostname'))
'Test for Test connectivity to a host using a particular port from the minion.'
def test_connect(self):
with patch('socket.socket') as mock_socket: self.assertDictEqual(network.connect(False, 'port'), {'comment': 'Required argument, host, is missing.', 'result': False}) self.assertDictEqual(network.connect('host', False), {'comment': 'Required argument, port, is missing.', 'result': False}) ret = 'Unable to connect to host (0) on tcp port port' mock_socket.side_effect = Exception('foo') with patch.object(salt.utils.network, 'sanitize_host', return_value='A'): with patch.object(socket, 'getaddrinfo', return_value=[['ipv4', 'A', 6, 'B', '0.0.0.0']]): self.assertDictEqual(network.connect('host', 'port'), {'comment': ret, 'result': False}) ret = 'Successfully connected to host (0) on tcp port port' mock_socket.side_effect = MagicMock() mock_socket.settimeout().return_value = None mock_socket.connect().return_value = None mock_socket.shutdown().return_value = None with patch.object(salt.utils.network, 'sanitize_host', return_value='A'): with patch.object(socket, 'getaddrinfo', return_value=[['ipv4', 'A', 6, 'B', '0.0.0.0']]): self.assertDictEqual(network.connect('host', 'port'), {'comment': ret, 'result': True})
'Test for Check if the given IP address is a private address'
@skipIf((HAS_IPADDRESS is False), "unable to import 'ipaddress'") def test_is_private(self):
with patch.object(ipaddress.IPv4Address, 'is_private', return_value=True): self.assertTrue(network.is_private('0.0.0.0')) with patch.object(ipaddress.IPv6Address, 'is_private', return_value=True): self.assertTrue(network.is_private('::1'))
'Test for Check if the given IP address is a loopback address'
@skipIf((HAS_IPADDRESS is False), "unable to import 'ipaddress'") def test_is_loopback(self):
with patch.object(ipaddress.IPv4Address, 'is_loopback', return_value=True): self.assertTrue(network.is_loopback('127.0.0.1')) with patch.object(ipaddress.IPv6Address, 'is_loopback', return_value=True): self.assertTrue(network.is_loopback('::1'))
'Test for return network buffer sizes as a dict'
def test_get_bufsize(self):
with patch.dict(network.__grains__, {'kernel': 'Linux'}): with patch.object(os.path, 'exists', return_value=True): with patch.object(network, '_get_bufsize_linux', return_value={'size': 1}): self.assertDictEqual(network.get_bufsize('iface'), {'size': 1}) with patch.dict(network.__grains__, {'kernel': 'A'}): self.assertDictEqual(network.get_bufsize('iface'), {})
'Test for Modify network interface buffers (currently linux only)'
def test_mod_bufsize(self):
with patch.dict(network.__grains__, {'kernel': 'Linux'}): with patch.object(os.path, 'exists', return_value=True): with patch.object(network, '_mod_bufsize_linux', return_value={'size': 1}): self.assertDictEqual(network.mod_bufsize('iface'), {'size': 1}) with patch.dict(network.__grains__, {'kernel': 'A'}): self.assertFalse(network.mod_bufsize('iface'))
'Test for return currently configured routes from routing table'
def test_routes(self):
self.assertRaises(CommandExecutionError, network.routes, 'family') with patch.dict(network.__grains__, {'kernel': 'A', 'os': 'B'}): self.assertRaises(CommandExecutionError, network.routes, 'inet') with patch.dict(network.__grains__, {'kernel': 'Linux'}): with patch.object(network, '_netstat_route_linux', side_effect=['A', [{'addr_family': 'inet'}]]): with patch.object(network, '_ip_route_linux', side_effect=['A', [{'addr_family': 'inet'}]]): self.assertEqual(network.routes(None), 'A') self.assertListEqual(network.routes('inet'), [{'addr_family': 'inet'}])
'Test for return default route(s) from routing table'
def test_default_route(self):
self.assertRaises(CommandExecutionError, network.default_route, 'family') with patch.object(network, 'routes', side_effect=[[{'addr_family': 'inet'}, {'destination': 'A'}], []]): with patch.dict(network.__grains__, {'kernel': 'A', 'os': 'B'}): self.assertRaises(CommandExecutionError, network.default_route, 'inet') with patch.dict(network.__grains__, {'kernel': 'Linux'}): self.assertListEqual(network.default_route('inet'), [])
'Test if it adds an HTTP user using the htpasswd command'
def test_useradd(self):
mock = MagicMock(return_value={'out': 'Salt'}) with patch.dict(htpasswd.__salt__, {'cmd.run_all': mock}): with patch('os.path.exists', MagicMock(return_value=True)): self.assertDictEqual(htpasswd.useradd('/etc/httpd/htpasswd', 'larry', 'badpassword'), {'out': 'Salt'})
'Test if it delete an HTTP user from the specified htpasswd file.'
def test_userdel(self):
mock = MagicMock(return_value='Salt') with patch.dict(htpasswd.__salt__, {'cmd.run': mock}): with patch('os.path.exists', MagicMock(return_value=True)): self.assertEqual(htpasswd.userdel('/etc/httpd/htpasswd', 'larry'), ['Salt'])
'Test if it returns error when no htpasswd file exists'
def test_userdel_missing_htpasswd(self):
with patch('os.path.exists', MagicMock(return_value=False)): self.assertEqual(htpasswd.userdel('/etc/httpd/htpasswd', 'larry'), 'Error: The specified htpasswd file does not exist')
'Test if it gets a value from a db, using a uri in the form of sdb://<profile>/<key>'
def test_get(self):
self.assertEqual(sdb.get('sdb://salt/foo'), 'sdb://salt/foo')
'Test if it sets a value from a db, using a uri in the form of sdb://<profile>/<key>'
def test_set(self):
self.assertFalse(sdb.set_('sdb://mymemcached/foo', 'bar'))
'Test if it get the output volume (range 0 to 100)'
def test_get_output_volume(self):
mock = MagicMock(return_value={'retcode': 0, 'stdout': '25'}) with patch.dict(mac_desktop.__salt__, {'cmd.run_all': mock}): self.assertEqual(mac_desktop.get_output_volume(), '25')
'Tests that an error is raised when cmd.run_all errors'
def test_get_output_volume_error(self):
mock = MagicMock(return_value={'retcode': 1}) with patch.dict(mac_desktop.__salt__, {'cmd.run_all': mock}): self.assertRaises(CommandExecutionError, mac_desktop.get_output_volume)
'Test if it set the volume of sound (range 0 to 100)'
def test_set_output_volume(self):
mock = MagicMock(return_value={'retcode': 0}) with patch.dict(mac_desktop.__salt__, {'cmd.run_all': mock}): with patch('salt.modules.mac_desktop.get_output_volume', MagicMock(return_value='25')): self.assertTrue(mac_desktop.set_output_volume('25'))
'Tests that an error is raised when cmd.run_all errors'
def test_set_output_volume_error(self):
mock = MagicMock(return_value={'retcode': 1}) with patch.dict(mac_desktop.__salt__, {'cmd.run_all': mock}): self.assertRaises(CommandExecutionError, mac_desktop.set_output_volume, '25')
'Test if it launch the screensaver'
def test_screensaver(self):
mock = MagicMock(return_value={'retcode': 0}) with patch.dict(mac_desktop.__salt__, {'cmd.run_all': mock}): self.assertTrue(mac_desktop.screensaver())
'Tests that an error is raised when cmd.run_all errors'
def test_screensaver_error(self):
mock = MagicMock(return_value={'retcode': 1}) with patch.dict(mac_desktop.__salt__, {'cmd.run_all': mock}): self.assertRaises(CommandExecutionError, mac_desktop.screensaver)
'Test if it lock the desktop session'
def test_lock(self):
mock = MagicMock(return_value={'retcode': 0}) with patch.dict(mac_desktop.__salt__, {'cmd.run_all': mock}): self.assertTrue(mac_desktop.lock())
'Tests that an error is raised when cmd.run_all errors'
def test_lock_error(self):
mock = MagicMock(return_value={'retcode': 1}) with patch.dict(mac_desktop.__salt__, {'cmd.run_all': mock}): self.assertRaises(CommandExecutionError, mac_desktop.lock)
'Test if it says some words.'
def test_say(self):
mock = MagicMock(return_value={'retcode': 0}) with patch.dict(mac_desktop.__salt__, {'cmd.run_all': mock}): self.assertTrue(mac_desktop.say())
'Tests that an error is raised when cmd.run_all errors'
def test_say_error(self):
mock = MagicMock(return_value={'retcode': 1}) with patch.dict(mac_desktop.__salt__, {'cmd.run_all': mock}): self.assertRaises(CommandExecutionError, mac_desktop.say)
'Test if it gets memcached status'
def test_status(self):
class MockMemcache(object, ): '\n Mock of memcache\n ' @staticmethod def get_stats(): '\n Mock of stats method\n ' return [('127.0.0.1:11211 (1)', {})] with patch.object(memcached, '_connect', MagicMock(return_value=MockMemcache())): self.assertDictEqual(memcached.status(), {'127.0.0.1:11211 (1)': {}})
'Test if it gets memcached status'
def test_status_false(self):
class MockMemcache(object, ): '\n Mock of memcache\n ' @staticmethod def get_stats(): '\n Mock of stats method\n ' return [] with patch.object(memcached, '_connect', MagicMock(return_value=MockMemcache())): self.assertFalse(memcached.status())
'Test if it retrieve value for a key'
def test_get(self):
class MockMemcache(object, ): '\n Mock of memcache\n ' @staticmethod def get_stats(): '\n Mock of stats method\n ' return [('127.0.0.1:11211 (1)', {})] @staticmethod def get(key): '\n Mock of get method\n ' return key with patch.object(memcached, '_connect', MagicMock(return_value=MockMemcache())): self.assertEqual(memcached.get('salt'), 'salt')
'Test if it set a key on the memcached server'
def test_set(self):
class MockMemcache(object, ): '\n Mock of memcache\n ' def __init__(self): self.key = None self.value = None self.time = None self.min_compress_len = None @staticmethod def get_stats(): '\n Mock of stats method\n ' return [('127.0.0.1:11211 (1)', {})] def set(self, key, value, time, min_compress_len): '\n Mock of set method\n ' self.key = key self.value = value self.time = time self.min_compress_len = min_compress_len return True with patch.object(memcached, '_connect', MagicMock(return_value=MockMemcache())): self.assertTrue(memcached.set_('salt', '1111')) self.assertRaises(SaltInvocationError, memcached.set_, 'salt', '1111', time='0.1') self.assertRaises(SaltInvocationError, memcached.set_, 'salt', '1111', min_compress_len='0.1')
'Test if it delete a key from memcache server'
def test_delete(self):
class MockMemcache(object, ): '\n Mock of memcache\n ' def __init__(self): self.key = None self.time = None @staticmethod def get_stats(): '\n Mock of stats method\n ' return [('127.0.0.1:11211 (1)', {})] def delete(self, key, time): '\n Mock of delete method\n ' self.key = key self.time = time return True with patch.object(memcached, '_connect', MagicMock(return_value=MockMemcache())): self.assertTrue(memcached.delete('salt')) self.assertRaises(SaltInvocationError, memcached.delete, 'salt', '1111', time='0.1')
'Test if it add a key from memcache server'
def test_add(self):
class MockMemcache(object, ): '\n Mock of memcache\n ' def __init__(self): self.key = None self.value = None self.time = None self.min_compress_len = None @staticmethod def get_stats(): '\n Mock of stats method\n ' return [('127.0.0.1:11211 (1)', {})] def add(self, key, value, time, min_compress_len): '\n Mock of add method\n ' self.key = key self.value = value self.time = time self.min_compress_len = min_compress_len return True with patch.object(memcached, '_connect', MagicMock(return_value=MockMemcache())): self.assertTrue(memcached.add('salt', '1111')) self.assertRaises(SaltInvocationError, memcached.add, 'salt', '1111', time='0.1') self.assertRaises(SaltInvocationError, memcached.add, 'salt', '1111', min_compress_len='0.1')
'Test if it replace a key from memcache server'
def test_replace(self):
class MockMemcache(object, ): '\n Mock of memcache\n ' def __init__(self): self.key = None self.value = None self.time = None self.min_compress_len = None @staticmethod def get_stats(): '\n Mock of stats method\n ' return [('127.0.0.1:11211 (1)', {})] def replace(self, key, value, time, min_compress_len): '\n Mock of replace method\n ' self.key = key self.value = value self.time = time self.min_compress_len = min_compress_len return True with patch.object(memcached, '_connect', MagicMock(return_value=MockMemcache())): self.assertTrue(memcached.replace('salt', '1111')) self.assertRaises(SaltInvocationError, memcached.replace, 'salt', '1111', time='0.1') self.assertRaises(SaltInvocationError, memcached.replace, 'salt', '1111', min_compress_len='0.1')
'Test if it increment the value of a key'
def test_increment(self):
class MockMemcache(object, ): '\n Mock of memcache\n ' def __init__(self): self.key = None @staticmethod def get_stats(): '\n Mock of stats method\n ' return [('127.0.0.1:11211 (1)', {})] def get(self, key): '\n Mock of get method\n ' self.key = key return 1 def incr(self, key, delta): '\n Mock of incr method\n ' self.key = key if (not isinstance(delta, integer_types)): raise SaltInvocationError('Delta value must be an integer') return key with patch.object(memcached, '_connect', MagicMock(return_value=MockMemcache())): self.assertEqual(memcached.increment('salt'), 'salt') self.assertRaises(SaltInvocationError, memcached.increment, 'salt', delta='sa')
'Test if it increment the value of a key'
def test_increment_exist(self):
class MockMemcache(object, ): '\n Mock of memcache\n ' def __init__(self): self.key = None @staticmethod def get_stats(): '\n Mock of stats method\n ' return [('127.0.0.1:11211 (1)', {})] def get(self, key): '\n Mock of get method\n ' self.key = key return key with patch.object(memcached, '_connect', MagicMock(return_value=MockMemcache())): self.assertRaises(CommandExecutionError, memcached.increment, 'salt')
'Test if it increment the value of a key'
def test_increment_none(self):
class MockMemcache(object, ): '\n Mock of memcache\n ' def __init__(self): self.key = None @staticmethod def get_stats(): '\n Mock of stats method\n ' return [('127.0.0.1:11211 (1)', {})] def get(self, key): '\n Mock of get method\n ' self.key = key return None with patch.object(memcached, '_connect', MagicMock(return_value=MockMemcache())): self.assertRaises(CommandExecutionError, memcached.increment, 'salt')
'Test if it decrement the value of a key'
def test_decrement(self):
class MockMemcache(object, ): '\n Mock of memcache\n ' def __init__(self): self.key = None @staticmethod def get_stats(): '\n Mock of stats method\n ' return [('127.0.0.1:11211 (1)', {})] def get(self, key): '\n Mock of get method\n ' self.key = key return 1 def decr(self, key, delta): '\n Mock of decr method\n ' self.key = key if (not isinstance(delta, integer_types)): raise SaltInvocationError('Delta value must be an integer') return key with patch.object(memcached, '_connect', MagicMock(return_value=MockMemcache())): self.assertEqual(memcached.decrement('salt'), 'salt') self.assertRaises(SaltInvocationError, memcached.decrement, 'salt', delta='sa')
'Test if it decrement the value of a key'
def test_decrement_exist(self):
class MockMemcache(object, ): '\n Mock of memcache\n ' def __init__(self): self.key = None @staticmethod def get_stats(): '\n Mock of stats method\n ' return [('127.0.0.1:11211 (1)', {})] def get(self, key): '\n Mock of get method\n ' self.key = key return key with patch.object(memcached, '_connect', MagicMock(return_value=MockMemcache())): self.assertRaises(CommandExecutionError, memcached.decrement, 'salt')
'Test if it decrement the value of a key'
def test_decrement_none(self):
class MockMemcache(object, ): '\n Mock of memcache\n ' def __init__(self): self.key = None @staticmethod def get_stats(): '\n Mock of stats method\n ' return [('127.0.0.1:11211 (1)', {})] def get(self, key): '\n Mock of get method\n ' self.key = key return None with patch.object(memcached, '_connect', MagicMock(return_value=MockMemcache())): self.assertRaises(CommandExecutionError, memcached.decrement, 'salt')
'Test if it change package selection for each package specified to \'install\''
def test_unpurge(self):
mock = MagicMock(return_value=[]) with patch.dict(dpkg.__salt__, {'pkg.list_pkgs': mock, 'cmd.run': mock}): self.assertDictEqual(dpkg.unpurge('curl'), {})
'Test if it change package selection for each package specified to \'install\''
def test_unpurge_empty_package(self):
self.assertDictEqual(dpkg.unpurge(), {})
'Test if it lists the packages currently installed'
def test_list_pkgs(self):
mock = MagicMock(return_value={'retcode': 0, 'stderr': '', 'stdout': 'Salt'}) with patch.dict(dpkg.__salt__, {'cmd.run_all': mock}): self.assertDictEqual(dpkg.list_pkgs('httpd'), {}) mock = MagicMock(return_value={'retcode': 1, 'stderr': 'error', 'stdout': 'Salt'}) with patch.dict(dpkg.__salt__, {'cmd.run_all': mock}): self.assertEqual(dpkg.list_pkgs('httpd'), 'Error: error')
'Test if it lists the files that belong to a package.'
def test_file_list(self):
mock = MagicMock(return_value={'retcode': 0, 'stderr': '', 'stdout': 'Salt'}) with patch.dict(dpkg.__salt__, {'cmd.run_all': mock}): self.assertDictEqual(dpkg.file_list('httpd'), {'errors': [], 'files': []}) mock = MagicMock(return_value={'retcode': 1, 'stderr': 'error', 'stdout': 'Salt'}) with patch.dict(dpkg.__salt__, {'cmd.run_all': mock}): self.assertEqual(dpkg.file_list('httpd'), 'Error: error')
'Test if it lists the files that belong to a package, grouped by package'
def test_file_dict(self):
mock = MagicMock(return_value={'retcode': 0, 'stderr': '', 'stdout': 'Salt'}) with patch.dict(dpkg.__salt__, {'cmd.run_all': mock}): self.assertDictEqual(dpkg.file_dict('httpd'), {'errors': [], 'packages': {}}) mock = MagicMock(return_value={'retcode': 1, 'stderr': 'error', 'stdout': 'Salt'}) with patch.dict(dpkg.__salt__, {'cmd.run_all': mock}): self.assertEqual(dpkg.file_dict('httpd'), 'Error: error')
'Check that file.replace append_if_not_found works'
def test_replace_append_if_not_found(self):
args = {'pattern': '#*baz=(?P<value>.*)', 'repl': 'baz=\\g<value>', 'append_if_not_found': True} base = 'foo=1\nbar=2' expected = '{base}\n{repl}\n'.format(base=base, **args) with tempfile.NamedTemporaryFile(mode='w+') as tfile: tfile.write((base + '\n')) tfile.flush() filemod.replace(tfile.name, **args) with salt.utils.files.fopen(tfile.name) as tfile2: self.assertEqual(tfile2.read(), expected) with tempfile.NamedTemporaryFile('w+') as tfile: tfile.write(base) tfile.flush() filemod.replace(tfile.name, **args) with salt.utils.files.fopen(tfile.name) as tfile2: self.assertEqual(tfile2.read(), expected) with tempfile.NamedTemporaryFile('w+') as tfile: filemod.replace(tfile.name, **args) with salt.utils.files.fopen(tfile.name) as tfile2: self.assertEqual(tfile2.read(), (args['repl'] + '\n')) with tempfile.NamedTemporaryFile('w+') as tfile: args['not_found_content'] = 'baz=3' expected = '{base}\n{not_found_content}\n'.format(base=base, **args) tfile.write(base) tfile.flush() filemod.replace(tfile.name, **args) with salt.utils.files.fopen(tfile.name) as tfile2: self.assertEqual(tfile2.read(), expected) with tempfile.NamedTemporaryFile('w+') as tfile: base = 'foo=1\n#baz=42\nbar=2\n' expected = 'foo=1\nbaz=42\nbar=2\n' tfile.write(base) tfile.flush() filemod.replace(tfile.name, **args) with salt.utils.files.fopen(tfile.name) as tfile2: self.assertEqual(tfile2.read(), expected)