def test_exists_change_negative_index_add_exception(name): """ Tests win_path.exists when the directory is already in the PATH but an exception is raised when we attempt to add the key to its new location. This tests a negative index. """ add_mock = MagicMock(side_effect=Exception("Global Thermonuclear War")) rehash_mock = MagicMock(return_value=True) dunder_salt = { "win_path.get_path": MagicMock(side_effect=[["foo", "bar", name, "baz"], ["foo", "bar", name, "baz"]]), "win_path.add": add_mock, "win_path.rehash": rehash_mock, } dunder_opts = {"test": False} with patch.dict(win_path.__salt__, dunder_salt), patch.dict(win_path.__opts__, dunder_opts): ret = win_path.exists(name, index=-1) add_mock.assert_called_once_with(name, index=-1, rehash=False) rehash_mock.assert_not_called() assert ret == { "name": name, "changes": {}, "result": False, "comment": ("Encountered error: Global Thermonuclear War. " "Failed to move {} from index -2 to -1.".format(name)), }
def test_exists_change_negative_index_failure(name): """ Tests win_path.exists when the directory is already in the PATH and needs to be moved to a different position (failed run). This tests a negative index. """ add_mock = MagicMock(return_value=False) rehash_mock = MagicMock(return_value=True) dunder_salt = { "win_path.get_path": MagicMock(side_effect=[["foo", "bar", name, "baz"], ["foo", "bar", name, "baz"]]), "win_path.add": add_mock, "win_path.rehash": rehash_mock, } dunder_opts = {"test": False} with patch.dict(win_path.__salt__, dunder_salt), patch.dict(win_path.__opts__, dunder_opts): ret = win_path.exists(name, index=-1) add_mock.assert_called_once_with(name, index=-1, rehash=False) rehash_mock.assert_not_called() assert ret == { "name": name, "changes": {}, "result": False, "comment": "Failed to move {} from index -2 to -1.".format(name), }
def test_format_slots_malformed(self): ''' Test the format slots keeps malformed slots untouched. ''' sls_data = { 'args': [ '__slot__:NOT_SUPPORTED:not.called()', '__slot__:salt:not.called(', '__slot__:salt:', '__slot__:salt', '__slot__:', '__slot__', ], 'kwargs': { 'key3': '__slot__:NOT_SUPPORTED:not.called()', 'key4': '__slot__:salt:not.called(', 'key5': '__slot__:salt:', 'key6': '__slot__:salt', 'key7': '__slot__:', 'key8': '__slot__', } } cdata = sls_data.copy() mock = MagicMock(return_value='return') with patch.dict(self.state_obj.functions, {'not.called': mock}): self.state_obj.format_slots(cdata) mock.assert_not_called() self.assertEqual(cdata, sls_data)
def test_exists_add_no_index_failure_exception(name): """ Tests win_path.exists when the directory isn't already in the PATH and no index is specified (failed run due to exception). """ add_mock = MagicMock(side_effect=Exception("Global Thermonuclear War")) rehash_mock = MagicMock(return_value=True) dunder_salt = { "win_path.get_path": MagicMock(side_effect=[["foo", "bar", "baz"], ["foo", "bar", "baz"]]), "win_path.add": add_mock, "win_path.rehash": rehash_mock, } dunder_opts = {"test": False} with patch.dict(win_path.__salt__, dunder_salt), patch.dict(win_path.__opts__, dunder_opts): ret = win_path.exists(name) add_mock.assert_called_once_with(name, index=None, rehash=False) rehash_mock.assert_not_called() assert ret == { "name": name, "changes": {}, "result": False, "comment": ("Encountered error: Global Thermonuclear War. " "Failed to add {} to the PATH.".format(name)), }
def test_network_defined_no_change(test): """ network_defined state tests if the network doesn't need update. """ with patch.dict(virt.__opts__, {"test": test}): define_mock = MagicMock(return_value=True) update_mock = MagicMock(return_value=False) with patch.dict( virt.__salt__, { "virt.network_info": MagicMock( return_value={"mynet": {"active": True, "autostart": True}} ), "virt.network_define": define_mock, "virt.network_update": update_mock, }, ): assert { "name": "mynet", "changes": {}, "result": True, "comment": "Network mynet unchanged", } == virt.network_defined("mynet", "br2", "bridge") define_mock.assert_not_called() assert [ network_update_call("mynet", "br2", "bridge", test=True) ] == update_mock.call_args_list
def test_run_with_pre_flight_thin_dir_exists(self): """ test Single.run() when ssh_pre_flight is set and thin_dir already exists """ target = self.target.copy() target["ssh_pre_flight"] = os.path.join(RUNTIME_VARS.TMP, "script.sh") single = ssh.Single( self.opts, self.opts["argv"], "localhost", mods={}, fsclient=None, thin=salt.utils.thin.thin_path(self.opts["cachedir"]), mine=False, **target ) cmd_ret = ("", "", 0) mock_flight = MagicMock(return_value=cmd_ret) mock_cmd = MagicMock(return_value=cmd_ret) patch_flight = patch("salt.client.ssh.Single.run_ssh_pre_flight", mock_flight) patch_cmd = patch("salt.client.ssh.shell.Shell.exec_cmd", mock_cmd) patch_cmd_block = patch("salt.client.ssh.Single.cmd_block", mock_cmd) patch_os = patch("os.path.exists", return_value=True) with patch_os, patch_flight, patch_cmd, patch_cmd_block: ret = single.run() mock_cmd.assert_called() mock_flight.assert_not_called() assert ret == cmd_ret
def test_format_slots_malformed(state_obj): """ Test the format slots keeps malformed slots untouched. """ sls_data = { "args": [ "__slot__:NOT_SUPPORTED:not.called()", "__slot__:salt:not.called(", "__slot__:salt:", "__slot__:salt", "__slot__:", "__slot__", ], "kwargs": { "key3": "__slot__:NOT_SUPPORTED:not.called()", "key4": "__slot__:salt:not.called(", "key5": "__slot__:salt:", "key6": "__slot__:salt", "key7": "__slot__:", "key8": "__slot__", }, } cdata = sls_data.copy() mock = MagicMock(return_value="return") with patch.dict(state_obj.functions, {"not.called": mock}): state_obj.format_slots(cdata) mock.assert_not_called() assert cdata == sls_data
def test_exists_change_negative_index_test_mode(self): ''' Tests win_path.exists when the directory is already in the PATH and needs to be moved to a different position (test mode enabled). ''' add_mock = Mock() rehash_mock = MagicMock(return_value=True) dunder_salt = { 'win_path.get_path': MagicMock(side_effect=[ ['foo', 'bar', NAME, 'baz'], ]), 'win_path.add': add_mock, 'win_path.rehash': rehash_mock, } dunder_opts = {'test': True} with patch.dict(win_path.__salt__, dunder_salt), \ patch.dict(win_path.__opts__, dunder_opts): ret = win_path.exists(NAME, index=-1) add_mock.assert_not_called() rehash_mock.assert_not_called() self.assertDictEqual( ret, { 'name': NAME, 'changes': {'index': {'old': -2, 'new': -1}}, 'result': None, 'comment': '{0} would be moved from index -2 to -1.'.format(NAME) } )
def test_exists_change_negative_index_failure(self): ''' Tests win_path.exists when the directory is already in the PATH and needs to be moved to a different position (failed run). This tests a negative index. ''' add_mock = MagicMock(return_value=False) rehash_mock = MagicMock(return_value=True) dunder_salt = { 'win_path.get_path': MagicMock(side_effect=[ ['foo', 'bar', NAME, 'baz'], ['foo', 'bar', NAME, 'baz'] ]), 'win_path.add': add_mock, 'win_path.rehash': rehash_mock, } dunder_opts = {'test': False} with patch.dict(win_path.__salt__, dunder_salt), \ patch.dict(win_path.__opts__, dunder_opts): ret = win_path.exists(NAME, index=-1) add_mock.assert_called_once_with(NAME, index=-1, rehash=False) rehash_mock.assert_not_called() self.assertDictEqual( ret, { 'name': NAME, 'changes': {}, 'result': False, 'comment': 'Failed to move {0} from index -2 to -1.'.format(NAME) } )
def test_exists_change_negative_index_test_mode(name): """ Tests win_path.exists when the directory is already in the PATH and needs to be moved to a different position (test mode enabled). """ add_mock = Mock() rehash_mock = MagicMock(return_value=True) dunder_salt = { "win_path.get_path": MagicMock(side_effect=[["foo", "bar", name, "baz"]]), "win_path.add": add_mock, "win_path.rehash": rehash_mock, } dunder_opts = {"test": True} with patch.dict(win_path.__salt__, dunder_salt), patch.dict(win_path.__opts__, dunder_opts): ret = win_path.exists(name, index=-1) add_mock.assert_not_called() rehash_mock.assert_not_called() assert ret == { "name": name, "changes": { "index": { "old": -2, "new": -1 } }, "result": None, "comment": "{} would be moved from index -2 to -1.".format(name), }
def test_defined_update_definition_error(test): """ defined state test, with definition update failure """ with patch.dict(virt.__opts__, {"test": test}): init_mock = MagicMock(return_value=True) update_mock = MagicMock( side_effect=[virt.libvirt.libvirtError("error message")] ) with patch.dict( virt.__salt__, { "virt.list_domains": MagicMock(return_value=["myvm"]), "virt.update": update_mock, "virt.init": init_mock, }, ): assert virt.defined("myvm", cpu=2) == { "name": "myvm", "changes": {}, "result": False, "comment": "error message", } init_mock.assert_not_called() assert update_mock.call_args_list == [ domain_update_call("myvm", cpu=2, test=test) ]
def test_exists_add_no_index_failure_exception(self): ''' Tests win_path.exists when the directory isn't already in the PATH and no index is specified (failed run due to exception). ''' add_mock = MagicMock(side_effect=Exception('Global Thermonuclear War')) rehash_mock = MagicMock(return_value=True) dunder_salt = { 'win_path.get_path': MagicMock(side_effect=[ ['foo', 'bar', 'baz'], ['foo', 'bar', 'baz'] ]), 'win_path.add': add_mock, 'win_path.rehash': rehash_mock, } dunder_opts = {'test': False} with patch.dict(win_path.__salt__, dunder_salt), \ patch.dict(win_path.__opts__, dunder_opts): ret = win_path.exists(NAME) add_mock.assert_called_once_with(NAME, index=None, rehash=False) rehash_mock.assert_not_called() self.assertDictEqual( ret, { 'name': NAME, 'changes': {}, 'result': False, 'comment': 'Encountered error: Global Thermonuclear War. ' 'Failed to add {0} to the PATH.'.format(NAME) } )
def test_rebooted(test): """ rebooted state test """ with patch.dict(virt.__opts__, {"test": test}): reboot_mock = MagicMock(return_value=True) with patch.dict( virt.__salt__, { "virt.list_domains": MagicMock(return_value=["myvm", "vm1"]), "virt.reboot": reboot_mock, }, ): assert virt.rebooted( "myvm", connection="myconnection", username="******", password="******", ) == { "name": "myvm", "result": True if not test else None, "changes": {"rebooted": [{"domain": "myvm", "reboot": True}]}, "comment": "Machine has been rebooted", } if not test: reboot_mock.assert_called_with( "myvm", connection="myconnection", username="******", password="******", ) else: reboot_mock.assert_not_called()
def test_running_update(test, running): """ running state test, update an existing guest """ with patch.dict(virt.__opts__, {"test": test}): start_mock = MagicMock(return_value=0) with patch.dict( virt.__salt__, { "virt.vm_state": MagicMock(return_value={"myvm": running}), "virt.update": MagicMock( return_value={"definition": True, "cpu": True} ), "virt.start": start_mock, "virt.list_domains": MagicMock(return_value=["myvm"]), }, ): changes = {"definition": True, "cpu": True} if running == "shutdown": changes["started"] = True assert virt.running("myvm", cpu=2) == { "name": "myvm", "changes": {"myvm": changes}, "result": True if not test else None, "comment": "Domain myvm updated" if running == "running" else "Domain myvm updated and started", } if running == "shutdown" and not test: start_mock.assert_called() else: start_mock.assert_not_called()
def test_snapshot(test): """ snapshot state test """ with patch.dict(virt.__opts__, {"test": test}): snapshot_mock = MagicMock(return_value=True) with patch.dict( virt.__salt__, { "virt.list_domains": MagicMock(return_value=["myvm", "vm1"]), "virt.snapshot": snapshot_mock, }, ): assert virt.snapshot( "myvm", suffix="snap", connection="myconnection", username="******", password="******", ) == { "name": "myvm", "result": True if not test else None, "changes": {"saved": [{"domain": "myvm", "snapshot": True}]}, "comment": "Snapshot has been taken", } if not test: snapshot_mock.assert_called_with( "myvm", suffix="snap", connection="myconnection", username="******", password="******", ) else: snapshot_mock.assert_not_called()
def test_running_no_change(test, running): """ running state test, no change required case. """ with patch.dict(virt.__opts__, {"test": test}): update_mock = MagicMock(return_value={"definition": False}) start_mock = MagicMock(return_value=0) with patch.dict( virt.__salt__, { "virt.vm_state": MagicMock(return_value={"myvm": running}), "virt.start": start_mock, "virt.update": MagicMock(return_value={"definition": False}), "virt.list_domains": MagicMock(return_value=["myvm"]), }, ): assert virt.running("myvm") == { "name": "myvm", "result": True, "changes": {"myvm": {"started": True}} if running == "shutdown" else {}, "comment": "Domain myvm started" if running == "shutdown" else "Domain myvm exists and is running", } if running == "shutdown" and not test: start_mock.assert_called() else: start_mock.assert_not_called()
def test_exists_change_negative_index_add_exception(self): ''' Tests win_path.exists when the directory is already in the PATH but an exception is raised when we attempt to add the key to its new location. This tests a negative index. ''' add_mock = MagicMock(side_effect=Exception('Global Thermonuclear War')) rehash_mock = MagicMock(return_value=True) dunder_salt = { 'win_path.get_path': MagicMock(side_effect=[ ['foo', 'bar', NAME, 'baz'], ['foo', 'bar', NAME, 'baz'], ]), 'win_path.add': add_mock, 'win_path.rehash': rehash_mock, } dunder_opts = {'test': False} with patch.dict(win_path.__salt__, dunder_salt), \ patch.dict(win_path.__opts__, dunder_opts): ret = win_path.exists(NAME, index=-1) add_mock.assert_called_once_with(NAME, index=-1, rehash=False) rehash_mock.assert_not_called() self.assertDictEqual( ret, { 'name': NAME, 'changes': {}, 'result': False, 'comment': 'Encountered error: Global Thermonuclear War. ' 'Failed to move {0} from index -2 to -1.'.format(NAME) } )
def test_defined_update(test): """ defined state test, with change required case. """ with patch.dict(virt.__opts__, {"test": test}): init_mock = MagicMock(return_value=True) update_mock = MagicMock(return_value={"definition": True, "cpu": True}) with patch.dict( virt.__salt__, { "virt.list_domains": MagicMock(return_value=["myvm"]), "virt.update": update_mock, "virt.init": init_mock, }, ): boot = { "kernel": "/root/f8-i386-vmlinuz", "initrd": "/root/f8-i386-initrd", "cmdline": "console=ttyS0 ks=http://example.com/f8-i386/os/", } assert virt.defined("myvm", cpu=2, boot=boot,) == { "name": "myvm", "changes": {"myvm": {"definition": True, "cpu": True}}, "result": True if not test else None, "comment": "Domain myvm updated", } init_mock.assert_not_called() assert update_mock.call_args_list == [ domain_update_call("myvm", cpu=2, test=test, boot=boot) ]
def test_on_aix_chattr_version_should_be_None_even_if_tune2fs_exists(self): patch_which = patch("hubblestack.utils.path.which", Mock(return_value="fnord"),) patch_aix = patch("hubblestack.utils.platform.is_aix", Mock(return_value=True),) mock_run = MagicMock(return_value="fnord") patch_run = patch.dict(filemod.__mods__, {"cmd.run": mock_run}) with patch_which, patch_aix, patch_run: actual = filemod._chattr_version() self.assertIsNone(actual) mock_run.assert_not_called()
def test_defined_update_error(test): """ defined state test, with error during the update. """ with patch.dict(virt.__opts__, {"test": test}): init_mock = MagicMock(return_value=True) update_mock = MagicMock(return_value={ "definition": True, "cpu": False, "errors": ["some error"] }) with patch.dict( virt.__salt__, { "virt.list_domains": MagicMock(return_value=["myvm"]), "virt.update": update_mock, "virt.init": init_mock, }, ): assert virt.defined("myvm", cpu=2, boot_dev="cdrom hd") == { "name": "myvm", "changes": { "myvm": { "definition": True, "cpu": False, "errors": ["some error"], } }, "result": True if not test else None, "comment": "Domain myvm updated with live update(s) failures", } init_mock.assert_not_called() update_mock.assert_called_with( "myvm", cpu=2, boot_dev="cdrom hd", mem=None, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, connection=None, username=None, password=None, boot=None, numatune=None, test=test, hypervisor_features=None, clock=None, serials=None, consoles=None, stop_on_reboot=False, host_devices=None, )
def test_network_running_stopped(test): """ network_running state test cases, network stopped case. """ with patch.dict(virt.__opts__, {"test": test}): define_mock = MagicMock(return_value=True) start_mock = MagicMock(return_value=True) update_mock = MagicMock(return_value=False) with patch.dict( virt.__salt__, { # pylint: disable=no-member "virt.network_info": MagicMock( return_value={"mynet": {"active": False, "autostart": True}} ), "virt.network_start": start_mock, "virt.network_define": define_mock, "virt.network_update": update_mock, }, ): assert virt.network_running( "mynet", "br2", "bridge", connection="myconnection", username="******", password="******", ) == { "name": "mynet", "changes": { "mynet": "Network started" }, "comment": "Network mynet unchanged and started", "result": None if test else True, } assert update_mock.call_args_list == [ network_update_call( "mynet", "br2", "bridge", connection="myconnection", username="******", password="******", test=True, ) ] if not test: start_mock.assert_called_with( "mynet", connection="myconnection", username="******", password="******", ) else: start_mock.assert_not_called()
def test_virtual_update_restart_state_not_called(self): """ Test - Update restart state is not called when dir contains files """ mock_cmd = MagicMock() with patch.dict(opkg.__grains__, {"os_family": "NILinuxRT"}): with patch.object(os, "makedirs", MagicMock(return_value=True)): with patch.object(os, "listdir", MagicMock(return_value=["test"])): with patch.object(opkg, "_update_nilrt_restart_state", mock_cmd): opkg.__virtual__() mock_cmd.assert_not_called()
def test_get_tok_with_valid_expiration_should_return_token(self): expected_token = {"expire": time.time() + 1} fake_get_token = MagicMock(return_value=expected_token) patch_opts = patch.dict(self.lauth.opts, {"eauth_tokens": "testfs"}) patch_get_token = patch.dict( self.lauth.tokens, {"testfs.get_token": fake_get_token}, ) mock_rm_token = MagicMock() patch_rm_token = patch.object(self.lauth, "rm_token", mock_rm_token) with patch_opts, patch_get_token, patch_rm_token: token_name = "fnord" actual_token = self.lauth.get_tok(token_name) mock_rm_token.assert_not_called() assert expected_token is actual_token, "Token was not returned"
def test_pkg_unhold(): """ Tests unholding packages with Zypper """ # Test openSUSE 15.3 list_locks_mock = { "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" }, } cmd = MagicMock( return_value={ "pid": 1234, "retcode": 0, "stdout": "1 lock has been successfully removed.", "stderr": "", }) with patch.object(zypper, "list_locks", MagicMock(return_value=list_locks_mock)), patch.dict( zypper.__salt__, {"cmd.run_all": cmd}): ret = zypper.unhold("foo") assert ret["foo"]["comment"] == "Package foo was already unheld." cmd.assert_not_called() cmd.reset_mock() ret = zypper.unhold(pkgs=["foo", "bar"]) assert ret["foo"]["changes"] == {} assert ret["foo"]["comment"] == "Package foo was already unheld." assert ret["bar"]["changes"]["old"] == "hold" assert ret["bar"]["changes"]["new"] == "" assert ret["bar"]["comment"] == "Package bar is no longer held." cmd.assert_called_once_with( ["zypper", "--non-interactive", "--no-refresh", "rl", "bar"], env={}, output_loglevel="trace", python_shell=False, )
def test_get_tok_with_valid_expiration_should_return_token(self): expected_token = {'expire': time.time() + 1} fake_get_token = MagicMock(return_value=expected_token) patch_opts = patch.dict(self.lauth.opts, {'eauth_tokens': 'testfs'}) patch_get_token = patch.dict( self.lauth.tokens, {'testfs.get_token': fake_get_token}, ) mock_rm_token = MagicMock() patch_rm_token = patch.object(self.lauth, 'rm_token', mock_rm_token) with patch_opts, patch_get_token, patch_rm_token: token_name = 'fnord' actual_token = self.lauth.get_tok(token_name) mock_rm_token.assert_not_called() assert expected_token is actual_token, 'Token was not returned'
def test_chloginclass(): # only runs on OpenBSD assert useradd.chloginclass("Salt", "staff") is False with patch.dict(useradd.__grains__, {"kernel": "OpenBSD"}): # command found and successful run userinfo = ["class salt", "class staff"] mock = MagicMock(return_value={"retcode": 0}) with patch( "salt.utils.path.which", MagicMock(return_value="/sbin/usermod") ), patch.dict( useradd.__salt__, {"cmd.run_stdout": MagicMock(side_effect=userinfo)} ), patch.dict( useradd.__salt__, {"cmd.run": mock} ): assert useradd.chloginclass("Salt", "staff") is True mock.assert_called_once_with( ["/sbin/usermod", "-L", "staff", "Salt"], python_shell=False ) # command found and unsuccessful run userinfo = ["class salt", "class salt"] mock = MagicMock(return_value={"retcode": 1, "stderr": ""}) with patch( "salt.utils.path.which", MagicMock(return_value="/sbin/usermod") ), patch.dict( useradd.__salt__, {"cmd.run_stdout": MagicMock(side_effect=userinfo)} ), patch.dict( useradd.__salt__, {"cmd.run": mock} ): assert useradd.chloginclass("Salt", "staff") is False mock.assert_called_once_with( ["/sbin/usermod", "-L", "staff", "Salt"], python_shell=False ) # command not found userinfo = ["class salt"] mock = MagicMock() with patch("salt.utils.path.which", MagicMock(return_value=None)), patch.dict( useradd.__salt__, {"cmd.run_stdout": MagicMock(side_effect=userinfo)} ), patch.dict(useradd.__salt__, {"cmd.run": mock}): with pytest.raises(CommandExecutionError): useradd.chloginclass("Salt", "staff") mock.assert_not_called()
def test_sls_queue_false_failing(): """Test transactional_update.sls""" transactional_update_highstate_mock = MagicMock() transactional_update_highstate_mock.return_value = ( transactional_update_highstate_mock) transactional_update_highstate_mock.render_highstate.return_value = (None, []) transactional_update_highstate_mock.state.reconcile_extend.return_value = ( None, []) transactional_update_highstate_mock.state.requisite_in.return_value = ( None, []) transactional_update_highstate_mock.state.verify_high.return_value = [] _create_and_execute_salt_state_mock = MagicMock(return_value="result") opts_mock = { "hash_type": "md5", } salt_mock = { "saltutil.is_running": MagicMock(side_effect=[ [{ "fun": "state.running", "pid": "4126", "jid": "20150325123407204096", }], [], ]), } get_sls_opts_mock = MagicMock(return_value=opts_mock) with patch.dict(tu.__opts__, opts_mock), patch.dict( statemod.__salt__, salt_mock ), patch("salt.utils.state.get_sls_opts", get_sls_opts_mock), patch( "salt.fileclient.get_file_client", MagicMock() ), patch( "salt.modules.transactional_update.TransactionalUpdateHighstate", transactional_update_highstate_mock, ), patch( "salt.modules.transactional_update._create_and_execute_salt_state", _create_and_execute_salt_state_mock, ): assert tu.sls("module", queue=False) == [ 'The function "state.running" is running as PID 4126 and was started at 2015, Mar 25 12:34:07.204096 with jid 20150325123407204096' ] _create_and_execute_salt_state_mock.assert_not_called()
def _test_exists_add_already_present(self, index, test_mode): """ Tests win_path.exists when the directory already exists in the PATH. Helper function to test both with and without and index, and with test mode both disabled and enabled. """ current_path = ["foo", "bar", "baz"] if index is None: current_path.append(NAME) else: pos = index if index >= 0 else len(current_path) + index + 1 current_path.insert(pos, NAME) add_mock = Mock() rehash_mock = MagicMock(return_value=True) dunder_salt = { "win_path.get_path": MagicMock(side_effect=[current_path]), "win_path.add": add_mock, "win_path.rehash": rehash_mock, } dunder_opts = {"test": test_mode} with patch.dict(win_path.__salt__, dunder_salt), patch.dict(win_path.__opts__, dunder_opts): ret = win_path.exists(NAME, index=index) add_mock.assert_not_called() rehash_mock.assert_not_called() self.assertDictEqual( ret, { "name": NAME, "changes": {}, "result": True, "comment": "{0} already exists in the PATH{1}.".format( NAME, " at index {0}".format(index) if index is not None else ""), }, )
def test_network_defined_error(test): """ network_defined state tests if an error is triggered by libvirt. """ with patch.dict(virt.__opts__, {"test": test}): define_mock = MagicMock(return_value=True) with patch.dict( virt.__salt__, { "virt.network_info": MagicMock(side_effect=virt.libvirt.libvirtError("Some error")) }, ): assert virt.network_defined("mynet", "br2", "bridge") == { "name": "mynet", "changes": {}, "result": False, "comment": "Some error", } define_mock.assert_not_called()
def test_rename(): # command not found with patch("salt.utils.path.which", MagicMock(return_value=None)): mock = MagicMock() with patch.object(useradd, "info", MagicMock(return_value={"uid": 10})), patch.dict( useradd.__salt__, {"cmd.run": mock}): with pytest.raises(CommandExecutionError): useradd.rename("salt", 1) mock.assert_not_called() # command found with patch("salt.utils.path.which", MagicMock(return_value="/sbin/usermod")): mock = MagicMock(return_value=False) with patch.object(useradd, "info", mock): with pytest.raises(CommandExecutionError): useradd.rename("salt", 1) mock = MagicMock(return_value=True) with patch.object(useradd, "info", mock): with pytest.raises(CommandExecutionError): useradd.rename("salt", 1) mock = MagicMock(return_value=None) with patch.dict(useradd.__salt__, {"cmd.run": mock}): mock = MagicMock( side_effect=[False, { "name": "" }, { "name": "salt" }]) with patch.object(useradd, "info", mock): assert useradd.rename("name", "salt") is True mock = MagicMock(return_value=None) with patch.dict(useradd.__salt__, {"cmd.run": mock}): mock = MagicMock(side_effect=[False, {"name": ""}, {"name": ""}]) with patch.object(useradd, "info", mock): assert useradd.rename("salt", "salt") is False