def test_create_wake_on_lan(self): ''' Test if wake on lan works ''' mock_sleep = MagicMock() mock_cmd = MagicMock(return_value=True) mm_cmd = MagicMock(return_value={'friend1': True}) lcl = salt.client.LocalClient() lcl.cmd = mm_cmd with patch('time.sleep', mock_sleep): with patch('salt.client.LocalClient', return_value=lcl): with patch.dict('salt.cloud.clouds.saltify.__utils__', {'cloud.bootstrap': mock_cmd}): vm_ = { 'deploy': True, 'driver': 'saltify', 'name': 'new1', 'profile': 'testprofile3', } result = saltify.create(vm_) mock_cmd.assert_called_once_with(vm_, ANY) mm_cmd.assert_called_with('friend1', 'network.wol', ['aa-bb-cc-dd-ee-ff']) # The test suite might call time.sleep, look for any call # that has the expected wait time. mock_sleep.assert_any_call(0.01) self.assertTrue(result)
def test_vagrant_destroy(self): path_mydir = os.path.join(os.sep, 'my', 'dir') if salt.utils.platform.is_windows(): path_mydir = 'c:{0}'.format(path_mydir) mock_cmd = MagicMock(return_value={'retcode': 0}) with patch.dict(vagrant.__salt__, {'cmd.run_all': mock_cmd}): mock_sdb = MagicMock(return_value=None) with patch.dict(vagrant.__utils__, {'sdb.sdb_delete': mock_sdb}): mock_sdb_get = MagicMock(return_value={ 'machine': 'macfour', 'cwd': path_mydir }) with patch.dict(vagrant.__utils__, {'sdb.sdb_get': mock_sdb_get}): self.assertTrue(vagrant.destroy('test4')) mock_sdb.assert_any_call( 'sdb://vagrant_sdb_data/macfour?{0}'.format( path_mydir), self.LOCAL_OPTS) mock_sdb.assert_any_call('sdb://vagrant_sdb_data/test4', self.LOCAL_OPTS) cmd = 'vagrant destroy -f macfour' mock_cmd.assert_called_with(cmd, runas=None, cwd=path_mydir, output_loglevel='info')
def test_vagrant_destroy(self): path_mydir = os.path.join(os.sep, "my", "dir") if salt.utils.platform.is_windows(): path_mydir = "c:{}".format(path_mydir) mock_cmd = MagicMock(return_value={"retcode": 0}) with patch.dict(vagrant.__salt__, {"cmd.run_all": mock_cmd}): mock_sdb = MagicMock(return_value=None) with patch.dict(vagrant.__utils__, {"sdb.sdb_delete": mock_sdb}): mock_sdb_get = MagicMock(return_value={ "machine": "macfour", "cwd": path_mydir }) with patch.dict(vagrant.__utils__, {"sdb.sdb_get": mock_sdb_get}): self.assertTrue(vagrant.destroy("test4")) mock_sdb.assert_any_call( "sdb://vagrant_sdb_data/macfour?{}".format(path_mydir), self.LOCAL_OPTS, ) mock_sdb.assert_any_call("sdb://vagrant_sdb_data/test4", self.LOCAL_OPTS) cmd = "vagrant destroy -f macfour" mock_cmd.assert_called_with(cmd, runas=None, cwd=path_mydir, output_loglevel="info")
def test_create_wake_on_lan(self): """ Test if wake on lan works """ mock_sleep = MagicMock() mock_cmd = MagicMock(return_value=True) mm_cmd = MagicMock(return_value={"friend1": True}) lcl = salt.client.LocalClient() lcl.cmd = mm_cmd with patch("time.sleep", mock_sleep): with patch("salt.client.LocalClient", return_value=lcl): with patch.dict("salt.cloud.clouds.saltify.__utils__", {"cloud.bootstrap": mock_cmd}): vm_ = { "deploy": True, "driver": "saltify", "name": "new1", "profile": "testprofile3", } result = saltify.create(vm_) mock_cmd.assert_called_once_with(vm_, ANY) mm_cmd.assert_called_with("friend1", "network.wol", ["aa-bb-cc-dd-ee-ff"]) # The test suite might call time.sleep, look for any call # that has the expected wait time. mock_sleep.assert_any_call(0.01) self.assertTrue(result)
def test_vagrant_init_positional(self): path_nowhere = os.path.join(os.sep, "tmp", "nowhere") if salt.utils.platform.is_windows(): path_nowhere = "c:{}".format(path_nowhere) mock_sdb = MagicMock(return_value=None) with patch.dict(vagrant.__utils__, {"sdb.sdb_set": mock_sdb}): resp = vagrant.init( "test1", path_nowhere, "onetest", "nobody", False, "french", {"different": "very"}, ) self.assertTrue(resp.startswith("Name test1 defined")) expected = dict( name="test1", cwd=path_nowhere, machine="onetest", runas="nobody", vagrant_provider="french", different="very", ) mock_sdb.assert_called_with( "sdb://vagrant_sdb_data/onetest?{}".format(path_nowhere), "test1", self.LOCAL_OPTS, ) mock_sdb.assert_any_call("sdb://vagrant_sdb_data/test1", expected, self.LOCAL_OPTS)
def test_vagrant_init_positional(self): path_nowhere = os.path.join(os.sep, 'tmp', 'nowhere') if salt.utils.platform.is_windows(): path_nowhere = 'c:{0}'.format(path_nowhere) mock_sdb = MagicMock(return_value=None) with patch.dict(vagrant.__utils__, {'sdb.sdb_set': mock_sdb}): resp = vagrant.init( 'test1', path_nowhere, 'onetest', 'nobody', False, 'french', {'different': 'very'} ) self.assertTrue(resp.startswith('Name test1 defined')) expected = dict(name='test1', cwd=path_nowhere, machine='onetest', runas='nobody', vagrant_provider='french', different='very' ) mock_sdb.assert_called_with( 'sdb://vagrant_sdb_data/onetest?{0}'.format(path_nowhere), 'test1', self.LOCAL_OPTS) mock_sdb.assert_any_call( 'sdb://vagrant_sdb_data/test1', expected, self.LOCAL_OPTS)
def test_vagrant_init_positional(self): mock_sdb = MagicMock(return_value=None) with patch.dict(vagrant.__utils__, {'sdb.sdb_set': mock_sdb}): resp = vagrant.init( 'test1', '/tmp/nowhere', 'onetest', 'nobody', False, 'french', {'different': 'very'} ) self.assertTrue(resp.startswith('Name test1 defined')) expected = dict(name='test1', cwd='/tmp/nowhere', machine='onetest', runas='nobody', vagrant_provider='french', different='very' ) mock_sdb.assert_called_with( 'sdb://vagrant_sdb_data/onetest?/tmp/nowhere', 'test1', self.LOCAL_OPTS) mock_sdb.assert_any_call( 'sdb://vagrant_sdb_data/test1', expected, self.LOCAL_OPTS)
def test_vagrant_init_arg_override(self): testdict = dict( cwd="/tmp/there", machine="treetest", runas="anybody", vagrant_provider="spansh", ) mock_sdb = MagicMock(return_value=None) with patch.dict(vagrant.__utils__, {"sdb.sdb_set": mock_sdb}): vagrant.init( "test3", cwd="/tmp", machine="threetest", runas="him", vagrant_provider="polish", vm=testdict, ) expected = dict( name="test3", cwd="/tmp", machine="threetest", runas="him", vagrant_provider="polish", ) mock_sdb.assert_any_call("sdb://vagrant_sdb_data/test3", expected, self.LOCAL_OPTS)
def test_format_(self): """ unit tests for disk.format_ """ device = "/dev/sdX1" mock = MagicMock(return_value=0) with patch.dict(disk.__salt__, {"cmd.retcode": mock}): disk.format_(device=device) mock.assert_any_call(["mkfs", "-t", "ext4", device], ignore_retcode=True)
def test_format__fat(self): ''' unit tests for disk.format_ with FAT parameter ''' device = '/dev/sdX1' mock = MagicMock(return_value=0) with patch.dict(disk.__salt__, {'cmd.retcode': mock}): disk.format_(device=device, fs_type='fat', fat=12) mock.assert_any_call(['mkfs', '-t', 'fat', '-F', 12, device], ignore_retcode=True)
def test_format_(self): ''' unit tests for disk.format_ ''' device = '/dev/sdX1' mock = MagicMock(return_value=0) with patch.dict(disk.__salt__, {'cmd.retcode': mock}): disk.format_(device=device) mock.assert_any_call(['mkfs', '-t', 'ext4', device], ignore_retcode=True)
def test_format__fat(self): """ unit tests for disk.format_ with FAT parameter """ device = "/dev/sdX1" mock = MagicMock(return_value=0) with patch.dict(disk.__salt__, {"cmd.retcode": mock}): disk.format_(device=device, fs_type="fat", fat=12) mock.assert_any_call(["mkfs", "-t", "fat", "-F", 12, device], ignore_retcode=True)
def test_vagrant_init_dict(self): testdict = dict(cwd='/tmp/anywhere', machine='twotest', runas='somebody', vagrant_provider='english') expected = testdict.copy() expected['name'] = 'test2' mock_sdb = MagicMock(return_value=None) with patch.dict(vagrant.__utils__, {'sdb.sdb_set': mock_sdb}): vagrant.init('test2', vm=testdict) mock_sdb.assert_any_call('sdb://vagrant_sdb_data/test2', expected, self.LOCAL_OPTS)
def test_vagrant_init_dict(self): testdict = dict( cwd="/tmp/anywhere", machine="twotest", runas="somebody", vagrant_provider="english", ) expected = testdict.copy() expected["name"] = "test2" mock_sdb = MagicMock(return_value=None) with patch.dict(vagrant.__utils__, {"sdb.sdb_set": mock_sdb}): vagrant.init("test2", vm=testdict) mock_sdb.assert_any_call("sdb://vagrant_sdb_data/test2", expected, self.LOCAL_OPTS)
def test_delete_snapshot(self): """ Test parallels.delete_snapshot """ delete_message = ( "Delete the snapshot...\nThe snapshot has been successfully deleted." ) # Validate single ID name = "macvm" snap_name = "kaon" snap_id = "c2eab062-a635-4ccd-b9ae-998370f898b5" mock_snap_name = MagicMock(return_value=snap_id) with patch.object(parallels, "_validate_snap_name", mock_snap_name): mock_delete = MagicMock(return_value=delete_message) with patch.object(parallels, "prlctl", mock_delete): ret = parallels.delete_snapshot(name, snap_name) self.assertEqual(ret, delete_message) mock_delete.assert_called_once_with("snapshot-delete", [name, "--id", snap_id], runas=None) # Validate multiple IDs name = "macvm" snap_name = "higgs doublet" snap_ids = [ "c2eab062-a635-4ccd-b9ae-998370f898b5", "8aca07c5-a0e1-4dcb-ba75-cb154d46d516", ] mock_snap_ids = MagicMock(return_value=snap_ids) with patch.object(parallels, "_validate_snap_name", mock_snap_ids): mock_delete = MagicMock(return_value=delete_message) with patch.object(parallels, "prlctl", mock_delete): ret = parallels.delete_snapshot(name, snap_name, all=True) mock_ret = { snap_ids[0]: delete_message, snap_ids[1]: delete_message } self.assertDictEqual(ret, mock_ret) mock_delete.assert_any_call("snapshot-delete", [name, "--id", snap_ids[0]], runas=None) mock_delete.assert_any_call("snapshot-delete", [name, "--id", snap_ids[1]], runas=None)
def test_get_proxy_win(self): """ Test to make sure that we correctly get the current proxy info on Windows """ result = [ { "vdata": ("http=192.168.0.1:3128;https=192.168.0.2:3128;ftp=192.168.0.3:3128" ) }, { "vdata": 1 }, ] mock_reg_read = MagicMock(side_effect=result) expected = { "enabled": True, "http": { "server": "192.168.0.1", "port": "3128" }, "https": { "server": "192.168.0.2", "port": "3128" }, "ftp": { "server": "192.168.0.3", "port": "3128" }, } with patch.dict(proxy.__grains__, {"os": "Windows"}), patch.dict( proxy.__utils__, {"reg.read_value": mock_reg_read}): out = proxy.get_proxy_win() self.assertDictEqual(out, expected) mock_reg_read.assert_any_call( hive="HKEY_CURRENT_USER", key= "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", vname="ProxyServer", ) mock_reg_read.assert_any_call( hive="HKEY_CURRENT_USER", key= "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", vname="ProxyEnable", )
def test_delete_snapshot(self): ''' Test parallels.delete_snapshot ''' delete_message = ('Delete the snapshot...\n' 'The snapshot has been successfully deleted.') # Validate single ID name = 'macvm' snap_name = 'kaon' snap_id = 'c2eab062-a635-4ccd-b9ae-998370f898b5' mock_snap_name = MagicMock(return_value=snap_id) with patch.object(parallels, '_validate_snap_name', mock_snap_name): mock_delete = MagicMock(return_value=delete_message) with patch.object(parallels, 'prlctl', mock_delete): ret = parallels.delete_snapshot(name, snap_name) self.assertEqual(ret, delete_message) mock_delete.assert_called_once_with('snapshot-delete', [name, '--id', snap_id], runas=None) # Validate multiple IDs name = 'macvm' snap_name = 'higgs doublet' snap_ids = [ 'c2eab062-a635-4ccd-b9ae-998370f898b5', '8aca07c5-a0e1-4dcb-ba75-cb154d46d516' ] mock_snap_ids = MagicMock(return_value=snap_ids) with patch.object(parallels, '_validate_snap_name', mock_snap_ids): mock_delete = MagicMock(return_value=delete_message) with patch.object(parallels, 'prlctl', mock_delete): ret = parallels.delete_snapshot(name, snap_name, all=True) mock_ret = { snap_ids[0]: delete_message, snap_ids[1]: delete_message } self.assertDictEqual(ret, mock_ret) mock_delete.assert_any_call('snapshot-delete', [name, '--id', snap_ids[0]], runas=None) mock_delete.assert_any_call('snapshot-delete', [name, '--id', snap_ids[1]], runas=None)
def test_ansible_module_call(self): ''' Test Ansible module call from ansible gate module :return: ''' class Module(object): ''' An ansible module mock. ''' __name__ = 'one.two.three' __file__ = 'foofile' def main(): pass ANSIBLE_MODULE_ARGS = '{"ANSIBLE_MODULE_ARGS": ["arg_1", {"kwarg1": "foobar"}]}' proc = MagicMock(side_effect=[ MockTimedProc(stdout=ANSIBLE_MODULE_ARGS.encode(), stderr=None), MockTimedProc(stdout='{"completed": true}'.encode(), stderr=None) ]) with patch.object(ansible, '_resolver', self.resolver), \ patch.object(ansible._resolver, 'load_module', MagicMock(return_value=Module())): _ansible_module_caller = ansible.AnsibleModuleCaller( ansible._resolver) with patch('salt.utils.timed_subprocess.TimedProc', proc): ret = _ansible_module_caller.call("one.two.three", "arg_1", kwarg1="foobar") if six.PY3: proc.assert_any_call(['python3', 'foofile'], stdin=ANSIBLE_MODULE_ARGS, stdout=-1, timeout=1200) else: proc.assert_any_call(['python', 'foofile'], stdin=ANSIBLE_MODULE_ARGS, stdout=-1, timeout=1200) try: proc.assert_any_call([ 'echo', '{"ANSIBLE_MODULE_ARGS": {"kwarg1": "foobar", "_raw_params": "arg_1"}}' ], stdout=-1, timeout=1200) except AssertionError: proc.assert_any_call([ 'echo', '{"ANSIBLE_MODULE_ARGS": {"_raw_params": "arg_1", "kwarg1": "foobar"}}' ], stdout=-1, timeout=1200) assert ret == {"completed": True, "timeout": 1200}
def test_vagrant_destroy(self): mock_cmd = MagicMock(return_value={'retcode': 0}) with patch.dict(vagrant.__salt__, {'cmd.run_all': mock_cmd}): mock_sdb = MagicMock(return_value=None) with patch.dict(vagrant.__utils__, {'sdb.sdb_delete': mock_sdb}): mock_sdb_get = MagicMock(return_value={ 'machine': 'macfour', 'cwd': '/my/dir'}) with patch.dict(vagrant.__utils__, {'sdb.sdb_get': mock_sdb_get}): self.assertTrue(vagrant.destroy('test4')) mock_sdb.assert_any_call( 'sdb://vagrant_sdb_data/macfour?/my/dir', self.LOCAL_OPTS) mock_sdb.assert_any_call( 'sdb://vagrant_sdb_data/test4', self.LOCAL_OPTS) cmd = 'vagrant destroy -f macfour' mock_cmd.assert_called_with(cmd, runas=None, cwd='/my/dir', output_loglevel='info')
def test_vagrant_init_arg_override(self): testdict = dict(cwd='/tmp/there', machine='treetest', runas='anybody', vagrant_provider='spansh') mock_sdb = MagicMock(return_value=None) with patch.dict(vagrant.__utils__, {'sdb.sdb_set': mock_sdb}): vagrant.init('test3', cwd='/tmp', machine='threetest', runas='him', vagrant_provider='polish', vm=testdict) expected = dict(name='test3', cwd='/tmp', machine='threetest', runas='him', vagrant_provider='polish') mock_sdb.assert_any_call('sdb://vagrant_sdb_data/test3', expected, self.LOCAL_OPTS)
def test_get_proxy_win(self): ''' Test to make sure that we correctly get the current proxy info on Windows ''' result = [{ 'vdata': 'http=192.168.0.1:3128;https=192.168.0.2:3128;ftp=192.168.0.3:3128' }, { 'vdata': 1 }] mock_reg_read = MagicMock(side_effect=result) expected = { 'enabled': True, 'http': { 'server': '192.168.0.1', 'port': '3128' }, 'https': { 'server': '192.168.0.2', 'port': '3128' }, 'ftp': { 'server': '192.168.0.3', 'port': '3128' } } with patch.dict(proxy.__grains__, {'os': 'Windows'}), \ patch.dict(proxy.__utils__, {'reg.read_value': mock_reg_read}): out = proxy.get_proxy_win() self.assertDictEqual(out, expected) mock_reg_read.assert_any_call( hive='HKEY_CURRENT_USER', key= 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings', vname='ProxyServer') mock_reg_read.assert_any_call( hive='HKEY_CURRENT_USER', key= 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings', vname='ProxyEnable')
def test_ansible_module_call(self): """ Test Ansible module call from ansible gate module :return: """ class Module(object): """ An ansible module mock. """ __name__ = "one.two.three" __file__ = "foofile" def main(): # pylint: disable=no-method-argument pass ANSIBLE_MODULE_ARGS = '{"ANSIBLE_MODULE_ARGS": ["arg_1", {"kwarg1": "foobar"}]}' proc = MagicMock(side_effect=[ MockTimedProc(stdout=ANSIBLE_MODULE_ARGS.encode(), stderr=None), MockTimedProc(stdout='{"completed": true}'.encode(), stderr=None), ]) with patch.object(ansible, "_resolver", self.resolver), patch.object( ansible._resolver, "load_module", MagicMock(return_value=Module())): _ansible_module_caller = ansible.AnsibleModuleCaller( ansible._resolver) with patch("salt.utils.timed_subprocess.TimedProc", proc): ret = _ansible_module_caller.call("one.two.three", "arg_1", kwarg1="foobar") proc.assert_any_call( [sys.executable, "foofile"], stdin=ANSIBLE_MODULE_ARGS, stdout=-1, timeout=1200, ) try: proc.assert_any_call( [ "echo", '{"ANSIBLE_MODULE_ARGS": {"kwarg1": "foobar", "_raw_params": "arg_1"}}', ], stdout=-1, timeout=1200, ) except AssertionError: proc.assert_any_call( [ "echo", '{"ANSIBLE_MODULE_ARGS": {"_raw_params": "arg_1", "kwarg1": "foobar"}}', ], stdout=-1, timeout=1200, ) assert ret == {"completed": True, "timeout": 1200}
class JBoss7TestCase(TestCase, LoaderModuleMockMixin): jboss_config = {} org_run_operation = None def setup_loader_modules(self): self.org_run_operation = MagicMock() self.addCleanup(delattr, self, 'org_run_operation') return { jboss7: { '__salt__': { 'jboss7_cli.run_operation': self.org_run_operation } } } def test_create_simple_binding(self): jboss7.create_simple_binding(self.jboss_config, 'java:global/env', 'DEV') self.org_run_operation.assert_called_with(self.jboss_config, '/subsystem=naming/binding="java:global/env":add(binding-type=simple, value="DEV")') def test_create_simple_binding_with_backslash(self): jboss7.create_simple_binding(self.jboss_config, 'java:global/env', r'DEV\2') self.org_run_operation.assert_called_with(self.jboss_config, r'/subsystem=naming/binding="java:global/env":add(binding-type=simple, value="DEV\\\\2")') def test_update_binding(self): jboss7.update_simple_binding(self.jboss_config, 'java:global/env', 'INT') self.org_run_operation.assert_called_with(self.jboss_config, '/subsystem=naming/binding="java:global/env":write-attribute(name=value, value="INT")') def test_update_binding_with_backslash(self): jboss7.update_simple_binding(self.jboss_config, 'java:global/env', r'INT\2') self.org_run_operation.assert_called_with(self.jboss_config, r'/subsystem=naming/binding="java:global/env":write-attribute(name=value, value="INT\\\\2")') def test_read_binding(self): def cli_command_response(jboss_config, cli_command): if cli_command == '/subsystem=naming/binding="java:global/env":read-resource': return {'outcome': 'success', 'result': { 'binding-type': 'simple', 'value': 'DEV' } } self.org_run_operation.side_effect = cli_command_response result = jboss7.read_simple_binding(self.jboss_config, 'java:global/env') self.assertEqual(result['outcome'], 'success') self.assertEqual(result['result']['value'], 'DEV') def test_create_datasource_all_properties_included(self): def cli_command_response(jboss_config, cli_command, fail_on_error=False): if cli_command == '/subsystem=datasources/data-source="appDS":read-resource-description': return {'outcome': 'success', 'result': { 'attributes': { 'driver-name': {'type': 'STRING'}, 'connection-url': {'type': 'STRING'}, 'jndi-name': {'type': 'STRING'}, 'user-name': {'type': 'STRING'}, 'password': {'type': 'STRING'} } } } self.org_run_operation.side_effect = cli_command_response datasource_properties = OrderedDict() datasource_properties['driver-name'] = 'mysql' datasource_properties['connection-url'] = 'jdbc:mysql://localhost:3306/app' datasource_properties['jndi-name'] = 'java:jboss/datasources/appDS' datasource_properties['user-name'] = 'app' datasource_properties['password'] = '******' jboss7.create_datasource(self.jboss_config, 'appDS', datasource_properties) self.org_run_operation.assert_called_with(self.jboss_config, '/subsystem=datasources/data-source="appDS":add(driver-name="mysql",connection-url="jdbc:mysql://localhost:3306/app",jndi-name="java:jboss/datasources/appDS",user-name="app",password="******")', fail_on_error=False) def test_create_datasource_format_boolean_value_when_string(self): def cli_command_response(jboss_config, cli_command, fail_on_error=False): if cli_command == '/subsystem=datasources/data-source="appDS":read-resource-description': return {'outcome': 'success', 'result': { 'attributes': { 'use-ccm': {'type': 'BOOLEAN'} } } } self.org_run_operation.side_effect = cli_command_response datasource_properties = OrderedDict() datasource_properties['use-ccm'] = 'true' jboss7.create_datasource(self.jboss_config, 'appDS', datasource_properties) self.org_run_operation.assert_called_with(self.jboss_config, '/subsystem=datasources/data-source="appDS":add(use-ccm=true)', fail_on_error=False) def test_create_datasource_format_boolean_value_when_boolean(self): def cli_command_response(jboss_config, cli_command, fail_on_error=False): if cli_command == '/subsystem=datasources/data-source="appDS":read-resource-description': return {'outcome': 'success', 'result': { 'attributes': { 'use-ccm': {'type': 'BOOLEAN'} } } } self.org_run_operation.side_effect = cli_command_response datasource_properties = OrderedDict() datasource_properties['use-ccm'] = True jboss7.create_datasource(self.jboss_config, 'appDS', datasource_properties) self.org_run_operation.assert_called_with(self.jboss_config, '/subsystem=datasources/data-source="appDS":add(use-ccm=true)', fail_on_error=False) def test_create_datasource_format_int_value_when_int(self): def cli_command_response(jboss_config, cli_command, fail_on_error=False): if cli_command == '/subsystem=datasources/data-source="appDS":read-resource-description': return {'outcome': 'success', 'result': { 'attributes': { 'min-pool-size': {'type': 'INT'} } } } self.org_run_operation.side_effect = cli_command_response datasource_properties = OrderedDict() datasource_properties['min-pool-size'] = 15 jboss7.create_datasource(self.jboss_config, 'appDS', datasource_properties) self.org_run_operation.assert_called_with(self.jboss_config, '/subsystem=datasources/data-source="appDS":add(min-pool-size=15)', fail_on_error=False) def test_create_datasource_format_int_value_when_string(self): def cli_command_response(jboss_config, cli_command, fail_on_error=False): if cli_command == '/subsystem=datasources/data-source="appDS":read-resource-description': return {'outcome': 'success', 'result': { 'attributes': { 'min-pool-size': {'type': 'INT'} } } } self.org_run_operation.side_effect = cli_command_response datasource_properties = OrderedDict() datasource_properties['min-pool-size'] = '15' jboss7.create_datasource(self.jboss_config, 'appDS', datasource_properties) self.org_run_operation.assert_called_with(self.jboss_config, '/subsystem=datasources/data-source="appDS":add(min-pool-size=15)', fail_on_error=False) def test_read_datasource(self): def cli_command_response(jboss_config, cli_command): if cli_command == '/subsystem=datasources/data-source="appDS":read-resource': return { 'outcome': 'success', 'result': { 'driver-name': 'mysql', 'connection-url': 'jdbc:mysql://localhost:3306/app', 'jndi-name': 'java:jboss/datasources/appDS', 'user-name': 'app', 'password': '******' } } self.org_run_operation.side_effect = cli_command_response ds_result = jboss7.read_datasource(self.jboss_config, 'appDS') ds_properties = ds_result['result'] self.assertEqual(ds_properties['driver-name'], 'mysql') self.assertEqual(ds_properties['connection-url'], 'jdbc:mysql://localhost:3306/app') self.assertEqual(ds_properties['jndi-name'], 'java:jboss/datasources/appDS') self.assertEqual(ds_properties['user-name'], 'app') self.assertEqual(ds_properties['password'], 'app_password') def test_update_datasource(self): datasource_properties = {'driver-name': 'mysql', 'connection-url': 'jdbc:mysql://localhost:3306/app', 'jndi-name': 'java:jboss/datasources/appDS', 'user-name': 'newuser', 'password': '******'} def cli_command_response(jboss_config, cli_command, fail_on_error=False): if cli_command == '/subsystem=datasources/data-source="appDS":read-resource-description': return {'outcome': 'success', 'result': { 'attributes': { 'driver-name': {'type': 'STRING'}, 'connection-url': {'type': 'STRING'}, 'jndi-name': {'type': 'STRING'}, 'user-name': {'type': 'STRING'}, 'password': {'type': 'STRING'} } } } elif cli_command == '/subsystem=datasources/data-source="appDS":read-resource': return { 'outcome': 'success', 'result': { 'driver-name': 'mysql', 'connection-url': 'jdbc:mysql://localhost:3306/app', 'jndi-name': 'java:jboss/datasources/appDS', 'user-name': 'app', 'password': '******' } } elif cli_command == '/subsystem=datasources/data-source="appDS":write-attribute(name="user-name",value="newuser")': return { 'outcome': 'success', 'success': True } self.org_run_operation.side_effect = cli_command_response jboss7.update_datasource(self.jboss_config, 'appDS', datasource_properties) self.org_run_operation.assert_any_call(self.jboss_config, '/subsystem=datasources/data-source="appDS":write-attribute(name="user-name",value="newuser")', fail_on_error=False)
def test_held_unheld(package_manager): """ Test pkg.held and pkg.unheld with Zypper, YUM/DNF and APT """ if package_manager == "Zypper": list_holds_func = "pkg.list_locks" list_holds_mock = MagicMock( return_value={ "bar": { "type": "package", "match_type": "glob", "case_sensitive": "on", }, "minimal_base": { "type": "pattern", "match_type": "glob", "case_sensitive": "on", }, "baz": { "type": "package", "match_type": "glob", "case_sensitive": "on", }, }) elif package_manager == "YUM/DNF": list_holds_func = "pkg.list_holds" list_holds_mock = MagicMock(return_value=[ "bar-0:1.2.3-1.1.*", "baz-0:2.3.4-2.1.*", ]) elif package_manager == "APT": list_holds_func = "pkg.get_selections" list_holds_mock = MagicMock(return_value={"hold": [ "bar", "baz", ]}) def pkg_hold(name, pkgs=None, *_args, **__kwargs): if name and pkgs is None: pkgs = [name] ret = {} for pkg in pkgs: ret.update({ pkg: { "name": pkg, "changes": { "new": "hold", "old": "" }, "result": True, "comment": "Package {} is now being held.".format(pkg), } }) return ret def pkg_unhold(name, pkgs=None, *_args, **__kwargs): if name and pkgs is None: pkgs = [name] ret = {} for pkg in pkgs: ret.update({ pkg: { "name": pkg, "changes": { "new": "", "old": "hold" }, "result": True, "comment": "Package {} is no longer held.".format(pkg), } }) return ret hold_mock = MagicMock(side_effect=pkg_hold) unhold_mock = MagicMock(side_effect=pkg_unhold) # Testing with Zypper with patch.dict( pkg.__salt__, { list_holds_func: list_holds_mock, "pkg.hold": hold_mock, "pkg.unhold": unhold_mock, }, ): # Holding one of two packages ret = pkg.held("held-test", pkgs=["foo", "bar"]) assert "foo" in ret["changes"] assert len(ret["changes"]) == 1 hold_mock.assert_called_once_with(name="held-test", pkgs=["foo"]) unhold_mock.assert_not_called() hold_mock.reset_mock() unhold_mock.reset_mock() # Holding one of two packages and replacing all the rest held packages ret = pkg.held("held-test", pkgs=["foo", "bar"], replace=True) assert "foo" in ret["changes"] assert "baz" in ret["changes"] assert len(ret["changes"]) == 2 hold_mock.assert_called_once_with(name="held-test", pkgs=["foo"]) unhold_mock.assert_called_once_with(name="held-test", pkgs=["baz"]) hold_mock.reset_mock() unhold_mock.reset_mock() # Remove all holds ret = pkg.held("held-test", pkgs=[], replace=True) assert "bar" in ret["changes"] assert "baz" in ret["changes"] assert len(ret["changes"]) == 2 hold_mock.assert_not_called() unhold_mock.assert_any_call(name="held-test", pkgs=["baz"]) unhold_mock.assert_any_call(name="held-test", pkgs=["bar"]) hold_mock.reset_mock() unhold_mock.reset_mock() # Unolding one of two packages ret = pkg.unheld("held-test", pkgs=["foo", "bar"]) assert "bar" in ret["changes"] assert len(ret["changes"]) == 1 unhold_mock.assert_called_once_with(name="held-test", pkgs=["bar"]) hold_mock.assert_not_called() hold_mock.reset_mock() unhold_mock.reset_mock() # Remove all holds ret = pkg.unheld("held-test", all=True) assert "bar" in ret["changes"] assert "baz" in ret["changes"] assert len(ret["changes"]) == 2 hold_mock.assert_not_called() unhold_mock.assert_any_call(name="held-test", pkgs=["baz"]) unhold_mock.assert_any_call(name="held-test", pkgs=["bar"])
def test_refresh_db_with_options(self): with patch('salt.utils.pkg.clear_rtag', Mock()): # With check_update=True we will do a cmd.run to run the clean_cmd, and # then a separate cmd.retcode to check for updates. # with fromrepo yum_call = MagicMock() with patch.dict( yumpkg.__salt__, { 'cmd.run_all': yum_call, 'config.get': MagicMock(return_value=False) }): yumpkg.refresh_db(check_update=True, fromrepo='good', branch='foo') assert yum_call.call_count == 2 yum_call.assert_any_call([ 'yum', '--quiet', '--assumeyes', 'clean', 'expire-cache', '--disablerepo=*', '--enablerepo=good', '--branch=foo' ], env={}, ignore_retcode=True, output_loglevel='trace', python_shell=False) yum_call.assert_any_call([ 'yum', '--quiet', '--assumeyes', 'check-update', '--setopt=autocheck_running_kernel=false', '--disablerepo=*', '--enablerepo=good', '--branch=foo' ], output_loglevel='trace', env={}, ignore_retcode=True, python_shell=False) # without fromrepo yum_call = MagicMock() with patch.dict( yumpkg.__salt__, { 'cmd.run_all': yum_call, 'config.get': MagicMock(return_value=False) }): yumpkg.refresh_db(check_update=True, enablerepo='good', disablerepo='bad', branch='foo') assert yum_call.call_count == 2 yum_call.assert_any_call([ 'yum', '--quiet', '--assumeyes', 'clean', 'expire-cache', '--disablerepo=bad', '--enablerepo=good', '--branch=foo' ], env={}, ignore_retcode=True, output_loglevel='trace', python_shell=False) yum_call.assert_any_call([ 'yum', '--quiet', '--assumeyes', 'check-update', '--setopt=autocheck_running_kernel=false', '--disablerepo=bad', '--enablerepo=good', '--branch=foo' ], output_loglevel='trace', env={}, ignore_retcode=True, python_shell=False) # With check_update=False we will just do a cmd.run for the clean_cmd # with fromrepo yum_call = MagicMock() with patch.dict( yumpkg.__salt__, { 'cmd.run_all': yum_call, 'config.get': MagicMock(return_value=False) }): yumpkg.refresh_db(check_update=False, fromrepo='good', branch='foo') assert yum_call.call_count == 1 yum_call.assert_called_once_with([ 'yum', '--quiet', '--assumeyes', 'clean', 'expire-cache', '--disablerepo=*', '--enablerepo=good', '--branch=foo' ], env={}, output_loglevel='trace', ignore_retcode=True, python_shell=False) # without fromrepo yum_call = MagicMock() with patch.dict( yumpkg.__salt__, { 'cmd.run_all': yum_call, 'config.get': MagicMock(return_value=False) }): yumpkg.refresh_db(check_update=False, enablerepo='good', disablerepo='bad', branch='foo') assert yum_call.call_count == 1 yum_call.assert_called_once_with([ 'yum', '--quiet', '--assumeyes', 'clean', 'expire-cache', '--disablerepo=bad', '--enablerepo=good', '--branch=foo' ], env={}, output_loglevel='trace', ignore_retcode=True, python_shell=False)
def test_netdev(): """ Test status.netdev for AIX :return: """ # Output from netstat -i -n -I <en0|en1|lo0> -f inet netstat_inet4_en0 = """Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll en0 1500 link#2 fa.41.f5.e9.bd.20 1523125 0 759364 0 0 en0 1500 129.40.94.5 129.40.94.58 1523125 0 759364 0 0 """ netstat_inet4_en1 = """Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll en1 1500 link#3 fa.41.f5.e9.bd.21 1089 0 402 0 0 en1 1500 172.24.94.5 172.24.94.58 1089 0 402 0 0 """ netstat_inet4_lo0 = """Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll lo0 16896 link#1 25568 0 25568 0 0 lo0 16896 127 127.0.0.1 25568 0 25568 0 0 """ # Output from netstat -i -n -I <en0|en1|lo0> -f inet6 netstat_inet6_en0 = """Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll en0 1500 link#2 fa.41.f5.e9.bd.20 1523160 0 759397 0 0 """ netstat_inet6_en1 = """Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll en1 1500 link#3 fa.41.f5.e9.bd.21 1089 0 402 0 0 """ netstat_inet6_lo0 = """Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll lo0 16896 link#1 25611 0 25611 0 0 lo0 16896 ::1%1 25611 0 25611 0 0 """ # allow en0, en1 and lo0 for ipv4 and ipv6 netstats_out = MagicMock(side_effect=[ netstat_inet4_en0, netstat_inet6_en0, netstat_inet4_en1, netstat_inet6_en1, netstat_inet4_lo0, netstat_inet6_lo0, netstat_inet4_en0, netstat_inet6_en0, netstat_inet4_en1, netstat_inet6_en1, netstat_inet4_lo0, netstat_inet6_lo0, ]) with patch.dict( status.__grains__, { "osarch": "PowerPC_POWER8", "ip4_interfaces": { "en0": ["129.40.94.58"], "en1": ["172.24.94.58"], "lo0": ["127.0.0.1"], }, "ip6_interfaces": { "en0": [], "en1": [], "lo0": ["::1"], }, "kernel": "AIX", }, ), patch.dict(status.__salt__, {"cmd.run": netstats_out}): netdev_out = status.netdev() assert netstats_out.call_count == 12 netstats_out.assert_any_call("netstat -i -n -I en0 -f inet") netstats_out.assert_any_call("netstat -i -n -I en1 -f inet") netstats_out.assert_any_call("netstat -i -n -I lo0 -f inet") netstats_out.assert_any_call("netstat -i -n -I en0 -f inet6") netstats_out.assert_any_call("netstat -i -n -I en1 -f inet6") netstats_out.assert_any_call("netstat -i -n -I lo0 -f inet6") expected = { "en0": [{ "ipv4": { "Mtu": "1500", "Network": "129.40.94.5", "Address": "129.40.94.58", "Ipkts": "1523125", "Ierrs": "0", "Opkts": "759364", "Oerrs": "0", "Coll": "0", } }], "en1": [{ "ipv4": { "Mtu": "1500", "Network": "172.24.94.5", "Address": "172.24.94.58", "Ipkts": "1089", "Ierrs": "0", "Opkts": "402", "Oerrs": "0", "Coll": "0", } }], "lo0": [ { "ipv4": { "Mtu": "16896", "Network": "127", "Address": "127.0.0.1", "Ipkts": "25568", "Ierrs": "0", "Opkts": "25568", "Oerrs": "0", "Coll": "0", } }, { "ipv6": { "Mtu": "16896", "Network": "::1%1", "Address": "25611", "Ipkts": "0", "Ierrs": "25611", "Opkts": "0", "Oerrs": "0", } }, ], } assert netdev_out == expected
class JBoss7TestCase(TestCase, LoaderModuleMockMixin): jboss_config = {} org_run_operation = None def setup_loader_modules(self): self.org_run_operation = MagicMock() self.addCleanup(delattr, self, "org_run_operation") return { jboss7: { "__salt__": { "jboss7_cli.run_operation": self.org_run_operation } } } def test_create_simple_binding(self): jboss7.create_simple_binding(self.jboss_config, "java:global/env", "DEV") self.org_run_operation.assert_called_with( self.jboss_config, '/subsystem=naming/binding="java:global/env":add(binding-type=simple,' ' value="DEV")', ) def test_create_simple_binding_with_backslash(self): jboss7.create_simple_binding(self.jboss_config, "java:global/env", r"DEV\2") self.org_run_operation.assert_called_with( self.jboss_config, r'/subsystem=naming/binding="java:global/env":add(binding-type=simple,' r' value="DEV\\\\2")', ) def test_update_binding(self): jboss7.update_simple_binding(self.jboss_config, "java:global/env", "INT") self.org_run_operation.assert_called_with( self.jboss_config, '/subsystem=naming/binding="java:global/env":write-attribute(name=value,' ' value="INT")', ) def test_update_binding_with_backslash(self): jboss7.update_simple_binding(self.jboss_config, "java:global/env", r"INT\2") self.org_run_operation.assert_called_with( self.jboss_config, r'/subsystem=naming/binding="java:global/env":write-attribute(name=value,' r' value="INT\\\\2")', ) def test_read_binding(self): def cli_command_response(jboss_config, cli_command): if (cli_command == '/subsystem=naming/binding="java:global/env":read-resource' ): return { "outcome": "success", "result": { "binding-type": "simple", "value": "DEV" }, } self.org_run_operation.side_effect = cli_command_response result = jboss7.read_simple_binding(self.jboss_config, "java:global/env") self.assertEqual(result["outcome"], "success") self.assertEqual(result["result"]["value"], "DEV") def test_create_datasource_all_properties_included(self): def cli_command_response(jboss_config, cli_command, fail_on_error=False): if (cli_command == '/subsystem=datasources/data-source="appDS":read-resource-description' ): return { "outcome": "success", "result": { "attributes": { "driver-name": { "type": "STRING" }, "connection-url": { "type": "STRING" }, "jndi-name": { "type": "STRING" }, "user-name": { "type": "STRING" }, "password": { "type": "STRING" }, } }, } self.org_run_operation.side_effect = cli_command_response datasource_properties = OrderedDict() datasource_properties["driver-name"] = "mysql" datasource_properties[ "connection-url"] = "jdbc:mysql://localhost:3306/app" datasource_properties["jndi-name"] = "java:jboss/datasources/appDS" datasource_properties["user-name"] = "app" datasource_properties["password"] = "******" jboss7.create_datasource(self.jboss_config, "appDS", datasource_properties) self.org_run_operation.assert_called_with( self.jboss_config, '/subsystem=datasources/data-source="appDS":add(driver-name="mysql",connection-url="jdbc:mysql://localhost:3306/app",jndi-name="java:jboss/datasources/appDS",user-name="app",password="******")', fail_on_error=False, ) def test_create_datasource_format_boolean_value_when_string(self): def cli_command_response(jboss_config, cli_command, fail_on_error=False): if (cli_command == '/subsystem=datasources/data-source="appDS":read-resource-description' ): return { "outcome": "success", "result": { "attributes": { "use-ccm": { "type": "BOOLEAN" } } }, } self.org_run_operation.side_effect = cli_command_response datasource_properties = OrderedDict() datasource_properties["use-ccm"] = "true" jboss7.create_datasource(self.jboss_config, "appDS", datasource_properties) self.org_run_operation.assert_called_with( self.jboss_config, '/subsystem=datasources/data-source="appDS":add(use-ccm=true)', fail_on_error=False, ) def test_create_datasource_format_boolean_value_when_boolean(self): def cli_command_response(jboss_config, cli_command, fail_on_error=False): if (cli_command == '/subsystem=datasources/data-source="appDS":read-resource-description' ): return { "outcome": "success", "result": { "attributes": { "use-ccm": { "type": "BOOLEAN" } } }, } self.org_run_operation.side_effect = cli_command_response datasource_properties = OrderedDict() datasource_properties["use-ccm"] = True jboss7.create_datasource(self.jboss_config, "appDS", datasource_properties) self.org_run_operation.assert_called_with( self.jboss_config, '/subsystem=datasources/data-source="appDS":add(use-ccm=true)', fail_on_error=False, ) def test_create_datasource_format_int_value_when_int(self): def cli_command_response(jboss_config, cli_command, fail_on_error=False): if (cli_command == '/subsystem=datasources/data-source="appDS":read-resource-description' ): return { "outcome": "success", "result": { "attributes": { "min-pool-size": { "type": "INT" } } }, } self.org_run_operation.side_effect = cli_command_response datasource_properties = OrderedDict() datasource_properties["min-pool-size"] = 15 jboss7.create_datasource(self.jboss_config, "appDS", datasource_properties) self.org_run_operation.assert_called_with( self.jboss_config, '/subsystem=datasources/data-source="appDS":add(min-pool-size=15)', fail_on_error=False, ) def test_create_datasource_format_int_value_when_string(self): def cli_command_response(jboss_config, cli_command, fail_on_error=False): if (cli_command == '/subsystem=datasources/data-source="appDS":read-resource-description' ): return { "outcome": "success", "result": { "attributes": { "min-pool-size": { "type": "INT" } } }, } self.org_run_operation.side_effect = cli_command_response datasource_properties = OrderedDict() datasource_properties["min-pool-size"] = "15" jboss7.create_datasource(self.jboss_config, "appDS", datasource_properties) self.org_run_operation.assert_called_with( self.jboss_config, '/subsystem=datasources/data-source="appDS":add(min-pool-size=15)', fail_on_error=False, ) def test_read_datasource(self): def cli_command_response(jboss_config, cli_command): if (cli_command == '/subsystem=datasources/data-source="appDS":read-resource' ): return { "outcome": "success", "result": { "driver-name": "mysql", "connection-url": "jdbc:mysql://localhost:3306/app", "jndi-name": "java:jboss/datasources/appDS", "user-name": "app", "password": "******", }, } self.org_run_operation.side_effect = cli_command_response ds_result = jboss7.read_datasource(self.jboss_config, "appDS") ds_properties = ds_result["result"] self.assertEqual(ds_properties["driver-name"], "mysql") self.assertEqual(ds_properties["connection-url"], "jdbc:mysql://localhost:3306/app") self.assertEqual(ds_properties["jndi-name"], "java:jboss/datasources/appDS") self.assertEqual(ds_properties["user-name"], "app") self.assertEqual(ds_properties["password"], "app_password") def test_update_datasource(self): datasource_properties = { "driver-name": "mysql", "connection-url": "jdbc:mysql://localhost:3306/app", "jndi-name": "java:jboss/datasources/appDS", "user-name": "newuser", "password": "******", } def cli_command_response(jboss_config, cli_command, fail_on_error=False): if (cli_command == '/subsystem=datasources/data-source="appDS":read-resource-description' ): return { "outcome": "success", "result": { "attributes": { "driver-name": { "type": "STRING" }, "connection-url": { "type": "STRING" }, "jndi-name": { "type": "STRING" }, "user-name": { "type": "STRING" }, "password": { "type": "STRING" }, } }, } elif (cli_command == '/subsystem=datasources/data-source="appDS":read-resource'): return { "outcome": "success", "result": { "driver-name": "mysql", "connection-url": "jdbc:mysql://localhost:3306/app", "jndi-name": "java:jboss/datasources/appDS", "user-name": "app", "password": "******", }, } elif (cli_command == '/subsystem=datasources/data-source="appDS":write-attribute(name="user-name",value="newuser")' ): return {"outcome": "success", "success": True} self.org_run_operation.side_effect = cli_command_response jboss7.update_datasource(self.jboss_config, "appDS", datasource_properties) self.org_run_operation.assert_any_call( self.jboss_config, '/subsystem=datasources/data-source="appDS":write-attribute(name="user-name",value="newuser")', fail_on_error=False, )