desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'TestCse for salt.modules.boto_apigateway state.module, checking that if __opts__[\'test\'] is set and usage plan does not exist, correct diagnostic will be returned'
def test_usage_plan_present_if_there_is_no_such_plan_and_test_option_is_set(self, *args):
with patch.dict(boto_apigateway.__opts__, {'test': True}): with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(return_value={'plans': []})}): result = boto_apigateway.usage_plan_present('name', 'plan_name', **conn_parameters) self.assertIn('comment', result) self.assertEqual(result['comment'], 'a new usage plan plan_name would be created') self.assertIn('result', result) self.assertEqual(result['result'], None)
'Tests behavior for the case when creating a new usage plan fails'
def test_usage_plan_present_if_create_usage_plan_fails(self, *args):
with patch.dict(boto_apigateway.__opts__, {'test': False}): with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(return_value={'plans': []}), 'boto_apigateway.create_usage_plan': MagicMock(return_value={'error': 'error'})}): result = boto_apigateway.usage_plan_present('name', 'plan_name', **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], False) self.assertIn('comment', result) self.assertEqual(result['comment'], 'Failed to create a usage plan plan_name, error') self.assertIn('changes', result) self.assertEqual(result['changes'], {})
'Tests behavior for the case when plan is present and needs no updates'
def test_usage_plan_present_if_plan_is_there_and_needs_no_updates(self, *args):
with patch.dict(boto_apigateway.__opts__, {'test': False}): with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(return_value={'plans': [{'id': 'planid', 'name': 'planname'}]}), 'boto_apigateway.update_usage_plan': MagicMock()}): result = boto_apigateway.usage_plan_present('name', 'plan_name', **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], True) self.assertIn('comment', result) self.assertEqual(result['comment'], 'usage plan plan_name is already in a correct state') self.assertIn('changes', result) self.assertEqual(result['changes'], {}) self.assertTrue((boto_apigateway.__salt__['boto_apigateway.update_usage_plan'].call_count == 0))
'Tests behavior when usage plan needs to be updated by tests option is set'
def test_usage_plan_present_if_plan_is_there_and_needs_updates_but_test_is_set(self, *args):
with patch.dict(boto_apigateway.__opts__, {'test': True}): with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(return_value={'plans': [{'id': 'planid', 'name': 'planname', 'throttle': {'rateLimit': 10.0}}]}), 'boto_apigateway.update_usage_plan': MagicMock()}): result = boto_apigateway.usage_plan_present('name', 'plan_name', **conn_parameters) self.assertIn('comment', result) self.assertEqual(result['comment'], 'a new usage plan plan_name would be updated') self.assertIn('result', result) self.assertEqual(result['result'], None) self.assertTrue((boto_apigateway.__salt__['boto_apigateway.update_usage_plan'].call_count == 0))
'Tests error processing for the case when updating an existing usage plan fails'
def test_usage_plan_present_if_plan_is_there_and_needs_updates_but_update_fails(self, *args):
with patch.dict(boto_apigateway.__opts__, {'test': False}): with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(return_value={'plans': [{'id': 'planid', 'name': 'planname', 'throttle': {'rateLimit': 10.0}}]}), 'boto_apigateway.update_usage_plan': MagicMock(return_value={'error': 'error'})}): result = boto_apigateway.usage_plan_present('name', 'plan_name', **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], False) self.assertIn('comment', result) self.assertEqual(result['comment'], 'Failed to update a usage plan plan_name, error')
'Tests successful case for creating a new usage plan'
def test_usage_plan_present_if_plan_has_been_created(self, *args):
with patch.dict(boto_apigateway.__opts__, {'test': False}): with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(side_effect=[{'plans': []}, {'plans': [{'id': 'id'}]}]), 'boto_apigateway.create_usage_plan': MagicMock(return_value={'created': True})}): result = boto_apigateway.usage_plan_present('name', 'plan_name', **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], True) self.assertIn('comment', result) self.assertEqual(result['comment'], 'A new usage plan plan_name has been created') self.assertEqual(result['changes']['old'], {'plan': None}) self.assertEqual(result['changes']['new'], {'plan': {'id': 'id'}})
'Tests successful case for updating a usage plan'
def test_usage_plan_present_if_plan_has_been_updated(self, *args):
with patch.dict(boto_apigateway.__opts__, {'test': False}): with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(side_effect=[{'plans': [{'id': 'id'}]}, {'plans': [{'id': 'id', 'throttle': {'rateLimit': throttle_rateLimit}}]}]), 'boto_apigateway.update_usage_plan': MagicMock(return_value={'updated': True})}): result = boto_apigateway.usage_plan_present('name', 'plan_name', throttle={'rateLimit': throttle_rateLimit}, **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], True) self.assertIn('comment', result) self.assertEqual(result['comment'], 'usage plan plan_name has been updated') self.assertEqual(result['changes']['old'], {'plan': {'id': 'id'}}) self.assertEqual(result['changes']['new'], {'plan': {'id': 'id', 'throttle': {'rateLimit': throttle_rateLimit}}})
'Tests error processing for the case when ValueError is raised when creating a usage plan'
def test_usage_plan_present_if_ValueError_is_raised(self, *args):
with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(side_effect=ValueError('error'))}): result = boto_apigateway.usage_plan_present('name', 'plan_name', throttle={'rateLimit': throttle_rateLimit}, **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], False) self.assertIn('comment', result) self.assertEqual(result['comment'], "('error',)")
'Tests error processing for the case when IOError is raised when creating a usage plan'
def test_usage_plan_present_if_IOError_is_raised(self, *args):
with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(side_effect=IOError('error'))}): result = boto_apigateway.usage_plan_present('name', 'plan_name', throttle={'rateLimit': throttle_rateLimit}, **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], False) self.assertIn('comment', result) self.assertEqual(result['comment'], "('error',)")
'Tests correct error processing for describe_usage_plan failure'
def test_usage_plan_absent_if_describe_fails(self, *args):
with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(return_value={'error': 'error'})}): result = {} result = boto_apigateway.usage_plan_absent('name', 'plan_name', **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], False) self.assertIn('comment', result) self.assertEqual(result['comment'], 'Failed to describe existing usage plans') self.assertIn('changes', result) self.assertEqual(result['changes'], {})
'Tests behavior for the case when the plan that needs to be absent does not exist'
def test_usage_plan_absent_if_plan_is_not_present(self, *args):
with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(return_value={'plans': []})}): result = {} result = boto_apigateway.usage_plan_absent('name', 'plan_name', **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], True) self.assertIn('comment', result) self.assertEqual(result['comment'], 'Usage plan plan_name does not exist already') self.assertIn('changes', result) self.assertEqual(result['changes'], {})
'Tests behavior for the case when usage plan needs to be deleted by tests option is set'
def test_usage_plan_absent_if_plan_is_present_but_test_option_is_set(self, *args):
with patch.dict(boto_apigateway.__opts__, {'test': True}): with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(return_value={'plans': [{'id': 'id'}]})}): result = {} result = boto_apigateway.usage_plan_absent('name', 'plan_name', **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], None) self.assertIn('comment', result) self.assertEqual(result['comment'], 'Usage plan plan_name exists and would be deleted') self.assertIn('changes', result) self.assertEqual(result['changes'], {})
'Tests correct error processing when deleting a usage plan fails'
def test_usage_plan_absent_if_plan_is_present_but_delete_fails(self, *args):
with patch.dict(boto_apigateway.__opts__, {'test': False}): with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(return_value={'plans': [{'id': 'id'}]}), 'boto_apigateway.delete_usage_plan': MagicMock(return_value={'error': 'error'})}): result = boto_apigateway.usage_plan_absent('name', 'plan_name', **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], False) self.assertIn('comment', result) self.assertEqual(result['comment'], "Failed to delete usage plan plan_name, {'error': 'error'}") self.assertIn('changes', result) self.assertEqual(result['changes'], {})
'Tests successful case for deleting a usage plan'
def test_usage_plan_absent_if_plan_has_been_deleted(self, *args):
with patch.dict(boto_apigateway.__opts__, {'test': False}): with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(return_value={'plans': [{'id': 'id'}]}), 'boto_apigateway.delete_usage_plan': MagicMock(return_value={'deleted': True})}): result = boto_apigateway.usage_plan_absent('name', 'plan_name', **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], True) self.assertIn('comment', result) self.assertEqual(result['comment'], 'Usage plan plan_name has been deleted') self.assertIn('changes', result) self.assertEqual(result['changes'], {'new': {'plan': None}, 'old': {'plan': {'id': 'id'}}})
'Tests correct error processing for the case when ValueError is raised when deleting a usage plan'
def test_usage_plan_absent_if_ValueError_is_raised(self, *args):
with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(side_effect=ValueError('error'))}): result = boto_apigateway.usage_plan_absent('name', 'plan_name', **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], False) self.assertIn('comment', result) self.assertEqual(result['comment'], "('error',)")
'Tests correct error processing for the case when IOError is raised when deleting a usage plan'
def test_usage_plan_absent_if_IOError_is_raised(self, *args):
with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(side_effect=IOError('error'))}): result = boto_apigateway.usage_plan_absent('name', 'plan_name', **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], False) self.assertIn('comment', result) self.assertEqual(result['comment'], "('error',)")
'Tests correct error processing for describe_usage_plan failure'
def test_usage_plan_association_present_if_describe_fails(self, *args):
with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(return_value={'error': 'error'})}): result = boto_apigateway.usage_plan_association_present('name', 'plan_name', [association_stage_1], **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], False) self.assertIn('comment', result) self.assertEqual(result['comment'], 'Failed to describe existing usage plans') self.assertIn('changes', result) self.assertEqual(result['changes'], {})
'Tests correct error processing if a plan for which association has been requested is not present'
def test_usage_plan_association_present_if_plan_is_not_present(self, *args):
with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(return_value={'plans': []})}): result = boto_apigateway.usage_plan_association_present('name', 'plan_name', [association_stage_1], **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], False) self.assertIn('comment', result) self.assertEqual(result['comment'], 'Usage plan plan_name does not exist') self.assertIn('changes', result) self.assertEqual(result['changes'], {})
'Tests correct error processing for the case when multiple plans with the same name exist'
def test_usage_plan_association_present_if_multiple_plans_with_the_same_name_exist(self, *args):
with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(return_value={'plans': [{'id': 'id1'}, {'id': 'id2'}]})}): result = boto_apigateway.usage_plan_association_present('name', 'plan_name', [association_stage_1], **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], False) self.assertIn('comment', result) self.assertEqual(result['comment'], 'There are multiple usage plans with the same name - it is not supported') self.assertIn('changes', result) self.assertEqual(result['changes'], {})
'Tests the behavior for the case when requested association is already present'
def test_usage_plan_association_present_if_association_already_exists(self, *args):
with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(return_value={'plans': [{'id': 'id1', 'apiStages': [association_stage_1]}]})}): result = boto_apigateway.usage_plan_association_present('name', 'plan_name', [association_stage_1], **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], True) self.assertIn('comment', result) self.assertEqual(result['comment'], 'Usage plan is already asssociated to all api stages') self.assertIn('changes', result) self.assertEqual(result['changes'], {})
'Tests correct error processing for the case when adding associations fails'
def test_usage_plan_association_present_if_update_fails(self, *args):
with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(return_value={'plans': [{'id': 'id1', 'apiStages': [association_stage_1]}]}), 'boto_apigateway.attach_usage_plan_to_apis': MagicMock(return_value={'error': 'error'})}): result = boto_apigateway.usage_plan_association_present('name', 'plan_name', [association_stage_2], **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], False) self.assertIn('comment', result) self.assertTrue(result['comment'].startswith('Failed to associate a usage plan')) self.assertIn('changes', result) self.assertEqual(result['changes'], {})
'Tests successful case for adding usage plan associations to a given api stage'
def test_usage_plan_association_present_success(self, *args):
with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(return_value={'plans': [{'id': 'id1', 'apiStages': [association_stage_1]}]}), 'boto_apigateway.attach_usage_plan_to_apis': MagicMock(return_value={'result': {'apiStages': [association_stage_1, association_stage_2]}})}): result = boto_apigateway.usage_plan_association_present('name', 'plan_name', [association_stage_2], **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], True) self.assertIn('comment', result) self.assertEqual(result['comment'], 'successfully associated usage plan to apis') self.assertIn('changes', result) self.assertEqual(result['changes'], {'new': [association_stage_1, association_stage_2], 'old': [association_stage_1]})
'Tests correct error processing for the case when IOError is raised while trying to set usage plan associations'
def test_usage_plan_association_present_if_value_error_is_thrown(self, *args):
with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(side_effect=ValueError('error'))}): result = boto_apigateway.usage_plan_association_present('name', 'plan_name', [], **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], False) self.assertIn('comment', result) self.assertEqual(result['comment'], "('error',)") self.assertIn('changes', result) self.assertEqual(result['changes'], {})
'Tests correct error processing for the case when IOError is raised while trying to set usage plan associations'
def test_usage_plan_association_present_if_io_error_is_thrown(self, *args):
with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(side_effect=IOError('error'))}): result = boto_apigateway.usage_plan_association_present('name', 'plan_name', [], **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], False) self.assertIn('comment', result) self.assertEqual(result['comment'], "('error',)") self.assertIn('changes', result) self.assertEqual(result['changes'], {})
'Tests correct error processing for describe_usage_plan failure'
def test_usage_plan_association_absent_if_describe_fails(self, *args):
with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(return_value={'error': 'error'})}): result = boto_apigateway.usage_plan_association_absent('name', 'plan_name', [association_stage_1], **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], False) self.assertIn('comment', result) self.assertEqual(result['comment'], 'Failed to describe existing usage plans') self.assertIn('changes', result) self.assertEqual(result['changes'], {})
'Tests error processing for the case when plan for which associations need to be modified is not present'
def test_usage_plan_association_absent_if_plan_is_not_present(self, *args):
with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(return_value={'plans': []})}): result = boto_apigateway.usage_plan_association_absent('name', 'plan_name', [association_stage_1], **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], False) self.assertIn('comment', result) self.assertEqual(result['comment'], 'Usage plan plan_name does not exist') self.assertIn('changes', result) self.assertEqual(result['changes'], {})
'Tests the case when there are multiple plans with the same name but different Ids'
def test_usage_plan_association_absent_if_multiple_plans_with_the_same_name_exist(self, *args):
with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(return_value={'plans': [{'id': 'id1'}, {'id': 'id2'}]})}): result = boto_apigateway.usage_plan_association_absent('name', 'plan_name', [association_stage_1], **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], False) self.assertIn('comment', result) self.assertEqual(result['comment'], 'There are multiple usage plans with the same name - it is not supported') self.assertIn('changes', result) self.assertEqual(result['changes'], {})
'Tests the case when the plan has no associations at all'
def test_usage_plan_association_absent_if_plan_has_no_associations(self, *args):
with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(return_value={'plans': [{'id': 'id1', 'apiStages': []}]})}): result = boto_apigateway.usage_plan_association_absent('name', 'plan_name', [association_stage_1], **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], True) self.assertIn('comment', result) self.assertEqual(result['comment'], 'Usage plan plan_name has no associated stages already') self.assertIn('changes', result) self.assertEqual(result['changes'], {})
'Tests the case when requested association is not present already'
def test_usage_plan_association_absent_if_plan_has_no_specific_association(self, *args):
with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(return_value={'plans': [{'id': 'id1', 'apiStages': [association_stage_1]}]})}): result = boto_apigateway.usage_plan_association_absent('name', 'plan_name', [association_stage_2], **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], True) self.assertIn('comment', result) self.assertEqual(result['comment'], 'Usage plan is already not asssociated to any api stages') self.assertIn('changes', result) self.assertEqual(result['changes'], {})
'Tests correct error processing when detaching the usage plan from the api function is called'
def test_usage_plan_association_absent_if_detaching_association_fails(self, *args):
with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(return_value={'plans': [{'id': 'id1', 'apiStages': [association_stage_1, association_stage_2]}]}), 'boto_apigateway.detach_usage_plan_from_apis': MagicMock(return_value={'error': 'error'})}): result = boto_apigateway.usage_plan_association_absent('name', 'plan_name', [association_stage_2], **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], False) self.assertIn('comment', result) self.assertTrue(result['comment'].startswith('Failed to disassociate a usage plan plan_name from the apis')) self.assertIn('changes', result) self.assertEqual(result['changes'], {})
'Tests successful case of disaccosiation the usage plan from api stages'
def test_usage_plan_association_absent_success(self, *args):
with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(return_value={'plans': [{'id': 'id1', 'apiStages': [association_stage_1, association_stage_2]}]}), 'boto_apigateway.detach_usage_plan_from_apis': MagicMock(return_value={'result': {'apiStages': [association_stage_1]}})}): result = boto_apigateway.usage_plan_association_absent('name', 'plan_name', [association_stage_2], **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], True) self.assertIn('comment', result) self.assertEqual(result['comment'], 'successfully disassociated usage plan from apis') self.assertIn('changes', result) self.assertEqual(result['changes'], {'new': [association_stage_1], 'old': [association_stage_1, association_stage_2]})
'Tests correct error processing for the case where ValueError is raised while trying to remove plan associations'
def test_usage_plan_association_absent_if_ValueError_is_raised(self, *args):
with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(side_effect=ValueError('error'))}): result = boto_apigateway.usage_plan_association_absent('name', 'plan_name', [association_stage_1], **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], False) self.assertIn('comment', result) self.assertEqual(result['comment'], "('error',)") self.assertIn('changes', result) self.assertEqual(result['changes'], {})
'Tests correct error processing for the case where IOError exception is raised while trying to remove plan associations'
def test_usage_plan_association_absent_if_IOError_is_raised(self, *args):
with patch.dict(boto_apigateway.__salt__, {'boto_apigateway.describe_usage_plans': MagicMock(side_effect=IOError('error'))}): result = boto_apigateway.usage_plan_association_absent('name', 'plan_name', [association_stage_1], **conn_parameters) self.assertIn('result', result) self.assertEqual(result['result'], False) self.assertIn('comment', result) self.assertEqual(result['comment'], "('error',)") self.assertIn('changes', result) self.assertEqual(result['changes'], {})
'Test to sets values in the org.gnome.desktop.wm.preferences schema'
def test_wm_preferences(self):
name = 'salt' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} self.assertDictEqual(gnomedesktop.wm_preferences(name), ret)
'Test to sets values in the org.gnome.desktop.lockdown schema'
def test_desktop_lockdown(self):
name = 'salt' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} self.assertDictEqual(gnomedesktop.desktop_lockdown(name), ret)
'Test to sets values in the org.gnome.desktop.interface schema'
def test_desktop_interface(self):
name = 'salt' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} self.assertDictEqual(gnomedesktop.desktop_interface(name), ret)
'Test to execute the onlyif and unless logic.'
def test_mod_run_check(self):
cmd_kwargs = {} creates = '/tmp' mock = MagicMock(return_value=1) with patch.dict(cmd.__salt__, {'cmd.retcode': mock}): with patch.dict(cmd.__opts__, {'test': True}): ret = {'comment': 'onlyif execution failed', 'result': True, 'skip_watch': True} self.assertDictEqual(cmd.mod_run_check(cmd_kwargs, '', '', creates), ret) self.assertDictEqual(cmd.mod_run_check(cmd_kwargs, {}, '', creates), ret) mock = MagicMock(return_value=1) with patch.dict(cmd.__salt__, {'cmd.retcode': mock}): with patch.dict(cmd.__opts__, {'test': True}): ret = {'comment': 'onlyif execution failed: ', 'result': True, 'skip_watch': True} self.assertDictEqual(cmd.mod_run_check(cmd_kwargs, [''], '', creates), ret) mock = MagicMock(return_value=0) with patch.dict(cmd.__salt__, {'cmd.retcode': mock}): ret = {'comment': 'unless execution succeeded', 'result': True, 'skip_watch': True} self.assertDictEqual(cmd.mod_run_check(cmd_kwargs, None, '', creates), ret) self.assertDictEqual(cmd.mod_run_check(cmd_kwargs, None, [''], creates), ret) self.assertDictEqual(cmd.mod_run_check(cmd_kwargs, None, True, creates), ret) with patch.object(os.path, 'exists', MagicMock(sid_effect=[True, True, False])): ret = {'comment': '/tmp exists', 'result': True} self.assertDictEqual(cmd.mod_run_check(cmd_kwargs, None, None, creates), ret) ret = {'comment': 'All files in creates exist', 'result': True} self.assertDictEqual(cmd.mod_run_check(cmd_kwargs, None, None, [creates]), ret) self.assertTrue(cmd.mod_run_check(cmd_kwargs, None, None, {}))
'Test to run the given command only if the watch statement calls it.'
def test_wait(self):
name = 'cmd.script' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} self.assertDictEqual(cmd.wait(name), ret)
'Test to download a script from a remote source and execute it only if a watch statement calls it.'
def test_wait_script(self):
name = 'cmd.script' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} self.assertDictEqual(cmd.wait_script(name), ret)
'Test to run a command if certain circumstances are met.'
def test_run(self):
name = 'cmd.script' ret = {'name': name, 'result': False, 'changes': {}, 'comment': ''} with patch.dict(cmd.__opts__, {'test': False}): comt = "Invalidly-formatted 'env' parameter. See documentation." ret.update({'comment': comt}) self.assertDictEqual(cmd.run(name, env='salt'), ret) with patch.dict(cmd.__grains__, {'shell': 'shell'}): with patch.dict(cmd.__opts__, {'test': False}): mock = MagicMock(side_effect=[CommandExecutionError, {'retcode': 1}]) with patch.dict(cmd.__salt__, {'cmd.run_all': mock}): ret.update({'comment': '', 'result': False}) self.assertDictEqual(cmd.run(name), ret) ret.update({'comment': 'Command "cmd.script" run', 'result': False, 'changes': {'retcode': 1}}) self.assertDictEqual(cmd.run(name), ret) with patch.dict(cmd.__opts__, {'test': True}): comt = 'Command "cmd.script" would have been executed' ret.update({'comment': comt, 'result': None, 'changes': {}}) self.assertDictEqual(cmd.run(name), ret) mock = MagicMock(return_value=1) with patch.dict(cmd.__salt__, {'cmd.retcode': mock}): with patch.dict(cmd.__opts__, {'test': False}): comt = 'onlyif execution failed' ret.update({'comment': comt, 'result': True, 'skip_watch': True}) self.assertDictEqual(cmd.run(name, onlyif=''), ret)
'Test to download a script and execute it with specified arguments.'
def test_script(self):
name = 'cmd.script' ret = {'name': name, 'result': False, 'changes': {}, 'comment': ''} with patch.dict(cmd.__opts__, {'test': False}): comt = "Invalidly-formatted 'env' parameter. See documentation." ret.update({'comment': comt}) self.assertDictEqual(cmd.script(name, env='salt'), ret) with patch.dict(cmd.__grains__, {'shell': 'shell'}): with patch.dict(cmd.__opts__, {'test': True}): comt = "Command 'cmd.script' would have been executed" ret.update({'comment': comt, 'result': None, 'changes': {}}) self.assertDictEqual(cmd.script(name), ret) with patch.dict(cmd.__opts__, {'test': False}): mock = MagicMock(side_effect=[CommandExecutionError, {'retcode': 1}]) with patch.dict(cmd.__salt__, {'cmd.script': mock}): ret.update({'comment': '', 'result': False}) self.assertDictEqual(cmd.script(name), ret) ret.update({'comment': "Command 'cmd.script' run", 'result': False, 'changes': {'retcode': 1}}) self.assertDictEqual(cmd.script(name), ret) mock = MagicMock(return_value=1) with patch.dict(cmd.__salt__, {'cmd.retcode': mock}): with patch.dict(cmd.__opts__, {'test': False}): comt = 'onlyif execution failed' ret.update({'comment': comt, 'result': True, 'skip_watch': True, 'changes': {}}) self.assertDictEqual(cmd.script(name, onlyif=''), ret)
'Test to invoke a pre-defined Python function with arguments specified in the state declaration.'
def test_call(self):
name = 'cmd.script' ret = {'name': name, 'result': False, 'changes': {}, 'comment': ''} flag = None def func(): '\n Mock func method\n ' if flag: return {} else: return [] with patch.dict(cmd.__grains__, {'shell': 'shell'}): flag = True self.assertDictEqual(cmd.call(name, func), ret) flag = False comt = 'onlyif execution failed' ret.update({'comment': '', 'result': False, 'changes': {'retval': []}}) self.assertDictEqual(cmd.call(name, func), ret) mock = MagicMock(return_value=1) with patch.dict(cmd.__salt__, {'cmd.retcode': mock}): with patch.dict(cmd.__opts__, {'test': True}): comt = 'onlyif execution failed' ret.update({'comment': comt, 'skip_watch': True, 'result': True, 'changes': {}}) self.assertDictEqual(cmd.call(name, func, onlyif=''), ret)
'Test to run wait_call.'
def test_wait_call(self):
name = 'cmd.script' func = 'myfunc' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} self.assertDictEqual(cmd.wait_call(name, func), ret)
'Test to execute a cmd function based on a watch call'
def test_mod_watch(self):
name = 'cmd.script' ret = {'name': name, 'result': False, 'changes': {}, 'comment': ''} def func(): '\n Mock func method\n ' return {} with patch.dict(cmd.__grains__, {'shell': 'shell'}): with patch.dict(cmd.__opts__, {'test': False}): mock = MagicMock(return_value={'retcode': 1}) with patch.dict(cmd.__salt__, {'cmd.run_all': mock}): self.assertDictEqual(cmd.mod_watch(name, sfun='wait', stateful=True), ret) comt = 'Command "cmd.script" run' ret.update({'comment': comt, 'changes': {'retcode': 1}}) self.assertDictEqual(cmd.mod_watch(name, sfun='wait', stateful=False), ret) with patch.dict(cmd.__salt__, {'cmd.script': mock}): ret.update({'comment': '', 'changes': {}}) self.assertDictEqual(cmd.mod_watch(name, sfun='script', stateful=True), ret) comt = "Command 'cmd.script' run" ret.update({'comment': comt, 'changes': {'retcode': 1}}) self.assertDictEqual(cmd.mod_watch(name, sfun='script', stateful=False), ret) with patch.dict(cmd.__salt__, {'cmd.script': mock}): ret.update({'comment': '', 'changes': {}}) self.assertDictEqual(cmd.mod_watch(name, sfun='call', func=func), ret) comt = 'cmd.call needs a named parameter func' ret.update({'comment': comt}) self.assertDictEqual(cmd.mod_watch(name, sfun='call'), ret) comt = 'cmd.salt does not work with the watch requisite, please use cmd.wait or cmd.wait_script' ret.update({'comment': comt}) self.assertDictEqual(cmd.mod_watch(name, sfun='salt'), ret)
'Test installing a certificate into the macOS keychain'
def test_install_cert(self):
expected = {'changes': {'installed': 'Friendly Name'}, 'comment': '', 'name': '/path/to/cert.p12', 'result': True} list_mock = MagicMock(return_value=['Cert1']) friendly_mock = MagicMock(return_value='Friendly Name') install_mock = MagicMock(return_value='1 identity imported.') with patch.dict(keychain.__salt__, {'keychain.list_certs': list_mock, 'keychain.get_friendly_name': friendly_mock, 'keychain.install': install_mock}): out = keychain.installed('/path/to/cert.p12', 'passw0rd') list_mock.assert_called_once_with('/Library/Keychains/System.keychain') friendly_mock.assert_called_once_with('/path/to/cert.p12', 'passw0rd') install_mock.assert_called_once_with('/path/to/cert.p12', 'passw0rd', '/Library/Keychains/System.keychain') self.assertEqual(out, expected)
'Test installing a certificate into the macOS keychain when it\'s already installed'
def test_installed_cert(self):
expected = {'changes': {}, 'comment': 'Friendly Name already installed.', 'name': '/path/to/cert.p12', 'result': True} list_mock = MagicMock(return_value=['Friendly Name']) friendly_mock = MagicMock(return_value='Friendly Name') install_mock = MagicMock(return_value='1 identity imported.') hash_mock = MagicMock(return_value='ABCD') with patch.dict(keychain.__salt__, {'keychain.list_certs': list_mock, 'keychain.get_friendly_name': friendly_mock, 'keychain.install': install_mock, 'keychain.get_hash': hash_mock}): out = keychain.installed('/path/to/cert.p12', 'passw0rd') list_mock.assert_called_once_with('/Library/Keychains/System.keychain') friendly_mock.assert_called_once_with('/path/to/cert.p12', 'passw0rd') assert (not install_mock.called) self.assertEqual(out, expected)
'Test uninstalling a certificate into the macOS keychain when it\'s already installed'
def test_uninstall_cert(self):
expected = {'changes': {'uninstalled': 'Friendly Name'}, 'comment': '', 'name': '/path/to/cert.p12', 'result': True} list_mock = MagicMock(return_value=['Friendly Name']) friendly_mock = MagicMock(return_value='Friendly Name') uninstall_mock = MagicMock(return_value='1 identity imported.') with patch.dict(keychain.__salt__, {'keychain.list_certs': list_mock, 'keychain.get_friendly_name': friendly_mock, 'keychain.uninstall': uninstall_mock}): out = keychain.uninstalled('/path/to/cert.p12', 'passw0rd') list_mock.assert_called_once_with('/Library/Keychains/System.keychain') friendly_mock.assert_called_once_with('/path/to/cert.p12', 'passw0rd') uninstall_mock.assert_called_once_with('Friendly Name', '/Library/Keychains/System.keychain', None) self.assertEqual(out, expected)
'Test uninstalling a certificate into the macOS keychain when it\'s not installed'
def test_uninstalled_cert(self):
expected = {'changes': {}, 'comment': 'Friendly Name already uninstalled.', 'name': '/path/to/cert.p12', 'result': True} list_mock = MagicMock(return_value=['Cert2']) friendly_mock = MagicMock(return_value='Friendly Name') uninstall_mock = MagicMock(return_value='1 identity imported.') with patch.dict(keychain.__salt__, {'keychain.list_certs': list_mock, 'keychain.get_friendly_name': friendly_mock, 'keychain.uninstall': uninstall_mock}): out = keychain.uninstalled('/path/to/cert.p12', 'passw0rd') list_mock.assert_called_once_with('/Library/Keychains/System.keychain') friendly_mock.assert_called_once_with('/path/to/cert.p12', 'passw0rd') assert (not uninstall_mock.called) self.assertEqual(out, expected)
'Test setting the default keychain'
def test_default_keychain(self):
with patch('os.path.exists') as exists_mock: expected = {'changes': {'default': '/path/to/chain.keychain'}, 'comment': '', 'name': '/path/to/chain.keychain', 'result': True} exists_mock.return_value = True get_default_mock = MagicMock(return_value='/path/to/other.keychain') set_mock = MagicMock(return_value='') with patch.dict(keychain.__salt__, {'keychain.get_default_keychain': get_default_mock, 'keychain.set_default_keychain': set_mock}): out = keychain.default_keychain('/path/to/chain.keychain', 'system', 'frank') get_default_mock.assert_called_once_with('frank', 'system') set_mock.assert_called_once_with('/path/to/chain.keychain', 'system', 'frank') self.assertEqual(out, expected)
'Test setting the default keychain when it\'s already set'
def test_default_keychain_set_already(self):
with patch('os.path.exists') as exists_mock: expected = {'changes': {}, 'comment': '/path/to/chain.keychain was already the default keychain.', 'name': '/path/to/chain.keychain', 'result': True} exists_mock.return_value = True get_default_mock = MagicMock(return_value='/path/to/chain.keychain') set_mock = MagicMock(return_value='') with patch.dict(keychain.__salt__, {'keychain.get_default_keychain': get_default_mock, 'keychain.set_default_keychain': set_mock}): out = keychain.default_keychain('/path/to/chain.keychain', 'system', 'frank') get_default_mock.assert_called_once_with('frank', 'system') assert (not set_mock.called) self.assertEqual(out, expected)
'Test setting the default keychain when the keychain is missing'
def test_default_keychain_missing(self):
with patch('os.path.exists') as exists_mock: expected = {'changes': {}, 'comment': 'Keychain not found at /path/to/cert.p12', 'name': '/path/to/cert.p12', 'result': False} exists_mock.return_value = False out = keychain.default_keychain('/path/to/cert.p12', 'system', 'frank') self.assertEqual(out, expected)
'Test installing a certificate into the macOS keychain from the salt fileserver'
def test_install_cert_salt_fileserver(self):
expected = {'changes': {'installed': 'Friendly Name'}, 'comment': '', 'name': 'salt://path/to/cert.p12', 'result': True} list_mock = MagicMock(return_value=['Cert1']) friendly_mock = MagicMock(return_value='Friendly Name') install_mock = MagicMock(return_value='1 identity imported.') cp_cache_mock = MagicMock(return_value='/tmp/path/to/cert.p12') with patch.dict(keychain.__salt__, {'keychain.list_certs': list_mock, 'keychain.get_friendly_name': friendly_mock, 'keychain.install': install_mock, 'cp.cache_file': cp_cache_mock}): out = keychain.installed('salt://path/to/cert.p12', 'passw0rd') list_mock.assert_called_once_with('/Library/Keychains/System.keychain') friendly_mock.assert_called_once_with('/tmp/path/to/cert.p12', 'passw0rd') install_mock.assert_called_once_with('/tmp/path/to/cert.p12', 'passw0rd', '/Library/Keychains/System.keychain') self.assertEqual(out, expected)
'Test installing a certificate into the macOS keychain when it\'s already installed but the certificate has changed'
def test_installed_cert_hash_different(self):
expected = {'changes': {'installed': 'Friendly Name', 'uninstalled': 'Friendly Name'}, 'comment': 'Found a certificate with the same name but different hash, removing it.\n', 'name': '/path/to/cert.p12', 'result': True} list_mock = MagicMock(side_effect=[['Friendly Name'], []]) friendly_mock = MagicMock(return_value='Friendly Name') install_mock = MagicMock(return_value='1 identity imported.') uninstall_mock = MagicMock(return_value='removed.') hash_mock = MagicMock(side_effect=['ABCD', 'XYZ']) with patch.dict(keychain.__salt__, {'keychain.list_certs': list_mock, 'keychain.get_friendly_name': friendly_mock, 'keychain.install': install_mock, 'keychain.uninstall': uninstall_mock, 'keychain.get_hash': hash_mock}): out = keychain.installed('/path/to/cert.p12', 'passw0rd') list_mock.assert_has_calls(calls=[call('/Library/Keychains/System.keychain'), call('/Library/Keychains/System.keychain')]) friendly_mock.assert_called_once_with('/path/to/cert.p12', 'passw0rd') install_mock.assert_called_once_with('/path/to/cert.p12', 'passw0rd', '/Library/Keychains/System.keychain') uninstall_mock.assert_called_once_with('Friendly Name', '/Library/Keychains/System.keychain', keychain_password=None) self.assertEqual(out, expected)
'Test to ensure that the grant is present with the specified properties.'
def test_present(self):
name = 'frank_exampledb' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} mock = MagicMock(side_effect=[True, False, False, False]) mock_t = MagicMock(return_value=True) mock_str = MagicMock(return_value='salt') mock_none = MagicMock(return_value=None) with patch.dict(mysql_grants.__salt__, {'mysql.grant_exists': mock, 'mysql.grant_add': mock_t}): comt = 'Grant None on None to None@localhost is already present' ret.update({'comment': comt}) self.assertDictEqual(mysql_grants.present(name), ret) with patch.object(mysql_grants, '_get_mysql_error', mock_str): ret.update({'comment': 'salt', 'result': False}) self.assertDictEqual(mysql_grants.present(name), ret) with patch.object(mysql_grants, '_get_mysql_error', mock_none): with patch.dict(mysql_grants.__opts__, {'test': True}): comt = 'MySQL grant frank_exampledb is set to be created' ret.update({'comment': comt, 'result': None}) self.assertDictEqual(mysql_grants.present(name), ret) with patch.dict(mysql_grants.__opts__, {'test': False}): comt = 'Grant None on None to None@localhost has been added' ret.update({'comment': comt, 'result': True, 'changes': {name: 'Present'}}) self.assertDictEqual(mysql_grants.present(name), ret)
'Test to ensure that the grant is absent.'
def test_absent(self):
name = 'frank_exampledb' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} mock = MagicMock(side_effect=[True, False]) mock_t = MagicMock(side_effect=[True, True, True, False, False]) mock_str = MagicMock(return_value='salt') mock_none = MagicMock(return_value=None) with patch.dict(mysql_grants.__salt__, {'mysql.grant_exists': mock_t, 'mysql.grant_revoke': mock}): with patch.dict(mysql_grants.__opts__, {'test': True}): comt = 'MySQL grant frank_exampledb is set to be revoked' ret.update({'comment': comt, 'result': None}) self.assertDictEqual(mysql_grants.absent(name), ret) with patch.dict(mysql_grants.__opts__, {'test': False}): comt = 'Grant None on None for None@localhost has been revoked' ret.update({'comment': comt, 'result': True, 'changes': {name: 'Absent'}}) self.assertDictEqual(mysql_grants.absent(name), ret) with patch.object(mysql_grants, '_get_mysql_error', mock_str): comt = 'Unable to revoke grant None on None for None@localhost (salt)' ret.update({'comment': comt, 'result': False, 'changes': {}}) self.assertDictEqual(mysql_grants.absent(name), ret) comt = 'Unable to determine if grant None on None for None@localhost exists (salt)' ret.update({'comment': comt}) self.assertDictEqual(mysql_grants.absent(name), ret) with patch.object(mysql_grants, '_get_mysql_error', mock_none): comt = 'Grant None on None to None@localhost is not present, so it cannot be revoked' ret.update({'comment': comt, 'result': True}) self.assertDictEqual(mysql_grants.absent(name), ret)
'Test to ensure the kinesis stream exists.'
def test_stream_present(self):
name = 'new_stream' retention_hours = 24 enhanced_monitoring = ['IteratorAgeMilliseconds'] different_enhanced_monitoring = ['IncomingBytes'] num_shards = 1 ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} shards = [{'ShardId': 'shardId-000000000000', 'HashKeyRange': {'EndingHashKey': 'big number', 'StartingHashKey': '0'}, 'SequenceNumberRange': {'StartingSequenceNumber': 'bigger number'}}] stream_description = {'HasMoreShards': False, 'RetentionPeriodHours': retention_hours, 'StreamName': name, 'Shards': shards, 'StreamARN': '', 'EnhancedMonitoring': [{'ShardLevelMetrics': enhanced_monitoring}], 'StreamStatus': 'ACTIVE'} exists_mock = MagicMock(side_effect=[{'result': True}, {'result': False}, {'result': True}, {'result': False}]) get_stream_mock = MagicMock(return_value={'result': {'StreamDescription': stream_description}}) shard_mock = MagicMock(return_value=[0, 0, {'OpenShards': shards}]) dict_mock = MagicMock(return_value={'result': True}) mock_bool = MagicMock(return_value=True) with patch.dict(boto_kinesis.__salt__, {'boto_kinesis.exists': exists_mock, 'boto_kinesis.create_stream': dict_mock, 'boto_kinesis.get_stream_when_active': get_stream_mock, 'boto_kinesis.get_info_for_reshard': shard_mock, 'boto_kinesis.num_shards_matches': mock_bool}): comt = 'Kinesis stream {0} already exists,\nKinesis stream {0}: retention hours did not require change, already set at {1},\nKinesis stream {0}: enhanced monitoring did not require change, already set at {2},\nKinesis stream {0}: did not require resharding, remains at {3} shards'.format(name, retention_hours, enhanced_monitoring, num_shards) ret.update({'comment': comt}) self.assertDictEqual(boto_kinesis.present(name, retention_hours, enhanced_monitoring, num_shards), ret) with patch.dict(boto_kinesis.__opts__, {'test': True}): comt = 'Kinesis stream {0} would be created'.format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(boto_kinesis.present(name, retention_hours, enhanced_monitoring, num_shards), ret) comt = 'Kinesis stream {0} already exists,\nKinesis stream {0}: retention hours would be updated to {1},\nKinesis stream {0}: would enable enhanced monitoring for {2},\nKinesis stream {0}: would disable enhanced monitoring for {3},\nKinesis stream {0}: would be resharded from {4} to {5} shards'.format(name, (retention_hours + 1), different_enhanced_monitoring, enhanced_monitoring, num_shards, (num_shards + 1)) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(boto_kinesis.present(name, (retention_hours + 1), different_enhanced_monitoring, (num_shards + 1)), ret) changes = {'new': {'name': name, 'num_shards': num_shards}} with patch.dict(boto_kinesis.__opts__, {'test': False}): comt = 'Kinesis stream {0} successfully created,\nKinesis stream {0}: retention hours did not require change, already set at {1},\nKinesis stream {0}: enhanced monitoring did not require change, already set at {2},\nKinesis stream {0}: did not require resharding, remains at {3} shards'.format(name, retention_hours, enhanced_monitoring, num_shards) ret.update({'comment': comt, 'result': True, 'changes': changes}) self.assertDictEqual(ret, boto_kinesis.present(name, retention_hours, enhanced_monitoring, num_shards))
'Test to ensure the Kinesis stream does not exist.'
def test_absent(self):
name = 'new_stream' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} mock = MagicMock(side_effect=[{'result': False}, {'result': True}, {'result': True}]) mock_bool = MagicMock(return_value={'result': True}) with patch.dict(boto_kinesis.__salt__, {'boto_kinesis.exists': mock, 'boto_kinesis.delete_stream': mock_bool}): comt = 'Kinesis stream {0} does not exist'.format(name) ret.update({'comment': comt}) self.assertDictEqual(boto_kinesis.absent(name), ret) with patch.dict(boto_kinesis.__opts__, {'test': True}): comt = 'Kinesis stream {0} would be deleted'.format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(boto_kinesis.absent(name), ret) changes = {'new': 'Stream {0} deleted'.format(name), 'old': 'Stream {0} exists'.format(name)} with patch.dict(boto_kinesis.__opts__, {'test': False}): comt = 'Deleted stream {0}'.format(name) ret.update({'comment': comt, 'result': True, 'changes': changes}) self.assertDictEqual(boto_kinesis.absent(name), ret)
'Test to request power state change.'
def test_boot_device(self):
name = 'salt' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} mock = MagicMock(return_value=name) with patch.dict(ipmi.__salt__, {'ipmi.get_bootdev': mock, 'ipmi.set_bootdev': mock}): comt = 'system already in this state' ret.update({'comment': comt}) self.assertDictEqual(ipmi.boot_device(name), ret) with patch.dict(ipmi.__opts__, {'test': False}): comt = 'changed boot device' ret.update({'name': 'default', 'comment': comt, 'result': True, 'changes': {'new': 'default', 'old': 'salt'}}) self.assertDictEqual(ipmi.boot_device(), ret) with patch.dict(ipmi.__opts__, {'test': True}): comt = 'would change boot device' ret.update({'comment': comt, 'result': None}) self.assertDictEqual(ipmi.boot_device(), ret)
'Test to request power state change'
def test_power(self):
ret = {'name': 'power_on', 'result': True, 'comment': '', 'changes': {}} mock = MagicMock(return_value='on') with patch.dict(ipmi.__salt__, {'ipmi.get_power': mock, 'ipmi.set_power': mock}): comt = 'system already in this state' ret.update({'comment': comt}) self.assertDictEqual(ipmi.power(), ret) with patch.dict(ipmi.__opts__, {'test': False}): comt = 'changed system power' ret.update({'name': 'off', 'comment': comt, 'result': True, 'changes': {'new': 'off', 'old': 'on'}}) self.assertDictEqual(ipmi.power('off'), ret) with patch.dict(ipmi.__opts__, {'test': True}): comt = 'would power: off system' ret.update({'comment': comt, 'result': None}) self.assertDictEqual(ipmi.power('off'), ret)
'Test to ensure IPMI user and user privileges.'
def test_user_present(self):
name = 'salt' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} mock_ret = {'access': {'callback': False, 'link_auth': True, 'ipmi_msg': True, 'privilege_level': 'administrator'}} mock = MagicMock(return_value=mock_ret) mock_bool = MagicMock(side_effect=[True, False, False, False]) with patch.dict(ipmi.__salt__, {'ipmi.get_user': mock, 'ipmi.set_user_password': mock_bool, 'ipmi.ensure_user': mock_bool}): comt = 'user already present' ret.update({'comment': comt}) self.assertDictEqual(ipmi.user_present(name, 5, 'salt@123'), ret) with patch.dict(ipmi.__opts__, {'test': True}): comt = 'would (re)create user' ret.update({'comment': comt, 'result': None, 'changes': {'new': 'salt', 'old': mock_ret}}) self.assertDictEqual(ipmi.user_present(name, 5, 'pw@123'), ret) with patch.dict(ipmi.__opts__, {'test': False}): comt = '(re)created user' ret.update({'comment': comt, 'result': True, 'changes': {'new': mock_ret, 'old': mock_ret}}) self.assertDictEqual(ipmi.user_present(name, 5, 'pw@123'), ret)
'Test to delete all user (uid) records having the matching name.'
def test_user_absent(self):
name = 'salt' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} mock = MagicMock(side_effect=[[], [5], [5]]) mock_bool = MagicMock(return_value=True) with patch.dict(ipmi.__salt__, {'ipmi.get_name_uids': mock, 'ipmi.delete_user': mock_bool}): comt = 'user already absent' ret.update({'comment': comt}) self.assertDictEqual(ipmi.user_absent(name), ret) with patch.dict(ipmi.__opts__, {'test': True}): comt = 'would delete user(s)' ret.update({'comment': comt, 'result': None, 'changes': {'delete': [5]}}) self.assertDictEqual(ipmi.user_absent(name), ret) with patch.dict(ipmi.__opts__, {'test': False}): comt = 'user(s) removed' ret.update({'comment': comt, 'result': False, 'changes': {'new': 'None', 'old': [5]}}) self.assertDictEqual(ipmi.user_absent(name), ret)
'archive.extracted tar options'
def test_extracted_tar(self):
source = '/tmp/foo.tar.gz' tmp_dir = '/tmp/test_extracted_tar' test_tar_opts = ['--no-anchored foo', 'v -p --opt', '-v -p', '--long-opt -z', 'z -v -weird-long-opt arg'] ret_tar_opts = [['tar', 'x', '--no-anchored', 'foo', '-f'], ['tar', 'xv', '-p', '--opt', '-f'], ['tar', 'x', '-v', '-p', '-f'], ['tar', 'x', '--long-opt', '-z', '-f'], ['tar', 'xz', '-v', '-weird-long-opt', 'arg', '-f']] mock_true = MagicMock(return_value=True) mock_false = MagicMock(return_value=False) ret = {'stdout': ['cheese', 'ham', 'saltines'], 'stderr': 'biscuits', 'retcode': '31337', 'pid': '1337'} mock_run = MagicMock(return_value=ret) mock_source_list = MagicMock(return_value=(source, None)) state_single_mock = MagicMock(return_value={'local': {'result': True}}) list_mock = MagicMock(return_value={'dirs': [], 'files': ['cheese', 'saltines'], 'links': ['ham'], 'top_level_dirs': [], 'top_level_files': ['cheese', 'saltines'], 'top_level_links': ['ham']}) isfile_mock = MagicMock(side_effect=_isfile_side_effect) with patch.dict(archive.__opts__, {'test': False, 'cachedir': tmp_dir, 'hash_type': 'sha256'}): with patch.dict(archive.__salt__, {'file.directory_exists': mock_false, 'file.file_exists': mock_false, 'state.single': state_single_mock, 'file.makedirs': mock_true, 'cmd.run_all': mock_run, 'archive.list': list_mock, 'file.source_list': mock_source_list}): with patch.dict(archive.__states__, {'file.directory': mock_true}): with patch.object(os.path, 'isfile', isfile_mock): for (test_opts, ret_opts) in zip(test_tar_opts, ret_tar_opts): ret = archive.extracted(tmp_dir, source, options=test_opts, enforce_toplevel=False) ret_opts.append(source) mock_run.assert_called_with(ret_opts, cwd=(tmp_dir + os.sep), python_shell=False)
'Tests the call of extraction with gnutar'
def test_tar_gnutar(self):
gnutar = MagicMock(return_value='tar (GNU tar)') source = '/tmp/foo.tar.gz' mock_false = MagicMock(return_value=False) mock_true = MagicMock(return_value=True) state_single_mock = MagicMock(return_value={'local': {'result': True}}) run_all = MagicMock(return_value={'retcode': 0, 'stdout': 'stdout', 'stderr': 'stderr'}) mock_source_list = MagicMock(return_value=(source, None)) list_mock = MagicMock(return_value={'dirs': [], 'files': ['stdout'], 'links': [], 'top_level_dirs': [], 'top_level_files': ['stdout'], 'top_level_links': []}) isfile_mock = MagicMock(side_effect=_isfile_side_effect) with patch.dict(archive.__salt__, {'cmd.run': gnutar, 'file.directory_exists': mock_false, 'file.file_exists': mock_false, 'state.single': state_single_mock, 'file.makedirs': mock_true, 'cmd.run_all': run_all, 'archive.list': list_mock, 'file.source_list': mock_source_list}): with patch.dict(archive.__states__, {'file.directory': mock_true}): with patch.object(os.path, 'isfile', isfile_mock): ret = archive.extracted('/tmp/out', source, options='xvzf', enforce_toplevel=False, keep=True) self.assertEqual(ret['changes']['extracted_files'], 'stdout')
'Tests the call of extraction with bsdtar'
def test_tar_bsdtar(self):
bsdtar = MagicMock(return_value='tar (bsdtar)') source = '/tmp/foo.tar.gz' mock_false = MagicMock(return_value=False) mock_true = MagicMock(return_value=True) state_single_mock = MagicMock(return_value={'local': {'result': True}}) run_all = MagicMock(return_value={'retcode': 0, 'stdout': 'stdout', 'stderr': 'stderr'}) mock_source_list = MagicMock(return_value=(source, None)) list_mock = MagicMock(return_value={'dirs': [], 'files': ['stderr'], 'links': [], 'top_level_dirs': [], 'top_level_files': ['stderr'], 'top_level_links': []}) isfile_mock = MagicMock(side_effect=_isfile_side_effect) with patch.dict(archive.__salt__, {'cmd.run': bsdtar, 'file.directory_exists': mock_false, 'file.file_exists': mock_false, 'state.single': state_single_mock, 'file.makedirs': mock_true, 'cmd.run_all': run_all, 'archive.list': list_mock, 'file.source_list': mock_source_list}): with patch.dict(archive.__states__, {'file.directory': mock_true}): with patch.object(os.path, 'isfile', isfile_mock): ret = archive.extracted('/tmp/out', source, options='xvzf', enforce_toplevel=False, keep=True) self.assertEqual(ret['changes']['extracted_files'], 'stderr')
'Setup data for the tests'
def setUp(self):
self.table_name = 'awl' self.group_name = 'admins' self.name = 'baruwa' self.ret = {'name': self.name, 'changes': {}, 'result': False, 'comment': ''} self.mock_true = MagicMock(return_value=True) self.mock_false = MagicMock(return_value=False)
'Test present'
def test_present_table(self):
with patch.dict(postgres_privileges.__salt__, {'postgres.has_privileges': self.mock_true}): comt = 'The requested privilege(s) are already set' self.ret.update({'comment': comt, 'result': True}) self.assertDictEqual(postgres_privileges.present(self.name, self.table_name, 'table'), self.ret) with patch.dict(postgres_privileges.__salt__, {'postgres.has_privileges': self.mock_false, 'postgres.privileges_grant': self.mock_true}): with patch.dict(postgres_privileges.__opts__, {'test': True}): comt = 'The privilege(s): {0} are set to be granted to {1}'.format('ALL', self.name) self.ret.update({'comment': comt, 'result': None}) self.assertDictEqual(postgres_privileges.present(self.name, self.table_name, 'table', privileges=['ALL']), self.ret) with patch.dict(postgres_privileges.__opts__, {'test': False}): comt = 'The privilege(s): {0} have been granted to {1}'.format('ALL', self.name) self.ret.update({'comment': comt, 'result': True, 'changes': {'baruwa': 'Present'}}) self.assertDictEqual(postgres_privileges.present(self.name, self.table_name, 'table', privileges=['ALL']), self.ret)
'Test present group'
def test_present_group(self):
with patch.dict(postgres_privileges.__salt__, {'postgres.has_privileges': self.mock_false, 'postgres.privileges_grant': self.mock_true}): with patch.dict(postgres_privileges.__opts__, {'test': True}): comt = 'The privilege(s): {0} are set to be granted to {1}'.format(self.group_name, self.name) self.ret.update({'comment': comt, 'result': None}) self.assertDictEqual(postgres_privileges.present(self.name, self.group_name, 'group'), self.ret) with patch.dict(postgres_privileges.__opts__, {'test': False}): comt = 'The privilege(s): {0} have been granted to {1}'.format(self.group_name, self.name) self.ret.update({'comment': comt, 'result': True, 'changes': {'baruwa': 'Present'}}) self.assertDictEqual(postgres_privileges.present(self.name, self.group_name, 'group'), self.ret)
'Test absent'
def test_absent_table(self):
with patch.dict(postgres_privileges.__salt__, {'postgres.has_privileges': self.mock_false}): with patch.dict(postgres_privileges.__opts__, {'test': True}): comt = 'The requested privilege(s) are not set so cannot be revoked' self.ret.update({'comment': comt, 'result': True}) self.assertDictEqual(postgres_privileges.absent(self.name, self.table_name, 'table'), self.ret) with patch.dict(postgres_privileges.__salt__, {'postgres.has_privileges': self.mock_true, 'postgres.privileges_revoke': self.mock_true}): with patch.dict(postgres_privileges.__opts__, {'test': True}): comt = 'The privilege(s): {0} are set to be revoked from {1}'.format('ALL', self.name) self.ret.update({'comment': comt, 'result': None}) self.assertDictEqual(postgres_privileges.absent(self.name, self.table_name, 'table', privileges=['ALL']), self.ret) with patch.dict(postgres_privileges.__opts__, {'test': False}): comt = 'The privilege(s): {0} have been revoked from {1}'.format('ALL', self.name) self.ret.update({'comment': comt, 'result': True, 'changes': {'baruwa': 'Absent'}}) self.assertDictEqual(postgres_privileges.absent(self.name, self.table_name, 'table', privileges=['ALL']), self.ret)
'Test absent group'
def test_absent_group(self):
with patch.dict(postgres_privileges.__salt__, {'postgres.has_privileges': self.mock_true, 'postgres.privileges_revoke': self.mock_true}): with patch.dict(postgres_privileges.__opts__, {'test': True}): comt = 'The privilege(s): {0} are set to be revoked from {1}'.format(self.group_name, self.name) self.ret.update({'comment': comt, 'result': None}) self.assertDictEqual(postgres_privileges.absent(self.name, self.group_name, 'group'), self.ret) with patch.dict(postgres_privileges.__opts__, {'test': False}): comt = 'The privilege(s): {0} have been revoked from {1}'.format(self.group_name, self.name) self.ret.update({'comment': comt, 'result': True, 'changes': {'baruwa': 'Absent'}}) self.assertDictEqual(postgres_privileges.absent(self.name, self.group_name, 'group'), self.ret)
'Setup data for the tests'
def setUp(self):
self.name = '/var/lib/psql/data' self.ret = {'name': self.name, 'changes': {}, 'result': False, 'comment': ''} self.mock_true = MagicMock(return_value=True) self.mock_false = MagicMock(return_value=False)
'Test existing data directory handled correctly'
def test_present_existing(self):
with patch.dict(postgres_initdb.__salt__, {'postgres.datadir_exists': self.mock_true}): _comt = 'Postgres data directory {0} is already present'.format(self.name) self.ret.update({'comment': _comt, 'result': True}) self.assertDictEqual(postgres_initdb.present(self.name), self.ret)
'Test non existing data directory ok'
def test_present_non_existing_pass(self):
with patch.dict(postgres_initdb.__salt__, {'postgres.datadir_exists': self.mock_false, 'postgres.datadir_init': self.mock_true}): with patch.dict(postgres_initdb.__opts__, {'test': True}): _comt = 'Postgres data directory {0} is set to be initialized'.format(self.name) self.ret.update({'comment': _comt, 'result': None}) self.assertDictEqual(postgres_initdb.present(self.name), self.ret) with patch.dict(postgres_initdb.__opts__, {'test': False}): _comt = 'Postgres data directory {0} has been initialized'.format(self.name) _changes = {self.name: 'Present'} self.ret.update({'comment': _comt, 'result': True, 'changes': _changes}) self.assertDictEqual(postgres_initdb.present(self.name), self.ret)
'Test non existing data directory fail'
def test_present_non_existing_fail(self):
with patch.dict(postgres_initdb.__salt__, {'postgres.datadir_exists': self.mock_false, 'postgres.datadir_init': self.mock_false}): with patch.dict(postgres_initdb.__opts__, {'test': False}): _comt = 'Postgres data directory {0} initialization failed'.format(self.name) self.ret.update({'comment': _comt, 'result': False}) self.assertDictEqual(postgres_initdb.present(self.name), self.ret)
'Test to verify that the desired port is installed, and that it was compiled with the desired options.'
def test_installed(self):
name = 'security/nmap' options = [{'IPV6': 'on'}] ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} mock = MagicMock(side_effect=SaltInvocationError) with patch.dict(ports.__salt__, {'ports.showconfig': mock}): comt = 'Unable to get configuration for {0}. Port name may be invalid, or ports tree may need to be updated. Error message: '.format(name) ret.update({'comment': comt, 'result': False}) self.assertDictEqual(ports.installed(name), ret) mock = MagicMock(return_value={}) mock_lst = MagicMock(return_value={'origin': {'origin': name}}) with patch.dict(ports.__salt__, {'ports.showconfig': mock, 'pkg.list_pkgs': mock_lst}): comt = 'security/nmap is already installed' ret.update({'comment': comt, 'result': True}) self.assertDictEqual(ports.installed(name), ret) comt = 'security/nmap does not have any build options, yet options were specified' ret.update({'comment': comt, 'result': False}) self.assertDictEqual(ports.installed(name, options), ret) mock_dict = MagicMock(return_value={'origin': {'origin': 'salt'}}) with patch.dict(ports.__salt__, {'pkg.list_pkgs': mock_dict}): with patch.dict(ports.__opts__, {'test': True}): comt = '{0} will be installed'.format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(ports.installed(name), ret) mock = MagicMock(return_value={'salt': {'salt': 'salt'}}) mock_dict = MagicMock(return_value={'origin': {'origin': 'salt'}}) mock_f = MagicMock(return_value=False) mock_t = MagicMock(return_value=True) with patch.dict(ports.__salt__, {'ports.showconfig': mock, 'pkg.list_pkgs': mock_dict, 'ports.config': mock_f, 'ports.rmconfig': mock_t}): with patch.dict(ports.__opts__, {'test': True}): comt = 'The following options are not available for security/nmap: IPV6' ret.update({'comment': comt, 'result': False}) self.assertDictEqual(ports.installed(name, options), ret) comt = 'security/nmap will be installed with the default build options' ret.update({'comment': comt, 'result': None}) self.assertDictEqual(ports.installed(name), ret) with patch.dict(ports.__opts__, {'test': False}): comt = 'Unable to set options for security/nmap' ret.update({'comment': comt, 'result': False}) self.assertDictEqual(ports.installed(name, [{'salt': 'salt'}]), ret) with patch.object(os.path, 'isfile', mock_t): with patch.object(os.path, 'isdir', mock_t): comt = 'Unable to clear options for security/nmap' ret.update({'comment': comt, 'result': False}) self.assertDictEqual(ports.installed(name), ret) with patch.dict(ports.__salt__, {'ports.config': mock_t, 'ports.install': mock_t, 'test.ping': MockModule()}): comt = 'Failed to install security/nmap. Error message:\nsalt' ret.update({'comment': comt, 'result': False, 'changes': True}) self.assertDictEqual(ports.installed(name, [{'salt': 'salt'}]), ret)
'Test to set the keyboard layout for the system.'
def test_system(self):
name = 'salt' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} mock = MagicMock(side_effect=[name, '', '', '']) mock_t = MagicMock(side_effect=[True, False]) with patch.dict(keyboard.__salt__, {'keyboard.get_sys': mock, 'keyboard.set_sys': mock_t}): comt = 'System layout {0} already set'.format(name) ret.update({'comment': comt}) self.assertDictEqual(keyboard.system(name), ret) with patch.dict(keyboard.__opts__, {'test': True}): comt = 'System layout {0} needs to be set'.format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(keyboard.system(name), ret) with patch.dict(keyboard.__opts__, {'test': False}): comt = 'Set system keyboard layout {0}'.format(name) ret.update({'comment': comt, 'result': True, 'changes': {'layout': name}}) self.assertDictEqual(keyboard.system(name), ret) comt = 'Failed to set system keyboard layout' ret.update({'comment': comt, 'result': False, 'changes': {}}) self.assertDictEqual(keyboard.system(name), ret)
'Test to set the keyboard layout for XOrg.'
def test_xorg(self):
name = 'salt' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} mock = MagicMock(side_effect=[name, '', '', '']) mock_t = MagicMock(side_effect=[True, False]) with patch.dict(keyboard.__salt__, {'keyboard.get_x': mock, 'keyboard.set_x': mock_t}): comt = 'XOrg layout {0} already set'.format(name) ret.update({'comment': comt}) self.assertDictEqual(keyboard.xorg(name), ret) with patch.dict(keyboard.__opts__, {'test': True}): comt = 'XOrg layout {0} needs to be set'.format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(keyboard.xorg(name), ret) with patch.dict(keyboard.__opts__, {'test': False}): comt = 'Set XOrg keyboard layout {0}'.format(name) ret.update({'comment': comt, 'result': True, 'changes': {'layout': name}}) self.assertDictEqual(keyboard.xorg(name), ret) comt = 'Failed to set XOrg keyboard layout' ret.update({'comment': comt, 'result': False, 'changes': {}}) self.assertDictEqual(keyboard.xorg(name), ret)
'test user_is_blacklisted'
def test_user_is_blacklisted(self):
client_acl = acl.PublisherACL(self.blacklist) self.assertTrue(client_acl.user_is_blacklisted('joker')) self.assertTrue(client_acl.user_is_blacklisted('penguin')) self.assertTrue(client_acl.user_is_blacklisted('bad_')) self.assertTrue(client_acl.user_is_blacklisted('bad_user')) self.assertTrue(client_acl.user_is_blacklisted('bad_*')) self.assertTrue(client_acl.user_is_blacklisted('user_bad_')) self.assertTrue(client_acl.user_is_blacklisted('blocked_')) self.assertTrue(client_acl.user_is_blacklisted('blocked_user')) self.assertTrue(client_acl.user_is_blacklisted('blocked_.*')) self.assertTrue(client_acl.user_is_blacklisted('Homer')) self.assertFalse(client_acl.user_is_blacklisted('batman')) self.assertFalse(client_acl.user_is_blacklisted('robin')) self.assertFalse(client_acl.user_is_blacklisted('bad')) self.assertFalse(client_acl.user_is_blacklisted('blocked')) self.assertFalse(client_acl.user_is_blacklisted('NotHomer')) self.assertFalse(client_acl.user_is_blacklisted('HomerSimpson'))
'test cmd_is_blacklisted'
def test_cmd_is_blacklisted(self):
client_acl = acl.PublisherACL(self.blacklist) self.assertTrue(client_acl.cmd_is_blacklisted('cmd.run')) self.assertTrue(client_acl.cmd_is_blacklisted('test.fib')) self.assertTrue(client_acl.cmd_is_blacklisted('rm-rf.root')) self.assertFalse(client_acl.cmd_is_blacklisted('cmd.shell')) self.assertFalse(client_acl.cmd_is_blacklisted('test.versions')) self.assertFalse(client_acl.cmd_is_blacklisted('arm-rf.root')) self.assertTrue(client_acl.cmd_is_blacklisted(['cmd.run', 'state.sls'])) self.assertFalse(client_acl.cmd_is_blacklisted(['state.highstate', 'state.sls']))
'Test passing a jid on the command line'
def test_condition_input_string(self):
cmd = salt.utils.args.condition_input(['*', 'foo.bar', 20141020201325675584L], None) self.assertIsInstance(cmd[2], str)
'Test matching ssh password patterns'
def test_ssh_password_regex(self):
for pattern in ('Password for [email protected]:', '[email protected] Password:', ' Password:'): self.assertNotEqual(cloud.SSH_PASSWORD_PROMP_RE.match(pattern), None) self.assertNotEqual(cloud.SSH_PASSWORD_PROMP_RE.match(pattern.lower()), None) self.assertNotEqual(cloud.SSH_PASSWORD_PROMP_RE.match(pattern.strip()), None) self.assertNotEqual(cloud.SSH_PASSWORD_PROMP_RE.match(pattern.lower().strip()), None)
'Test storing password in the keyring'
@skipIf((HAS_KEYRING is False), 'The python keyring library is not installed') def test__save_password_in_keyring(self):
cloud._save_password_in_keyring('salt.cloud.provider.test_case_provider', 'fake_username', 'fake_password_c8231') stored_pw = keyring.get_password('salt.cloud.provider.test_case_provider', 'fake_username') keyring.delete_password('salt.cloud.provider.test_case_provider', 'fake_username') self.assertEqual(stored_pw, 'fake_password_c8231')
'Test a single event is received'
def test_event_single(self):
with eventpublisher_process(): me = salt.utils.event.MasterEvent(SOCK_DIR, listen=True) me.fire_event({'data': 'foo1'}, 'evt1') evt1 = me.get_event(tag='evt1') self.assertGotEvent(evt1, {'data': 'foo1'})
'Test a single event is received, no block'
def test_event_single_no_block(self):
with eventpublisher_process(): me = salt.utils.event.MasterEvent(SOCK_DIR, listen=True) start = time.time() finish = (start + 5) evt1 = me.get_event(wait=0, tag='evt1', no_block=True) self.assertIsNone(evt1, None) self.assertLess(start, finish) me.fire_event({'data': 'foo1'}, 'evt1') evt1 = me.get_event(wait=0, tag='evt1') self.assertGotEvent(evt1, {'data': 'foo1'})
'Test a single event is received with wait=0 and no_block=False and doesn\'t spin the while loop'
def test_event_single_wait_0_no_block_False(self):
with eventpublisher_process(): me = salt.utils.event.MasterEvent(SOCK_DIR, listen=True) me.fire_event({'data': 'foo1'}, 'evt1') evt1 = me.get_event(wait=0, tag='evt1', no_block=False) self.assertGotEvent(evt1, {'data': 'foo1'})
'Test no event is received if the timeout is reached'
def test_event_timeout(self):
with eventpublisher_process(): me = salt.utils.event.MasterEvent(SOCK_DIR, listen=True) me.fire_event({'data': 'foo1'}, 'evt1') evt1 = me.get_event(tag='evt1') self.assertGotEvent(evt1, {'data': 'foo1'}) evt2 = me.get_event(tag='evt1') self.assertIsNone(evt2)
'Test no wait timeout, we should block forever, until we get one'
def test_event_no_timeout(self):
with eventpublisher_process(): me = salt.utils.event.MasterEvent(SOCK_DIR, listen=True) with eventsender_process({'data': 'foo2'}, 'evt2', 5): evt = me.get_event(tag='evt2', wait=0, no_block=False) self.assertGotEvent(evt, {'data': 'foo2'})
'Test a startswith match'
def test_event_matching(self):
with eventpublisher_process(): me = salt.utils.event.MasterEvent(SOCK_DIR, listen=True) me.fire_event({'data': 'foo1'}, 'evt1') evt1 = me.get_event(tag='ev') self.assertGotEvent(evt1, {'data': 'foo1'})
'Test a regex match'
def test_event_matching_regex(self):
with eventpublisher_process(): me = salt.utils.event.MasterEvent(SOCK_DIR, listen=True) me.fire_event({'data': 'foo1'}, 'evt1') evt1 = me.get_event(tag='^ev', match_type='regex') self.assertGotEvent(evt1, {'data': 'foo1'})
'Test an all match'
def test_event_matching_all(self):
with eventpublisher_process(): me = salt.utils.event.MasterEvent(SOCK_DIR, listen=True) me.fire_event({'data': 'foo1'}, 'evt1') evt1 = me.get_event(tag='') self.assertGotEvent(evt1, {'data': 'foo1'})
'Test event matching all when not passing a tag'
def test_event_matching_all_when_tag_is_None(self):
with eventpublisher_process(): me = salt.utils.event.MasterEvent(SOCK_DIR, listen=True) me.fire_event({'data': 'foo1'}, 'evt1') evt1 = me.get_event() self.assertGotEvent(evt1, {'data': 'foo1'})
'Test get_event drops non-subscribed events'
def test_event_not_subscribed(self):
with eventpublisher_process(): me = salt.utils.event.MasterEvent(SOCK_DIR, listen=True) me.fire_event({'data': 'foo1'}, 'evt1') me.fire_event({'data': 'foo2'}, 'evt2') evt2 = me.get_event(tag='evt2') evt1 = me.get_event(tag='evt1') self.assertGotEvent(evt2, {'data': 'foo2'}) self.assertIsNone(evt1)
'Test subscriptions cache a message until requested'
def test_event_subscription_cache(self):
with eventpublisher_process(): me = salt.utils.event.MasterEvent(SOCK_DIR, listen=True) me.subscribe('evt1') me.fire_event({'data': 'foo1'}, 'evt1') me.fire_event({'data': 'foo2'}, 'evt2') evt2 = me.get_event(tag='evt2') evt1 = me.get_event(tag='evt1') self.assertGotEvent(evt2, {'data': 'foo2'}) self.assertGotEvent(evt1, {'data': 'foo1'})
'Test regex subscriptions cache a message until requested'
def test_event_subscriptions_cache_regex(self):
with eventpublisher_process(): me = salt.utils.event.MasterEvent(SOCK_DIR, listen=True) me.subscribe('e..1$', 'regex') me.fire_event({'data': 'foo1'}, 'evt1') me.fire_event({'data': 'foo2'}, 'evt2') evt2 = me.get_event(tag='evt2') evt1 = me.get_event(tag='evt1') self.assertGotEvent(evt2, {'data': 'foo2'}) self.assertGotEvent(evt1, {'data': 'foo1'})
'Test event is received by multiple clients'
def test_event_multiple_clients(self):
with eventpublisher_process(): me1 = salt.utils.event.MasterEvent(SOCK_DIR, listen=True) me2 = salt.utils.event.MasterEvent(SOCK_DIR, listen=True) time.sleep(0.5) me1.fire_event({'data': 'foo1'}, 'evt1') evt1 = me1.get_event(tag='evt1') self.assertGotEvent(evt1, {'data': 'foo1'}) evt2 = me2.get_event(tag='evt1') self.assertGotEvent(evt2, {'data': 'foo1'})
'Test nested event subscriptions do not drop events, get event for all tags'
@expectedFailure def test_event_nested_sub_all(self):
with eventpublisher_process(): me = salt.utils.event.MasterEvent(SOCK_DIR, listen=True) me.fire_event({'data': 'foo1'}, 'evt1') me.fire_event({'data': 'foo2'}, 'evt2') evt2 = me.get_event(tag='') evt1 = me.get_event(tag='') self.assertGotEvent(evt2, {'data': 'foo2'}) self.assertGotEvent(evt1, {'data': 'foo1'})
'Test a large number of events, one at a time'
def test_event_many(self):
with eventpublisher_process(): me = salt.utils.event.MasterEvent(SOCK_DIR, listen=True) for i in range(500): me.fire_event({'data': '{0}'.format(i)}, 'testevents') evt = me.get_event(tag='testevents') self.assertGotEvent(evt, {'data': '{0}'.format(i)}, 'Event {0}'.format(i))
'Test a large number of events, send all then recv all'
def test_event_many_backlog(self):
with eventpublisher_process(): me = salt.utils.event.MasterEvent(SOCK_DIR, listen=True) for i in range(500): me.fire_event({'data': '{0}'.format(i)}, 'testevents') for i in range(500): evt = me.get_event(tag='testevents') self.assertGotEvent(evt, {'data': '{0}'.format(i)}, 'Event {0}'.format(i))
'Tests that sending an event through fire_master generates expected event'
def test_send_master_event(self):
with eventpublisher_process(): me = salt.utils.event.MasterEvent(SOCK_DIR, listen=True) data = {'data': 'foo1'} me.fire_master(data, 'test_master') evt = me.get_event(tag='fire_master') self.assertGotEvent(evt, {'data': data, 'tag': 'test_master', 'events': None, 'pretag': None})
'Test a single event is received'
def test_event_subscription(self):
me = salt.utils.event.MinionEvent(self.opts, listen=True) me.fire_event({'data': 'foo1'}, 'evt1') self.wait() evt1 = me.get_event(tag='evt1') self.assertEqual(self.tag, 'evt1') self.data.pop('_stamp') self.assertEqual(self.data, {'data': 'foo1'})
'Test IPv4 address validation'
def test_ipv4_addr(self):
true_addrs = ['127.0.0.1', '127.0.0.1', '127.0.0.19', '1.1.1.1/28', '127.0.0.11/32'] false_addrs = ['127.0.0.911', '127.0.0911', '127.0.011', '127.0.011/32', '::1', '::1/128', '::1/28'] for addr in true_addrs: self.assertTrue(net.ipv4_addr(addr)) for addr in false_addrs: self.assertFalse(net.ipv4_addr(addr))