desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'scenario of creating upgrading extensions with possible schema and version specifications'
def test_absent_failed(self):
with patch.dict(postgres_extension.__opts__, {'test': False}): with patch.dict(postgres_extension.__salt__, {'postgres.is_installed_extension': Mock(side_effect=[True, True]), 'postgres.drop_extension': Mock(side_effect=[False, False])}): ret = postgres_extension.absent('foo') self.assertEqual(ret, {'comment': 'Extension foo failed to be removed', 'changes': {}, 'name': 'foo', 'result': False})
'Test to ensures that the named DNS record is present with the given ttl.'
def test_present(self):
name = 'webserver' zone = 'example.com' ttl = '60' data = '111.222.333.444' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} with patch.dict(ddns.__opts__, {'test': True}): comt = 'A record "{0}" will be updated'.format(name) ret.update({'comment': comt}) self.assertDictEqual(ddns.present(name, zone, ttl, data), ret) with patch.dict(ddns.__opts__, {'test': False}): mock = MagicMock(return_value=None) with patch.dict(ddns.__salt__, {'ddns.update': mock}): comt = 'A record "{0}" already present with ttl of {1}'.format(name, ttl) ret.update({'comment': comt, 'result': True}) self.assertDictEqual(ddns.present(name, zone, ttl, data), ret)
'Test to ensures that the named DNS record is absent.'
def test_absent(self):
name = 'webserver' zone = 'example.com' data = '111.222.333.444' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} with patch.dict(ddns.__opts__, {'test': True}): comt = 'None record "{0}" will be deleted'.format(name) ret.update({'comment': comt}) self.assertDictEqual(ddns.absent(name, zone, data), ret) with patch.dict(ddns.__opts__, {'test': False}): mock = MagicMock(return_value=None) with patch.dict(ddns.__salt__, {'ddns.delete': mock}): comt = 'No matching DNS record(s) present' ret.update({'comment': comt, 'result': True}) self.assertDictEqual(ddns.absent(name, zone, data), ret)
'Test to ensure the launch configuration exists.'
def test_present(self):
name = 'mylc' image_id = 'ami-0b9c9f62' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} self.assertRaises(SaltInvocationError, boto_lc.present, name, image_id, user_data=True, cloud_init=True) mock = MagicMock(side_effect=[True, False]) with patch.dict(boto_lc.__salt__, {'boto_asg.launch_configuration_exists': mock}): comt = 'Launch configuration present.' ret.update({'comment': comt}) self.assertDictEqual(boto_lc.present(name, image_id), ret) with patch.dict(boto_lc.__opts__, {'test': True}): comt = 'Launch configuration set to be created.' ret.update({'comment': comt, 'result': None}) self.assertDictEqual(boto_lc.present(name, image_id), ret)
'Test to ensure the named launch configuration is deleted.'
def test_absent(self):
name = 'mylc' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} mock = MagicMock(side_effect=[False, True]) with patch.dict(boto_lc.__salt__, {'boto_asg.launch_configuration_exists': mock}): comt = 'Launch configuration does not exist.' ret.update({'comment': comt}) self.assertDictEqual(boto_lc.absent(name), ret) with patch.dict(boto_lc.__opts__, {'test': True}): comt = 'Launch configuration set to be deleted.' ret.update({'comment': comt, 'result': None}) self.assertDictEqual(boto_lc.absent(name), ret)
'Test to set the timezone for the system.'
def test_system(self):
ret = {'name': 'salt', 'changes': {}, 'result': True, 'comment': ''} mock = MagicMock(side_effect=[CommandExecutionError, True, True, True]) mock1 = MagicMock(side_effect=['local', 'localtime', 'localtime']) mock2 = MagicMock(return_value=False) with patch.dict(timezone.__salt__, {'timezone.zone_compare': mock, 'timezone.get_hwclock': mock1, 'timezone.set_hwclock': mock2}): ret.update({'comment': "Unable to compare desired timezone 'salt' to system timezone: ", 'result': False}) self.assertDictEqual(timezone.system('salt'), ret) ret.update({'comment': 'Timezone salt already set, UTC already set to salt', 'result': True}) self.assertDictEqual(timezone.system('salt'), ret) with patch.dict(timezone.__opts__, {'test': True}): ret.update({'comment': 'UTC needs to be set to True', 'result': None}) self.assertDictEqual(timezone.system('salt'), ret) with patch.dict(timezone.__opts__, {'test': False}): ret.update({'comment': 'Failed to set UTC to True', 'result': False}) self.assertDictEqual(timezone.system('salt'), ret)
'Test to ensure that the keystone user is present with the specified properties.'
def test_user_present(self):
name = 'nova' password = '$up3rn0v4' email = '[email protected]' tenant = 'demo' ret = {'name': name, 'result': False, 'changes': {}, 'comment': ''} mock_f = MagicMock(return_value=False) mock_lst = MagicMock(return_value=['Error']) with patch.dict(keystone.__salt__, {'keystone.tenant_get': mock_lst}): comt = 'Tenant / project "{0}" does not exist'.format(tenant) ret.update({'comment': comt}) self.assertDictEqual(keystone.user_present(name, password, email, tenant), ret) mock_dict = MagicMock(side_effect=[{name: {'email': '[email protected]'}}, {name: {'email': email, 'enabled': False}}, {name: {'email': email, 'enabled': True}}, {name: {'email': email, 'enabled': True}}, {'Error': 'error'}, {'Error': 'error'}]) mock_l = MagicMock(return_value={tenant: {'id': 'abc'}}) with patch.dict(keystone.__salt__, {'keystone.user_get': mock_dict, 'keystone.tenant_get': mock_l, 'keystone.user_verify_password': mock_f, 'keystone.user_create': mock_f}): with patch.dict(keystone.__opts__, {'test': True}): comt = 'User "{0}" will be updated'.format(name) ret.update({'comment': comt, 'result': None, 'changes': {'Email': 'Will be updated', 'Enabled': 'Will be True', 'Password': 'Will be updated'}}) self.assertDictEqual(keystone.user_present(name, password, email), ret) ret.update({'comment': comt, 'result': None, 'changes': {'Enabled': 'Will be True', 'Password': 'Will be updated'}}) self.assertDictEqual(keystone.user_present(name, password, email), ret) ret.update({'comment': comt, 'result': None, 'changes': {'Tenant': 'Will be added to "demo" tenant', 'Password': 'Will be updated'}}) self.assertDictEqual(keystone.user_present(name, password, email, tenant), ret) ret.update({'comment': comt, 'result': None, 'changes': {'Password': 'Will be updated'}}) self.assertDictEqual(keystone.user_present(name, password, email), ret) comt = 'Keystone user "nova" will be added' ret.update({'comment': comt, 'result': None, 'changes': {'User': 'Will be created'}}) self.assertDictEqual(keystone.user_present(name, password, email), ret) with patch.dict(keystone.__opts__, {'test': False}): comt = 'Keystone user {0} has been added'.format(name) ret.update({'comment': comt, 'result': True, 'changes': {'User': 'Created'}}) self.assertDictEqual(keystone.user_present(name, password, email), ret)
'Test to ensure that the keystone user is absent.'
def test_user_absent(self):
name = 'nova' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'User "{0}" is already absent'.format(name)} mock_lst = MagicMock(side_effect=[['Error'], []]) with patch.dict(keystone.__salt__, {'keystone.user_get': mock_lst}): self.assertDictEqual(keystone.user_absent(name), ret) with patch.dict(keystone.__opts__, {'test': True}): comt = 'User "{0}" will be deleted'.format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(keystone.user_absent(name), ret)
'Test to ensures that the keystone tenant exists'
def test_tenant_present(self):
name = 'nova' description = 'OpenStack Compute Service' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Tenant / project "{0}" already exists'.format(name)} mock_dict = MagicMock(side_effect=[{name: {'description': 'desc'}}, {name: {'description': description, 'enabled': False}}, {'Error': 'error'}, {'Error': 'error'}]) mock_t = MagicMock(return_value=True) with patch.dict(keystone.__salt__, {'keystone.tenant_get': mock_dict, 'keystone.tenant_create': mock_t}): with patch.dict(keystone.__opts__, {'test': True}): comt = 'Tenant / project "{0}" will be updated'.format(name) ret.update({'comment': comt, 'result': None, 'changes': {'Description': 'Will be updated'}}) self.assertDictEqual(keystone.tenant_present(name), ret) comt = 'Tenant / project "{0}" will be updated'.format(name) ret.update({'comment': comt, 'result': None, 'changes': {'Enabled': 'Will be True'}}) self.assertDictEqual(keystone.tenant_present(name, description), ret) comt = 'Tenant / project "{0}" will be added'.format(name) ret.update({'comment': comt, 'result': None, 'changes': {'Tenant': 'Will be created'}}) self.assertDictEqual(keystone.tenant_present(name), ret) with patch.dict(keystone.__opts__, {'test': False}): comt = 'Tenant / project "{0}" has been added'.format(name) ret.update({'comment': comt, 'result': True, 'changes': {'Tenant': 'Created'}}) self.assertDictEqual(keystone.tenant_present(name), ret)
'Test to ensure that the keystone tenant is absent.'
def test_tenant_absent(self):
name = 'nova' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Tenant / project "{0}" is already absent'.format(name)} mock_lst = MagicMock(side_effect=[['Error'], []]) with patch.dict(keystone.__salt__, {'keystone.tenant_get': mock_lst}): self.assertDictEqual(keystone.tenant_absent(name), ret) with patch.dict(keystone.__opts__, {'test': True}): comt = 'Tenant / project "{0}" will be deleted'.format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(keystone.tenant_absent(name), ret)
'Test to ensures that the keystone role exists'
def test_role_present(self):
name = 'nova' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Role "{0}" already exists'.format(name)} mock_lst = MagicMock(side_effect=[[], ['Error']]) with patch.dict(keystone.__salt__, {'keystone.role_get': mock_lst}): self.assertDictEqual(keystone.role_present(name), ret) with patch.dict(keystone.__opts__, {'test': True}): comt = 'Role "{0}" will be added'.format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(keystone.role_present(name), ret)
'Test to ensure that the keystone role is absent.'
def test_role_absent(self):
name = 'nova' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Role "{0}" is already absent'.format(name)} mock_lst = MagicMock(side_effect=[['Error'], []]) with patch.dict(keystone.__salt__, {'keystone.role_get': mock_lst}): self.assertDictEqual(keystone.role_absent(name), ret) with patch.dict(keystone.__opts__, {'test': True}): comt = 'Role "{0}" will be deleted'.format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(keystone.role_absent(name), ret)
'Test to ensure service present in Keystone catalog'
def test_service_present(self):
name = 'nova' service_type = 'compute' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Service "{0}" already exists'.format(name)} mock_lst = MagicMock(side_effect=[[], ['Error']]) with patch.dict(keystone.__salt__, {'keystone.service_get': mock_lst}): self.assertDictEqual(keystone.service_present(name, service_type), ret) with patch.dict(keystone.__opts__, {'test': True}): comt = 'Service "{0}" will be added'.format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(keystone.service_present(name, service_type), ret)
'Test to ensure that the service doesn\'t exist in Keystone catalog'
def test_service_absent(self):
name = 'nova' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Service "{0}" is already absent'.format(name)} mock_lst = MagicMock(side_effect=[['Error'], []]) with patch.dict(keystone.__salt__, {'keystone.service_get': mock_lst}): self.assertDictEqual(keystone.service_absent(name), ret) with patch.dict(keystone.__opts__, {'test': True}): comt = 'Service "{0}" will be deleted'.format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(keystone.service_absent(name), ret)
'Test to ensure the specified endpoints exists for service'
def test_endpoint_present(self):
name = 'nova' region = 'RegionOne' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} endpoint = {'adminurl': None, 'region': None, 'internalurl': None, 'publicurl': None, 'id': 1, 'service_id': None} mock_lst = MagicMock(side_effect=[endpoint, ['Error'], {'id': 1, 'service_id': None}, []]) mock = MagicMock(return_value=True) with patch.dict(keystone.__salt__, {'keystone.endpoint_get': mock_lst, 'keystone.endpoint_create': mock}): comt = 'Endpoint for service "{0}" already exists'.format(name) ret.update({'comment': comt, 'result': True, 'changes': {}}) self.assertDictEqual(keystone.endpoint_present(name), ret) with patch.dict(keystone.__opts__, {'test': True}): comt = 'Endpoint for service "{0}" will be added'.format(name) ret.update({'comment': comt, 'result': None, 'changes': {'Endpoint': 'Will be created'}}) self.assertDictEqual(keystone.endpoint_present(name), ret) comt = 'Endpoint for service "{0}" already exists'.format(name) ret.update({'comment': comt, 'result': True, 'changes': {}}) self.assertDictEqual(keystone.endpoint_present(name), ret) with patch.dict(keystone.__opts__, {'test': False}): comt = 'Endpoint for service "{0}" has been added'.format(name) ret.update({'comment': comt, 'result': True, 'changes': True}) self.assertDictEqual(keystone.endpoint_present(name), ret)
'Test to ensure that the endpoint for a service doesn\'t exist in Keystone catalog'
def test_endpoint_absent(self):
name = 'nova' region = 'RegionOne' comment = 'Endpoint for service "{0}" is already absent'.format(name) ret = {'name': name, 'changes': {}, 'result': True, 'comment': comment} mock_lst = MagicMock(side_effect=[[], ['Error']]) with patch.dict(keystone.__salt__, {'keystone.endpoint_get': mock_lst}): self.assertDictEqual(keystone.endpoint_absent(name, region), ret) with patch.dict(keystone.__opts__, {'test': True}): comt = 'Endpoint for service "{0}" will be deleted'.format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(keystone.endpoint_absent(name, region), ret)
'Test to enable the RDP service and make sure access to the RDP port is allowed in the firewall configuration.'
def test_enabled(self):
name = 'my_service' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} mock_t = MagicMock(side_effect=[False, False, True]) mock_f = MagicMock(return_value=False) with patch.dict(rdp.__salt__, {'rdp.status': mock_t, 'rdp.enable': mock_f}): with patch.dict(rdp.__opts__, {'test': True}): comt = 'RDP will be enabled' ret.update({'comment': comt, 'result': None}) self.assertDictEqual(rdp.enabled(name), ret) with patch.dict(rdp.__opts__, {'test': False}): ret.update({'comment': '', 'result': False, 'changes': {'RDP was enabled': True}}) self.assertDictEqual(rdp.enabled(name), ret) comt = 'RDP is enabled' ret.update({'comment': comt, 'result': True, 'changes': {}}) self.assertDictEqual(rdp.enabled(name), ret)
'Test to disable the RDP service.'
def test_disabled(self):
name = 'my_service' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} mock = MagicMock(side_effect=[True, True, False]) mock_t = MagicMock(return_value=True) with patch.dict(rdp.__salt__, {'rdp.status': mock, 'rdp.disable': mock_t}): with patch.dict(rdp.__opts__, {'test': True}): comt = 'RDP will be disabled' ret.update({'comment': comt, 'result': None}) self.assertDictEqual(rdp.disabled(name), ret) with patch.dict(rdp.__opts__, {'test': False}): ret.update({'comment': '', 'result': True, 'changes': {'RDP was disabled': True}}) self.assertDictEqual(rdp.disabled(name), ret) comt = 'RDP is disabled' ret.update({'comment': comt, 'result': True, 'changes': {}}) self.assertDictEqual(rdp.disabled(name), ret)
'Test to verify that the given module is set to the given target'
def test_set_(self):
name = 'myeselect' target = 'hardened/linux/amd64' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} mock = MagicMock(return_value=target) with patch.dict(eselect.__salt__, {'eselect.get_current_target': mock}): comt = "Target '{0}' is already set on '{1}' module.".format(target, name) ret.update({'comment': comt}) self.assertDictEqual(eselect.set_(name, target), ret)
'Test to manage libvirt keys.'
def test_keys(self):
with patch('os.path.isfile', MagicMock(return_value=False)): name = 'sunrise' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} mock = MagicMock(side_effect=[[], ['libvirt.servercert.pem'], {'libvirt.servercert.pem': 'A'}]) with patch.dict(virt.__salt__, {'pillar.ext': mock}): comt = 'All keys are correct' ret.update({'comment': comt}) self.assertDictEqual(virt.keys(name, basepath=self.pki_dir), ret) with patch.dict(virt.__opts__, {'test': True}): comt = 'Libvirt keys are set to be updated' ret.update({'comment': comt, 'result': None}) self.assertDictEqual(virt.keys(name, basepath=self.pki_dir), ret) with patch.dict(virt.__opts__, {'test': False}): with patch.object(salt.utils.files, 'fopen', MagicMock(mock_open())): comt = 'Updated libvirt certs and keys' ret.update({'comment': comt, 'result': True, 'changes': {'servercert': 'new'}}) self.assertDictEqual(virt.keys(name, basepath=self.pki_dir), ret)
'Test to manage libvirt keys.'
def test_keys_with_expiration_days(self):
with patch('os.path.isfile', MagicMock(return_value=False)): name = 'sunrise' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} mock = MagicMock(side_effect=[[], ['libvirt.servercert.pem'], {'libvirt.servercert.pem': 'A'}]) with patch.dict(virt.__salt__, {'pillar.ext': mock}): comt = 'All keys are correct' ret.update({'comment': comt}) self.assertDictEqual(virt.keys(name, basepath=self.pki_dir, expiration_days=700), ret) with patch.dict(virt.__opts__, {'test': True}): comt = 'Libvirt keys are set to be updated' ret.update({'comment': comt, 'result': None}) self.assertDictEqual(virt.keys(name, basepath=self.pki_dir, expiration_days=700), ret) with patch.dict(virt.__opts__, {'test': False}): with patch.object(salt.utils.files, 'fopen', MagicMock(mock_open())): comt = 'Updated libvirt certs and keys' ret.update({'comment': comt, 'result': True, 'changes': {'servercert': 'new'}}) self.assertDictEqual(virt.keys(name, basepath=self.pki_dir, expiration_days=700), ret)
'Test to manage libvirt keys.'
def test_keys_with_state(self):
with patch('os.path.isfile', MagicMock(return_value=False)): name = 'sunrise' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} mock = MagicMock(side_effect=[[], ['libvirt.servercert.pem'], {'libvirt.servercert.pem': 'A'}]) with patch.dict(virt.__salt__, {'pillar.ext': mock}): comt = 'All keys are correct' ret.update({'comment': comt}) self.assertDictEqual(virt.keys(name, basepath=self.pki_dir, st='California'), ret) with patch.dict(virt.__opts__, {'test': True}): comt = 'Libvirt keys are set to be updated' ret.update({'comment': comt, 'result': None}) self.assertDictEqual(virt.keys(name, basepath=self.pki_dir, st='California'), ret) with patch.dict(virt.__opts__, {'test': False}): with patch.object(salt.utils.files, 'fopen', MagicMock(mock_open())): comt = 'Updated libvirt certs and keys' ret.update({'comment': comt, 'result': True, 'changes': {'servercert': 'new'}}) self.assertDictEqual(virt.keys(name, basepath=self.pki_dir, st='California'), ret)
'Test to manage libvirt keys.'
def test_keys_with_all_options(self):
with patch('os.path.isfile', MagicMock(return_value=False)): name = 'sunrise' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} mock = MagicMock(side_effect=[[], ['libvirt.servercert.pem'], {'libvirt.servercert.pem': 'A'}]) with patch.dict(virt.__salt__, {'pillar.ext': mock}): comt = 'All keys are correct' ret.update({'comment': comt}) self.assertDictEqual(virt.keys(name, basepath=self.pki_dir, country='USA', st='California', locality='Los_Angeles', organization='SaltStack', expiration_days=700), ret) with patch.dict(virt.__opts__, {'test': True}): comt = 'Libvirt keys are set to be updated' ret.update({'comment': comt, 'result': None}) self.assertDictEqual(virt.keys(name, basepath=self.pki_dir, country='USA', st='California', locality='Los_Angeles', organization='SaltStack', expiration_days=700), ret) with patch.dict(virt.__opts__, {'test': False}): with patch.object(salt.utils.files, 'fopen', MagicMock(mock_open())): comt = 'Updated libvirt certs and keys' ret.update({'comment': comt, 'result': True, 'changes': {'servercert': 'new'}}) self.assertDictEqual(virt.keys(name, basepath=self.pki_dir, country='USA', st='California', locality='Los_Angeles', organization='SaltStack', expiration_days=700), ret)
'Test to ensure that the named extension is present with the specified privileges.'
def test_present(self):
name = 'frank' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} mock = MagicMock(return_value={}) with patch.dict(postgres_extension.__salt__, {'postgres.create_metadata': mock}): with patch.dict(postgres_extension.__opts__, {'test': True}): comt = 'Extension {0} is set to be created'.format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(postgres_extension.present(name), ret) with patch.dict(postgres_extension.__opts__, {'test': False}): comt = 'Extension {0} is already present'.format(name) ret.update({'comment': comt, 'result': True}) self.assertDictEqual(postgres_extension.present(name), ret)
'Test to ensure that the named extension is absent.'
def test_absent(self):
name = 'frank' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} mock_t = MagicMock(side_effect=[True, False]) mock = MagicMock(side_effect=[True, True, True, False]) with patch.dict(postgres_extension.__salt__, {'postgres.is_installed_extension': mock, 'postgres.drop_extension': mock_t}): with patch.dict(postgres_extension.__opts__, {'test': True}): comt = 'Extension {0} is set to be removed'.format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(postgres_extension.absent(name), ret) with patch.dict(postgres_extension.__opts__, {'test': False}): comt = 'Extension {0} has been removed'.format(name) ret.update({'comment': comt, 'result': True, 'changes': {name: 'Absent'}}) self.assertDictEqual(postgres_extension.absent(name), ret) comt = 'Extension {0} failed to be removed'.format(name) ret.update({'comment': comt, 'result': False, 'changes': {}}) self.assertDictEqual(postgres_extension.absent(name), ret) comt = 'Extension {0} is not present, so it cannot be removed'.format(name) ret.update({'comment': comt, 'result': True}) self.assertDictEqual(postgres_extension.absent(name), ret)
'Test to ensure the DynamoDB table exists.'
def test_present(self):
name = 'new_table' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} exists_mock = MagicMock(side_effect=[True, False, False]) dict_mock = MagicMock(return_value={}) mock_bool = MagicMock(return_value=True) pillar_mock = MagicMock(return_value=[]) with patch.dict(boto_dynamodb.__salt__, {'boto_dynamodb.exists': exists_mock, 'boto_dynamodb.describe': dict_mock, 'config.option': dict_mock, 'pillar.get': pillar_mock, 'boto_dynamodb.create_table': mock_bool}): comt = 'DynamoDB table {0} exists,\nDynamoDB table {0} throughput matches,\nAll global secondary indexes match,\n'.format(name) ret.update({'comment': comt}) self.assertDictEqual(boto_dynamodb.present(name), ret) with patch.dict(boto_dynamodb.__opts__, {'test': True}): comt = 'DynamoDB table {0} is set to be created.,\nDynamoDB table {0} throughput matches,\nAll global secondary indexes match,\n'.format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(boto_dynamodb.present(name), ret) changes = {'new': {'global_indexes': None, 'hash_key': None, 'hash_key_data_type': None, 'local_indexes': None, 'range_key': None, 'range_key_data_type': None, 'read_capacity_units': None, 'table': 'new_table', 'write_capacity_units': None}} with patch.dict(boto_dynamodb.__opts__, {'test': False}): comt = 'DynamoDB table {0} was successfully created,\nDynamoDB table new_table throughput matches,\n'.format(name) ret.update({'comment': comt, 'result': True, 'changes': changes}) self.assertDictEqual(ret, boto_dynamodb.present(name))
'Test to ensure the DynamoDB table does not exist.'
def test_absent(self):
name = 'new_table' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} mock = MagicMock(side_effect=[False, True, True]) mock_bool = MagicMock(return_value=True) with patch.dict(boto_dynamodb.__salt__, {'boto_dynamodb.exists': mock, 'boto_dynamodb.delete': mock_bool}): comt = 'DynamoDB table {0} does not exist'.format(name) ret.update({'comment': comt}) self.assertDictEqual(boto_dynamodb.absent(name), ret) with patch.dict(boto_dynamodb.__opts__, {'test': True}): comt = 'DynamoDB table {0} is set to be deleted '.format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(boto_dynamodb.absent(name), ret) changes = {'new': 'Table new_table deleted', 'old': 'Table new_table exists'} with patch.dict(boto_dynamodb.__opts__, {'test': False}): comt = 'Deleted DynamoDB table {0}'.format(name) ret.update({'comment': comt, 'result': True, 'changes': changes}) self.assertDictEqual(boto_dynamodb.absent(name), ret)
'According following sls, .. code-block:: yaml image:latest: docker_image.present: - force: true if ``image:latest`` is already downloaded locally the state should not report changes.'
def test_present_already_local(self):
docker_inspect_image = Mock(return_value={'Id': 'abcdefghijk'}) docker_pull = Mock(return_value={'Layers': {'Already_Pulled': ['abcdefghijk'], 'Pulled': []}, 'Status': 'Image is up to date for image:latest', 'Time_Elapsed': 1.1}) docker_list_tags = Mock(return_value=['image:latest']) __salt__ = {'docker.list_tags': docker_list_tags, 'docker.pull': docker_pull, 'docker.inspect_image': docker_inspect_image} with patch.dict(docker_state.__dict__, {'__salt__': __salt__}): ret = docker_state.present('image:latest', force=True) self.assertEqual(ret, {'changes': {}, 'result': True, 'comment': "Image 'image:latest' was pulled, but there were no changes", 'name': 'image:latest'})
'According following sls, .. code-block:: yaml image:latest: docker_image.present: - force: true if ``image:latest`` is not downloaded and force is true should pull a new image successfuly.'
def test_present_and_force(self):
docker_inspect_image = Mock(side_effect=CommandExecutionError('Error 404: No such image/container: image:latest')) docker_pull = Mock(return_value={'Layers': {'Already_Pulled': ['abcdefghijk'], 'Pulled': ['abcdefghijk']}, 'Status': "Image 'image:latest' was pulled", 'Time_Elapsed': 1.1}) docker_list_tags = Mock(side_effect=[[], ['image:latest']]) __salt__ = {'docker.list_tags': docker_list_tags, 'docker.pull': docker_pull, 'docker.inspect_image': docker_inspect_image} with patch.dict(docker_state.__dict__, {'__salt__': __salt__}): ret = docker_state.present('image:latest', force=True) self.assertEqual(ret, {'changes': {'Layers': {'Already_Pulled': ['abcdefghijk'], 'Pulled': ['abcdefghijk']}, 'Status': "Image 'image:latest' was pulled", 'Time_Elapsed': 1.1}, 'result': True, 'comment': "Image 'image:latest' was pulled", 'name': 'image:latest'})
'Check that `name` parameter containing bad characters is not parsed by pip when package is being installed in editable mode. For more information, see issue #21890.'
def test_install_in_editable_mode(self):
mock = MagicMock(return_value={'retcode': 0, 'stdout': ''}) pip_list = MagicMock(return_value={}) pip_install = MagicMock(return_value={'retcode': 0, 'stderr': '', 'stdout': 'Cloned!'}) with patch.dict(pip_state.__salt__, {'cmd.run_all': mock, 'pip.list': pip_list, 'pip.install': pip_install}): ret = pip_state.installed('state@name', cwd='/path/to/project', editable=['.']) self.assertSaltTrueReturn({'test': ret}) self.assertInSaltComment('successfully installed', {'test': ret})
'Tests exceptions when describing identity pools'
def test_present_when_failing_to_describe_identity_pools(self):
self.conn.list_identity_pools.return_value = identity_pools_ret self.conn.describe_identity_pool.side_effect = ClientError(error_content, 'error on describe identity pool') result = self.salt_states['boto_cognitoidentity.pool_present'](name='test pool present', IdentityPoolName=first_pool_name, AuthenticatedRole='my_auth_role', **conn_parameters) self.assertEqual(result.get('result'), False) self.assertTrue(('error on describe identity pool' in result.get('comment', {})))
'Tests present on an identity pool name where it matched multiple pools. The result should fail.'
def test_present_when_multiple_pools_with_same_name_exist(self):
self.conn.list_identity_pools.return_value = identity_pools_ret self.conn.describe_identity_pool.side_effect = self._describe_identity_pool_side_effect result = self.salt_states['boto_cognitoidentity.pool_present'](name='test pool present', IdentityPoolName=first_pool_name, AuthenticatedRole='my_auth_role', **conn_parameters) self.assertEqual(result.get('result'), False) self.assertIn('{0}'.format([first_pool_ret, third_pool_ret]), result.get('comment', ''))
'Tests present on an identity pool name that doesn\'t exist and an error is thrown on creation.'
def test_present_when_failing_to_create_a_new_identity_pool(self):
self.conn.list_identity_pools.return_value = identity_pools_ret self.conn.describe_identity_pool.side_effect = self._describe_identity_pool_side_effect self.conn.create_identity_pool.side_effect = ClientError(error_content, 'error on create_identity_pool') result = self.salt_states['boto_cognitoidentity.pool_present'](name='test pool present', IdentityPoolName=default_pool_name, AuthenticatedRole='my_auth_role', **conn_parameters) self.assertEqual(result.get('result'), False) self.assertTrue(('error on create_identity_pool' in result.get('comment', ''))) self.assertTrue((self.conn.update_identity_pool.call_count == 0))
'Tests present on a unique instance of identity pool having the matching IdentityPoolName, and an error is thrown on updating the pool properties.'
def test_present_when_failing_to_update_an_existing_identity_pool(self):
self.conn.list_identity_pools.return_value = identity_pools_ret self.conn.describe_identity_pool.side_effect = self._describe_identity_pool_side_effect self.conn.update_identity_pool.side_effect = ClientError(error_content, 'error on update_identity_pool') result = self.salt_states['boto_cognitoidentity.pool_present'](name='test pool present', IdentityPoolName=second_pool_name, AuthenticatedRole='my_auth_role', AllowUnauthenticatedIdentities=True, **conn_parameters) self.assertEqual(result.get('result'), False) self.assertTrue(('error on update_identity_pool' in result.get('comment', ''))) self.assertTrue((self.conn.create_identity_pool.call_count == 0))
'Tests present on a unique instance of identity pool having the matching IdentityPoolName, where update_identity_pool succeeded, but an error is thrown on getting the identity pool role prior to setting the roles.'
def test_present_when_failing_to_get_identity_pool_roles(self):
self.conn.list_identity_pools.return_value = identity_pools_ret self.conn.describe_identity_pool.side_effect = self._describe_identity_pool_side_effect self.conn.update_identity_pool.return_value = second_pool_update_ret self.conn.get_identity_pool_roles.side_effect = ClientError(error_content, 'error on get_identity_pool_roles') result = self.salt_states['boto_cognitoidentity.pool_present'](name='test pool present', IdentityPoolName=second_pool_name, AuthenticatedRole='my_auth_role', AllowUnauthenticatedIdentities=True, **conn_parameters) self.assertEqual(result.get('result'), False) self.assertTrue(('error on get_identity_pool_roles' in result.get('comment', ''))) self.assertTrue((self.conn.create_identity_pool.call_count == 0)) self.assertTrue((self.conn.set_identity_pool_roles.call_count == 0))
'Tests present on a unique instance of identity pool having the matching IdentityPoolName, where update_identity_pool succeeded, but an error is thrown on setting the identity pool role.'
def test_present_when_failing_to_set_identity_pool_roles(self):
self.conn.list_identity_pools.return_value = identity_pools_ret self.conn.describe_identity_pool.side_effect = self._describe_identity_pool_side_effect self.conn.update_identity_pool.return_value = second_pool_update_ret self.conn.get_identity_pool_roles.return_value = second_pool_role_ret self.conn.set_identity_pool_roles.side_effect = ClientError(error_content, 'error on set_identity_pool_roles') with patch.dict(self.funcs, {'boto_iam.describe_role': MagicMock(return_value={'arn': 'my_auth_role_arn'})}): result = self.salt_states['boto_cognitoidentity.pool_present'](name='test pool present', IdentityPoolName=second_pool_name, AuthenticatedRole='my_auth_role', AllowUnauthenticatedIdentities=True, **conn_parameters) self.assertEqual(result.get('result'), False) self.assertTrue(('error on set_identity_pool_roles' in result.get('comment', ''))) expected_call_args = (dict(IdentityPoolId=second_pool_id, Roles={'authenticated': 'my_auth_role_arn'}),) self.assertTrue((self.conn.set_identity_pool_roles.call_args == expected_call_args))
'Tests the successful case of creating a new instance, and updating its roles'
def test_present_when_pool_name_does_not_exist(self):
self.conn.list_identity_pools.return_value = identity_pools_ret self.conn.create_identity_pool.side_effect = self._describe_identity_pool_side_effect self.conn.get_identity_pool_roles.return_value = default_pool_role_ret self.conn.set_identity_pool_roles.return_value = None with patch.dict(self.funcs, {'boto_iam.describe_role': MagicMock(return_value={'arn': 'my_auth_role_arn'})}): result = self.salt_states['boto_cognitoidentity.pool_present'](name='test pool present', IdentityPoolName=default_pool_name, AuthenticatedRole='my_auth_role', AllowUnauthenticatedIdentities=True, DeveloperProviderName=default_dev_provider, **conn_parameters) self.assertEqual(result.get('result'), True) expected_call_args = (dict(AllowUnauthenticatedIdentities=True, IdentityPoolName=default_pool_name, DeveloperProviderName=default_dev_provider, SupportedLoginProviders={}, OpenIdConnectProviderARNs=[]),) self.assertTrue((self.conn.create_identity_pool.call_args == expected_call_args)) expected_call_args = (dict(IdentityPoolId=default_pool_id, Roles={'authenticated': 'my_auth_role_arn'}),) self.assertTrue((self.conn.set_identity_pool_roles.call_args == expected_call_args)) self.assertTrue((self.conn.update_identity_pool.call_count == 0))
'Tests the successful case of updating a single instance with matching IdentityPoolName and its roles.'
def test_present_when_pool_name_exists(self):
self.conn.list_identity_pools.return_value = identity_pools_ret self.conn.describe_identity_pool.side_effect = self._describe_identity_pool_side_effect self.conn.update_identity_pool.return_value = second_pool_update_ret self.conn.get_identity_pool_roles.return_value = second_pool_role_ret self.conn.set_identity_pool_roles.return_value = None with patch.dict(self.funcs, {'boto_iam.describe_role': MagicMock(return_value={'arn': 'my_auth_role_arn'})}): result = self.salt_states['boto_cognitoidentity.pool_present'](name='test pool present', IdentityPoolName=second_pool_name, AuthenticatedRole='my_auth_role', AllowUnauthenticatedIdentities=True, **conn_parameters) self.assertEqual(result.get('result'), True) expected_call_args = (dict(AllowUnauthenticatedIdentities=True, IdentityPoolId=second_pool_id, IdentityPoolName=second_pool_name),) self.assertTrue((self.conn.update_identity_pool.call_args == expected_call_args)) expected_call_args = (dict(IdentityPoolId=second_pool_id, Roles={'authenticated': 'my_auth_role_arn'}),) self.assertTrue((self.conn.set_identity_pool_roles.call_args == expected_call_args)) self.assertTrue((self.conn.create_identity_pool.call_count == 0))
'Tests absent on an identity pool that does not exist.'
def test_absent_when_pool_does_not_exist(self):
self.conn.list_identity_pools.return_value = identity_pools_ret result = self.salt_states['boto_cognitoidentity.pool_absent'](name='test pool absent', IdentityPoolName='no_such_pool_name', RemoveAllMatched=False, **conn_parameters) self.assertEqual(result.get('result'), True) self.assertEqual(result['changes'], {})
'Tests absent on when RemoveAllMatched flag is false and there are multiple matches for the given pool name first_pool_name is matched to first and third pool with different id\'s'
def test_absent_when_removeallmatched_is_false_and_multiple_pools_matched(self):
self.conn.list_identity_pools.return_value = identity_pools_ret self.conn.describe_identity_pool.side_effect = self._describe_identity_pool_side_effect result = self.salt_states['boto_cognitoidentity.pool_absent'](name='test pool absent', IdentityPoolName=first_pool_name, RemoveAllMatched=False, **conn_parameters) self.assertEqual(result.get('result'), False) self.assertEqual(result['changes'], {}) self.assertTrue(('{0}'.format([first_pool_ret, third_pool_ret]) in result.get('comment', '')))
'Tests exceptions when describing identity pools'
def test_absent_when_failing_to_describe_identity_pools(self):
self.conn.list_identity_pools.return_value = identity_pools_ret self.conn.describe_identity_pool.side_effect = ClientError(error_content, 'error on describe identity pool') result = self.salt_states['boto_cognitoidentity.pool_absent'](name='test pool absent', IdentityPoolName=first_pool_name, RemoveAllMatched=False, **conn_parameters) self.assertEqual(result.get('result'), False) self.assertTrue(('error on describe identity pool' in result.get('comment', {})))
'Tests error due to delete_identity_pools'
def test_absent_when_erroring_on_delete_identity_pool(self):
self.conn.list_identity_pools.return_value = identity_pools_ret self.conn.describe_identity_pool.side_effect = self._describe_identity_pool_side_effect self.conn.delete_identity_pool.side_effect = ClientError(error_content, 'error on delete identity pool') result = self.salt_states['boto_cognitoidentity.pool_absent'](name='test pool absent', IdentityPoolName=first_pool_name, RemoveAllMatched=True, **conn_parameters) self.assertEqual(result.get('result'), False) self.assertEqual(result['changes'], {}) self.assertTrue(('error on delete identity pool' in result.get('comment', '')))
'Tests absent succeeds on delete when a single pool matched and RemoveAllMatched is False'
def test_absent_when_a_single_pool_exists(self):
self.conn.list_identity_pools.return_value = identity_pools_ret self.conn.describe_identity_pool.return_value = second_pool_ret self.conn.delete_identity_pool.return_value = None result = self.salt_states['boto_cognitoidentity.pool_absent'](name='test pool absent', IdentityPoolName=second_pool_name, RemoveAllMatched=False, **conn_parameters) self.assertEqual(result.get('result'), True) expected_changes = {'new': {'Identity Pool Id {0}'.format(second_pool_id): None}, 'old': {'Identity Pool Id {0}'.format(second_pool_id): second_pool_name}} self.assertEqual(result['changes'], expected_changes)
'Tests absent succeeds on delete when a multiple pools matched and RemoveAllMatched is True first_pool_name should match to first_pool_id and third_pool_id'
def test_absent_when_multiple_pool_exists_and_removeallmatched_flag_is_true(self):
self.conn.list_identity_pools.return_value = identity_pools_ret self.conn.describe_identity_pool.side_effect = self._describe_identity_pool_side_effect self.conn.delete_identity_pool.return_value = None result = self.salt_states['boto_cognitoidentity.pool_absent'](name='test pool absent', IdentityPoolName=first_pool_name, RemoveAllMatched=True, **conn_parameters) self.assertEqual(result.get('result'), True) expected_changes = {'new': {'Identity Pool Id {0}'.format(first_pool_id): None, 'Identity Pool Id {0}'.format(third_pool_id): None}, 'old': {'Identity Pool Id {0}'.format(first_pool_id): first_pool_name, 'Identity Pool Id {0}'.format(third_pool_id): third_pool_name}} self.assertEqual(result['changes'], expected_changes)
'Test to ensure that the named database is present.'
def test_present(self):
name = 'salt' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} mock = MagicMock(side_effect=[False, False, False, True]) mock_t = MagicMock(side_effect=[True, False]) with patch.dict(influxdb08_database.__salt__, {'influxdb08.db_exists': mock, 'influxdb08.db_create': mock_t}): with patch.dict(influxdb08_database.__opts__, {'test': True}): comt = 'Database {0} is absent and needs to be created'.format(name) ret.update({'comment': comt}) self.assertDictEqual(influxdb08_database.present(name), ret) with patch.dict(influxdb08_database.__opts__, {'test': False}): comt = 'Database {0} has been created'.format(name) ret.update({'comment': comt, 'result': True, 'changes': {'salt': 'Present'}}) self.assertDictEqual(influxdb08_database.present(name), ret) comt = 'Failed to create database {0}'.format(name) ret.update({'comment': comt, 'result': False, 'changes': {}}) self.assertDictEqual(influxdb08_database.present(name), ret) comt = 'Database {0} is already present, so cannot be created'.format(name) ret.update({'comment': comt, 'result': True}) self.assertDictEqual(influxdb08_database.present(name), ret)
'Test to ensure that the named database is absent.'
def test_absent(self):
name = 'salt' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} mock = MagicMock(side_effect=[True, True, True, False]) mock_t = MagicMock(side_effect=[True, False]) with patch.dict(influxdb08_database.__salt__, {'influxdb08.db_exists': mock, 'influxdb08.db_remove': mock_t}): with patch.dict(influxdb08_database.__opts__, {'test': True}): comt = 'Database {0} is present and needs to be removed'.format(name) ret.update({'comment': comt}) self.assertDictEqual(influxdb08_database.absent(name), ret) with patch.dict(influxdb08_database.__opts__, {'test': False}): comt = 'Database {0} has been removed'.format(name) ret.update({'comment': comt, 'result': True, 'changes': {'salt': 'Absent'}}) self.assertDictEqual(influxdb08_database.absent(name), ret) comt = 'Failed to remove database {0}'.format(name) ret.update({'comment': comt, 'result': False, 'changes': {}}) self.assertDictEqual(influxdb08_database.absent(name), ret) comt = 'Database {0} is not present, so it cannot be removed'.format(name) ret.update({'comment': comt, 'result': True}) self.assertDictEqual(influxdb08_database.absent(name), ret)
'Test to ensure that the key exists in redis with the value specified.'
def test_string(self):
name = 'key_in_redis' value = 'string data' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Key already set to defined value'} mock = MagicMock(return_value=value) with patch.dict(redismod.__salt__, {'redis.get_key': mock}): self.assertDictEqual(redismod.string(name, value), ret)
'Test to ensure key absent from redis.'
def test_absent(self):
name = 'key_in_redis' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} mock = MagicMock(side_effect=[False, True, True]) mock_t = MagicMock(return_value=False) with patch.dict(redismod.__salt__, {'redis.exists': mock, 'redis.delete': mock_t}): comt = '`keys` not formed as a list type' ret.update({'comment': comt, 'result': False}) self.assertDictEqual(redismod.absent(name, 'key'), ret) comt = 'Key(s) specified already absent' ret.update({'comment': comt, 'result': True}) self.assertDictEqual(redismod.absent(name, ['key']), ret) comt = 'Keys deleted' ret.update({'comment': comt, 'changes': {'deleted': ['key']}}) self.assertDictEqual(redismod.absent(name, ['key']), ret) comt = 'Key deleted' ret.update({'comment': comt, 'changes': {'deleted': ['key_in_redis']}}) self.assertDictEqual(redismod.absent(name), ret)
'Test to verify if node is peered.'
def test_peered(self):
name = 'server1' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} mock_ip = MagicMock(return_value=['1.2.3.4', '1.2.3.5']) mock_hostbyname = MagicMock(return_value='1.2.3.5') mock_peer = MagicMock(return_value=True) mock_status = MagicMock(return_value={'uuid1': {'hostnames': [name]}}) with patch.dict(glusterfs.__salt__, {'glusterfs.peer_status': mock_status, 'glusterfs.peer': mock_peer, 'network.ip_addrs': mock_ip}): with patch.object(socket, 'gethostbyname', mock_hostbyname): comt = 'Peering with localhost is not needed' ret.update({'comment': comt}) self.assertDictEqual(glusterfs.peered(name), ret) mock_hostbyname.return_value = '1.2.3.42' comt = 'Host {0} already peered'.format(name) ret.update({'comment': comt}) self.assertDictEqual(glusterfs.peered(name), ret) with patch.dict(glusterfs.__opts__, {'test': False}): old = {'uuid1': {'hostnames': ['other1']}} new = {'uuid1': {'hostnames': ['other1']}, 'uuid2': {'hostnames': ['someAlias', name]}} mock_status.side_effect = [old, new] comt = 'Host {0} successfully peered'.format(name) ret.update({'comment': comt, 'changes': {'old': old, 'new': new}}) self.assertDictEqual(glusterfs.peered(name), ret) mock_status.side_effect = None mock_status.return_value = {'uuid1': {'hostnames': ['other']}} mock_peer.return_value = False ret.update({'result': False}) comt = ('Failed to peer with {0},' + ' please check logs for errors').format(name) ret.update({'comment': comt, 'changes': {}}) self.assertDictEqual(glusterfs.peered(name), ret) comt = 'Invalid characters in peer name.' ret.update({'comment': comt, 'name': ':/'}) self.assertDictEqual(glusterfs.peered(':/'), ret) ret.update({'name': name}) with patch.dict(glusterfs.__opts__, {'test': True}): comt = 'Peer {0} will be added.'.format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(glusterfs.peered(name), ret)
'Test to ensure that a volume exists'
def test_volume_present(self):
name = 'salt' bricks = ['host1:/brick1'] ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} started_info = {name: {'status': '1'}} stopped_info = {name: {'status': '0'}} mock_info = MagicMock() mock_list = MagicMock() mock_create = MagicMock() mock_start = MagicMock(return_value=True) with patch.dict(glusterfs.__salt__, {'glusterfs.info': mock_info, 'glusterfs.list_volumes': mock_list, 'glusterfs.create_volume': mock_create, 'glusterfs.start_volume': mock_start}): with patch.dict(glusterfs.__opts__, {'test': False}): mock_list.return_value = [name] mock_info.return_value = started_info comt = 'Volume {0} already exists and is started'.format(name) ret.update({'comment': comt}) self.assertDictEqual(glusterfs.volume_present(name, bricks, start=True), ret) mock_info.return_value = stopped_info comt = 'Volume {0} already exists and is now started'.format(name) ret.update({'comment': comt, 'changes': {'old': 'stopped', 'new': 'started'}}) self.assertDictEqual(glusterfs.volume_present(name, bricks, start=True), ret) comt = 'Volume {0} already exists'.format(name) ret.update({'comment': comt, 'changes': {}}) self.assertDictEqual(glusterfs.volume_present(name, bricks, start=False), ret) with patch.dict(glusterfs.__opts__, {'test': True}): comt = 'Volume {0} already exists'.format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(glusterfs.volume_present(name, bricks, start=False), ret) comt = ('Volume {0} already exists' + ' and will be started').format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(glusterfs.volume_present(name, bricks, start=True), ret) mock_list.return_value = [] comt = 'Volume {0} will be created'.format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(glusterfs.volume_present(name, bricks, start=False), ret) comt = ('Volume {0} will be created' + ' and started').format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(glusterfs.volume_present(name, bricks, start=True), ret) with patch.dict(glusterfs.__opts__, {'test': False}): mock_list.side_effect = [[], [name]] comt = 'Volume {0} is created'.format(name) ret.update({'comment': comt, 'result': True, 'changes': {'old': [], 'new': [name]}}) self.assertDictEqual(glusterfs.volume_present(name, bricks, start=False), ret) mock_list.side_effect = [[], [name]] comt = 'Volume {0} is created and is now started'.format(name) ret.update({'comment': comt, 'result': True}) self.assertDictEqual(glusterfs.volume_present(name, bricks, start=True), ret) mock_list.side_effect = None mock_list.return_value = [] mock_create.return_value = False comt = 'Creation of volume {0} failed'.format(name) ret.update({'comment': comt, 'result': False, 'changes': {}}) self.assertDictEqual(glusterfs.volume_present(name, bricks), ret) with patch.object(salt.utils.cloud, 'check_name', MagicMock(return_value=True)): comt = 'Invalid characters in volume name.' ret.update({'comment': comt, 'result': False}) self.assertDictEqual(glusterfs.volume_present(name, bricks), ret)
'Test to check if volume has been started'
def test_started(self):
name = 'salt' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} started_info = {name: {'status': '1'}} stopped_info = {name: {'status': '0'}} mock_info = MagicMock(return_value={}) mock_start = MagicMock(return_value=True) with patch.dict(glusterfs.__salt__, {'glusterfs.info': mock_info, 'glusterfs.start_volume': mock_start}): comt = 'Volume {0} does not exist'.format(name) ret.update({'comment': comt}) self.assertDictEqual(glusterfs.started(name), ret) mock_info.return_value = started_info comt = 'Volume {0} is already started'.format(name) ret.update({'comment': comt, 'result': True}) self.assertDictEqual(glusterfs.started(name), ret) with patch.dict(glusterfs.__opts__, {'test': True}): mock_info.return_value = stopped_info comt = 'Volume {0} will be started'.format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(glusterfs.started(name), ret) with patch.dict(glusterfs.__opts__, {'test': False}): comt = 'Volume {0} is started'.format(name) ret.update({'comment': comt, 'result': True, 'change': {'new': 'started', 'old': 'stopped'}}) self.assertDictEqual(glusterfs.started(name), ret)
'Test to add brick(s) to an existing volume'
def test_add_volume_bricks(self):
name = 'salt' bricks = ['host1:/drive1'] old_bricks = ['host1:/drive2'] ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} stopped_volinfo = {'salt': {'status': '0'}} volinfo = {'salt': {'status': '1', 'bricks': {'brick1': {'path': old_bricks[0]}}}} new_volinfo = {'salt': {'status': '1', 'bricks': {'brick1': {'path': old_bricks[0]}, 'brick2': {'path': bricks[0]}}}} mock_info = MagicMock(return_value={}) mock_add = MagicMock(side_effect=[False, True]) with patch.dict(glusterfs.__salt__, {'glusterfs.info': mock_info, 'glusterfs.add_volume_bricks': mock_add}): ret.update({'comment': 'Volume salt does not exist'}) self.assertDictEqual(glusterfs.add_volume_bricks(name, bricks), ret) mock_info.return_value = stopped_volinfo ret.update({'comment': 'Volume salt is not started'}) self.assertDictEqual(glusterfs.add_volume_bricks(name, bricks), ret) mock_info.return_value = volinfo ret.update({'comment': 'Adding bricks to volume salt failed'}) self.assertDictEqual(glusterfs.add_volume_bricks(name, bricks), ret) ret.update({'result': True}) ret.update({'comment': 'Bricks already added in volume salt'}) self.assertDictEqual(glusterfs.add_volume_bricks(name, old_bricks), ret) mock_info.side_effect = [volinfo, new_volinfo] ret.update({'comment': 'Bricks successfully added to volume salt', 'changes': {'new': (bricks + old_bricks), 'old': old_bricks}}) result = glusterfs.add_volume_bricks(name, bricks) ret['changes']['new'] = sorted(ret['changes']['new']) result['changes']['new'] = sorted(result['changes']['new']) self.assertDictEqual(result, ret)
'Test to manage NTP servers.'
def test_managed(self):
name = 'coffee-script' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} mock_lst = MagicMock(return_value=[]) with patch.dict(ntp.__salt__, {'ntp.get_servers': mock_lst, 'ntp.set_servers': mock_lst}): comt = 'NTP servers already configured as specified' ret.update({'comment': comt, 'result': True}) self.assertDictEqual(ntp.managed(name, []), ret) with patch.dict(ntp.__opts__, {'test': True}): comt = 'NTP servers will be updated to: coffee-script' ret.update({'comment': comt, 'result': None}) self.assertDictEqual(ntp.managed(name, [name]), ret) with patch.dict(ntp.__opts__, {'test': False}): comt = 'Failed to update NTP servers' ret.update({'comment': comt, 'result': False}) self.assertDictEqual(ntp.managed(name, [name]), ret)
'Test to install new alternative for defined <name>'
def test_install(self):
name = 'pager' link = '/usr/bin/pager' path = '/usr/bin/less' priority = 5 ret = {'name': name, 'link': link, 'path': path, 'priority': priority, 'result': None, 'changes': {}, 'comment': ''} bad_link = '/bin/pager' err = 'the primary link for {0} must be {1}'.format(name, link) mock = MagicMock(side_effect=[True, False, False, False]) mock_out = MagicMock(side_effect=['', err]) mock_path = MagicMock(return_value=path) mock_link = MagicMock(return_value=link) with patch.dict(alternatives.__salt__, {'alternatives.check_installed': mock, 'alternatives.install': mock_out, 'alternatives.show_current': mock_path, 'alternatives.show_link': mock_link}): comt = 'Alternatives for {0} is already set to {1}'.format(name, path) ret.update({'comment': comt, 'result': True}) self.assertDictEqual(alternatives.install(name, link, path, priority), ret) comt = 'Alternative will be set for {0} to {1} with priority {2}'.format(name, path, priority) ret.update({'comment': comt, 'result': None}) with patch.dict(alternatives.__opts__, {'test': True}): self.assertDictEqual(alternatives.install(name, link, path, priority), ret) comt = 'Alternative for {0} set to path {1} with priority {2}'.format(name, path, priority) ret.update({'comment': comt, 'result': True, 'changes': {'name': name, 'link': link, 'path': path, 'priority': priority}}) with patch.dict(alternatives.__opts__, {'test': False}): self.assertDictEqual(alternatives.install(name, link, path, priority), ret) comt = 'Alternative for {0} not installed: {1}'.format(name, err) ret.update({'comment': comt, 'result': False, 'changes': {}, 'link': bad_link}) with patch.dict(alternatives.__opts__, {'test': False}): self.assertDictEqual(alternatives.install(name, bad_link, path, priority), ret)
'Test to removes installed alternative for defined <name> and <path> or fallback to default alternative, if some defined before.'
def test_remove(self):
name = 'pager' path = '/usr/bin/less' ret = {'name': name, 'path': path, 'result': None, 'changes': {}, 'comment': ''} mock = MagicMock(side_effect=[True, True, True, False, False]) mock_bool = MagicMock(return_value=True) mock_show = MagicMock(side_effect=[False, True, True, False]) with patch.dict(alternatives.__salt__, {'alternatives.check_exists': mock, 'alternatives.show_current': mock_show, 'alternatives.remove': mock_bool}): comt = 'Alternative for {0} will be removed'.format(name) ret.update({'comment': comt}) with patch.dict(alternatives.__opts__, {'test': True}): self.assertDictEqual(alternatives.remove(name, path), ret) comt = 'Alternative for {0} removed'.format(name) ret.update({'comment': comt, 'result': True}) with patch.dict(alternatives.__opts__, {'test': False}): self.assertDictEqual(alternatives.remove(name, path), ret) comt = 'Alternative for pager removed. Falling back to path True' ret.update({'comment': comt, 'result': True, 'changes': {'path': True}}) with patch.dict(alternatives.__opts__, {'test': False}): self.assertDictEqual(alternatives.remove(name, path), ret) comt = "Alternative for {0} is set to it's default path True".format(name) ret.update({'comment': comt, 'result': True, 'changes': {}}) self.assertDictEqual(alternatives.remove(name, path), ret) comt = "Alternative for {0} doesn't exist".format(name) ret.update({'comment': comt, 'result': False}) self.assertDictEqual(alternatives.remove(name, path), ret)
'Test to instruct alternatives to use the highest priority path for <name>'
def test_auto(self):
name = 'pager' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} mock = MagicMock(side_effect=[' auto mode', ' ', ' ']) mock_auto = MagicMock(return_value=True) with patch.dict(alternatives.__salt__, {'alternatives.display': mock, 'alternatives.auto': mock_auto}): comt = '{0} already in auto mode'.format(name) ret.update({'comment': comt}) self.assertDictEqual(alternatives.auto(name), ret) comt = '{0} will be put in auto mode'.format(name) ret.update({'comment': comt, 'result': None}) with patch.dict(alternatives.__opts__, {'test': True}): self.assertDictEqual(alternatives.auto(name), ret) ret.update({'comment': '', 'result': True, 'changes': {'result': True}}) with patch.dict(alternatives.__opts__, {'test': False}): self.assertDictEqual(alternatives.auto(name), ret)
'Test to sets alternative for <name> to <path>, if <path> is defined as an alternative for <name>.'
def test_set(self):
name = 'pager' path = '/usr/bin/less' ret = {'name': name, 'path': path, 'result': True, 'changes': {}, 'comment': ''} mock = MagicMock(side_effect=[path, path, '']) mock_bool = MagicMock(return_value=True) mock_show = MagicMock(side_effect=[path, False, False, False, False]) with patch.dict(alternatives.__salt__, {'alternatives.display': mock, 'alternatives.show_current': mock_show, 'alternatives.set': mock_bool}): comt = 'Alternative for {0} already set to {1}'.format(name, path) ret.update({'comment': comt}) self.assertDictEqual(alternatives.set_(name, path), ret) comt = 'Alternative for {0} will be set to path /usr/bin/less'.format(name) ret.update({'comment': comt, 'result': None}) with patch.dict(alternatives.__opts__, {'test': True}): self.assertDictEqual(alternatives.set_(name, path), ret) comt = 'Alternative for {0} not updated'.format(name) ret.update({'comment': comt, 'result': True}) with patch.dict(alternatives.__opts__, {'test': False}): self.assertDictEqual(alternatives.set_(name, path), ret) comt = "Alternative {0} for {1} doesn't exist".format(path, name) ret.update({'comment': comt, 'result': False}) self.assertDictEqual(alternatives.set_(name, path), ret)
'Test to ensure the Route53 record is present.'
def test_present(self):
name = 'test.example.com.' value = '1.1.1.1' zone = 'example.com.' record_type = 'A' ret = {'name': name, 'result': False, 'changes': {}, 'comment': ''} mock = MagicMock(side_effect=[{}, {}, {'value': ''}, False]) mock_bool = MagicMock(return_value=False) with patch.dict(boto_route53.__salt__, {'boto_route53.get_record': mock, 'boto_route53.add_record': mock_bool}): with patch.dict(boto_route53.__opts__, {'test': False}): comt = 'Failed to add {0} Route53 record.'.format(name) ret.update({'comment': comt}) self.assertDictEqual(boto_route53.present(name, value, zone, record_type), ret) with patch.dict(boto_route53.__opts__, {'test': True}): comt = 'Route53 record {0} set to be added.'.format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(boto_route53.present(name, value, zone, record_type), ret) comt = 'Route53 record {0} set to be updated.'.format(name) ret.update({'comment': comt}) self.assertDictEqual(boto_route53.present(name, value, zone, record_type), ret) ret.update({'comment': '', 'result': True}) self.assertDictEqual(boto_route53.present(name, value, zone, record_type), ret)
'Test to ensure the Route53 record is deleted.'
def test_absent(self):
name = 'test.example.com.' zone = 'example.com.' record_type = 'A' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} mock = MagicMock(side_effect=[False, True]) with patch.dict(boto_route53.__salt__, {'boto_route53.get_record': mock}): comt = '{0} does not exist.'.format(name) ret.update({'comment': comt}) self.assertDictEqual(boto_route53.absent(name, zone, record_type), ret) with patch.dict(boto_route53.__opts__, {'test': True}): comt = 'Route53 record {0} set to be deleted.'.format(name) ret.update({'comment': comt, 'result': None}) self.assertDictEqual(boto_route53.absent(name, zone, record_type), ret)
'Test to ensure the cloudwatch alarm exists.'
def test_present(self):
name = 'my test alarm' attributes = {'metric': 'ApproximateNumberOfMessagesVisible', 'namespace': 'AWS/SQS'} ret = {'name': name, 'result': None, 'changes': {}, 'comment': ''} mock = MagicMock(side_effect=[['ok_actions'], [], []]) mock_bool = MagicMock(return_value=True) with patch.dict(boto_cloudwatch_alarm.__salt__, {'boto_cloudwatch.get_alarm': mock, 'boto_cloudwatch.create_or_update_alarm': mock_bool}): with patch.dict(boto_cloudwatch_alarm.__opts__, {'test': True}): comt = 'alarm my test alarm is to be created/updated.' ret.update({'comment': comt}) self.assertDictEqual(boto_cloudwatch_alarm.present(name, attributes), ret) comt = 'alarm my test alarm is to be created/updated.' ret.update({'comment': comt}) self.assertDictEqual(boto_cloudwatch_alarm.present(name, attributes), ret) with patch.dict(boto_cloudwatch_alarm.__opts__, {'test': False}): changes = {'new': {'metric': 'ApproximateNumberOfMessagesVisible', 'namespace': 'AWS/SQS'}} comt = 'alarm my test alarm is to be created/updated.' ret.update({'changes': changes, 'comment': '', 'result': True}) self.assertDictEqual(boto_cloudwatch_alarm.present(name, attributes), ret)
'Test to ensure the named cloudwatch alarm is deleted.'
def test_absent(self):
name = 'my test alarm' ret = {'name': name, 'result': None, 'changes': {}, 'comment': ''} mock = MagicMock(side_effect=[True, False]) with patch.dict(boto_cloudwatch_alarm.__salt__, {'boto_cloudwatch.get_alarm': mock}): with patch.dict(boto_cloudwatch_alarm.__opts__, {'test': True}): comt = 'alarm {0} is set to be removed.'.format(name) ret.update({'comment': comt}) self.assertDictEqual(boto_cloudwatch_alarm.absent(name), ret) comt = 'my test alarm does not exist in None.' ret.update({'comment': comt, 'result': True}) self.assertDictEqual(boto_cloudwatch_alarm.absent(name), ret)
'Tests the return of module.run state when the module function is not available. :return:'
def test_run_module_not_available(self):
with patch.dict(module.__salt__, {}, clear=True): with patch.dict(module.__opts__, {'use_superseded': ['module.run']}): ret = module.run(**{CMD: None}) assert (ret['comment'] == 'Unavailable function: {0}.'.format(CMD)) assert (not ret['result'])
'Tests the return of module.run state when hidden varargs are used with wrong type.'
def test_module_run_hidden_varargs(self):
with patch('salt.utils.args.get_function_argspec', MagicMock(return_value=self.bspec)): ret = module._run(CMD, m_names='anyname') comment = "'names' must be a list." self.assertEqual(ret['comment'], comment)
'Tests the return of the module.run state when test=True is passed. :return:'
def test_run_testmode(self):
with patch.dict(module.__opts__, {'test': True, 'use_superseded': ['module.run']}): ret = module.run(**{CMD: None}) assert (ret['comment'] == 'Function {0} to be executed.'.format(CMD)) assert ret['result']
'Tests the return of module.run state when arguments are missing :return:'
def test_run_missing_arg(self):
with patch.dict(module.__salt__, {CMD: _mocked_func_named}): with patch.dict(module.__opts__, {'use_superseded': ['module.run']}): ret = module.run(**{CMD: None}) assert (ret['comment'] == "'{0}' failed: Function expects 1 parameters, got only 0".format(CMD))
'Tests the return of module.run state when arguments are correct :return:'
def test_run_correct_arg(self):
with patch.dict(module.__salt__, {CMD: _mocked_func_named}): with patch.dict(module.__opts__, {'use_superseded': ['module.run']}): ret = module.run(**{CMD: ['Fred']}) assert (ret['comment'] == '{0}: Success'.format(CMD)) assert ret['result']
'Test unnamed args. :return:'
def test_run_args(self):
with patch.dict(module.__salt__, {CMD: _mocked_func_args}): with patch.dict(module.__opts__, {'use_superseded': ['module.run']}): assert module.run(**{CMD: ['foo', 'bar']})['result']
'Test handling of a broken function that returns None. :return:'
def test_run_none_return(self):
with patch.dict(module.__salt__, {CMD: _mocked_none_return}): with patch.dict(module.__opts__, {'use_superseded': ['module.run']}): assert module.run(**{CMD: None})['result']
'Test handling of a broken function that returns any type. :return:'
def test_run_typed_return(self):
for val in [1, 0, 'a', '', (1, 2), (), [1, 2], [], {'a': 'b'}, {}, True, False]: with patch.dict(module.__salt__, {CMD: _mocked_none_return}): with patch.dict(module.__opts__, {'use_superseded': ['module.run']}): assert module.run(**{CMD: [{'ret': val}]})['result']
'Test batch call :return:'
def test_run_batch_call(self):
with patch.dict(module.__opts__, {'use_superseded': ['module.run']}): with patch.dict(module.__salt__, {'first': _mocked_none_return, 'second': _mocked_none_return, 'third': _mocked_none_return}, clear=True): for f_name in module.__salt__: assert module.run(**{f_name: None})['result']
'Tests the return of module.run state when the module function name isn\'t available'
def test_module_run_module_not_available(self):
with patch.dict(module.__salt__, {}, clear=True): ret = module._run(CMD) comment = 'Module function {0} is not available'.format(CMD) self.assertEqual(ret['comment'], comment) self.assertFalse(ret['result'])
'Tests the return of module.run state when test=True is passed in'
def test_module_run_test_true(self):
with patch.dict(module.__opts__, {'test': True}): ret = module._run(CMD) comment = 'Module function {0} is set to execute'.format(CMD) self.assertEqual(ret['comment'], comment)
'Tests the return of module.run state when arguments are missing'
def test_module_run_missing_arg(self):
with patch('salt.utils.args.get_function_argspec', MagicMock(return_value=self.aspec)): ret = module._run(CMD) comment = 'The following arguments are missing:' self.assertIn(comment, ret['comment']) self.assertIn('world', ret['comment']) self.assertIn('hello', ret['comment'])
'Test to verify the chain exists when it already exists.'
def test_already_exists(self):
ret = {'name': self.fake_name, 'result': True, 'comment': 'ipset set {0} already exists for ipv4'.format(self.fake_name), 'changes': {}} self._runner(ret, check_set=True, new_set_assertion=False)
'Test to verify that detects need for update but doesn\'t apply when in test mode.'
def test_needs_update_test_mode(self):
ret = {'name': self.fake_name, 'result': None, 'comment': 'ipset set {0} would be added for ipv4'.format(self.fake_name), 'changes': {}} self._runner(ret, test=True, new_set_assertion=False)
'Test activating the given product key'
def test_activate(self):
expected = {'changes': {}, 'comment': 'Windows is now activated.', 'name': 'AAAAA-AAAAA-AAAAA-AAAA-AAAAA-ABCDE', 'result': True} info = {'description': 'Prof', 'licensed': False, 'name': 'Win7', 'partial_key': 'XXXXX'} info_mock = MagicMock(return_value=info) install_mock = MagicMock(return_value='Installed successfully') activate_mock = MagicMock(return_value='Activated successfully') with patch.dict(win_license.__salt__, {'license.info': info_mock, 'license.install': install_mock, 'license.activate': activate_mock}): out = win_license.activate('AAAAA-AAAAA-AAAAA-AAAA-AAAAA-ABCDE') info_mock.assert_called_once_with() install_mock.assert_called_once_with('AAAAA-AAAAA-AAAAA-AAAA-AAAAA-ABCDE') activate_mock.assert_called_once_with() self.assertEqual(out, expected)
'Test activating the given product key when the key is installed but not activated'
def test_installed_not_activated(self):
expected = {'changes': {}, 'comment': 'Windows is now activated.', 'name': 'AAAAA-AAAAA-AAAAA-AAAA-AAAAA-ABCDE', 'result': True} info = {'description': 'Prof', 'licensed': False, 'name': 'Win7', 'partial_key': 'ABCDE'} info_mock = MagicMock(return_value=info) install_mock = MagicMock(return_value='Installed successfully') activate_mock = MagicMock(return_value='Activated successfully') with patch.dict(win_license.__salt__, {'license.info': info_mock, 'license.install': install_mock, 'license.activate': activate_mock}): out = win_license.activate('AAAAA-AAAAA-AAAAA-AAAA-AAAAA-ABCDE') info_mock.assert_called_once_with() assert (not install_mock.called) activate_mock.assert_called_once_with() self.assertEqual(out, expected)
'Test activating the given product key when its already activated'
def test_installed_activated(self):
expected = {'changes': {}, 'comment': 'Windows is already activated.', 'name': 'AAAAA-AAAAA-AAAAA-AAAA-AAAAA-ABCDE', 'result': True} info = {'description': 'Prof', 'licensed': True, 'name': 'Win7', 'partial_key': 'ABCDE'} info_mock = MagicMock(return_value=info) install_mock = MagicMock(return_value='Installed successfully') activate_mock = MagicMock(return_value='Activated successfully') with patch.dict(win_license.__salt__, {'license.info': info_mock, 'license.install': install_mock, 'license.activate': activate_mock}): out = win_license.activate('AAAAA-AAAAA-AAAAA-AAAA-AAAAA-ABCDE') info_mock.assert_called_once_with() assert (not install_mock.called) assert (not activate_mock.called) self.assertEqual(out, expected)
'Test activating the given product key when the install fails'
def test_installed_install_fail(self):
expected = {'changes': {}, 'comment': 'Unable to install the given product key is it valid?', 'name': 'AAAAA-AAAAA-AAAAA-AAAA-AAAAA-ABCDE', 'result': False} info = {'description': 'Prof', 'licensed': False, 'name': 'Win7', 'partial_key': '12345'} info_mock = MagicMock(return_value=info) install_mock = MagicMock(return_value='Failed') activate_mock = MagicMock() with patch.dict(win_license.__salt__, {'license.info': info_mock, 'license.install': install_mock, 'license.activate': activate_mock}): out = win_license.activate('AAAAA-AAAAA-AAAAA-AAAA-AAAAA-ABCDE') info_mock.assert_called_once_with() install_mock.assert_called_once_with('AAAAA-AAAAA-AAAAA-AAAA-AAAAA-ABCDE') assert (not activate_mock.called) self.assertEqual(out, expected)
'Test activating the given product key when the install fails'
def test_installed_activate_fail(self):
expected = {'changes': {}, 'comment': 'Unable to activate the given product key.', 'name': 'AAAAA-AAAAA-AAAAA-AAAA-AAAAA-ABCDE', 'result': False} info = {'description': 'Prof', 'licensed': False, 'name': 'Win7', 'partial_key': 'ABCDE'} info_mock = MagicMock(return_value=info) install_mock = MagicMock() activate_mock = MagicMock(return_value='Failed to activate') with patch.dict(win_license.__salt__, {'license.info': info_mock, 'license.install': install_mock, 'license.activate': activate_mock}): out = win_license.activate('AAAAA-AAAAA-AAAAA-AAAA-AAAAA-ABCDE') info_mock.assert_called_once_with() assert (not install_mock.called) activate_mock.assert_called_once_with() self.assertEqual(out, expected)
'Test to ensure the named service is running.'
def test_running(self):
name = 'wsgi_server' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} comt = 'Supervisord module not activated. Do you need to install supervisord?' ret.update({'comment': comt, 'result': False}) self.assertDictEqual(supervisord.running(name), ret) mock = MagicMock(return_value={name: {'state': 'running'}}) with patch.dict(supervisord.__salt__, {'supervisord.status': mock}): with patch.dict(supervisord.__opts__, {'test': True}): comt = 'Service wsgi_server is already running' ret.update({'comment': comt, 'result': True}) self.assertDictEqual(supervisord.running(name), ret) with patch.dict(supervisord.__opts__, {'test': False}): comt = 'Not starting already running service: wsgi_server' ret.update({'comment': comt}) self.assertDictEqual(supervisord.running(name), ret)
'Test to ensure the named service is dead (not running).'
def test_dead(self):
name = 'wsgi_server' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} with patch.dict(supervisord.__opts__, {'test': True}): comt = 'Service {0} is set to be stopped'.format(name) ret.update({'comment': comt}) self.assertDictEqual(supervisord.dead(name), ret)
'Test to always restart on watch.'
def test_mod_watch(self):
name = 'wsgi_server' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} comt = 'Supervisord module not activated. Do you need to install supervisord?' ret.update({'comment': comt, 'result': False}) self.assertDictEqual(supervisord.mod_watch(name), ret)
'Test to ensure a value is set in an OpenStack configuration file.'
def test_present(self):
name = 'salt' filename = '/tmp/salt' section = 'A' value = 'SALT' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} mock_lst = MagicMock(side_effect=[value, CommandExecutionError, 'A']) mock_t = MagicMock(return_value=True) with patch.dict(openstack_config.__salt__, {'openstack_config.get': mock_lst, 'openstack_config.set': mock_t}): comt = 'The value is already set to the correct value' ret.update({'comment': comt, 'result': True}) self.assertDictEqual(openstack_config.present(name, filename, section, value), ret) self.assertRaises(CommandExecutionError, openstack_config.present, name, filename, section, value) comt = 'The value has been updated' ret.update({'comment': comt, 'changes': {'Value': 'Updated'}}) self.assertDictEqual(openstack_config.present(name, filename, section, value), ret)
'Test to ensure a value is not set in an OpenStack configuration file.'
def test_absent(self):
name = 'salt' filename = '/tmp/salt' section = 'A' ret = {'name': name, 'result': False, 'comment': '', 'changes': {}} mock_lst = MagicMock(side_effect=[CommandExecutionError('parameter not found:'), CommandExecutionError, 'A']) mock_t = MagicMock(return_value=True) with patch.dict(openstack_config.__salt__, {'openstack_config.get': mock_lst, 'openstack_config.delete': mock_t}): comt = 'The value is already absent' ret.update({'comment': comt, 'result': True}) self.assertDictEqual(openstack_config.absent(name, filename, section), ret) self.assertRaises(CommandExecutionError, openstack_config.absent, name, filename, section) comt = 'The value has been deleted' ret.update({'comment': comt, 'changes': {'Value': 'Deleted'}}) self.assertDictEqual(openstack_config.absent(name, filename, section), ret)
'Test to ensure that the VirtualBox Guest Additions are installed'
def test_additions_installed(self):
ret = {'name': 'salt', 'changes': {}, 'result': True, 'comment': ''} mock = MagicMock(side_effect=[True, False, False, False]) with patch.dict(vbox_guest.__salt__, {'vbox_guest.additions_version': mock, 'vbox_guest.additions_install': mock}): ret.update({'comment': 'System already in the correct state'}) self.assertDictEqual(vbox_guest.additions_installed('salt'), ret) with patch.dict(vbox_guest.__opts__, {'test': True}): ret.update({'changes': {'new': True, 'old': False}, 'comment': 'The state of VirtualBox Guest Additions will be changed.', 'result': None}) self.assertDictEqual(vbox_guest.additions_installed('salt'), ret) with patch.dict(vbox_guest.__opts__, {'test': False}): ret.update({'changes': {'new': False, 'old': False}, 'comment': 'The state of VirtualBox Guest Additions was changed!', 'result': False}) self.assertDictEqual(vbox_guest.additions_installed('salt'), ret)
'Test to ensure that the VirtualBox Guest Additions are removed.'
def test_additions_removed(self):
ret = {'name': 'salt', 'changes': {}, 'result': True, 'comment': ''} mock = MagicMock(side_effect=[False, True, True, True]) with patch.dict(vbox_guest.__salt__, {'vbox_guest.additions_version': mock, 'vbox_guest.additions_remove': mock}): ret.update({'comment': 'System already in the correct state'}) self.assertDictEqual(vbox_guest.additions_removed('salt'), ret) with patch.dict(vbox_guest.__opts__, {'test': True}): ret.update({'changes': {'new': True, 'old': True}, 'comment': 'The state of VirtualBox Guest Additions will be changed.', 'result': None}) self.assertDictEqual(vbox_guest.additions_removed('salt'), ret) with patch.dict(vbox_guest.__opts__, {'test': False}): ret.update({'comment': 'The state of VirtualBox Guest Additions was changed!', 'result': True}) self.assertDictEqual(vbox_guest.additions_removed('salt'), ret)
'Test to grant access to auto-mounted shared folders to the users.'
def test_grantaccess_to_sharedfolders(self):
ret = {'name': 'AB', 'changes': {}, 'result': True, 'comment': ''} mock = MagicMock(side_effect=[['AB'], 'salt', 'salt', 'salt']) with patch.dict(vbox_guest.__salt__, {'vbox_guest.list_shared_folders_users': mock, 'vbox_guest.grant_access_to_shared_folders_to': mock}): ret.update({'comment': 'System already in the correct state'}) self.assert_method(ret) with patch.dict(vbox_guest.__opts__, {'test': True}): ret.update({'changes': {'new': ['AB'], 'old': 'salt'}, 'comment': 'List of users who have access to auto-mounted shared folders will be changed', 'result': None}) self.assert_method(ret) with patch.dict(vbox_guest.__opts__, {'test': False}): ret.update({'changes': {'new': 'salt', 'old': 'salt'}, 'comment': 'List of users who have access to auto-mounted shared folders was changed', 'result': True}) self.assert_method(ret)
'Method call for assert statements'
def assert_method(self, ret):
self.assertDictEqual(vbox_guest.grant_access_to_shared_folders_to('AB'), ret)
'Test installing a bundle ID as being allowed to run with assistive access'
def test_installed(self):
expected = {'changes': {}, 'comment': 'Installed com.apple.Chess into the assistive access panel', 'name': 'com.apple.Chess', 'result': True} installed_mock = MagicMock(return_value=False) install_mock = MagicMock() with patch.dict(assistive.__salt__, {'assistive.installed': installed_mock, 'assistive.install': install_mock}): out = assistive.installed('com.apple.Chess') installed_mock.assert_called_once_with('com.apple.Chess') install_mock.assert_called_once_with('com.apple.Chess', True) self.assertEqual(out, expected)
'Test installing a bundle ID as being allowed to run with assistive access'
def test_installed_not_enabled(self):
expected = {'changes': {}, 'comment': 'Updated enable to True', 'name': 'com.apple.Chess', 'result': True} installed_mock = MagicMock(return_value=True) install_mock = MagicMock() enabled_mock = MagicMock(return_value=False) enable_mock = MagicMock() with patch.dict(assistive.__salt__, {'assistive.installed': installed_mock, 'assistive.install': install_mock, 'assistive.enabled': enabled_mock, 'assistive.enable': enable_mock}): out = assistive.installed('com.apple.Chess') enabled_mock.assert_called_once_with('com.apple.Chess') enable_mock.assert_called_once_with('com.apple.Chess', True) assert (not install_mock.called) self.assertEqual(out, expected)
'Test enabling an already enabled bundle ID'
def test_installed_enabled(self):
expected = {'changes': {}, 'comment': 'Already in the correct state', 'name': 'com.apple.Chess', 'result': True} installed_mock = MagicMock(return_value=True) install_mock = MagicMock() enabled_mock = MagicMock(return_value=True) enable_mock = MagicMock() with patch.dict(assistive.__salt__, {'assistive.installed': installed_mock, 'assistive.install': install_mock, 'assistive.enabled': enabled_mock, 'assistive.enable': enable_mock}): out = assistive.installed('com.apple.Chess') enabled_mock.assert_called_once_with('com.apple.Chess') assert (not enable_mock.called) assert (not install_mock.called) self.assertEqual(out, expected)
'Test disabling an enabled and installed bundle ID'
def test_installed_not_disabled(self):
expected = {'changes': {}, 'comment': 'Updated enable to False', 'name': 'com.apple.Chess', 'result': True} installed_mock = MagicMock(return_value=True) install_mock = MagicMock() enabled_mock = MagicMock(return_value=True) enable_mock = MagicMock() with patch.dict(assistive.__salt__, {'assistive.installed': installed_mock, 'assistive.install': install_mock, 'assistive.enabled': enabled_mock, 'assistive.enable': enable_mock}): out = assistive.installed('com.apple.Chess', False) enabled_mock.assert_called_once_with('com.apple.Chess') enable_mock.assert_called_once_with('com.apple.Chess', False) assert (not install_mock.called) self.assertEqual(out, expected)
'Test to verifies that the specified incron job is present for the specified user.'
def test_present(self):
name = 'salt' path = '/home/user' mask = 'IN_MODIFY' cmd = 'echo "$$ $@"' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} comt4 = 'Incron {0} for user root failed to commit with error \nabsent'.format(name) mock_dict = MagicMock(return_value={'crons': [{'path': path, 'cmd': cmd, 'mask': mask}]}) mock = MagicMock(side_effect=['present', 'new', 'updated', 'absent']) with patch.dict(incron.__salt__, {'incron.list_tab': mock_dict, 'incron.set_job': mock}): with patch.dict(incron.__opts__, {'test': True}): comt = 'Incron {0} is set to be added'.format(name) ret.update({'comment': comt}) self.assertDictEqual(incron.present(name, path, mask, cmd), ret) with patch.dict(incron.__opts__, {'test': False}): comt = 'Incron {0} already present'.format(name) ret.update({'comment': comt, 'result': True}) self.assertDictEqual(incron.present(name, path, mask, cmd), ret) comt = "Incron {0} added to root's incrontab".format(name) ret.update({'comment': comt, 'changes': {'root': 'salt'}}) self.assertDictEqual(incron.present(name, path, mask, cmd), ret) comt = 'Incron {0} updated'.format(name) ret.update({'comment': comt}) self.assertDictEqual(incron.present(name, path, mask, cmd), ret) ret.update({'comment': comt4, 'result': False, 'changes': {}}) self.assertDictEqual(incron.present(name, path, mask, cmd), ret)
'Test to verifies that the specified incron job is absent for the specified user.'
def test_absent(self):
name = 'salt' path = '/home/user' mask = 'IN_MODIFY' cmd = 'echo "$$ $@"' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} comt4 = 'Incron {0} for user root failed to commit with error new'.format(name) mock_dict = MagicMock(return_value={'crons': [{'path': path, 'cmd': cmd, 'mask': mask}]}) mock = MagicMock(side_effect=['absent', 'removed', 'new']) with patch.dict(incron.__salt__, {'incron.list_tab': mock_dict, 'incron.rm_job': mock}): with patch.dict(incron.__opts__, {'test': True}): comt = 'Incron {0} is absent'.format(name) ret.update({'comment': comt}) self.assertDictEqual(incron.absent(name, path, mask, cmd), ret) with patch.dict(incron.__opts__, {'test': False}): comt = 'Incron {0} already absent'.format(name) ret.update({'comment': comt, 'result': True}) self.assertDictEqual(incron.absent(name, path, mask, cmd), ret) comt = "Incron {0} removed from root's crontab".format(name) ret.update({'comment': comt, 'changes': {'root': 'salt'}}) self.assertDictEqual(incron.absent(name, path, mask, cmd), ret) ret.update({'comment': comt4, 'result': False, 'changes': {}}) self.assertDictEqual(incron.absent(name, path, mask, cmd), ret)
'Test to ensures that the specified PowerPath license key is present on the host.'
def test_license_present(self):
name = 'mylic' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} mock_t = MagicMock(side_effect=[{'result': True, 'output': name}, {'result': False, 'output': name}]) mock = MagicMock(side_effect=[False, True, True, True, True]) mock_l = MagicMock(return_value=[{'key': name}]) with patch.dict(powerpath.__salt__, {'powerpath.has_powerpath': mock, 'powerpath.list_licenses': mock_l, 'powerpath.add_license': mock_t}): comt = 'PowerPath is not installed.' ret.update({'comment': comt, 'result': False}) self.assertDictEqual(powerpath.license_present(name), ret) comt = 'License key {0} already present'.format(name) ret.update({'comment': comt, 'result': True}) self.assertDictEqual(powerpath.license_present(name), ret) with patch.dict(powerpath.__opts__, {'test': True}): comt = 'License key Mylic is set to be added' ret.update({'comment': comt, 'result': None, 'name': 'Mylic'}) self.assertDictEqual(powerpath.license_present('Mylic'), ret) with patch.dict(powerpath.__opts__, {'test': False}): ret.update({'comment': name, 'result': True, 'changes': {'Mylic': 'added'}}) self.assertDictEqual(powerpath.license_present('Mylic'), ret) ret.update({'result': False, 'changes': {}}) self.assertDictEqual(powerpath.license_present('Mylic'), ret)
'Test to ensures that the specified PowerPath license key is absent on the host.'
def test_license_absent(self):
name = 'mylic' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} mock_t = MagicMock(side_effect=[{'result': True, 'output': name}, {'result': False, 'output': name}]) mock = MagicMock(side_effect=[False, True, True, True, True]) mock_l = MagicMock(return_value=[{'key': 'salt'}]) with patch.dict(powerpath.__salt__, {'powerpath.has_powerpath': mock, 'powerpath.list_licenses': mock_l, 'powerpath.remove_license': mock_t}): comt = 'PowerPath is not installed.' ret.update({'comment': comt, 'result': False}) self.assertDictEqual(powerpath.license_absent(name), ret) comt = 'License key {0} not present'.format(name) ret.update({'comment': comt, 'result': True}) self.assertDictEqual(powerpath.license_absent(name), ret) with patch.dict(powerpath.__opts__, {'test': True}): comt = 'License key salt is set to be removed' ret.update({'comment': comt, 'result': None, 'name': 'salt'}) self.assertDictEqual(powerpath.license_absent('salt'), ret) with patch.dict(powerpath.__opts__, {'test': False}): ret.update({'comment': name, 'result': True, 'changes': {'salt': 'removed'}}) self.assertDictEqual(powerpath.license_absent('salt'), ret) ret.update({'result': False, 'changes': {}}) self.assertDictEqual(powerpath.license_absent('salt'), ret)
'Test to remove the directory from the SYSTEM path'
def test_absent(self):
ret = {'name': 'salt', 'changes': {}, 'result': None, 'comment': ''} mock = MagicMock(return_value=False) with patch.dict(win_path.__salt__, {'win_path.exists': mock}): with patch.dict(win_path.__opts__, {'test': True}): ret.update({'comment': 'salt is not in the PATH'}) self.assertDictEqual(win_path.absent('salt'), ret) with patch.dict(win_path.__opts__, {'test': False}): mock = MagicMock(return_value=True) with patch.dict(win_path.__salt__, {'win_path.remove': mock}): ret.update({'result': True}) self.assertDictEqual(win_path.absent('salt'), ret)
'Test to add the directory to the system PATH at index location'
def test_exists(self):
ret = {'name': 'salt', 'changes': {}, 'result': True, 'comment': ''} mock = MagicMock(return_value=['Salt', 'Saltdude']) with patch.dict(win_path.__salt__, {'win_path.get_path': mock}): mock = MagicMock(side_effect=['Saltdude', 'Saltdude', '/Saltdude', 'Saltdude']) with patch.object(win_path, '_normalize_dir', mock): ret.update({'comment': 'salt is already present in the PATH at the right location'}) self.assertDictEqual(win_path.exists('salt', 1), ret) self.assertDictEqual(win_path.exists('salt'), ret) with patch.dict(win_path.__opts__, {'test': True}): ret.update({'comment': '', 'result': None, 'changes': {'added': 'salt will be added at index 2'}}) self.assertDictEqual(win_path.exists('salt'), ret) with patch.dict(win_path.__opts__, {'test': False}): mock = MagicMock(return_value=False) with patch.dict(win_path.__salt__, {'win_path.add': mock}): ret.update({'comment': 'salt is already present in the PATH at the right location', 'result': True, 'changes': {}}) self.assertDictEqual(win_path.exists('salt'), ret)
'Test to ensure the cache cluster exists.'
def test_present(self):
name = 'myelasticache' engine = 'redis' cache_node_type = 'cache.t1.micro' ret = {'name': name, 'result': None, 'changes': {}, 'comment': ''} mock = MagicMock(side_effect=[None, False, False, True]) mock_bool = MagicMock(return_value=False) with patch.dict(boto_elasticache.__salt__, {'boto_elasticache.get_config': mock, 'boto_elasticache.create': mock_bool}): comt = 'Failed to retrieve cache cluster info from AWS.' ret.update({'comment': comt}) self.assertDictEqual(boto_elasticache.present(name, engine, cache_node_type), ret) with patch.dict(boto_elasticache.__opts__, {'test': True}): comt = 'Cache cluster {0} is set to be created.'.format(name) ret.update({'comment': comt}) self.assertDictEqual(boto_elasticache.present(name, engine, cache_node_type), ret) with patch.dict(boto_elasticache.__opts__, {'test': False}): comt = 'Failed to create {0} cache cluster.'.format(name) ret.update({'comment': comt, 'result': False}) self.assertDictEqual(boto_elasticache.present(name, engine, cache_node_type), ret) comt = 'Cache cluster {0} is present.'.format(name) ret.update({'comment': comt, 'result': True}) self.assertDictEqual(boto_elasticache.present(name, engine, cache_node_type), ret)