desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Test to send a message via SMTP'
def test_send_msg(self):
name = 'This is a salt states module' comt = 'Need to send message to [email protected]: This is a salt states module' ret = {'name': name, 'changes': {}, 'result': None, 'comment': comt} with patch.dict(smtp.__opts__, {'test': True}): self.assertDictEqual(smtp.send_msg(name, '[email protected]', 'Message from Salt', '[email protected]', 'my-smtp-account'), ret) comt = 'Sent message to [email protected]: This is a salt states module' with patch.dict(smtp.__opts__, {'test': False}): mock = MagicMock(return_value=True) with patch.dict(smtp.__salt__, {'smtp.send_msg': mock}): ret['comment'] = comt ret['result'] = True self.assertDictEqual(smtp.send_msg(name, '[email protected]', 'Message from Salt', '[email protected]', 'my-smtp-account'), ret)
'Tests exceptions when checking rule existence'
def test_present_when_failing_to_describe_rule(self):
self.conn.list_rules.side_effect = ClientError(error_content, 'error on list rules') result = self.salt_states['boto_cloudwatch_event.present'](name='test present', Name=rule_name, Description=rule_desc, ScheduleExpression=rule_sched, Targets=[{'Id': 'target1', 'Arn': 'arn::::::*'}], **conn_parameters) self.assertEqual(result.get('result'), False) self.assertTrue(('error on list rules' in result.get('comment', {})))
'Tests present on a rule name that doesn\'t exist and an error is thrown on creation.'
def test_present_when_failing_to_create_a_new_rule(self):
self.conn.list_rules.return_value = {'Rules': []} self.conn.put_rule.side_effect = ClientError(error_content, 'put_rule') result = self.salt_states['boto_cloudwatch_event.present'](name='test present', Name=rule_name, Description=rule_desc, ScheduleExpression=rule_sched, Targets=[{'Id': 'target1', 'Arn': 'arn::::::*'}], **conn_parameters) self.assertEqual(result.get('result'), False) self.assertTrue(('put_rule' in result.get('comment', '')))
'Tests present on a rule name that doesn\'t exist and an error is thrown when adding targets.'
def test_present_when_failing_to_describe_the_new_rule(self):
self.conn.list_rules.return_value = {'Rules': []} self.conn.put_rule.return_value = rule_ret self.conn.describe_rule.side_effect = ClientError(error_content, 'describe_rule') result = self.salt_states['boto_cloudwatch_event.present'](name='test present', Name=rule_name, Description=rule_desc, ScheduleExpression=rule_sched, Targets=[{'Id': 'target1', 'Arn': 'arn::::::*'}], **conn_parameters) self.assertEqual(result.get('result'), False) self.assertTrue(('describe_rule' in result.get('comment', '')))
'Tests present on a rule name that doesn\'t exist and an error is thrown when adding targets.'
def test_present_when_failing_to_create_a_new_rules_targets(self):
self.conn.list_rules.return_value = {'Rules': []} self.conn.put_rule.return_value = rule_ret self.conn.describe_rule.return_value = rule_ret self.conn.put_targets.side_effect = ClientError(error_content, 'put_targets') result = self.salt_states['boto_cloudwatch_event.present'](name='test present', Name=rule_name, Description=rule_desc, ScheduleExpression=rule_sched, Targets=[{'Id': 'target1', 'Arn': 'arn::::::*'}], **conn_parameters) self.assertEqual(result.get('result'), False) self.assertTrue(('put_targets' in result.get('comment', '')))
'Tests the successful case of creating a new rule, and updating its targets'
def test_present_when_rule_does_not_exist(self):
self.conn.list_rules.return_value = {'Rules': []} self.conn.put_rule.return_value = rule_ret self.conn.describe_rule.return_value = rule_ret self.conn.put_targets.return_value = {'FailedEntryCount': 0} result = self.salt_states['boto_cloudwatch_event.present'](name='test present', Name=rule_name, Description=rule_desc, ScheduleExpression=rule_sched, Targets=[{'Id': 'target1', 'Arn': 'arn::::::*'}], **conn_parameters) self.assertEqual(result.get('result'), True)
'Tests present on an existing rule where an error is thrown on updating the pool properties.'
def test_present_when_failing_to_update_an_existing_rule(self):
self.conn.list_rules.return_value = {'Rules': [rule_ret]} self.conn.describe_rule.side_effect = ClientError(error_content, 'describe_rule') result = self.salt_states['boto_cloudwatch_event.present'](name='test present', Name=rule_name, Description=rule_desc, ScheduleExpression=rule_sched, Targets=[{'Id': 'target1', 'Arn': 'arn::::::*'}], **conn_parameters) self.assertEqual(result.get('result'), False) self.assertTrue(('describe_rule' in result.get('comment', '')))
'Tests present on an existing rule where put_rule succeeded, but an error is thrown on getting targets'
def test_present_when_failing_to_get_targets(self):
self.conn.list_rules.return_value = {'Rules': [rule_ret]} self.conn.put_rule.return_value = rule_ret self.conn.describe_rule.return_value = rule_ret self.conn.list_targets_by_rule.side_effect = ClientError(error_content, 'list_targets') result = self.salt_states['boto_cloudwatch_event.present'](name='test present', Name=rule_name, Description=rule_desc, ScheduleExpression=rule_sched, Targets=[{'Id': 'target1', 'Arn': 'arn::::::*'}], **conn_parameters) self.assertEqual(result.get('result'), False) self.assertTrue(('list_targets' in result.get('comment', '')))
'Tests present on an existing rule where put_rule succeeded, but an error is thrown on putting targets'
def test_present_when_failing_to_put_targets(self):
self.conn.list_rules.return_value = {'Rules': []} self.conn.put_rule.return_value = rule_ret self.conn.describe_rule.return_value = rule_ret self.conn.list_targets.return_value = {'Targets': []} self.conn.put_targets.side_effect = ClientError(error_content, 'put_targets') result = self.salt_states['boto_cloudwatch_event.present'](name='test present', Name=rule_name, Description=rule_desc, ScheduleExpression=rule_sched, Targets=[{'Id': 'target1', 'Arn': 'arn::::::*'}], **conn_parameters) self.assertEqual(result.get('result'), False) self.assertTrue(('put_targets' in result.get('comment', '')))
'Tests present on an existing rule where put_rule succeeded, and targets must be added'
def test_present_when_putting_targets(self):
self.conn.list_rules.return_value = {'Rules': []} self.conn.put_rule.return_value = rule_ret self.conn.describe_rule.return_value = rule_ret self.conn.list_targets.return_value = {'Targets': []} self.conn.put_targets.return_value = {'FailedEntryCount': 0} result = self.salt_states['boto_cloudwatch_event.present'](name='test present', Name=rule_name, Description=rule_desc, ScheduleExpression=rule_sched, Targets=[{'Id': 'target1', 'Arn': 'arn::::::*'}], **conn_parameters) self.assertEqual(result.get('result'), True)
'Tests present on an existing rule where put_rule succeeded, and targets must be removed'
def test_present_when_removing_targets(self):
self.conn.list_rules.return_value = {'Rules': []} self.conn.put_rule.return_value = rule_ret self.conn.describe_rule.return_value = rule_ret self.conn.list_targets.return_value = {'Targets': [{'Id': 'target1'}, {'Id': 'target2'}]} self.conn.put_targets.return_value = {'FailedEntryCount': 0} result = self.salt_states['boto_cloudwatch_event.present'](name='test present', Name=rule_name, Description=rule_desc, ScheduleExpression=rule_sched, Targets=[{'Id': 'target1', 'Arn': 'arn::::::*'}], **conn_parameters) self.assertEqual(result.get('result'), True)
'Tests exceptions when checking rule existence'
def test_absent_when_failing_to_describe_rule(self):
self.conn.list_rules.side_effect = ClientError(error_content, 'error on list rules') result = self.salt_states['boto_cloudwatch_event.absent'](name='test present', Name=rule_name, **conn_parameters) self.assertEqual(result.get('result'), False) self.assertTrue(('error on list rules' in result.get('comment', {})))
'Tests absent on an non-existing rule'
def test_absent_when_rule_does_not_exist(self):
self.conn.list_rules.return_value = {'Rules': []} result = self.salt_states['boto_cloudwatch_event.absent'](name='test absent', Name=rule_name, **conn_parameters) self.assertEqual(result.get('result'), True) self.assertEqual(result['changes'], {})
'Tests absent on an rule when the list_targets call fails'
def test_absent_when_failing_to_list_targets(self):
self.conn.list_rules.return_value = {'Rules': [rule_ret]} self.conn.list_targets_by_rule.side_effect = ClientError(error_content, 'list_targets') result = self.salt_states['boto_cloudwatch_event.absent'](name='test absent', Name=rule_name, **conn_parameters) self.assertEqual(result.get('result'), False) self.assertTrue(('list_targets' in result.get('comment', '')))
'Tests absent on an rule when the remove_targets call fails'
def test_absent_when_failing_to_remove_targets_exception(self):
self.conn.list_rules.return_value = {'Rules': [rule_ret]} self.conn.list_targets_by_rule.return_value = {'Targets': [{'Id': 'target1'}]} self.conn.remove_targets.side_effect = ClientError(error_content, 'remove_targets') result = self.salt_states['boto_cloudwatch_event.absent'](name='test absent', Name=rule_name, **conn_parameters) self.assertEqual(result.get('result'), False) self.assertTrue(('remove_targets' in result.get('comment', '')))
'Tests absent on an rule when the remove_targets call fails'
def test_absent_when_failing_to_remove_targets_nonexception(self):
self.conn.list_rules.return_value = {'Rules': [rule_ret]} self.conn.list_targets_by_rule.return_value = {'Targets': [{'Id': 'target1'}]} self.conn.remove_targets.return_value = {'FailedEntryCount': 1} result = self.salt_states['boto_cloudwatch_event.absent'](name='test absent', Name=rule_name, **conn_parameters) self.assertEqual(result.get('result'), False)
'Tests absent on an rule when the delete_rule call fails'
def test_absent_when_failing_to_delete_rule(self):
self.conn.list_rules.return_value = {'Rules': [rule_ret]} self.conn.list_targets_by_rule.return_value = {'Targets': [{'Id': 'target1'}]} self.conn.remove_targets.return_value = {'FailedEntryCount': 0} self.conn.delete_rule.side_effect = ClientError(error_content, 'delete_rule') result = self.salt_states['boto_cloudwatch_event.absent'](name='test absent', Name=rule_name, **conn_parameters) self.assertEqual(result.get('result'), False) self.assertTrue(('delete_rule' in result.get('comment', '')))
'Tests absent on an rule'
def test_absent(self):
self.conn.list_rules.return_value = {'Rules': [rule_ret]} self.conn.list_targets_by_rule.return_value = {'Targets': [{'Id': 'target1'}]} self.conn.remove_targets.return_value = {'FailedEntryCount': 0} result = self.salt_states['boto_cloudwatch_event.absent'](name='test absent', Name=rule_name, **conn_parameters) self.assertEqual(result.get('result'), True)
'Test to add a job to queue.'
def test_present(self):
name = 'jboss' timespec = '9:09 11/04/15' tag = 'love' user = 'jam' mock_atat = {'jobs': [{'date': '2015-11-04', 'job': '1476031633.a', 'queue': 'a', 'tag': tag, 'time': '09:09:00', 'user': user}]} ret = {'name': name, 'result': True, 'changes': {'date': '2015-11-04', 'job': '1476031633.a', 'queue': 'a', 'tag': 'love', 'time': '09:09:00', 'user': 'jam'}, 'comment': 'job {name} added and will run on {timespec}'.format(name=name, timespec=timespec)} ret_user = {} ret_user.update(ret) ret_user.update({'result': False, 'changes': {}, 'comment': 'user {0} does not exists'.format(user)}) mock = MagicMock(return_value=mock_atat) with patch.dict(at.__opts__, {'test': False}): with patch.dict(at.__salt__, {'at.at': mock}): self.assertDictEqual(at.present(name, timespec, tag), ret) mock = MagicMock(return_value=False) with patch.dict(at.__opts__, {'test': False}): with patch.dict(at.__salt__, {'user.info': mock}): self.assertDictEqual(at.present(name, timespec, tag, user), ret_user) with patch.dict(at.__opts__, {'test': True}): ret_test = {} ret_test.update(ret) ret_test.update({'result': None, 'changes': {}}) self.assertDictEqual(at.present(name, timespec, tag, user), ret_test)
'Test to remove a job from queue'
def test_absent(self):
name = 'jboss' tag = 'rose' user = 'jam' mock_atatrm = {'jobs': {'removed': ['1476033859.a', '1476033855.a'], 'tag': None}} mock_atjobcheck = {'jobs': [{'date': '2015-11-04', 'job': '1476031633.a', 'queue': 'a', 'tag': tag, 'time': '09:09:00', 'user': user}]} ret = {'name': name, 'result': True, 'changes': {'removed': ['1476033859.a', '1476033855.a']}, 'comment': 'removed 2 job(s)'} with patch.dict(at.__opts__, {'test': True}): ret_test = {} ret_test.update(ret) ret_test.update({'result': None, 'changes': {}, 'comment': 'removed ? job(s)'}) self.assertDictEqual(at.absent(name), ret_test) with patch.dict(at.__opts__, {'test': False}): ret_limit = {} ret_limit.update(ret) ret_limit.update({'result': False, 'changes': {}, 'comment': 'limit parameter not supported {0}'.format(name)}) self.assertDictEqual(at.absent(name, limit='all'), ret_limit) mock = MagicMock(return_value=mock_atatrm) with patch.dict(at.__salt__, {'at.atrm': mock}): with patch.dict(at.__opts__, {'test': False}): self.assertDictEqual(at.absent(name), ret) mock_atatrm_nojobs = {} mock_atatrm_nojobs.update(mock_atatrm) mock_atatrm_nojobs.update({'jobs': {'removed': []}}) mock = MagicMock(return_value=mock_atatrm_nojobs) with patch.dict(at.__salt__, {'at.atrm': mock}): with patch.dict(at.__opts__, {'test': False}): ret_nojobs = {} ret_nojobs.update(ret) ret_nojobs.update({'changes': {}, 'comment': ret['comment'].replace('2', '0')}) self.assertDictEqual(at.absent(name), ret_nojobs) mock_atatrm_tag = {} mock_atatrm_tag.update(mock_atatrm) mock_atatrm_tag.update({'jobs': {'removed': ['1476031633.a'], 'tag': 'rose'}}) mock = MagicMock(return_value=mock_atatrm_tag) with patch.dict(at.__salt__, {'at.atrm': mock}): mock = MagicMock(return_value=mock_atjobcheck) with patch.dict(at.__salt__, {'at.jobcheck': mock}): with patch.dict(at.__opts__, {'test': False}): ret_tag = {} ret_tag.update(ret) ret_tag.update({'changes': {'removed': ['1476031633.a']}, 'comment': ret['comment'].replace('2', '1')}) self.assertDictEqual(at.absent(name, tag=tag), ret_tag)
'Test to ensure a search is present.'
def test_present(self):
name = 'API Error Search' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} mock = MagicMock(side_effect=[True, False, False, True]) with patch.dict(splunk_search.__salt__, {'splunk_search.get': mock, 'splunk_search.create': mock}): with patch.dict(splunk_search.__opts__, {'test': True}): comt = 'Would update {0}'.format(name) ret.update({'comment': comt}) self.assertDictEqual(splunk_search.present(name), ret) comt = 'Would create {0}'.format(name) ret.update({'comment': comt}) self.assertDictEqual(splunk_search.present(name), ret) with patch.dict(splunk_search.__opts__, {'test': False}): ret.update({'comment': '', 'result': True, 'changes': {'new': {}, 'old': False}}) self.assertDictEqual(splunk_search.present(name), ret)
'Test to ensure a search is absent.'
def test_absent(self):
name = 'API Error Search' ret = {'name': name, 'result': None, 'comment': ''} mock = MagicMock(side_effect=[True, False]) with patch.dict(splunk_search.__salt__, {'splunk_search.get': mock}): with patch.dict(splunk_search.__opts__, {'test': True}): comt = 'Would delete {0}'.format(name) ret.update({'comment': comt}) self.assertDictEqual(splunk_search.absent(name), ret) comt = '{0} is absent.'.format(name) ret.update({'comment': comt, 'result': True, 'changes': {}}) self.assertDictEqual(splunk_search.absent(name), ret)
'Test to verify that the given package is installed and is at the correct version.'
def test_installed(self):
name = 'coffee-script' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} mock_err = MagicMock(side_effect=CommandExecutionError) mock_dict = MagicMock(return_value={name: {'version': '1.2'}}) with patch.dict(npm.__salt__, {'npm.list': mock_err}): comt = "Error looking up 'coffee-script': " ret.update({'comment': comt}) self.assertDictEqual(npm.installed(name), ret) with patch.dict(npm.__salt__, {'npm.list': mock_dict, 'npm.install': mock_err}): with patch.dict(npm.__opts__, {'test': True}): comt = "Package(s) 'coffee-script' satisfied by [email protected]" ret.update({'comment': comt, 'result': True}) self.assertDictEqual(npm.installed(name), ret) with patch.dict(npm.__opts__, {'test': False}): comt = "Package(s) 'coffee-script' satisfied by [email protected]" ret.update({'comment': comt, 'result': True}) self.assertDictEqual(npm.installed(name), ret) comt = "Error installing 'n, p, m': " ret.update({'comment': comt, 'result': False}) self.assertDictEqual(npm.installed(name, 'npm'), ret) with patch.dict(npm.__salt__, {'npm.install': mock_dict}): comt = "Package(s) 'n, p, m' successfully installed" ret.update({'comment': comt, 'result': True, 'changes': {'new': ['n', 'p', 'm'], 'old': []}}) self.assertDictEqual(npm.installed(name, 'npm'), ret)
'Test to verify that the given package is not installed.'
def test_removed(self):
name = 'coffee-script' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} mock_err = MagicMock(side_effect=[CommandExecutionError, {}, {name: ''}, {name: ''}]) mock_t = MagicMock(return_value=True) with patch.dict(npm.__salt__, {'npm.list': mock_err, 'npm.uninstall': mock_t}): comt = "Error uninstalling 'coffee-script': " ret.update({'comment': comt}) self.assertDictEqual(npm.removed(name), ret) comt = "Package 'coffee-script' is not installed" ret.update({'comment': comt, 'result': True}) self.assertDictEqual(npm.removed(name), ret) with patch.dict(npm.__opts__, {'test': True}): comt = "Package 'coffee-script' is set to be removed" ret.update({'comment': comt, 'result': None}) self.assertDictEqual(npm.removed(name), ret) with patch.dict(npm.__opts__, {'test': False}): comt = "Package 'coffee-script' was successfully removed" ret.update({'comment': comt, 'result': True, 'changes': {name: 'Removed'}}) self.assertDictEqual(npm.removed(name), ret)
'Test to bootstraps a node.js application.'
def test_bootstrap(self):
name = 'coffee-script' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} mock_err = MagicMock(side_effect=[CommandExecutionError, False, True]) with patch.dict(npm.__salt__, {'npm.install': mock_err}): comt = "Error Bootstrapping 'coffee-script': " ret.update({'comment': comt}) self.assertDictEqual(npm.bootstrap(name), ret) comt = 'Directory is already bootstrapped' ret.update({'comment': comt, 'result': True}) self.assertDictEqual(npm.bootstrap(name), ret) comt = 'Directory was successfully bootstrapped' ret.update({'comment': comt, 'result': True, 'changes': {name: 'Bootstrapped'}}) self.assertDictEqual(npm.bootstrap(name), ret)
'Test to verify that the npm cache is cleaned.'
def test_cache_cleaned(self):
name = 'coffee-script' pkg_ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} ret = {'name': None, 'result': False, 'comment': '', 'changes': {}} mock_list = MagicMock(return_value=['~/.npm', '~/.npm/{0}/'.format(name)]) mock_cache_clean_success = MagicMock(return_value=True) mock_cache_clean_failure = MagicMock(return_value=False) mock_err = MagicMock(side_effect=CommandExecutionError) with patch.dict(npm.__salt__, {'npm.cache_list': mock_err}): comt = 'Error looking up cached packages: ' ret.update({'comment': comt}) self.assertDictEqual(npm.cache_cleaned(), ret) with patch.dict(npm.__salt__, {'npm.cache_list': mock_err}): comt = 'Error looking up cached {0}: '.format(name) pkg_ret.update({'comment': comt}) self.assertDictEqual(npm.cache_cleaned(name), pkg_ret) mock_data = {'npm.cache_list': mock_list, 'npm.cache_clean': MagicMock()} with patch.dict(npm.__salt__, mock_data): non_cached_pkg = 'salt' comt = 'Package {0} is not in the cache'.format(non_cached_pkg) pkg_ret.update({'name': non_cached_pkg, 'result': True, 'comment': comt}) self.assertDictEqual(npm.cache_cleaned(non_cached_pkg), pkg_ret) pkg_ret.update({'name': name}) with patch.dict(npm.__opts__, {'test': True}): comt = 'Cached packages set to be removed' ret.update({'result': None, 'comment': comt}) self.assertDictEqual(npm.cache_cleaned(), ret) with patch.dict(npm.__opts__, {'test': True}): comt = 'Cached {0} set to be removed'.format(name) pkg_ret.update({'result': None, 'comment': comt}) self.assertDictEqual(npm.cache_cleaned(name), pkg_ret) with patch.dict(npm.__opts__, {'test': False}): comt = 'Cached packages successfully removed' ret.update({'result': True, 'comment': comt, 'changes': {'cache': 'Removed'}}) self.assertDictEqual(npm.cache_cleaned(), ret) with patch.dict(npm.__opts__, {'test': False}): comt = 'Cached {0} successfully removed'.format(name) pkg_ret.update({'result': True, 'comment': comt, 'changes': {name: 'Removed'}}) self.assertDictEqual(npm.cache_cleaned(name), pkg_ret) mock_data = {'npm.cache_list': mock_list, 'npm.cache_clean': MagicMock(return_value=False)} with patch.dict(npm.__salt__, mock_data): with patch.dict(npm.__opts__, {'test': False}): comt = 'Error cleaning cached packages' ret.update({'result': False, 'comment': comt}) ret['changes'] = {} self.assertDictEqual(npm.cache_cleaned(), ret) with patch.dict(npm.__opts__, {'test': False}): comt = 'Error cleaning cached {0}'.format(name) pkg_ret.update({'result': False, 'comment': comt}) pkg_ret['changes'] = {} self.assertDictEqual(npm.cache_cleaned(name), pkg_ret)
'Mock interface method'
@staticmethod def interfaces():
return {'salt': {'up': 1}}
'Mock grains method'
@staticmethod def grains(lis, bol):
return {'A': 'B'}
'Test to ensure that the named interface is configured properly'
def test_managed(self):
with patch('salt.states.network.salt.utils.network', MockNetwork()): with patch('salt.states.network.salt.loader', MockGrains()): ret = {'name': 'salt', 'changes': {}, 'result': False, 'comment': ''} change = {'interface': '--- \n+++ \n@@ -1 +1 @@\n-A\n+B', 'status': 'Interface salt restart to validate'} mock = MagicMock(side_effect=[AttributeError, 'A', 'A', 'A', 'A', 'A']) with patch.dict(network.__salt__, {'ip.get_interface': mock}): self.assertDictEqual(network.managed('salt', 'stack', test='a'), ret) mock = MagicMock(return_value='B') with patch.dict(network.__salt__, {'ip.build_interface': mock}): mock = MagicMock(side_effect=AttributeError) with patch.dict(network.__salt__, {'ip.get_bond': mock}): self.assertDictEqual(network.managed('salt', 'bond', test='a'), ret) ret.update({'comment': 'Interface salt is set to be updated:\n--- \n+++ \n@@ -1 +1 @@\n-A\n+B', 'result': None}) self.assertDictEqual(network.managed('salt', 'stack', test='a'), ret) mock = MagicMock(return_value=True) with patch.dict(network.__salt__, {'ip.down': mock}): with patch.dict(network.__salt__, {'ip.up': mock}): ret.update({'comment': 'Interface salt updated.', 'result': True, 'changes': change}) self.assertDictEqual(network.managed('salt', 'stack'), ret) with patch.dict(network.__grains__, {'A': True}): with patch.dict(network.__salt__, {'saltutil.refresh_modules': mock}): ret.update({'result': True, 'changes': {'interface': '--- \n+++ \n@@ -1 +1 @@\n-A\n+B', 'status': 'Interface salt down'}}) self.assertDictEqual(network.managed('salt', 'stack', False), ret) ret.update({'changes': {'interface': '--- \n+++ \n@@ -1 +1 @@\n-A\n+B'}, 'result': False, 'comment': "'ip.down'"}) self.assertDictEqual(network.managed('salt', 'stack'), ret)
'Test to manage network interface static routes.'
def test_routes(self):
ret = {'name': 'salt', 'changes': {}, 'result': False, 'comment': ''} mock = MagicMock(side_effect=[AttributeError, False, False, 'True', False, False]) with patch.dict(network.__salt__, {'ip.get_routes': mock}): self.assertDictEqual(network.routes('salt'), ret) mock = MagicMock(side_effect=[False, True, '', True, True]) with patch.dict(network.__salt__, {'ip.build_routes': mock}): ret.update({'result': True, 'comment': 'Interface salt routes are up to date.'}) self.assertDictEqual(network.routes('salt', test='a'), ret) ret.update({'comment': 'Interface salt routes are set to be added.', 'result': None}) self.assertDictEqual(network.routes('salt', test='a'), ret) ret.update({'comment': 'Interface salt routes are set to be updated:\n--- \n+++ \n@@ -1,4 +0,0 @@\n-T\n-r\n-u\n-e'}) self.assertDictEqual(network.routes('salt', test='a'), ret) mock = MagicMock(side_effect=[AttributeError, True]) with patch.dict(network.__salt__, {'ip.apply_network_settings': mock}): ret.update({'changes': {'network_routes': 'Added interface salt routes.'}, 'comment': '', 'result': False}) self.assertDictEqual(network.routes('salt'), ret) ret.update({'changes': {'network_routes': 'Added interface salt routes.'}, 'comment': 'Interface salt routes added.', 'result': True}) self.assertDictEqual(network.routes('salt'), ret)
'Test to ensure that global network settings are configured properly'
def test_system(self):
ret = {'name': 'salt', 'changes': {}, 'result': False, 'comment': ''} with patch.dict(network.__opts__, {'test': True}): mock = MagicMock(side_effect=[AttributeError, False, False, 'As']) with patch.dict(network.__salt__, {'ip.get_network_settings': mock}): self.assertDictEqual(network.system('salt'), ret) mock = MagicMock(side_effect=[False, True, '']) with patch.dict(network.__salt__, {'ip.build_network_settings': mock}): ret.update({'comment': 'Global network settings are up to date.', 'result': True}) self.assertDictEqual(network.system('salt'), ret) ret.update({'comment': 'Global network settings are set to be added.', 'result': None}) self.assertDictEqual(network.system('salt'), ret) ret.update({'comment': 'Global network settings are set to be updated:\n--- \n+++ \n@@ -1,2 +0,0 @@\n-A\n-s'}) self.assertDictEqual(network.system('salt'), ret) with patch.dict(network.__opts__, {'test': False}): mock = MagicMock(side_effect=[False, False]) with patch.dict(network.__salt__, {'ip.get_network_settings': mock}): mock = MagicMock(side_effect=[True, True]) with patch.dict(network.__salt__, {'ip.build_network_settings': mock}): mock = MagicMock(side_effect=[AttributeError, True]) with patch.dict(network.__salt__, {'ip.apply_network_settings': mock}): ret.update({'changes': {'network_settings': 'Added global network settings.'}, 'comment': '', 'result': False}) self.assertDictEqual(network.system('salt'), ret) ret.update({'changes': {'network_settings': 'Added global network settings.'}, 'comment': 'Global network settings are up to date.', 'result': True}) self.assertDictEqual(network.system('salt'), ret)
'Test if it returns True when user already exists in htpasswd file'
def test_user_exists_already(self):
mock = MagicMock(return_value={'retcode': 0}) with patch.dict(htpasswd.__salt__, {'file.grep': mock}): ret = htpasswd.user_exists('larry', 'badpass', '/etc/httpd/htpasswd') expected = {'name': 'larry', 'result': True, 'comment': 'User already known', 'changes': {}} self.assertEqual(ret, expected)
'Test if it returns True when new user is added to htpasswd file'
def test_new_user_success(self):
mock_grep = MagicMock(return_value={'retcode': 1}) mock_useradd = MagicMock(return_value={'retcode': 0, 'stderr': 'Success'}) with patch.dict(htpasswd.__salt__, {'file.grep': mock_grep, 'webutil.useradd': mock_useradd}): ret = htpasswd.user_exists('larry', 'badpass', '/etc/httpd/htpasswd') expected = {'name': 'larry', 'result': True, 'comment': 'Success', 'changes': {'larry': True}} self.assertEqual(ret, expected)
'Test if it returns False when adding user to htpasswd failed'
def test_new_user_error(self):
mock_grep = MagicMock(return_value={'retcode': 1}) mock_useradd = MagicMock(return_value={'retcode': 1, 'stderr': 'Error'}) with patch.dict(htpasswd.__salt__, {'file.grep': mock_grep, 'webutil.useradd': mock_useradd}): ret = htpasswd.user_exists('larry', 'badpass', '/etc/httpd/htpasswd') expected = {'name': 'larry', 'result': False, 'comment': 'Error', 'changes': {}} self.assertEqual(ret, expected)
'Test to ensure the RabbitMQ policy exists.'
def test_present(self):
name = 'HA' pattern = '.*' definition = '{"ha-mode":"all"}' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} mock = MagicMock(side_effect=[{'/': {name: {'pattern': pattern, 'definition': definition, 'priority': 0}}}, {}]) with patch.dict(rabbitmq_policy.__salt__, {'rabbitmq.list_policies': mock}): comt = 'Policy / HA is already present' ret.update({'comment': comt}) self.assertDictEqual(rabbitmq_policy.present(name, pattern, definition), ret) with patch.dict(rabbitmq_policy.__opts__, {'test': True}): comment = 'Policy / HA is set to be created' changes = {'new': 'HA', 'old': {}} ret.update({'comment': comment, 'result': None, 'changes': changes}) self.assertDictEqual(rabbitmq_policy.present(name, pattern, definition), ret)
'Test to ensure the named policy is absent.'
def test_absent(self):
name = 'HA' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} mock = MagicMock(side_effect=[False, True]) with patch.dict(rabbitmq_policy.__salt__, {'rabbitmq.policy_exists': mock}): comment = "Policy '/ HA' is not present." ret.update({'comment': comment}) self.assertDictEqual(rabbitmq_policy.absent(name), ret) with patch.dict(rabbitmq_policy.__opts__, {'test': True}): comment = "Policy '/ HA' will be removed." changes = {'new': '', 'old': 'HA'} ret.update({'comment': comment, 'result': None, 'changes': changes}) self.assertDictEqual(rabbitmq_policy.absent(name), ret)
'Test to manage a memcached key.'
def test_managed(self):
name = 'foo' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} mock_t = MagicMock(side_effect=[CommandExecutionError, 'salt', True, True, True]) with patch.dict(memcached.__salt__, {'memcached.get': mock_t, 'memcached.set': mock_t}): self.assertDictEqual(memcached.managed(name), ret) comt = "Key 'foo' does not need to be updated" ret.update({'comment': comt, 'result': True}) self.assertDictEqual(memcached.managed(name, 'salt'), ret) with patch.dict(memcached.__opts__, {'test': True}): comt = "Value of key 'foo' would be changed" ret.update({'comment': comt, 'result': None}) self.assertDictEqual(memcached.managed(name, 'salt'), ret) with patch.dict(memcached.__opts__, {'test': False}): comt = "Successfully set key 'foo'" ret.update({'comment': comt, 'result': True, 'changes': {'new': 'salt', 'old': True}}) self.assertDictEqual(memcached.managed(name, 'salt'), ret)
'Test to ensure that a memcached key is not present.'
def test_absent(self):
name = 'foo' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} mock_t = MagicMock(side_effect=[CommandExecutionError, 'salt', None, True, True, True]) with patch.dict(memcached.__salt__, {'memcached.get': mock_t, 'memcached.delete': mock_t}): self.assertDictEqual(memcached.absent(name), ret) comt = "Value of key 'foo' ('salt') is not 'bar'" ret.update({'comment': comt, 'result': True}) self.assertDictEqual(memcached.absent(name, 'bar'), ret) comt = "Key 'foo' does not exist" ret.update({'comment': comt}) self.assertDictEqual(memcached.absent(name), ret) with patch.dict(memcached.__opts__, {'test': True}): comt = "Key 'foo' would be deleted" ret.update({'comment': comt, 'result': None}) self.assertDictEqual(memcached.absent(name), ret) with patch.dict(memcached.__opts__, {'test': False}): comt = "Successfully deleted key 'foo'" ret.update({'comment': comt, 'result': True, 'changes': {'key deleted': 'foo', 'value': True}}) self.assertDictEqual(memcached.absent(name), ret)
'Test to create a symlink.'
def test_symlink(self):
name = '/tmp/testfile.txt' target = salt.utils.files.mkstemp() test_dir = '/tmp' user = 'salt' if salt.utils.platform.is_windows(): group = 'salt' else: group = 'saltstack' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} mock_t = MagicMock(return_value=True) mock_f = MagicMock(return_value=False) mock_empty = MagicMock(return_value='') mock_uid = MagicMock(return_value='U1001') mock_gid = MagicMock(return_value='g1001') mock_target = MagicMock(return_value=target) mock_user = MagicMock(return_value=user) mock_grp = MagicMock(return_value=group) mock_os_error = MagicMock(side_effect=OSError) with patch.dict(filestate.__salt__, {'config.manage_mode': mock_t}): comt = 'Must provide name to file.symlink' ret.update({'comment': comt, 'name': ''}) self.assertDictEqual(filestate.symlink('', target), ret) with patch.dict(filestate.__salt__, {'config.manage_mode': mock_t, 'file.user_to_uid': mock_empty, 'file.group_to_gid': mock_empty, 'user.info': mock_empty, 'user.current': mock_user}): comt = 'User {0} does not exist. Group {1} does not exist.'.format(user, group) ret.update({'comment': comt, 'name': name}) self.assertDictEqual(filestate.symlink(name, target, user=user, group=group), ret) with patch.dict(filestate.__salt__, {'config.manage_mode': mock_t, 'file.user_to_uid': mock_uid, 'file.group_to_gid': mock_gid, 'file.is_link': mock_f, 'user.info': mock_empty, 'user.current': mock_user}): with patch.dict(filestate.__opts__, {'test': True}): with patch.object(os.path, 'exists', mock_f): comt = 'Symlink {0} to {1} is set for creation'.format(name, target) ret.update({'comment': comt, 'result': None, 'pchanges': {'new': name}}) self.assertDictEqual(filestate.symlink(name, target, user=user, group=group), ret) with patch.dict(filestate.__salt__, {'config.manage_mode': mock_t, 'file.user_to_uid': mock_uid, 'file.group_to_gid': mock_gid, 'file.is_link': mock_f, 'user.info': mock_empty, 'user.current': mock_user}): with patch.dict(filestate.__opts__, {'test': False}): with patch.object(os.path, 'isdir', mock_f): with patch.object(os.path, 'exists', mock_f): comt = 'Directory {0} for symlink is not present'.format(test_dir) ret.update({'comment': comt, 'result': False, 'pchanges': {'new': name}}) self.assertDictEqual(filestate.symlink(name, target, user=user, group=group), ret) with patch.dict(filestate.__salt__, {'config.manage_mode': mock_t, 'file.user_to_uid': mock_uid, 'file.group_to_gid': mock_gid, 'file.is_link': mock_t, 'file.readlink': mock_target, 'user.info': mock_empty, 'user.current': mock_user}): with patch.dict(filestate.__opts__, {'test': False}): with patch.object(os.path, 'isdir', mock_t): with patch.object(salt.states.file, '_check_symlink_ownership', mock_t): comt = 'Symlink {0} is present and owned by {1}:{2}'.format(name, user, group) ret.update({'comment': comt, 'result': True, 'pchanges': {}}) self.assertDictEqual(filestate.symlink(name, target, user=user, group=group), ret) with patch.dict(filestate.__salt__, {'config.manage_mode': mock_t, 'file.user_to_uid': mock_uid, 'file.group_to_gid': mock_gid, 'file.is_link': mock_f, 'file.readlink': mock_target, 'user.info': mock_empty, 'user.current': mock_user}): with patch.dict(filestate.__opts__, {'test': False}): with patch.object(os.path, 'isdir', mock_t): with patch.object(os.path, 'exists', mock_f): with patch.object(os.path, 'lexists', mock_t): comt = 'File exists where the backup target SALT should go' ret.update({'comment': comt, 'result': False, 'pchanges': {'new': name}}) self.assertDictEqual(filestate.symlink(name, target, user=user, group=group, backupname='SALT'), ret) with patch.dict(filestate.__salt__, {'config.manage_mode': mock_t, 'file.user_to_uid': mock_uid, 'file.group_to_gid': mock_gid, 'file.is_link': mock_f, 'file.readlink': mock_target, 'user.info': mock_empty, 'user.current': mock_user}): with patch.dict(filestate.__opts__, {'test': False}): with patch.object(os.path, 'isdir', mock_t): with patch.object(os.path, 'exists', mock_f): with patch.object(os.path, 'isfile', mock_t): comt = 'File exists where the symlink {0} should be'.format(name) ret.update({'comment': comt, 'pchanges': {'new': name}, 'result': False}) self.assertDictEqual(filestate.symlink(name, target, user=user, group=group), ret) with patch.dict(filestate.__salt__, {'config.manage_mode': mock_t, 'file.user_to_uid': mock_uid, 'file.group_to_gid': mock_gid, 'file.is_link': mock_f, 'file.readlink': mock_target, 'file.symlink': mock_t, 'user.info': mock_t, 'file.lchown': mock_f}): with patch.dict(filestate.__opts__, {'test': False}): with patch.object(os.path, 'isdir', MagicMock(side_effect=[True, False])): with patch.object(os.path, 'isfile', mock_t): with patch.object(os.path, 'exists', mock_f): comt = 'File exists where the symlink {0} should be'.format(name) ret.update({'comment': comt, 'result': False}) self.assertDictEqual(filestate.symlink(name, target, user=user, group=group), ret) with patch.dict(filestate.__salt__, {'config.manage_mode': mock_t, 'file.user_to_uid': mock_uid, 'file.group_to_gid': mock_gid, 'file.is_link': mock_f, 'file.readlink': mock_target, 'file.symlink': mock_t, 'user.info': mock_t, 'file.lchown': mock_f}): with patch.dict(filestate.__opts__, {'test': False}): with patch.object(os.path, 'isdir', MagicMock(side_effect=[True, False])): with patch.object(os.path, 'isdir', mock_t): with patch.object(os.path, 'exists', mock_f): comt = 'Directory exists where the symlink {0} should be'.format(name) ret.update({'comment': comt, 'result': False}) self.assertDictEqual(filestate.symlink(name, target, user=user, group=group), ret) with patch.dict(filestate.__salt__, {'config.manage_mode': mock_t, 'file.user_to_uid': mock_uid, 'file.group_to_gid': mock_gid, 'file.is_link': mock_f, 'file.readlink': mock_target, 'file.symlink': mock_os_error, 'user.info': mock_t, 'file.lchown': mock_f}): with patch.dict(filestate.__opts__, {'test': False}): with patch.object(os.path, 'isdir', MagicMock(side_effect=[True, False])): with patch.object(os.path, 'isfile', mock_f): comt = 'Unable to create new symlink {0} -> {1}: '.format(name, target) ret.update({'comment': comt, 'result': False}) self.assertDictEqual(filestate.symlink(name, target, user=user, group=group), ret) with patch.dict(filestate.__salt__, {'config.manage_mode': mock_t, 'file.user_to_uid': mock_uid, 'file.group_to_gid': mock_gid, 'file.is_link': mock_f, 'file.readlink': mock_target, 'file.symlink': mock_t, 'user.info': mock_t, 'file.lchown': mock_f, 'file.get_user': mock_user, 'file.get_group': mock_grp}): with patch.dict(filestate.__opts__, {'test': False}): with patch.object(os.path, 'isdir', MagicMock(side_effect=[True, False])): with patch.object(os.path, 'isfile', mock_f): comt = 'Created new symlink {0} -> {1}'.format(name, target) ret.update({'comment': comt, 'result': True, 'changes': {'new': name}}) self.assertDictEqual(filestate.symlink(name, target, user=user, group=group), ret) with patch.dict(filestate.__salt__, {'config.manage_mode': mock_t, 'file.user_to_uid': mock_uid, 'file.group_to_gid': mock_gid, 'file.is_link': mock_f, 'file.readlink': mock_target, 'file.symlink': mock_t, 'user.info': mock_t, 'file.lchown': mock_f, 'file.get_user': mock_empty, 'file.get_group': mock_empty}): with patch.dict(filestate.__opts__, {'test': False}): with patch.object(os.path, 'isdir', MagicMock(side_effect=[True, False])): with patch.object(os.path, 'isfile', mock_f): comt = 'Created new symlink {0} -> {1}, but was unable to set ownership to {2}:{3}'.format(name, target, user, group) ret.update({'comment': comt, 'result': False, 'changes': {'new': name}}) self.assertDictEqual(filestate.symlink(name, target, user=user, group=group), ret)
'Test to make sure that the named file or directory is absent.'
def test_absent(self):
name = '/fake/file.conf' ret = {'name': name, 'result': False, 'comment': '', 'pchanges': {}, 'changes': {}} mock_t = MagicMock(return_value=True) mock_f = MagicMock(return_value=False) mock_file = MagicMock(side_effect=[True, CommandExecutionError]) mock_tree = MagicMock(side_effect=[True, OSError]) comt = 'Must provide name to file.absent' ret.update({'comment': comt, 'name': ''}) with patch.object(os.path, 'islink', MagicMock(return_value=False)): self.assertDictEqual(filestate.absent(''), ret) with patch.object(os.path, 'isabs', mock_f): comt = 'Specified file {0} is not an absolute path'.format(name) ret.update({'comment': comt, 'name': name}) self.assertDictEqual(filestate.absent(name), ret) with patch.object(os.path, 'isabs', mock_t): comt = 'Refusing to make "/" absent' ret.update({'comment': comt, 'name': '/'}) self.assertDictEqual(filestate.absent('/'), ret) with patch.object(os.path, 'isfile', mock_t): with patch.dict(filestate.__opts__, {'test': True}): comt = 'File {0} is set for removal'.format(name) ret.update({'comment': comt, 'name': name, 'result': None, 'pchanges': {'removed': '/fake/file.conf'}}) self.assertDictEqual(filestate.absent(name), ret) ret.update({'pchanges': {}}) with patch.dict(filestate.__opts__, {'test': False}): with patch.dict(filestate.__salt__, {'file.remove': mock_file}): comt = 'Removed file {0}'.format(name) ret.update({'comment': comt, 'result': True, 'changes': {'removed': name}, 'pchanges': {'removed': name}}) self.assertDictEqual(filestate.absent(name), ret) comt = 'Removed file {0}'.format(name) ret.update({'comment': '', 'result': False, 'changes': {}}) self.assertDictEqual(filestate.absent(name), ret) ret.update({'pchanges': {}}) with patch.object(os.path, 'isfile', mock_f): with patch.object(os.path, 'isdir', mock_t): with patch.dict(filestate.__opts__, {'test': True}): comt = 'Directory {0} is set for removal'.format(name) ret.update({'comment': comt, 'pchanges': {'removed': name}, 'result': None}) self.assertDictEqual(filestate.absent(name), ret) with patch.dict(filestate.__opts__, {'test': False}): with patch.dict(filestate.__salt__, {'file.remove': mock_tree}): comt = 'Removed directory {0}'.format(name) ret.update({'comment': comt, 'result': True, 'changes': {'removed': name}}) self.assertDictEqual(filestate.absent(name), ret) comt = 'Failed to remove directory {0}'.format(name) ret.update({'comment': comt, 'result': False, 'changes': {}}) self.assertDictEqual(filestate.absent(name), ret) ret.update({'pchanges': {}}) with patch.object(os.path, 'isdir', mock_f): with patch.dict(filestate.__opts__, {'test': True}): comt = 'File {0} is not present'.format(name) ret.update({'comment': comt, 'result': True}) self.assertDictEqual(filestate.absent(name), ret)
'Test to verify that the named file or directory is present or exists.'
def test_exists(self):
name = '/etc/grub.conf' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}, 'pchanges': {}} mock_t = MagicMock(return_value=True) mock_f = MagicMock(return_value=False) comt = 'Must provide name to file.exists' ret.update({'comment': comt, 'name': ''}) self.assertDictEqual(filestate.exists(''), ret) with patch.object(os.path, 'exists', mock_f): comt = 'Specified path {0} does not exist'.format(name) ret.update({'comment': comt, 'name': name}) self.assertDictEqual(filestate.exists(name), ret) with patch.object(os.path, 'exists', mock_t): comt = 'Path {0} exists'.format(name) ret.update({'comment': comt, 'result': True}) self.assertDictEqual(filestate.exists(name), ret)
'Test to verify that the named file or directory is missing.'
def test_missing(self):
name = '/etc/grub.conf' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} mock_t = MagicMock(return_value=True) mock_f = MagicMock(return_value=False) comt = 'Must provide name to file.missing' ret.update({'comment': comt, 'name': '', 'pchanges': {}}) self.assertDictEqual(filestate.missing(''), ret) with patch.object(os.path, 'exists', mock_t): comt = 'Specified path {0} exists'.format(name) ret.update({'comment': comt, 'name': name}) self.assertDictEqual(filestate.missing(name), ret) with patch.object(os.path, 'exists', mock_f): comt = 'Path {0} is missing'.format(name) ret.update({'comment': comt, 'result': True}) self.assertDictEqual(filestate.missing(name), ret)
'Test to manage a given file, this function allows for a file to be downloaded from the salt master and potentially run through a templating system.'
def test_managed(self):
with patch('salt.states.file._load_accumulators', MagicMock(return_value=([], []))): name = '/etc/grub.conf' user = 'salt' group = 'saltstack' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} mock_t = MagicMock(return_value=True) mock_f = MagicMock(return_value=False) mock_cmd_fail = MagicMock(return_value={'retcode': 1}) mock_uid = MagicMock(side_effect=['', 'U12', 'U12', 'U12', 'U12', 'U12', 'U12', 'U12', 'U12', 'U12', 'U12', 'U12', 'U12', 'U12', 'U12', 'U12']) mock_gid = MagicMock(side_effect=['', 'G12', 'G12', 'G12', 'G12', 'G12', 'G12', 'G12', 'G12', 'G12', 'G12', 'G12', 'G12', 'G12', 'G12', 'G12']) mock_if = MagicMock(side_effect=[True, False, False, False, False, False, False, False]) if salt.utils.is_windows(): mock_ret = MagicMock(return_value=ret) else: mock_ret = MagicMock(return_value=(ret, None)) mock_dict = MagicMock(return_value={}) mock_cp = MagicMock(side_effect=[Exception, True]) mock_ex = MagicMock(side_effect=[Exception, {'changes': {name: name}}, True, Exception]) mock_mng = MagicMock(side_effect=[Exception, ('', '', ''), ('', '', ''), ('', '', True), ('', '', True), ('', '', ''), ('', '', '')]) mock_file = MagicMock(side_effect=[CommandExecutionError, ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', '')]) with patch.dict(filestate.__salt__, {'config.manage_mode': mock_t, 'file.user_to_uid': mock_uid, 'file.group_to_gid': mock_gid, 'file.file_exists': mock_if, 'file.check_perms': mock_ret, 'file.check_managed_changes': mock_dict, 'file.get_managed': mock_mng, 'file.source_list': mock_file, 'file.copy': mock_cp, 'file.manage_file': mock_ex, 'cmd.run_all': mock_cmd_fail}): comt = 'Must provide name to file.managed' ret.update({'comment': comt, 'name': '', 'pchanges': {}}) self.assertDictEqual(filestate.managed(''), ret) with patch.object(os.path, 'isfile', mock_f): comt = 'File {0} is not present and is not set for creation'.format(name) ret.update({'comment': comt, 'name': name, 'result': True}) self.assertDictEqual(filestate.managed(name, create=False), ret) if salt.utils.is_windows(): comt = 'User salt is not available Group salt is not available' else: comt = 'User salt is not available Group saltstack is not available' ret.update({'comment': comt, 'result': False}) self.assertDictEqual(filestate.managed(name, user=user, group=group), ret) with patch.object(os.path, 'isabs', mock_f): comt = 'Specified file {0} is not an absolute path'.format(name) ret.update({'comment': comt, 'result': False}) self.assertDictEqual(filestate.managed(name, user=user, group=group), ret) with patch.object(os.path, 'isabs', mock_t): with patch.object(os.path, 'isdir', mock_t): comt = 'Specified target {0} is a directory'.format(name) ret.update({'comment': comt}) self.assertDictEqual(filestate.managed(name, user=user, group=group), ret) with patch.object(os.path, 'isdir', mock_f): comt = 'Context must be formed as a dict' ret.update({'comment': comt}) self.assertDictEqual(filestate.managed(name, user=user, group=group, context=True), ret) comt = 'Defaults must be formed as a dict' ret.update({'comment': comt}) self.assertDictEqual(filestate.managed(name, user=user, group=group, defaults=True), ret) comt = "Only one of 'contents', 'contents_pillar', and 'contents_grains' is permitted" ret.update({'comment': comt}) self.assertDictEqual(filestate.managed(name, user=user, group=group, contents='A', contents_grains='B', contents_pillar='C'), ret) with patch.object(os.path, 'exists', mock_t): with patch.dict(filestate.__opts__, {'test': True}): comt = 'File {0} not updated'.format(name) ret.update({'comment': comt}) self.assertDictEqual(filestate.managed(name, user=user, group=group, replace=False), ret) comt = 'The file {0} is in the correct state'.format(name) ret.update({'comment': comt, 'result': True}) self.assertDictEqual(filestate.managed(name, user=user, contents='A', group=group), ret) with patch.object(os.path, 'exists', mock_f): with patch.dict(filestate.__opts__, {'test': False}): comt = 'Unable to manage file: ' ret.update({'comment': comt, 'result': False}) self.assertDictEqual(filestate.managed(name, user=user, group=group, contents='A'), ret) comt = 'Unable to manage file: ' ret.update({'comment': comt, 'result': False}) self.assertDictEqual(filestate.managed(name, user=user, group=group, contents='A'), ret) with patch.object(salt.utils.files, 'mkstemp', return_value=name): comt = 'Unable to copy file {0} to {1}: '.format(name, name) ret.update({'comment': comt, 'result': False}) self.assertDictEqual(filestate.managed(name, user=user, group=group, check_cmd='A'), ret) comt = 'Unable to check_cmd file: ' ret.update({'comment': comt, 'result': False}) self.assertDictEqual(filestate.managed(name, user=user, group=group, check_cmd='A'), ret) comt = 'check_cmd execution failed' ret.update({'comment': comt, 'result': False, 'skip_watch': True}) ret.pop('pchanges') self.assertDictEqual(filestate.managed(name, user=user, group=group, check_cmd='A'), ret) comt = 'check_cmd execution failed' ret.update({'comment': True, 'pchanges': {}}) ret.pop('skip_watch', None) self.assertDictEqual(filestate.managed(name, user=user, group=group), ret) self.assertTrue(filestate.managed(name, user=user, group=group)) comt = 'Unable to manage file: ' ret.update({'comment': comt}) self.assertDictEqual(filestate.managed(name, user=user, group=group), ret)
'Test to ensure that a named directory is present and has the right perms'
def test_directory(self):
name = '/etc/grub.conf' user = 'salt' group = 'saltstack' ret = {'name': name, 'result': False, 'comment': '', 'pchanges': {}, 'changes': {}} comt = 'Must provide name to file.directory' ret.update({'comment': comt, 'name': ''}) self.assertDictEqual(filestate.directory(''), ret) comt = 'Cannot specify both max_depth and clean' ret.update({'comment': comt, 'name': name}) self.assertDictEqual(filestate.directory(name, clean=True, max_depth=2), ret) mock_t = MagicMock(return_value=True) mock_f = MagicMock(return_value=False) if salt.utils.is_windows(): mock_perms = MagicMock(return_value=ret) else: mock_perms = MagicMock(return_value=(ret, '')) mock_uid = MagicMock(side_effect=['', 'U12', 'U12', 'U12', 'U12', 'U12', 'U12', 'U12', 'U12', 'U12', 'U12']) mock_gid = MagicMock(side_effect=['', 'G12', 'G12', 'G12', 'G12', 'G12', 'G12', 'G12', 'G12', 'G12', 'G12']) mock_check = MagicMock(return_value=(None, 'The directory "{0}" will be changed'.format(name), {'directory': 'new'})) mock_error = CommandExecutionError with patch.dict(filestate.__salt__, {'config.manage_mode': mock_t, 'file.user_to_uid': mock_uid, 'file.group_to_gid': mock_gid, 'file.stats': mock_f, 'file.check_perms': mock_perms, 'file.mkdir': mock_t}): with patch('salt.utils.win_dacl.get_sid', mock_error): with patch('os.path.isdir', mock_t): with patch('salt.states.file._check_directory_win', mock_check): if salt.utils.platform.is_windows(): comt = 'User salt is not available Group salt is not available' else: comt = 'User salt is not available Group saltstack is not available' ret.update({'comment': comt, 'name': name}) self.assertDictEqual(filestate.directory(name, user=user, group=group), ret) with patch.object(os.path, 'isabs', mock_f): comt = 'Specified file {0} is not an absolute path'.format(name) ret.update({'comment': comt}) self.assertDictEqual(filestate.directory(name, user=user, group=group), ret) with patch.object(os.path, 'isabs', mock_t): with patch.object(os.path, 'isfile', MagicMock(side_effect=[True, True, False, True, True, True, False])): with patch.object(os.path, 'lexists', mock_t): comt = 'File exists where the backup target A should go' ret.update({'comment': comt}) self.assertDictEqual(filestate.directory(name, user=user, group=group, backupname='A'), ret) with patch.object(os.path, 'isfile', mock_t): comt = 'Specified location {0} exists and is a file'.format(name) ret.update({'comment': comt}) self.assertDictEqual(filestate.directory(name, user=user, group=group), ret) with patch.object(os.path, 'islink', mock_t): comt = 'Specified location {0} exists and is a symlink'.format(name) ret.update({'comment': comt}) self.assertDictEqual(filestate.directory(name, user=user, group=group), ret) with patch.object(os.path, 'isfile', mock_f): with patch.dict(filestate.__opts__, {'test': True}): if salt.utils.is_windows(): comt = 'The directory "{0}" will be changed'.format(name) p_chg = {'directory': 'new'} else: comt = 'The following files will be changed:\n{0}: directory - new\n'.format(name) p_chg = {'/etc/grub.conf': {'directory': 'new'}} ret.update({'comment': comt, 'result': None, 'pchanges': p_chg}) self.assertDictEqual(filestate.directory(name, user=user, group=group), ret) with patch.dict(filestate.__opts__, {'test': False}): with patch.object(os.path, 'isdir', mock_f): comt = 'No directory to create {0} in'.format(name) ret.update({'comment': comt, 'result': False}) self.assertDictEqual(filestate.directory(name, user=user, group=group), ret) with patch.object(os.path, 'isdir', MagicMock(side_effect=[True, False, True, True])): comt = 'Failed to create directory {0}'.format(name) ret.update({'comment': comt, 'result': False}) self.assertDictEqual(filestate.directory(name, user=user, group=group), ret) recurse = ['ignore_files', 'ignore_dirs'] with patch.object(os.path, 'isdir', mock_t): self.assertDictEqual(filestate.directory(name, user=user, recurse=recurse, group=group), ret) self.assertDictEqual(filestate.directory(name, user=user, group=group), ret)
'Test to recurse through a subdirectory on the master and copy said subdirectory over to the specified path.'
def test_recurse(self):
name = '/opt/code/flask' source = 'salt://code/flask' user = 'salt' group = 'saltstack' ret = {'name': name, 'result': False, 'comment': '', 'pchanges': {}, 'changes': {}} comt = "'mode' is not allowed in 'file.recurse'. Please use 'file_mode' and 'dir_mode'." ret.update({'comment': comt}) self.assertDictEqual(filestate.recurse(name, source, mode='W'), ret) mock_t = MagicMock(return_value=True) mock_f = MagicMock(return_value=False) mock_uid = MagicMock(return_value='') mock_gid = MagicMock(return_value='') mock_l = MagicMock(return_value=[]) mock_emt = MagicMock(side_effect=[[], ['code/flask'], ['code/flask']]) mock_lst = MagicMock(side_effect=[CommandExecutionError, (source, ''), (source, ''), (source, '')]) with patch.dict(filestate.__salt__, {'config.manage_mode': mock_t, 'file.user_to_uid': mock_uid, 'file.group_to_gid': mock_gid, 'file.source_list': mock_lst, 'cp.list_master_dirs': mock_emt, 'cp.list_master': mock_l}): if salt.utils.is_windows(): comt = 'User salt is not available Group salt is not available' else: comt = 'User salt is not available Group saltstack is not available' ret.update({'comment': comt}) self.assertDictEqual(filestate.recurse(name, source, user=user, group=group), ret) with patch.object(os.path, 'isabs', mock_f): comt = 'Specified file {0} is not an absolute path'.format(name) ret.update({'comment': comt}) self.assertDictEqual(filestate.recurse(name, source), ret) with patch.object(os.path, 'isabs', mock_t): comt = "Invalid source '1' (must be a salt:// URI)" ret.update({'comment': comt}) self.assertDictEqual(filestate.recurse(name, 1), ret) comt = "Invalid source '//code/flask' (must be a salt:// URI)" ret.update({'comment': comt}) self.assertDictEqual(filestate.recurse(name, '//code/flask'), ret) comt = 'Recurse failed: ' ret.update({'comment': comt}) self.assertDictEqual(filestate.recurse(name, source), ret) comt = "The directory 'code/flask' does not exist on the salt fileserver in saltenv 'base'" ret.update({'comment': comt}) self.assertDictEqual(filestate.recurse(name, source), ret) with patch.object(os.path, 'isdir', mock_f): with patch.object(os.path, 'exists', mock_t): comt = 'The path {0} exists and is not a directory'.format(name) ret.update({'comment': comt}) self.assertDictEqual(filestate.recurse(name, source), ret) with patch.object(os.path, 'isdir', mock_t): comt = 'The directory {0} is in the correct state'.format(name) ret.update({'comment': comt, 'result': True}) self.assertDictEqual(filestate.recurse(name, source), ret)
'Test to maintain an edit in a file.'
def test_replace(self):
name = '/etc/grub.conf' pattern = 'CentOS +' repl = 'salt' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} comt = 'Must provide name to file.replace' ret.update({'comment': comt, 'name': '', 'pchanges': {}}) self.assertDictEqual(filestate.replace('', pattern, repl), ret) mock_t = MagicMock(return_value=True) mock_f = MagicMock(return_value=False) with patch.object(os.path, 'isabs', mock_f): comt = 'Specified file {0} is not an absolute path'.format(name) ret.update({'comment': comt, 'name': name}) self.assertDictEqual(filestate.replace(name, pattern, repl), ret) with patch.object(os.path, 'isabs', mock_t): with patch.object(os.path, 'exists', mock_t): with patch.dict(filestate.__salt__, {'file.replace': mock_f}): with patch.dict(filestate.__opts__, {'test': False}): comt = 'No changes needed to be made' ret.update({'comment': comt, 'name': name, 'result': True}) self.assertDictEqual(filestate.replace(name, pattern, repl), ret)
'Test to maintain an edit in a file in a zone delimited by two line markers.'
def test_blockreplace(self):
with patch('salt.states.file._load_accumulators', MagicMock(return_value=([], []))): name = '/etc/hosts' ret = {'name': name, 'result': False, 'comment': '', 'pchanges': {}, 'changes': {}} comt = 'Must provide name to file.blockreplace' ret.update({'comment': comt, 'name': ''}) self.assertDictEqual(filestate.blockreplace(''), ret) mock_t = MagicMock(return_value=True) mock_f = MagicMock(return_value=False) with patch.object(os.path, 'isabs', mock_f): comt = 'Specified file {0} is not an absolute path'.format(name) ret.update({'comment': comt, 'name': name}) self.assertDictEqual(filestate.blockreplace(name), ret) with patch.object(os.path, 'isabs', mock_t): with patch.object(os.path, 'exists', mock_t): with patch.dict(filestate.__salt__, {'file.blockreplace': mock_t}): with patch.dict(filestate.__opts__, {'test': True}): comt = 'Changes would be made' ret.update({'comment': comt, 'result': None, 'changes': {'diff': True}, 'pchanges': {'diff': True}}) self.assertDictEqual(filestate.blockreplace(name), ret)
'Test to comment out specified lines in a file.'
def test_comment(self):
with patch.object(os.path, 'exists', MagicMock(return_value=True)): name = ('/etc/aliases' if salt.utils.platform.is_darwin() else '/etc/fstab') regex = 'bind 127.0.0.1' ret = {'name': name, 'result': False, 'comment': '', 'pchanges': {}, 'changes': {}} comt = 'Must provide name to file.comment' ret.update({'comment': comt, 'name': ''}) self.assertDictEqual(filestate.comment('', regex), ret) mock_t = MagicMock(return_value=True) mock_f = MagicMock(return_value=False) with patch.object(os.path, 'isabs', mock_f): comt = 'Specified file {0} is not an absolute path'.format(name) ret.update({'comment': comt, 'name': name}) self.assertDictEqual(filestate.comment(name, regex), ret) with patch.object(os.path, 'isabs', mock_t): with patch.dict(filestate.__salt__, {'file.search': MagicMock(side_effect=[True, True, True, False, False])}): comt = 'Pattern already commented' ret.update({'comment': comt, 'result': True}) self.assertDictEqual(filestate.comment(name, regex), ret) comt = '{0}: Pattern not found'.format(regex) ret.update({'comment': comt, 'result': False}) self.assertDictEqual(filestate.comment(name, regex), ret) with patch.dict(filestate.__salt__, {'file.search': MagicMock(side_effect=[False, True, False, True, True]), 'file.comment': mock_t, 'file.comment_line': mock_t}): with patch.dict(filestate.__opts__, {'test': True}): comt = 'File {0} is set to be updated'.format(name) ret.update({'comment': comt, 'result': None, 'pchanges': {name: 'updated'}}) self.assertDictEqual(filestate.comment(name, regex), ret) with patch.dict(filestate.__opts__, {'test': False}): with patch.object(salt.utils.files, 'fopen', MagicMock(mock_open())): comt = 'Commented lines successfully' ret.update({'comment': comt, 'result': True}) self.assertDictEqual(filestate.comment(name, regex), ret)
'Test to uncomment specified commented lines in a file'
def test_uncomment(self):
with patch.object(os.path, 'exists', MagicMock(return_value=True)): name = ('/etc/aliases' if salt.utils.platform.is_darwin() else '/etc/fstab') regex = 'bind 127.0.0.1' ret = {'name': name, 'pchanges': {}, 'result': False, 'comment': '', 'changes': {}} comt = 'Must provide name to file.uncomment' ret.update({'comment': comt, 'name': ''}) self.assertDictEqual(filestate.uncomment('', regex), ret) mock_t = MagicMock(return_value=True) mock_f = MagicMock(return_value=False) mock = MagicMock(side_effect=[True, False, False, False, True, False, True, True]) with patch.object(os.path, 'isabs', mock_f): comt = 'Specified file {0} is not an absolute path'.format(name) ret.update({'comment': comt, 'name': name}) self.assertDictEqual(filestate.uncomment(name, regex), ret) with patch.object(os.path, 'isabs', mock_t): with patch.dict(filestate.__salt__, {'file.search': mock, 'file.uncomment': mock_t, 'file.comment_line': mock_t}): comt = 'Pattern already uncommented' ret.update({'comment': comt, 'result': True}) self.assertDictEqual(filestate.uncomment(name, regex), ret) comt = '{0}: Pattern not found'.format(regex) ret.update({'comment': comt, 'result': False}) self.assertDictEqual(filestate.uncomment(name, regex), ret) with patch.dict(filestate.__opts__, {'test': True}): comt = 'File {0} is set to be updated'.format(name) ret.update({'comment': comt, 'result': None, 'pchanges': {name: 'updated'}}) self.assertDictEqual(filestate.uncomment(name, regex), ret) with patch.dict(filestate.__opts__, {'test': False}): with patch.object(salt.utils.files, 'fopen', MagicMock(mock_open())): comt = 'Uncommented lines successfully' ret.update({'comment': comt, 'result': True}) self.assertDictEqual(filestate.uncomment(name, regex), ret)
'Test to ensure that some text appears at the beginning of a file.'
def test_prepend(self):
name = '/etc/motd' source = ['salt://motd/hr-messages.tmpl'] sources = ['salt://motd/devops-messages.tmpl'] text = ['Trust no one unless you have eaten much salt with him.'] ret = {'name': name, 'result': False, 'comment': '', 'pchanges': {}, 'changes': {}} comt = 'Must provide name to file.prepend' ret.update({'comment': comt, 'name': ''}) self.assertDictEqual(filestate.prepend(''), ret) comt = 'source and sources are mutually exclusive' ret.update({'comment': comt, 'name': name}) self.assertDictEqual(filestate.prepend(name, source=source, sources=sources), ret) mock_t = MagicMock(return_value=True) mock_f = MagicMock(return_value=False) with patch.dict(filestate.__salt__, {'file.directory_exists': mock_f, 'file.makedirs': mock_t, 'file.stats': mock_f, 'cp.get_template': mock_f, 'file.search': mock_f, 'file.prepend': mock_t}): with patch.object(os.path, 'isdir', mock_t): comt = 'The following files will be changed:\n/etc: directory - new\n' ret.update({'comment': comt, 'name': name, 'pchanges': {'/etc': {'directory': 'new'}}}) self.assertDictEqual(filestate.prepend(name, makedirs=True), ret) with patch.object(os.path, 'isabs', mock_f): comt = 'Specified file {0} is not an absolute path'.format(name) ret.update({'comment': comt, 'pchanges': {}}) self.assertDictEqual(filestate.prepend(name), ret) with patch.object(os.path, 'isabs', mock_t): with patch.object(os.path, 'exists', mock_t): comt = 'Failed to load template file {0}'.format(source) ret.pop('pchanges') ret.update({'comment': comt, 'name': source, 'data': []}) self.assertDictEqual(filestate.prepend(name, source=source), ret) ret.pop('data', None) ret.update({'name': name}) with patch.object(salt.utils.files, 'fopen', MagicMock(mock_open(read_data=''))): with patch.object(salt.utils, 'istextfile', mock_f): with patch.dict(filestate.__opts__, {'test': True}): change = {'diff': 'Replace binary file'} comt = 'File {0} is set to be updated'.format(name) ret.update({'comment': comt, 'result': None, 'changes': change, 'pchanges': {}}) self.assertDictEqual(filestate.prepend(name, text=text), ret) with patch.dict(filestate.__opts__, {'test': False}): comt = 'Prepended 1 lines' ret.update({'comment': comt, 'result': True, 'changes': {}}) self.assertDictEqual(filestate.prepend(name, text=text), ret)
'Test to apply a patch to a file.'
def test_patch(self):
name = '/opt/file.txt' source = 'salt://file.patch' ha_sh = 'md5=e138491e9d5b97023cea823fe17bac22' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} comt = 'Must provide name to file.patch' ret.update({'comment': comt, 'name': ''}) self.assertDictEqual(filestate.patch(''), ret) comt = '{0}: file not found'.format(name) ret.update({'comment': comt, 'name': name}) self.assertDictEqual(filestate.patch(name), ret) mock_t = MagicMock(return_value=True) mock_true = MagicMock(side_effect=[True, False, False, False, False]) mock_false = MagicMock(side_effect=[False, True, True, True]) mock_ret = MagicMock(return_value={'retcode': True}) with patch.object(os.path, 'isabs', mock_t): with patch.object(os.path, 'exists', mock_t): comt = 'Source is required' ret.update({'comment': comt}) self.assertDictEqual(filestate.patch(name), ret) comt = 'Hash is required' ret.update({'comment': comt}) self.assertDictEqual(filestate.patch(name, source=source), ret) with patch.dict(filestate.__salt__, {'file.check_hash': mock_true, 'cp.cache_file': mock_false, 'file.patch': mock_ret}): comt = 'Patch is already applied' ret.update({'comment': comt, 'result': True}) self.assertDictEqual(filestate.patch(name, source=source, hash=ha_sh), ret) comt = "Unable to cache salt://file.patch from saltenv 'base'" ret.update({'comment': comt, 'result': False}) self.assertDictEqual(filestate.patch(name, source=source, hash=ha_sh), ret) with patch.dict(filestate.__opts__, {'test': True}): comt = 'File /opt/file.txt will be patched' ret.update({'comment': comt, 'result': None, 'changes': {'retcode': True}}) self.assertDictEqual(filestate.patch(name, source=source, hash=ha_sh), ret) with patch.dict(filestate.__opts__, {'test': False}): ret.update({'comment': '', 'result': False}) self.assertDictEqual(filestate.patch(name, source=source, hash=ha_sh), ret) self.assertDictEqual(filestate.patch(name, source=source, hash=ha_sh, dry_run_first=False), ret)
'Test to replicate the \'nix "touch" command to create a new empty file or update the atime and mtime of an existing file.'
def test_touch(self):
name = '/var/log/httpd/logrotate.empty' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} comt = 'Must provide name to file.touch' ret.update({'comment': comt, 'name': ''}) self.assertDictEqual(filestate.touch(''), ret) mock_t = MagicMock(return_value=True) mock_f = MagicMock(return_value=False) with patch.object(os.path, 'isabs', mock_f): comt = 'Specified file {0} is not an absolute path'.format(name) ret.update({'comment': comt, 'name': name}) self.assertDictEqual(filestate.touch(name), ret) with patch.object(os.path, 'isabs', mock_t): with patch.object(os.path, 'exists', mock_f): with patch.dict(filestate.__opts__, {'test': True}): comt = 'File {0} is set to be created'.format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(filestate.touch(name), ret) with patch.dict(filestate.__opts__, {'test': False}): with patch.object(os.path, 'isdir', mock_f): comt = 'Directory not present to touch file {0}'.format(name) ret.update({'comment': comt, 'result': False}) self.assertDictEqual(filestate.touch(name), ret) with patch.object(os.path, 'isdir', mock_t): with patch.dict(filestate.__salt__, {'file.touch': mock_t}): comt = 'Created empty file {0}'.format(name) ret.update({'comment': comt, 'result': True, 'changes': {'new': name}}) self.assertDictEqual(filestate.touch(name), ret)
'Test if the source file exists on the system, copy it to the named file.'
def test_copy(self):
name = '/tmp/salt' source = '/tmp/salt/salt' user = 'salt' group = 'saltstack' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} comt = 'Must provide name to file.copy' ret.update({'comment': comt, 'name': ''}) self.assertDictEqual(filestate.copy('', source), ret) mock_t = MagicMock(return_value=True) mock_f = MagicMock(return_value=False) mock_uid = MagicMock(side_effect=['']) mock_gid = MagicMock(side_effect=['']) mock_user = MagicMock(return_value=user) mock_grp = MagicMock(return_value=group) mock_io = MagicMock(side_effect=IOError) with patch.object(os.path, 'isabs', mock_f): comt = 'Specified file {0} is not an absolute path'.format(name) ret.update({'comment': comt, 'name': name}) self.assertDictEqual(filestate.copy(name, source), ret) with patch.object(os.path, 'isabs', mock_t): with patch.object(os.path, 'exists', mock_f): comt = 'Source file "{0}" is not present'.format(source) ret.update({'comment': comt, 'result': False}) self.assertDictEqual(filestate.copy(name, source), ret) with patch.object(os.path, 'exists', mock_t): with patch.dict(filestate.__salt__, {'file.user_to_uid': mock_uid, 'file.group_to_gid': mock_gid, 'file.get_user': mock_user, 'file.get_group': mock_grp, 'file.get_mode': mock_grp, 'file.check_perms': mock_t}): if salt.utils.is_windows(): comt = 'User salt is not available Group salt is not available' else: comt = 'User salt is not available Group saltstack is not available' ret.update({'comment': comt, 'result': False}) self.assertDictEqual(filestate.copy(name, source, user=user, group=group), ret) comt1 = 'Failed to delete "{0}" in preparation for forced move'.format(name) comt2 = 'The target file "{0}" exists and will not be overwritten'.format(name) comt3 = 'File "{0}" is set to be copied to "{1}"'.format(source, name) with patch.object(os.path, 'isdir', mock_f): with patch.object(os.path, 'lexists', mock_t): with patch.dict(filestate.__opts__, {'test': False}): with patch.dict(filestate.__salt__, {'file.remove': mock_io}): ret.update({'comment': comt1, 'result': False}) self.assertDictEqual(filestate.copy(name, source, preserve=True, force=True), ret) with patch.object(os.path, 'isfile', mock_t): ret.update({'comment': comt2, 'result': True}) self.assertDictEqual(filestate.copy(name, source, preserve=True), ret) with patch.object(os.path, 'lexists', mock_f): with patch.dict(filestate.__opts__, {'test': True}): ret.update({'comment': comt3, 'result': None}) self.assertDictEqual(filestate.copy(name, source, preserve=True), ret) with patch.dict(filestate.__opts__, {'test': False}): comt = 'The target directory /tmp is not present' ret.update({'comment': comt, 'result': False}) self.assertDictEqual(filestate.copy(name, source, preserve=True), ret)
'Test if the source file exists on the system, rename it to the named file.'
def test_rename(self):
name = '/tmp/salt' source = '/tmp/salt/salt' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} comt = 'Must provide name to file.rename' ret.update({'comment': comt, 'name': ''}) self.assertDictEqual(filestate.rename('', source), ret) mock_t = MagicMock(return_value=True) mock_f = MagicMock(return_value=False) mock_lex = MagicMock(side_effect=[False, True, True]) with patch.object(os.path, 'isabs', mock_f): comt = 'Specified file {0} is not an absolute path'.format(name) ret.update({'comment': comt, 'name': name}) self.assertDictEqual(filestate.rename(name, source), ret) mock_lex = MagicMock(return_value=False) with patch.object(os.path, 'isabs', mock_t): with patch.object(os.path, 'lexists', mock_lex): comt = 'Source file "{0}" has already been moved out of place'.format(source) ret.update({'comment': comt, 'result': True}) self.assertDictEqual(filestate.rename(name, source), ret) mock_lex = MagicMock(side_effect=[True, True, True]) with patch.object(os.path, 'isabs', mock_t): with patch.object(os.path, 'lexists', mock_lex): comt = 'The target file "{0}" exists and will not be overwritten'.format(name) ret.update({'comment': comt, 'result': False}) self.assertDictEqual(filestate.rename(name, source), ret) mock_lex = MagicMock(side_effect=[True, True, True]) mock_rem = MagicMock(side_effect=IOError) with patch.object(os.path, 'isabs', mock_t): with patch.object(os.path, 'lexists', mock_lex): with patch.dict(filestate.__opts__, {'test': False}): comt = 'Failed to delete "{0}" in preparation for forced move'.format(name) with patch.dict(filestate.__salt__, {'file.remove': mock_rem}): ret.update({'name': name, 'comment': comt, 'result': False}) self.assertDictEqual(filestate.rename(name, source, force=True), ret) mock_lex = MagicMock(side_effect=[True, False, False]) with patch.object(os.path, 'isabs', mock_t): with patch.object(os.path, 'lexists', mock_lex): with patch.dict(filestate.__opts__, {'test': True}): comt = 'File "{0}" is set to be moved to "{1}"'.format(source, name) ret.update({'name': name, 'comment': comt, 'result': None}) self.assertDictEqual(filestate.rename(name, source), ret) mock_lex = MagicMock(side_effect=[True, False, False]) with patch.object(os.path, 'isabs', mock_t): with patch.object(os.path, 'lexists', mock_lex): with patch.object(os.path, 'isdir', mock_f): with patch.dict(filestate.__opts__, {'test': False}): comt = 'The target directory /tmp is not present' ret.update({'name': name, 'comment': comt, 'result': False}) self.assertDictEqual(filestate.rename(name, source), ret) mock_lex = MagicMock(side_effect=[True, False, False]) with patch.object(os.path, 'isabs', mock_t): with patch.object(os.path, 'lexists', mock_lex): with patch.object(os.path, 'isdir', mock_t): with patch.object(os.path, 'islink', mock_f): with patch.dict(filestate.__opts__, {'test': False}): with patch.object(shutil, 'move', MagicMock(side_effect=IOError)): comt = 'Failed to move "{0}" to "{1}"'.format(source, name) ret.update({'name': name, 'comment': comt, 'result': False}) self.assertDictEqual(filestate.rename(name, source), ret) mock_lex = MagicMock(side_effect=[True, False, False]) with patch.object(os.path, 'isabs', mock_t): with patch.object(os.path, 'lexists', mock_lex): with patch.object(os.path, 'isdir', mock_t): with patch.object(os.path, 'islink', mock_f): with patch.dict(filestate.__opts__, {'test': False}): with patch.object(shutil, 'move', MagicMock()): comt = 'Moved "{0}" to "{1}"'.format(source, name) ret.update({'name': name, 'comment': comt, 'result': True, 'changes': {name: source}}) self.assertDictEqual(filestate.rename(name, source), ret)
'Test to prepare accumulator which can be used in template in file.'
def test_accumulated(self):
with patch('salt.states.file._load_accumulators', MagicMock(return_value=({}, {}))): with patch('salt.states.file._persist_accummulators', MagicMock(return_value=True)): name = 'animals_doing_things' filename = '/tmp/animal_file.txt' text = ' jumps over the lazy dog.' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} comt = 'Must provide name to file.accumulated' ret.update({'comment': comt, 'name': ''}) self.assertDictEqual(filestate.accumulated('', filename, text), ret) comt = 'No text supplied for accumulator' ret.update({'comment': comt, 'name': name}) self.assertDictEqual(filestate.accumulated(name, filename, None), ret) with patch.dict(filestate.__low__, {'require_in': 'file', 'watch_in': 'salt', '__sls__': 'SLS', '__id__': 'ID'}): comt = 'Orphaned accumulator animals_doing_things in SLS:ID' ret.update({'comment': comt, 'name': name}) self.assertDictEqual(filestate.accumulated(name, filename, text), ret) with patch.dict(filestate.__low__, {'require_in': [{'file': 'A'}], 'watch_in': [{'B': 'C'}], '__sls__': 'SLS', '__id__': 'ID'}): comt = 'Accumulator {0} for file {1} was charged by text'.format(name, filename) ret.update({'comment': comt, 'name': name, 'result': True}) self.assertDictEqual(filestate.accumulated(name, filename, text), ret) def test_serialize_into_managed_file(self): '\n Test to serializes dataset and store it into managed file.\n ' name = '/etc/dummy/package.json' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} comt = 'Must provide name to file.serialize' ret.update({'comment': comt, 'name': ''}) self.assertDictEqual(filestate.serialize(''), ret) mock_t = MagicMock(return_value=True) mock_f = MagicMock(return_value=False) with patch.object(os.path, 'isfile', mock_f): comt = 'File {0} is not present and is not set for creation'.format(name) ret.update({'comment': comt, 'name': name, 'result': True}) self.assertDictEqual(filestate.serialize(name, create=False), ret) comt = "Only one of 'dataset' and 'dataset_pillar' is permitted" ret.update({'comment': comt, 'result': False}) self.assertDictEqual(filestate.serialize(name, dataset=True, dataset_pillar=True), ret) comt = "Neither 'dataset' nor 'dataset_pillar' was defined" ret.update({'comment': comt, 'result': False}) self.assertDictEqual(filestate.serialize(name), ret) with patch.object(os.path, 'isfile', mock_t): comt = 'Python format is not supported for merging' ret.update({'comment': comt, 'result': False}) self.assertDictEqual(filestate.serialize(name, dataset=True, merge_if_exists=True, formatter='python'), ret) comt = 'A format is not supported' ret.update({'comment': comt, 'result': False}) self.assertDictEqual(filestate.serialize(name, dataset=True, formatter='A'), ret) mock_changes = MagicMock(return_value=True) mock_no_changes = MagicMock(return_value=False) with patch.dict(filestate.__salt__, {'file.check_managed_changes': mock_changes}): with patch.dict(filestate.__opts__, {'test': True}): comt = 'Dataset will be serialized and stored into {0}'.format(name) ret.update({'comment': comt, 'result': None, 'changes': True}) self.assertDictEqual(filestate.serialize(name, dataset=True, formatter='python'), ret) with patch.dict(filestate.__salt__, {'file.check_managed_changes': mock_no_changes}): with patch.dict(filestate.__opts__, {'test': True}): comt = 'The file {0} is in the correct state'.format(name) ret.update({'comment': comt, 'result': True, 'changes': False}) self.assertDictEqual(filestate.serialize(name, dataset=True, formatter='python'), ret) mock = MagicMock(return_value=ret) with patch.dict(filestate.__opts__, {'test': False}): with patch.dict(filestate.__salt__, {'file.manage_file': mock}): comt = 'Dataset will be serialized and stored into {0}'.format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(filestate.serialize(name, dataset=True, formatter='python'), ret)
'Test to create a special file similar to the \'nix mknod command.'
def test_mknod(self):
name = '/dev/AA' ntype = 'a' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} comt = 'Must provide name to file.mknod' ret.update({'comment': comt, 'name': ''}) self.assertDictEqual(filestate.mknod('', ntype), ret) comt = "Node type unavailable: 'a'. Available node types are character ('c'), block ('b'), and pipe ('p')" ret.update({'comment': comt, 'name': name}) self.assertDictEqual(filestate.mknod(name, ntype), ret)
'Test to execute the check_cmd logic.'
def test_mod_run_check_cmd(self):
cmd = 'A' filename = 'B' ret = {'comment': 'check_cmd execution failed', 'result': False, 'skip_watch': True} mock = MagicMock(side_effect=[{'retcode': 1}, {'retcode': 0}]) with patch.dict(filestate.__salt__, {'cmd.run_all': mock}): self.assertDictEqual(filestate.mod_run_check_cmd(cmd, filename), ret) self.assertTrue(filestate.mod_run_check_cmd(cmd, filename))
'Test to execute the retention_schedule logic. This test takes advantage of knowing which files it is generating, which means it can easily generate list of which files it should keep.'
@skipIf((not HAS_DATEUTIL), NO_DATEUTIL_REASON) def test_retention_schedule(self):
def generate_fake_files(format='example_name_%Y%m%dT%H%M%S.tar.bz2', starting=datetime(2016, 2, 8, 9), every=relativedelta(minutes=30), ending=datetime(2015, 12, 25), maxfiles=None): "\n For starting, make sure that it's over a week from the beginning of the month\n For every, pick only one of minutes, hours, days, weeks, months or years\n For ending, the further away it is from starting, the slower the tests run\n Full coverage requires over a year of separation, but that's painfully slow.\n " if every.years: ts = datetime(starting.year, 1, 1) elif every.months: ts = datetime(starting.year, starting.month, 1) elif every.days: ts = datetime(starting.year, starting.month, starting.day) elif every.hours: ts = datetime(starting.year, starting.month, starting.day, starting.hour) elif every.minutes: ts = datetime(starting.year, starting.month, starting.day, starting.hour, 0) else: raise NotImplementedError("not sure what you're trying to do here") fake_files = [] count = 0 while (ending < ts): fake_files.append(ts.strftime(format=format)) count += 1 if ((maxfiles and (maxfiles == 'all')) or (maxfiles and (count >= maxfiles))): break ts -= every return fake_files fake_name = '/some/dir/name' fake_retain = {'most_recent': 2, 'first_of_hour': 4, 'first_of_day': 7, 'first_of_week': 6, 'first_of_month': 6, 'first_of_year': 'all'} fake_strptime_format = 'example_name_%Y%m%dT%H%M%S.tar.bz2' fake_matching_file_list = generate_fake_files() fake_no_match_file_list = generate_fake_files(format='no_match_%Y%m%dT%H%M%S.tar.bz2', every=relativedelta(days=1)) def lstat_side_effect(path): import re from time import mktime x = re.match('^[^\\d]*(\\d{8}T\\d{6})\\.tar\\.bz2$', path).group(1) ts = mktime(datetime.strptime(x, '%Y%m%dT%H%M%S').timetuple()) return {'st_atime': 0.0, 'st_ctime': 0.0, 'st_gid': 0, 'st_mode': 33188, 'st_mtime': ts, 'st_nlink': 1, 'st_size': 0, 'st_uid': 0} mock_t = MagicMock(return_value=True) mock_f = MagicMock(return_value=False) mock_lstat = MagicMock(side_effect=lstat_side_effect) mock_remove = MagicMock() def run_checks(isdir=mock_t, strptime_format=None, test=False): expected_ret = {'name': fake_name, 'changes': {'retained': [], 'deleted': [], 'ignored': []}, 'pchanges': {'retained': [], 'deleted': [], 'ignored': []}, 'result': True, 'comment': 'Name provided to file.retention must be a directory'} if strptime_format: fake_file_list = sorted((fake_matching_file_list + fake_no_match_file_list)) else: fake_file_list = sorted(fake_matching_file_list) mock_readdir = MagicMock(return_value=fake_file_list) with patch.dict(filestate.__opts__, {'test': test}): with patch.object(os.path, 'isdir', isdir): mock_readdir.reset_mock() with patch.dict(filestate.__salt__, {'file.readdir': mock_readdir}): with patch.dict(filestate.__salt__, {'file.lstat': mock_lstat}): mock_remove.reset_mock() with patch.dict(filestate.__salt__, {'file.remove': mock_remove}): if strptime_format: actual_ret = filestate.retention_schedule(fake_name, fake_retain, strptime_format=fake_strptime_format) else: actual_ret = filestate.retention_schedule(fake_name, fake_retain) if (not isdir()): mock_readdir.assert_has_calls([]) expected_ret['result'] = False else: mock_readdir.assert_called_once_with(fake_name) ignored_files = (fake_no_match_file_list if strptime_format else []) retained_files = set(generate_fake_files(maxfiles=fake_retain['most_recent'])) junk_list = [('first_of_hour', relativedelta(hours=1)), ('first_of_day', relativedelta(days=1)), ('first_of_week', relativedelta(weeks=1)), ('first_of_month', relativedelta(months=1)), ('first_of_year', relativedelta(years=1))] for (retainable, retain_interval) in junk_list: new_retains = set(generate_fake_files(maxfiles=fake_retain[retainable], every=retain_interval)) if ((fake_retain[retainable] == 'all') or (len(new_retains) < fake_retain[retainable])): new_retains.add(fake_file_list[0]) retained_files |= new_retains deleted_files = sorted(list(((set(fake_file_list) - retained_files) - set(ignored_files))), reverse=True) retained_files = sorted(list(retained_files), reverse=True) changes = {'retained': retained_files, 'deleted': deleted_files, 'ignored': ignored_files} expected_ret['pchanges'] = changes if test: expected_ret['result'] = None expected_ret['comment'] = '{0} backups would have been removed from {1}.\n'.format(len(deleted_files), fake_name) else: expected_ret['comment'] = '{0} backups were removed from {1}.\n'.format(len(deleted_files), fake_name) expected_ret['changes'] = changes mock_remove.assert_has_calls([call(os.path.join(fake_name, x)) for x in deleted_files], any_order=True) self.assertDictEqual(actual_ret, expected_ret) run_checks(isdir=mock_f) run_checks() run_checks(test=True) run_checks(strptime_format=fake_strptime_format) run_checks(strptime_format=fake_strptime_format, test=True)
'tests a condition with no rules in present or desired group'
def test__get_rule_changes_no_rules_no_change(self):
present_rules = [] desired_rules = [] self.assertEqual(boto_secgroup._get_rule_changes(desired_rules, present_rules), ([], []))
'tests a condition where a rule must be created'
def test__get_rule_changes_create_rules(self):
present_rules = [OrderedDict([('ip_protocol', 'tcp'), ('from_port', 22), ('to_port', 22), ('cidr_ip', '0.0.0.0/0')])] desired_rules = [OrderedDict([('ip_protocol', 'tcp'), ('from_port', 22), ('to_port', 22), ('cidr_ip', '0.0.0.0/0')]), OrderedDict([('ip_protocol', 'tcp'), ('from_port', 80), ('to_port', 80), ('cidr_ip', '0.0.0.0/0')])] rules_to_create = [OrderedDict([('ip_protocol', 'tcp'), ('from_port', 80), ('to_port', 80), ('cidr_ip', '0.0.0.0/0')])] self.assertEqual(boto_secgroup._get_rule_changes(desired_rules, present_rules), ([], rules_to_create))
'tests a condition where a rule must be deleted'
def test__get_rule_changes_delete_rules(self):
present_rules = [OrderedDict([('ip_protocol', 'tcp'), ('from_port', 22), ('to_port', 22), ('cidr_ip', '0.0.0.0/0')]), OrderedDict([('ip_protocol', 'tcp'), ('from_port', 80), ('to_port', 80), ('cidr_ip', '0.0.0.0/0')])] desired_rules = [OrderedDict([('ip_protocol', 'tcp'), ('from_port', 22), ('to_port', 22), ('cidr_ip', '0.0.0.0/0')])] rules_to_delete = [OrderedDict([('ip_protocol', 'tcp'), ('from_port', 80), ('to_port', 80), ('cidr_ip', '0.0.0.0/0')])] self.assertEqual(boto_secgroup._get_rule_changes(desired_rules, present_rules), (rules_to_delete, []))
'Test to verify that the variable is in the ``make.conf`` and has the provided settings.'
def test_present(self):
name = 'makeopts' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} mock_t = MagicMock(return_value=True) with patch.dict(makeconf.__salt__, {'makeconf.get_var': mock_t}): comt = 'Variable {0} is already present in make.conf'.format(name) ret.update({'comment': comt}) self.assertDictEqual(makeconf.present(name), ret)
'Test to verify that the variable is not in the ``make.conf``.'
def test_absent(self):
name = 'makeopts' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} mock = MagicMock(return_value=None) with patch.dict(makeconf.__salt__, {'makeconf.get_var': mock}): comt = 'Variable {0} is already absent from make.conf'.format(name) ret.update({'comment': comt}) self.assertDictEqual(makeconf.absent(name), ret)
'Test to ensure the SQS queue exists.'
def test_present(self):
name = 'mysqs' attributes = {'DelaySeconds': 20} base_ret = {'name': name, 'changes': {}} mock = MagicMock(side_effect=[{'result': b} for b in [False, False, True, True]]) mock_bool = MagicMock(return_value={'error': 'create error'}) mock_attr = MagicMock(return_value={'result': {}}) with patch.dict(boto_sqs.__salt__, {'boto_sqs.exists': mock, 'boto_sqs.create': mock_bool, 'boto_sqs.get_attributes': mock_attr}): with patch.dict(boto_sqs.__opts__, {'test': False}): comt = 'Failed to create SQS queue {0}: create error'.format(name) ret = base_ret.copy() ret.update({'result': False, 'comment': comt}) self.assertDictEqual(boto_sqs.present(name), ret) with patch.dict(boto_sqs.__opts__, {'test': True}): comt = 'SQS queue {0} is set to be created.'.format(name) ret = base_ret.copy() ret.update({'result': None, 'comment': comt, 'pchanges': {'old': None, 'new': 'mysqs'}}) self.assertDictEqual(boto_sqs.present(name), ret) diff = textwrap.dedent(' --- \n +++ \n @@ -1 +1 @@\n -{}\n +DelaySeconds: 20\n ') comt = (textwrap.dedent(' SQS queue mysqs present.\n Attribute(s) DelaySeconds set to be updated:\n ') + diff) ret.update({'comment': comt, 'pchanges': {'attributes': {'diff': diff}}}) self.assertDictEqual(boto_sqs.present(name, attributes), ret) comt = 'SQS queue mysqs present.' ret = base_ret.copy() ret.update({'result': True, 'comment': comt}) self.assertDictEqual(boto_sqs.present(name), ret)
'Test to ensure the named sqs queue is deleted.'
def test_absent(self):
name = 'test.example.com.' base_ret = {'name': name, 'changes': {}} mock = MagicMock(side_effect=[{'result': False}, {'result': True}]) with patch.dict(boto_sqs.__salt__, {'boto_sqs.exists': mock}): comt = 'SQS queue {0} does not exist in None.'.format(name) ret = base_ret.copy() ret.update({'result': True, 'comment': comt}) self.assertDictEqual(boto_sqs.absent(name), ret) with patch.dict(boto_sqs.__opts__, {'test': True}): comt = 'SQS queue {0} is set to be removed.'.format(name) ret = base_ret.copy() ret.update({'result': None, 'comment': comt, 'pchanges': {'old': name, 'new': None}}) self.assertDictEqual(boto_sqs.absent(name), ret)
'Test to verify that the specified ruby is installed with rbenv.'
def test_installed(self):
name = 'rbenv-deps' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} mock_t = MagicMock(side_effect=[False, True, True]) mock_f = MagicMock(return_value=False) mock_def = MagicMock(return_value='2.7') mock_ver = MagicMock(return_value=['2.7']) with patch.dict(rbenv.__salt__, {'rbenv.is_installed': mock_f, 'rbenv.install': mock_t, 'rbenv.default': mock_def, 'rbenv.versions': mock_ver, 'rbenv.install_ruby': mock_t}): with patch.dict(rbenv.__opts__, {'test': True}): comt = 'Ruby rbenv-deps is set to be installed' ret.update({'comment': comt, 'result': None}) self.assertDictEqual(rbenv.installed(name), ret) with patch.dict(rbenv.__opts__, {'test': False}): comt = 'Rbenv failed to install' ret.update({'comment': comt, 'result': False}) self.assertDictEqual(rbenv.installed(name), ret) comt = 'Successfully installed ruby' ret.update({'comment': comt, 'result': True, 'default': False, 'changes': {name: 'Installed'}}) self.assertDictEqual(rbenv.installed(name), ret)
'Test to verify that the specified ruby is not installed with rbenv.'
def test_absent(self):
name = 'myqueue' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} mock = MagicMock(side_effect=[False, True]) mock_def = MagicMock(return_value='2.7') mock_ver = MagicMock(return_value=['2.7']) with patch.dict(rbenv.__salt__, {'rbenv.is_installed': mock, 'rbenv.default': mock_def, 'rbenv.versions': mock_ver}): with patch.dict(rbenv.__opts__, {'test': True}): comt = 'Ruby myqueue is set to be uninstalled' ret.update({'comment': comt, 'result': None}) self.assertDictEqual(rbenv.absent(name), ret) with patch.dict(rbenv.__opts__, {'test': False}): comt = 'Rbenv not installed, myqueue not either' ret.update({'comment': comt, 'result': True}) self.assertDictEqual(rbenv.absent(name), ret) comt = 'Ruby myqueue is already absent' ret.update({'comment': comt, 'result': True}) self.assertDictEqual(rbenv.absent(name), ret)
'Test to install rbenv if not installed.'
def test_install_rbenv(self):
name = 'myqueue' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} with patch.dict(rbenv.__opts__, {'test': True}): comt = 'Rbenv is set to be installed' ret.update({'comment': comt, 'result': None}) self.assertDictEqual(rbenv.install_rbenv(name), ret) with patch.dict(rbenv.__opts__, {'test': False}): mock = MagicMock(side_effect=[False, True]) with patch.dict(rbenv.__salt__, {'rbenv.is_installed': mock, 'rbenv.install': mock}): comt = 'Rbenv installed' ret.update({'comment': comt, 'result': True}) self.assertDictEqual(rbenv.install_rbenv(name), ret)
'Test to ensures that the named command is not running.'
def test_absent(self):
name = 'apache2' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} mock = MagicMock(return_value='') with patch.dict(process.__salt__, {'ps.pgrep': mock, 'ps.pkill': mock}): with patch.dict(process.__opts__, {'test': True}): comt = 'No matching processes running' ret.update({'comment': comt}) self.assertDictEqual(process.absent(name), ret) with patch.dict(process.__opts__, {'test': False}): ret.update({'result': True}) self.assertDictEqual(process.absent(name), ret)
'Test to perform an HTTP query and statefully return the result'
def test_query(self):
ret = [{'changes': {}, 'comment': ' Either match text (match) or a status code (status) is required.', 'data': {}, 'name': 'salt', 'result': False}, {'changes': {}, 'comment': ' (TEST MODE)', 'data': True, 'name': 'salt', 'result': None}] self.assertDictEqual(http.query('salt'), ret[0]) with patch.dict(http.__opts__, {'test': True}): mock = MagicMock(return_value=True) with patch.dict(http.__salt__, {'http.query': mock}): self.assertDictEqual(http.query('salt', 'Dude', 'stack'), ret[1])
'Test to ensure that the named schema is present in the database.'
def test_present(self):
name = 'myname' dbname = 'mydb' ret = {'name': name, 'dbname': dbname, 'changes': {}, 'result': True, 'comment': ''} mock = MagicMock(return_value=name) with patch.dict(postgres_schema.__salt__, {'postgres.schema_get': mock}): with patch.dict(postgres_schema.__opts__, {'test': False}): comt = 'Schema {0} already exists in database {1}'.format(name, dbname) ret.update({'comment': comt}) self.assertDictEqual(postgres_schema.present(dbname, name), ret)
'Test to ensure that the named schema is absent.'
def test_absent(self):
name = 'myname' dbname = 'mydb' ret = {'name': name, 'dbname': dbname, 'changes': {}, 'result': True, 'comment': ''} mock_t = MagicMock(side_effect=[True, False]) mock = MagicMock(side_effect=[True, True, True, False]) with patch.dict(postgres_schema.__salt__, {'postgres.schema_exists': mock, 'postgres.schema_remove': mock_t}): with patch.dict(postgres_schema.__opts__, {'test': True}): comt = 'Schema {0} is set to be removed from database {1}'.format(name, dbname) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(postgres_schema.absent(dbname, name), ret) with patch.dict(postgres_schema.__opts__, {'test': False}): comt = 'Schema {0} has been removed from database {1}'.format(name, dbname) ret.update({'comment': comt, 'result': True, 'changes': {name: 'Absent'}}) self.assertDictEqual(postgres_schema.absent(dbname, name), ret) comt = 'Schema {0} failed to be removed'.format(name) ret.update({'comment': comt, 'result': False, 'changes': {}}) self.assertDictEqual(postgres_schema.absent(dbname, name), ret) comt = 'Schema {0} is not present in database {1}, so it cannot be removed'.format(name, dbname) ret.update({'comment': comt, 'result': True}) self.assertDictEqual(postgres_schema.absent(dbname, name), ret)
'Test to send a message to a Hipchat room.'
def test_send_message(self):
name = 'salt' room_id = '123456' from_name = 'SuperAdmin' message = 'This state was executed successfully.' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} with patch.dict(hipchat.__opts__, {'test': True}): comt = 'The following message is to be sent to Hipchat: {0}'.format(message) ret.update({'comment': comt}) self.assertDictEqual(hipchat.send_message(name, room_id, from_name, message), ret) with patch.dict(hipchat.__opts__, {'test': False}): comt = 'Hipchat room id is missing: {0}'.format(name) ret.update({'comment': comt, 'result': False}) self.assertDictEqual(hipchat.send_message(name, None, from_name, message), ret) comt = 'Hipchat from name is missing: {0}'.format(name) ret.update({'comment': comt}) self.assertDictEqual(hipchat.send_message(name, room_id, None, message), ret) comt = 'Hipchat message is missing: {0}'.format(name) ret.update({'comment': comt}) self.assertDictEqual(hipchat.send_message(name, room_id, from_name, None), ret) mock = MagicMock(return_value=True) with patch.dict(hipchat.__salt__, {'hipchat.send_message': mock}): comt = 'Sent message: {0}'.format(name) ret.update({'comment': comt, 'result': True}) self.assertDictEqual(hipchat.send_message(name, room_id, from_name, message), ret)
'Test - Manage the SNMP sysContact, sysLocation, and sysServices settings.'
def test_agent_settings(self):
kwargs = {'name': 'agent-settings', 'contact': 'TestContact', 'location': 'TestLocation', 'services': ['Internet']} ret = {'name': kwargs['name'], 'changes': {}, 'comment': 'Agent settings already contain the provided values.', 'result': True} get_ret = dict(((key, value) for (key, value) in six.iteritems(kwargs) if (key != 'name'))) mock_value_get = MagicMock(return_value=get_ret) mock_value_set = MagicMock(return_value=True) with patch.dict(win_snmp.__salt__, {'win_snmp.get_agent_settings': mock_value_get, 'win_snmp.set_agent_settings': mock_value_set}): with patch.dict(win_snmp.__opts__, {'test': False}): self.assertEqual(win_snmp.agent_settings(**kwargs), ret)
'Test - Manage the sending of authentication traps.'
def test_auth_traps_enabled(self):
kwargs = {'name': 'auth-traps', 'status': True} ret = {'name': kwargs['name'], 'changes': {'old': False, 'new': True}, 'comment': 'Set EnableAuthenticationTraps to contain the provided value.', 'result': True} mock_value_get = MagicMock(return_value=False) mock_value_set = MagicMock(return_value=True) with patch.dict(win_snmp.__salt__, {'win_snmp.get_auth_traps_enabled': mock_value_get, 'win_snmp.set_auth_traps_enabled': mock_value_set}): with patch.dict(win_snmp.__opts__, {'test': False}): self.assertEqual(win_snmp.auth_traps_enabled(**kwargs), ret) with patch.dict(win_snmp.__opts__, {'test': True}): ret['comment'] = 'EnableAuthenticationTraps will be changed.' ret['result'] = None self.assertEqual(win_snmp.auth_traps_enabled(**kwargs), ret)
'Test - Manage the SNMP accepted community names and their permissions.'
def test_community_names(self):
kwargs = {'name': 'community-names', 'communities': {'TestCommunity': 'Read Create'}} ret = {'name': kwargs['name'], 'changes': {}, 'comment': 'Communities already contain the provided values.', 'result': True} mock_value_get = MagicMock(return_value=kwargs['communities']) mock_value_set = MagicMock(return_value=True) with patch.dict(win_snmp.__salt__, {'win_snmp.get_community_names': mock_value_get, 'win_snmp.set_community_names': mock_value_set}): with patch.dict(win_snmp.__opts__, {'test': False}): self.assertEqual(win_snmp.community_names(**kwargs), ret)
'Test to create a virtualenv and optionally manage it with pip'
def test_managed(self):
ret = {'name': 'salt', 'changes': {}, 'result': False, 'comment': ''} ret.update({'comment': 'Virtualenv was not detected on this system'}) self.assertDictEqual(virtualenv_mod.managed('salt'), ret) mock1 = MagicMock(return_value='True') mock = MagicMock(return_value=False) mock2 = MagicMock(return_value='1.1') with patch.dict(virtualenv_mod.__salt__, {'virtualenv.create': True, 'cp.is_cached': mock, 'cp.cache_file': mock, 'cp.hash_file': mock, 'pip.freeze': mock1, 'cmd.run_stderr': mock1, 'pip.version': mock2}): mock = MagicMock(side_effect=[True, True, True, False, True, True]) with patch.object(os.path, 'exists', mock): ret.update({'comment': "pip requirements file 'salt://a' not found"}) self.assertDictEqual(virtualenv_mod.managed('salt', None, 'salt://a'), ret) with patch.dict(virtualenv_mod.__opts__, {'test': True}): ret.update({'changes': {'cleared_packages': 'True', 'old': 'True'}, 'comment': 'Virtualenv salt is set to be cleared', 'result': None}) self.assertDictEqual(virtualenv_mod.managed('salt', clear=1), ret) ret.update({'comment': 'Virtualenv salt is already created', 'changes': {}, 'result': True}) self.assertDictEqual(virtualenv_mod.managed('salt'), ret) ret.update({'comment': 'Virtualenv salt is set to be created', 'result': None}) self.assertDictEqual(virtualenv_mod.managed('salt'), ret) with patch.dict(virtualenv_mod.__opts__, {'test': False}): ret.update({'comment': "The 'use_wheel' option is only supported in pip 1.4 and newer. The version of pip detected was 1.1.", 'result': False}) self.assertDictEqual(virtualenv_mod.managed('salt', use_wheel=1), ret) ret.update({'comment': 'virtualenv exists', 'result': True}) self.assertDictEqual(virtualenv_mod.managed('salt'), ret)
'Test adding a certificate to specified certificate store'
def test_add_serial(self):
expected = {'changes': {'added': '/path/to/cert.cer'}, 'comment': '', 'name': '/path/to/cert.cer', 'result': True} cache_mock = MagicMock(return_value='/tmp/cert.cer') get_cert_serial_mock = MagicMock(return_value='ABCDEF') get_store_serials_mock = MagicMock(return_value=['123456']) add_mock = MagicMock(return_value='Added successfully') with patch.dict(certutil.__salt__, {'cp.cache_file': cache_mock, 'certutil.get_cert_serial': get_cert_serial_mock, 'certutil.get_stored_cert_serials': get_store_serials_mock, 'certutil.add_store': add_mock}): out = certutil.add_store('/path/to/cert.cer', 'TrustedPublisher') cache_mock.assert_called_once_with('/path/to/cert.cer', 'base') get_cert_serial_mock.assert_called_once_with('/tmp/cert.cer') get_store_serials_mock.assert_called_once_with('TrustedPublisher') add_mock.assert_called_once_with('/path/to/cert.cer', 'TrustedPublisher') self.assertEqual(expected, out)
'Test adding a certificate to specified certificate store when the file doesn\'t exist'
def test_add_serial_missing(self):
expected = {'changes': {}, 'comment': 'Certificate file not found.', 'name': '/path/to/cert.cer', 'result': False} cache_mock = MagicMock(return_value=False) get_cert_serial_mock = MagicMock(return_value='ABCDEF') get_store_serials_mock = MagicMock(return_value=['123456']) add_mock = MagicMock(return_value='Added successfully') with patch.dict(certutil.__salt__, {'cp.cache_file': cache_mock, 'certutil.get_cert_serial': get_cert_serial_mock, 'certutil.get_stored_cert_serials': get_store_serials_mock, 'certutil.add_store': add_mock}): out = certutil.add_store('/path/to/cert.cer', 'TrustedPublisher') cache_mock.assert_called_once_with('/path/to/cert.cer', 'base') assert (not get_cert_serial_mock.called) assert (not get_store_serials_mock.called) assert (not add_mock.called) self.assertEqual(expected, out)
'Test adding a certificate to specified certificate store when the cert already exists'
def test_add_serial_exists(self):
expected = {'changes': {}, 'comment': '/path/to/cert.cer already stored.', 'name': '/path/to/cert.cer', 'result': True} cache_mock = MagicMock(return_value='/tmp/cert.cer') get_cert_serial_mock = MagicMock(return_value='ABCDEF') get_store_serials_mock = MagicMock(return_value=['123456', 'ABCDEF']) add_mock = MagicMock(return_value='Added successfully') with patch.dict(certutil.__salt__, {'cp.cache_file': cache_mock, 'certutil.get_cert_serial': get_cert_serial_mock, 'certutil.get_stored_cert_serials': get_store_serials_mock, 'certutil.add_store': add_mock}): out = certutil.add_store('/path/to/cert.cer', 'TrustedPublisher') cache_mock.assert_called_once_with('/path/to/cert.cer', 'base') get_cert_serial_mock.assert_called_once_with('/tmp/cert.cer') get_store_serials_mock.assert_called_once_with('TrustedPublisher') assert (not add_mock.called) self.assertEqual(expected, out)
'Test adding a certificate when the add fails'
def test_add_serial_fail(self):
expected = {'changes': {}, 'comment': 'Failed to store certificate /path/to/cert.cer', 'name': '/path/to/cert.cer', 'result': False} cache_mock = MagicMock(return_value='/tmp/cert.cer') get_cert_serial_mock = MagicMock(return_value='ABCDEF') get_store_serials_mock = MagicMock(return_value=['123456']) add_mock = MagicMock(return_value='Failed') with patch.dict(certutil.__salt__, {'cp.cache_file': cache_mock, 'certutil.get_cert_serial': get_cert_serial_mock, 'certutil.get_stored_cert_serials': get_store_serials_mock, 'certutil.add_store': add_mock}): out = certutil.add_store('/path/to/cert.cer', 'TrustedPublisher') cache_mock.assert_called_once_with('/path/to/cert.cer', 'base') get_cert_serial_mock.assert_called_once_with('/tmp/cert.cer') get_store_serials_mock.assert_called_once_with('TrustedPublisher') add_mock.assert_called_once_with('/path/to/cert.cer', 'TrustedPublisher') self.assertEqual(expected, out)
'Test deleting a certificate from a specified certificate store'
def test_del_serial(self):
expected = {'changes': {'removed': '/path/to/cert.cer'}, 'comment': '', 'name': '/path/to/cert.cer', 'result': True} cache_mock = MagicMock(return_value='/tmp/cert.cer') get_cert_serial_mock = MagicMock(return_value='ABCDEF') get_store_serials_mock = MagicMock(return_value=['123456', 'ABCDEF']) del_mock = MagicMock(return_value='Removed successfully') with patch.dict(certutil.__salt__, {'cp.cache_file': cache_mock, 'certutil.get_cert_serial': get_cert_serial_mock, 'certutil.get_stored_cert_serials': get_store_serials_mock, 'certutil.del_store': del_mock}): out = certutil.del_store('/path/to/cert.cer', 'TrustedPublisher') cache_mock.assert_called_once_with('/path/to/cert.cer', 'base') get_cert_serial_mock.assert_called_once_with('/tmp/cert.cer') get_store_serials_mock.assert_called_once_with('TrustedPublisher') del_mock.assert_called_once_with('/tmp/cert.cer', 'TrustedPublisher') self.assertEqual(expected, out)
'Test deleting a certificate to specified certificate store when the file doesn\'t exist'
def test_del_serial_missing(self):
expected = {'changes': {}, 'comment': 'Certificate file not found.', 'name': '/path/to/cert.cer', 'result': False} cache_mock = MagicMock(return_value=False) get_cert_serial_mock = MagicMock(return_value='ABCDEF') get_store_serials_mock = MagicMock(return_value=['123456']) del_mock = MagicMock(return_value='Added successfully') with patch.dict(certutil.__salt__, {'cp.cache_file': cache_mock, 'certutil.get_cert_serial': get_cert_serial_mock, 'certutil.get_stored_cert_serials': get_store_serials_mock, 'certutil.del_store': del_mock}): out = certutil.del_store('/path/to/cert.cer', 'TrustedPublisher') cache_mock.assert_called_once_with('/path/to/cert.cer', 'base') assert (not get_cert_serial_mock.called) assert (not get_store_serials_mock.called) assert (not del_mock.called) self.assertEqual(expected, out)
'Test deleting a certificate to specified certificate store when the cert doesn\'t exists'
def test_del_serial_doesnt_exists(self):
expected = {'changes': {}, 'comment': '/path/to/cert.cer already removed.', 'name': '/path/to/cert.cer', 'result': True} cache_mock = MagicMock(return_value='/tmp/cert.cer') get_cert_serial_mock = MagicMock(return_value='ABCDEF') get_store_serials_mock = MagicMock(return_value=['123456']) del_mock = MagicMock(return_value='Added successfully') with patch.dict(certutil.__salt__, {'cp.cache_file': cache_mock, 'certutil.get_cert_serial': get_cert_serial_mock, 'certutil.get_stored_cert_serials': get_store_serials_mock, 'certutil.del_store': del_mock}): out = certutil.del_store('/path/to/cert.cer', 'TrustedPublisher') cache_mock.assert_called_once_with('/path/to/cert.cer', 'base') get_cert_serial_mock.assert_called_once_with('/tmp/cert.cer') get_store_serials_mock.assert_called_once_with('TrustedPublisher') assert (not del_mock.called) self.assertEqual(expected, out)
'Test deleting a certificate from the store when the delete fails'
def test_del_serial_fail(self):
expected = {'changes': {}, 'comment': 'Failed to remove the certificate /path/to/cert.cer', 'name': '/path/to/cert.cer', 'result': False} cache_mock = MagicMock(return_value='/tmp/cert.cer') get_cert_serial_mock = MagicMock(return_value='ABCDEF') get_store_serials_mock = MagicMock(return_value=['123456', 'ABCDEF']) del_mock = MagicMock(return_value='Failed') with patch.dict(certutil.__salt__, {'cp.cache_file': cache_mock, 'certutil.get_cert_serial': get_cert_serial_mock, 'certutil.get_stored_cert_serials': get_store_serials_mock, 'certutil.del_store': del_mock}): out = certutil.del_store('/path/to/cert.cer', 'TrustedPublisher') cache_mock.assert_called_once_with('/path/to/cert.cer', 'base') get_cert_serial_mock.assert_called_once_with('/tmp/cert.cer') get_store_serials_mock.assert_called_once_with('TrustedPublisher') del_mock.assert_called_once_with('/tmp/cert.cer', 'TrustedPublisher') self.assertEqual(expected, out)
'Test to ensure that the named database is absent.'
def test_absent(self):
name = 'mydb' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} mock = MagicMock(side_effect=[True, True, False]) mock_t = MagicMock(return_value=True) with patch.dict(mongodb_database.__salt__, {'mongodb.db_exists': mock, 'mongodb.db_remove': mock_t}): with patch.dict(mongodb_database.__opts__, {'test': True}): comt = 'Database {0} is present and needs to be removed'.format(name) ret.update({'comment': comt}) self.assertDictEqual(mongodb_database.absent(name), ret) with patch.dict(mongodb_database.__opts__, {'test': False}): comt = 'Database {0} has been removed'.format(name) ret.update({'comment': comt, 'result': True, 'changes': {'mydb': 'Absent'}}) self.assertDictEqual(mongodb_database.absent(name), ret) comt = 'User {0} is not present, so it cannot be removed'.format(name) ret.update({'comment': comt, 'changes': {}}) self.assertDictEqual(mongodb_database.absent(name), ret)
'Setup data for the tests'
def setUp(self):
self.name = 'plpgsql' self.ret = {'name': self.name, 'changes': {}, 'result': False, 'comment': ''} self.mock_true = MagicMock(return_value=True) self.mock_false = MagicMock(return_value=False) self.mock_empty_language_list = MagicMock(return_value={}) self.mock_language_list = MagicMock(return_value={'plpgsql': self.name})
'Test present, language is already present in database'
def test_present_existing(self):
with patch.dict(postgres_language.__salt__, {'postgres.language_list': self.mock_language_list}): comt = 'Language {0} is already installed'.format(self.name) self.ret.update({'comment': comt, 'result': True}) self.assertDictEqual(postgres_language.present(self.name, 'testdb'), self.ret)
'Test present, language not present in database - pass'
def test_present_non_existing_pass(self):
with patch.dict(postgres_language.__salt__, {'postgres.language_list': self.mock_empty_language_list, 'postgres.language_create': self.mock_true}): with patch.dict(postgres_language.__opts__, {'test': True}): comt = 'Language {0} is set to be installed'.format(self.name) self.ret.update({'comment': comt, 'result': None}) self.assertDictEqual(postgres_language.present(self.name, 'testdb'), self.ret) with patch.dict(postgres_language.__opts__, {'test': False}): comt = 'Language {0} has been installed'.format(self.name) self.ret.update({'comment': comt, 'result': True, 'changes': {'plpgsql': 'Present'}}) self.assertDictEqual(postgres_language.present(self.name, 'testdb'), self.ret)
'Test present, language not present in database - fail'
def test_present_non_existing_fail(self):
with patch.dict(postgres_language.__salt__, {'postgres.language_list': self.mock_empty_language_list, 'postgres.language_create': self.mock_false}): with patch.dict(postgres_language.__opts__, {'test': True}): comt = 'Language {0} is set to be installed'.format(self.name) self.ret.update({'comment': comt, 'result': None}) self.assertDictEqual(postgres_language.present(self.name, 'testdb'), self.ret) with patch.dict(postgres_language.__opts__, {'test': False}): comt = 'Failed to install language {0}'.format(self.name) self.ret.update({'comment': comt, 'result': False}) self.assertDictEqual(postgres_language.present(self.name, 'testdb'), self.ret)
'Test absent, language present in database'
def test_absent_existing(self):
with patch.dict(postgres_language.__salt__, {'postgres.language_exists': self.mock_true, 'postgres.language_remove': self.mock_true}): with patch.dict(postgres_language.__opts__, {'test': True}): comt = 'Language {0} is set to be removed'.format(self.name) self.ret.update({'comment': comt, 'result': None}) self.assertDictEqual(postgres_language.absent(self.name, 'testdb'), self.ret) with patch.dict(postgres_language.__opts__, {'test': False}): comt = 'Language {0} has been removed'.format(self.name) self.ret.update({'comment': comt, 'result': True, 'changes': {'plpgsql': 'Absent'}}) self.assertDictEqual(postgres_language.absent(self.name, 'testdb'), self.ret)
'Test absent, language not present in database'
def test_absent_non_existing(self):
with patch.dict(postgres_language.__salt__, {'postgres.language_exists': self.mock_false}): with patch.dict(postgres_language.__opts__, {'test': True}): comt = 'Language {0} is not present so it cannot be removed'.format(self.name) self.ret.update({'comment': comt, 'result': True}) self.assertDictEqual(postgres_language.absent(self.name, 'testdb'), self.ret)
'Test to ensure key pair is present.'
def test_key_present(self):
name = 'mykeypair' upublic = 'salt://mybase/public_key.pub' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} mock = MagicMock(side_effect=[True, False, False]) mock_bool = MagicMock(side_effect=[IOError, True]) with patch.dict(boto_ec2.__salt__, {'boto_ec2.get_key': mock, 'cp.get_file_str': mock_bool}): comt = 'The key name {0} already exists'.format(name) ret.update({'comment': comt}) self.assertDictEqual(boto_ec2.key_present(name), ret) comt = 'File {0} not found.'.format(upublic) ret.update({'comment': comt, 'result': False}) self.assertDictEqual(boto_ec2.key_present(name, upload_public=upublic), ret) with patch.dict(boto_ec2.__opts__, {'test': True}): comt = 'The key {0} is set to be created.'.format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(boto_ec2.key_present(name, upload_public=upublic), ret)
'Test to deletes a key pair'
def test_key_absent(self):
name = 'new_table' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} mock = MagicMock(side_effect=[False, True]) with patch.dict(boto_ec2.__salt__, {'boto_ec2.get_key': mock}): comt = 'The key name {0} does not exist'.format(name) ret.update({'comment': comt}) self.assertDictEqual(boto_ec2.key_absent(name), ret) with patch.dict(boto_ec2.__opts__, {'test': True}): comt = 'The key {0} is set to be deleted.'.format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(boto_ec2.key_absent(name), ret)
'Test to ensure that the named user is present with the specified privileges.'
def test_present(self):
name = 'frank' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} mock_t = MagicMock(return_value=True) mock = MagicMock(return_value=None) with patch.dict(postgres_user.__salt__, {'postgres.role_get': mock, 'postgres.user_create': mock_t}): with patch.dict(postgres_user.__opts__, {'test': True}): comt = 'User {0} is set to be created'.format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(postgres_user.present(name), ret) with patch.dict(postgres_user.__opts__, {'test': False}): comt = 'The user {0} has been created'.format(name) ret.update({'comment': comt, 'result': True, 'changes': {name: 'Present'}}) self.assertDictEqual(postgres_user.present(name), ret)
'Test to ensure that the named user is absent.'
def test_absent(self):
name = 'frank' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} mock_t = MagicMock(return_value=True) mock = MagicMock(side_effect=[True, True, False]) with patch.dict(postgres_user.__salt__, {'postgres.user_exists': mock, 'postgres.user_remove': mock_t}): with patch.dict(postgres_user.__opts__, {'test': True}): comt = 'User {0} is set to be removed'.format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(postgres_user.absent(name), ret) with patch.dict(postgres_user.__opts__, {'test': False}): comt = 'User {0} has been removed'.format(name) ret.update({'comment': comt, 'result': True, 'changes': {name: 'Absent'}}) self.assertDictEqual(postgres_user.absent(name), ret) comt = 'User {0} is not present, so it cannot be removed'.format(name) ret.update({'comment': comt, 'result': True, 'changes': {}}) self.assertDictEqual(postgres_user.absent(name), ret)
'scenario of creating upgrading extensions with possible schema and version specifications'
def test_present_failed(self):
with patch.dict(postgres_extension.__salt__, {'postgres.create_metadata': Mock(side_effect=[[postgresmod._EXTENSION_NOT_INSTALLED], [postgresmod._EXTENSION_TO_MOVE, postgresmod._EXTENSION_INSTALLED]]), 'postgres.create_extension': Mock(side_effect=[False, False])}): ret = postgres_extension.present('foo') self.assertEqual(ret, {'comment': 'Failed to install extension foo', 'changes': {}, 'name': 'foo', 'result': False}) ret = postgres_extension.present('foo') self.assertEqual(ret, {'comment': 'Failed to upgrade extension foo', 'changes': {}, 'name': 'foo', 'result': False})
'scenario of creating upgrading extensions with possible schema and version specifications'
def test_present(self):
with patch.dict(postgres_extension.__salt__, {'postgres.create_metadata': Mock(side_effect=[[postgresmod._EXTENSION_NOT_INSTALLED], [postgresmod._EXTENSION_INSTALLED], [postgresmod._EXTENSION_TO_MOVE, postgresmod._EXTENSION_INSTALLED]]), 'postgres.create_extension': Mock(side_effect=[True, True, True])}): ret = postgres_extension.present('foo') self.assertEqual(ret, {'comment': 'The extension foo has been installed', 'changes': {'foo': 'Installed'}, 'name': 'foo', 'result': True}) ret = postgres_extension.present('foo') self.assertEqual(ret, {'comment': 'Extension foo is already present', 'changes': {}, 'name': 'foo', 'result': True}) ret = postgres_extension.present('foo') self.assertEqual(ret, {'comment': 'The extension foo has been upgraded', 'changes': {'foo': 'Upgraded'}, 'name': 'foo', 'result': True})
'scenario of creating upgrading extensions with possible schema and version specifications'
def test_presenttest(self):
with patch.dict(postgres_extension.__salt__, {'postgres.create_metadata': Mock(side_effect=[[postgresmod._EXTENSION_NOT_INSTALLED], [postgresmod._EXTENSION_INSTALLED], [postgresmod._EXTENSION_TO_MOVE, postgresmod._EXTENSION_INSTALLED]]), 'postgres.create_extension': Mock(side_effect=[True, True, True])}): with patch.dict(postgres_extension.__opts__, {'test': True}): ret = postgres_extension.present('foo') self.assertEqual(ret, {'comment': 'Extension foo is set to be installed', 'changes': {}, 'name': 'foo', 'result': None}) ret = postgres_extension.present('foo') self.assertEqual(ret, {'comment': 'Extension foo is set to be created', 'changes': {}, 'name': 'foo', 'result': None}) ret = postgres_extension.present('foo') self.assertEqual(ret, {'comment': 'Extension foo is set to be upgraded', 'changes': {}, 'name': 'foo', 'result': None})
'scenario of creating upgrading extensions with possible schema and version specifications'
def test_absent(self):
with patch.dict(postgres_extension.__salt__, {'postgres.is_installed_extension': Mock(side_effect=[True, False]), 'postgres.drop_extension': Mock(side_effect=[True, True])}): ret = postgres_extension.absent('foo') self.assertEqual(ret, {'comment': 'Extension foo has been removed', 'changes': {'foo': 'Absent'}, 'name': 'foo', 'result': True}) ret = postgres_extension.absent('foo') self.assertEqual(ret, {'comment': 'Extension foo is not present, so it cannot be removed', 'changes': {}, 'name': 'foo', 'result': True})