def test_display(self, call): for action in self.actions: self.display.progress(self.pkg, action, 0, 100, 1, 1000) msg = self.display._fmt_event(self.pkg, action, 1, 1000) # updating plymouth display means two plymouth calls call.assert_has_calls([ mock.call((PLYMOUTH, "system-update", "--progress", "0")), mock.call((PLYMOUTH, "display-message", "--text", msg)) ], any_order=True)
def test_setup_from_dnf_conf(self, setup_m): conf = mock.Mock(debuglevel=2, errorlevel=2, logdir=self.logdir) self.logging._setup_from_dnf_conf(conf) self.assertEqual(setup_m.call_args, mock.call(dnf.logging.INFO, dnf.logging.WARNING, self.logdir)) conf = mock.Mock(debuglevel=6, errorlevel=6, logdir=self.logdir) self.logging._setup_from_dnf_conf(conf) self.assertEqual(setup_m.call_args, mock.call(dnf.logging.DEBUG, dnf.logging.WARNING, self.logdir))
def test_filter_calls(self, call): action = PKG_INSTALL # first display update -> set percentage and text self.display.progress(self.pkg, action, 0, 100, 1, 1000) msg1 = self.display._fmt_event(self.pkg, action, 1, 1000) call.assert_has_calls([ mock.call((PLYMOUTH, "system-update", "--progress", "0")), mock.call((PLYMOUTH, "display-message", "--text", msg1)), ]) # event progress on the same transaction item. # no new calls to plymouth because the percentage and text don't change for te_cur in range(1, 100): self.display.progress(self.pkg, action, te_cur, 100, 1, 1000) call.assert_has_calls([ mock.call((PLYMOUTH, "system-update", "--progress", "0")), mock.call((PLYMOUTH, "display-message", "--text", msg1)), ]) # new item: new message ("[2/1000] ..."), but percentage still 0.. self.display.progress(self.pkg, action, 0, 100, 2, 1000) # old message hidden, new message displayed. no new percentage. msg2 = self.display._fmt_event(self.pkg, action, 2, 1000) call.assert_has_calls([ mock.call((PLYMOUTH, "system-update", "--progress", "0")), mock.call((PLYMOUTH, "display-message", "--text", msg1)), mock.call((PLYMOUTH, "hide-message", "--text", msg1)), mock.call((PLYMOUTH, "display-message", "--text", msg2)), ])
def test_userconfirm(self, input_fnc): # with defaultyes==False input_fnc.return_value = 'y' self.assertTrue(self.output.userconfirm()) self.assertEqual(input_fnc.call_args, mock.call(u'Is this ok [y/N]: ')) input_fnc.return_value = 'n' self.assertFalse(self.output.userconfirm()) input_fnc.return_value = '' self.assertFalse(self.output.userconfirm()) input_fnc.side_effect = self._keyboard_interrupt input_fnc.return_value = 'y' self.assertFalse(self.output.userconfirm()) input_fnc.side_effect = self._eof_error self.assertFalse(self.output.userconfirm()) # with defaultyes==True self.output.conf.defaultyes = True input_fnc.side_effect = None input_fnc.return_value = '' self.assertTrue(self.output.userconfirm()) input_fnc.side_effect = self._keyboard_interrupt input_fnc.return_value = '' self.assertFalse(self.output.userconfirm()) input_fnc.side_effect = self._eof_error self.assertTrue(self.output.userconfirm())
def test_downgradePkgs_notinstalled(self, logger): tests.support.ObjectMatcher(dnf.package.Package, {'name': 'lotus'}) with self.assertRaises(dnf.exceptions.Error) as ctx: self.base.downgradePkgs(('lotus',)) self.assertEqual(str(ctx.exception), 'No packages marked for downgrade.') self.assertEqual(self.base.downgrade_to.mock_calls, [mock.call('lotus', strict=False)])
def test_close(self): """Test close.""" yum_history = mock.create_autospec(dnf.yum.history.YumHistory) history = self._create_wrapper(yum_history) history.close() self.assertEqual(yum_history.close.mock_calls, [mock.call()])
def test_find_sap_folder_contain_units_error(self, mock_debug): mock_pattern = mock.Mock(pattern='my_pattern') mock_pattern.match.side_effect = [False, False] with patch( 'salt.utils.files.fopen', mock_open( read_data=['data\n', 'DATA_UNITS\n', 'data_2\n', IOError ])) as mock_file: with pytest.raises(hanamod.SapFolderNotFoundError) as err: hanamod._find_sap_folder(['1234'], mock_pattern) mock_pattern.match.assert_has_calls( [mock.call('data'), mock.call('data_2')]) mock_debug.assert_has_calls([ mock.call('%s folder does not contain %s pattern', '1234', 'my_pattern') ]) assert 'SAP folder with my_pattern pattern not found' in str(err.value)
def test_set_special(self, write_cron_lines_mock): expected_write_call = call('DUMMY_USER', [ '5 0 * * * /tmp/no_script.sh\n', '# Lines below here are managed by Salt, do not edit\n', '@hourly echo Hi!\n' ]) ret = cron.set_special('DUMMY_USER', '@hourly', 'echo Hi!') write_cron_lines_mock.assert_has_calls((expected_write_call, ), any_order=True)
def test_ha_cluster_join_complete(self, mock_corosync, mock_watchdog): ''' Test _ha_cluster_join method ''' mock_cmd_run = MagicMock(side_effect=[0, 0]) with patch.dict(crmshmod.__salt__, {'cmd.retcode': mock_cmd_run}): result = crmshmod._ha_cluster_join( '192.168.1.50', 'dog', 'eth1', True) assert result == 0 mock_corosync.assert_called_once_with('192.168.1.50', 'eth1') mock_watchdog.assert_called_once_with('dog') mock_cmd_run.assert_has_calls([ mock.call('{} -y -c {} -i {} -q'.format( crmshmod.HA_JOIN_COMMAND, '192.168.1.50', 'eth1')), mock.call('{} resource refresh'.format( crmshmod.CRM_COMMAND)) ])
def test_filter_by_site(self): with patch("pynetbox.api", MagicMock()) as mock: with patch.dict( netbox.__utils__, {"args.clean_kwargs": mocked_clean_kwargs_filter} ): netbox.filter_("dcim", "devices", site="test") self.assertEqual( mock.mock_calls[1], call().dcim.devices.filter(site="test") )
def test_get_by_name(self): with patch("pynetbox.api", MagicMock()) as mock: with patch.dict( netbox.__utils__, {"args.clean_kwargs": mocked_clean_kwargs_get} ): netbox.get_("dcim", "devices", name="test") self.assertEqual( mock.mock_calls[1], call().dcim.devices.get(name="test") )
def test_get_mpkg_ids(): """ Test getting the ids of a mpkg file """ with patch("salt.modules.macpackage.get_pkg_id") as get_pkg_id_mock: expected = ["com.apple.this", "com.salt.other"] mock = MagicMock(return_value="/tmp/dmg-X/file.pkg\n/tmp/dmg-X/other.pkg") get_pkg_id_mock.side_effect = [["com.apple.this"], ["com.salt.other"]] with patch.dict(macpackage.__salt__, {"cmd.run": mock}): out = macpackage.get_mpkg_ids("/path/to/file.mpkg") mock.assert_called_once_with("find /path/to -name *.pkg", python_shell=True) calls = [call("/tmp/dmg-X/file.pkg"), call("/tmp/dmg-X/other.pkg")] get_pkg_id_mock.assert_has_calls(calls) assert out == expected
def test_install_ruby_nonroot(self): mock = MagicMock(return_value={'retcode': 0, 'stdout': 'stdout'}) expected = [ call(['/usr/local/rvm/bin/rvm', 'autolibs', 'disable', '2.0.0'], runas='rvm', cwd=None, python_shell=False), call([ '/usr/local/rvm/bin/rvm', 'install', '--disable-binary', '2.0.0' ], runas='rvm', cwd=None, python_shell=False) ] with patch.dict(rvm.__salt__, {'cmd.run_all': mock}): rvm.install_ruby('2.0.0', runas='rvm') self.assertEqual(mock.call_args_list, expected)
def test_call_apt_dpkg_lock(self): """ Call apt and ensure the dpkg locking is handled :return: """ cmd_side_effect = [ { "stderr": "Could not get lock" }, { "stderr": "Could not get lock" }, { "stderr": "Could not get lock" }, { "stderr": "Could not get lock" }, { "stderr": "", "stdout": "" }, ] cmd_mock = MagicMock(side_effect=cmd_side_effect) cmd_call = (call( ["dpkg", "-l", "python"], env={}, ignore_retcode=False, output_loglevel="quiet", python_shell=True, username="******", ), ) expected_calls = [cmd_call * 5] with patch.dict( aptpkg.__salt__, { "cmd.run_all": cmd_mock, "config.get": MagicMock(return_value=False) }, ): with patch("time.sleep", MagicMock()) as sleep_mock: aptpkg._call_apt( ["dpkg", "-l", "python"], python_shell=True, output_loglevel="quiet", ignore_retcode=False, username="******", ) # pylint: disable=W0106 # We should have sleept at least 4 times assert sleep_mock.call_count >= 4 # We should attempt to call the cmd 5 times self.assertEqual(cmd_mock.call_count, 5) cmd_mock.has_calls(expected_calls)
def test_pkill(self): with patch('salt.utils.psutil_compat.Process.send_signal'), \ patch('salt.utils.psutil_compat.process_iter', MagicMock(return_value=[self.mocked_proc])): self.mocked_proc.send_signal = MagicMock() test_signal = 1234 ps.pkill(_get_proc_name(self.mocked_proc), signal=test_signal) self.assertEqual(self.mocked_proc.send_signal.call_args, call(test_signal))
def test_downgradePkgs_notinstalled(self): pkg = support.ObjectMatcher(dnf.package.Package, {"name": "lotus"}) with self.assertRaises(dnf.exceptions.Error) as ctx: self._base.downgradePkgs(("lotus",)) self.assertEqual(str(ctx.exception), "Nothing to do.") self.assertEqual(self._base.downgrade.mock_calls, [mock.call("lotus")]) self.assertEqual(self._base.logger.mock_calls, [mock.call.info("No match for available package: %s", pkg)] * 2)
def test_downgradePkgs_notfound(self): with self.assertRaises(dnf.exceptions.Error) as ctx: self._base.downgradePkgs(("non-existent",)) self.assertEqual(str(ctx.exception), "Nothing to do.") self.assertEqual(self._base.downgrade.mock_calls, [mock.call("non-existent")]) self.assertEqual( self._base.logger.mock_calls, [mock.call.info("No package %s%s%s available.", "", "non-existent", "")] )
def test_get_all_proxies_windows(self): ''' Test to make sure that we correctly get the current proxy info on Windows ''' with patch.dict(proxy.__grains__, {'os': 'Windows'}): results = [{ 'vdata': 'http=192.168.0.1:3128;https=192.168.0.2:3128;ftp=192.168.0.3:3128' }, { 'vdata': 1 }] mock = MagicMock(side_effect=results) 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.__salt__, {'reg.read_value': mock}): out = proxy.get_proxy_win() calls = [ call( 'HKEY_CURRENT_USER', 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings', 'ProxyServer'), call( 'HKEY_CURRENT_USER', 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings', 'ProxyEnable'), ] mock.assert_has_calls(calls) self.assertEqual(expected, out)
def test_installed_cert_hash_different(self): """ Test installing a certificate into the macOS keychain when it's already installed but the certificate has changed """ expected = { "changes": {"installed": "Friendly Name", "uninstalled": "Friendly Name"}, "comment": "Found a certificate with the same name but different hash, removing it.\n", "name": "/path/to/cert.p12", "result": True, } list_mock = MagicMock(side_effect=[["Friendly Name"], []]) friendly_mock = MagicMock(return_value="Friendly Name") install_mock = MagicMock(return_value="1 identity imported.") uninstall_mock = MagicMock(return_value="removed.") hash_mock = MagicMock(side_effect=["ABCD", "XYZ"]) with patch.dict( keychain.__salt__, { "keychain.list_certs": list_mock, "keychain.get_friendly_name": friendly_mock, "keychain.install": install_mock, "keychain.uninstall": uninstall_mock, "keychain.get_hash": hash_mock, }, ): out = keychain.installed("/path/to/cert.p12", "passw0rd") list_mock.assert_has_calls( calls=[ call("/Library/Keychains/System.keychain"), call("/Library/Keychains/System.keychain"), ] ) friendly_mock.assert_called_once_with("/path/to/cert.p12", "passw0rd") install_mock.assert_called_once_with( "/path/to/cert.p12", "passw0rd", "/Library/Keychains/System.keychain" ) uninstall_mock.assert_called_once_with( "Friendly Name", "/Library/Keychains/System.keychain", keychain_password=None, ) self.assertEqual(out, expected)
def test_set_proxy_windows_no_ftp(self): """ Test to make sure that we correctly set the proxy info on Windows """ calls = [ call( hive="HKEY_CURRENT_USER", key= "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", vname="ProxyServer", vdata="http=192.168.0.1:3128;https=192.168.0.1:3128;", ), call( hive="HKEY_CURRENT_USER", key= "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", vname="ProxyEnable", vdata=1, vtype="REG_DWORD", ), call( hive="HKEY_CURRENT_USER", key= "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", vname="ProxyOverride", vdata="<local>;.moo.com;.salt.com", ), ] mock_reg = MagicMock() mock_cmd = MagicMock() with patch.dict(proxy.__grains__, {"os": "Windows"}), patch.dict( proxy.__utils__, {"reg.set_value": mock_reg}), patch.dict(proxy.__salt__, {"cmd.run": mock_cmd}): out = proxy.set_proxy_win( server="192.168.0.1", port=3128, types=["http", "https"], bypass_hosts=[".moo.com", ".salt.com"], ) mock_reg.assert_has_calls(calls) mock_cmd.assert_called_once_with( "netsh winhttp import proxy source=ie") self.assertTrue(out)
def test_installed_cert_hash_different(self): ''' Test installing a certificate into the macOS keychain when it's already installed but the certificate has changed ''' expected = { 'changes': { 'installed': 'Friendly Name', 'uninstalled': 'Friendly Name' }, 'comment': 'Found a certificate with the same name but different hash, removing it.\n', 'name': '/path/to/cert.p12', 'result': True } list_mock = MagicMock(side_effect=[['Friendly Name'], []]) friendly_mock = MagicMock(return_value='Friendly Name') install_mock = MagicMock(return_value='1 identity imported.') uninstall_mock = MagicMock(return_value='removed.') hash_mock = MagicMock(side_effect=['ABCD', 'XYZ']) with patch.dict( keychain.__salt__, { 'keychain.list_certs': list_mock, 'keychain.get_friendly_name': friendly_mock, 'keychain.install': install_mock, 'keychain.uninstall': uninstall_mock, 'keychain.get_hash': hash_mock }): out = keychain.installed('/path/to/cert.p12', 'passw0rd') list_mock.assert_has_calls(calls=[ call('/Library/Keychains/System.keychain'), call('/Library/Keychains/System.keychain') ]) friendly_mock.assert_called_once_with('/path/to/cert.p12', 'passw0rd') install_mock.assert_called_once_with( '/path/to/cert.p12', 'passw0rd', '/Library/Keychains/System.keychain') uninstall_mock.assert_called_once_with( 'Friendly Name', '/Library/Keychains/System.keychain', keychain_password=None) self.assertEqual(out, expected)
def test_downgradePkgs_notinstalled(self, logger): pkg = support.ObjectMatcher(dnf.package.Package, {'name': 'lotus'}) with self.assertRaises(dnf.exceptions.Error) as ctx: self._base.downgradePkgs(('lotus',)) self.assertEqual(str(ctx.exception), 'Nothing to do.') self.assertEqual(self._base.downgrade_to.mock_calls, [mock.call('lotus')]) self.assertEqual(logger.mock_calls, [ mock.call.info('No match for available package: %s', pkg)] * 2)
def test_downgradePkgs_notfound(self, logger): with self.assertRaises(dnf.exceptions.Error) as ctx: self._base.downgradePkgs(('non-existent',)) self.assertEqual(str(ctx.exception), 'Nothing to do.') self.assertEqual(self._base.downgrade.mock_calls, [mock.call('non-existent')]) self.assertEqual(logger.mock_calls, [mock.call.info('No package %s%s%s available.', '', 'non-existent', '')])
def test_update_not_installed(self, logger): """ Updating an uninstalled package is a not valid operation. """ self.base._goal = goal = mock.create_autospec(dnf.goal.Goal) # no "mrkite" installed: with self.assertRaises(dnf.exceptions.MarkingError) as context: self.base.upgrade("mrkite") self.assertEqual(logger.mock_calls, [ mock.call(u'Package %s available, but not installed.', u'mrkite')]) self.assertEqual(context.exception.pkg_spec, 'mrkite') self.assertEqual(goal.mock_calls, [])
def test_get_hibernate_timeout(self): ''' Test to make sure we can get the hibernate timeout value ''' mock = MagicMock() mock.side_effect = [ 'Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced)', self.query_output] with patch.dict(powercfg.__salt__, {'cmd.run': mock}): ret = powercfg.get_hibernate_timeout() calls = [ call('powercfg /getactivescheme', python_shell=False), call('powercfg /q 381b4222-f694-41f0-9685-ff5bb260df2e SUB_SLEEP HIBERNATEIDLE', python_shell=False) ] mock.assert_has_calls(calls) self.assertEqual({'ac': 30, 'dc': 15}, ret)
def test_get_mpkg_ids(self, get_pkg_id_mock): ''' Test getting the ids of a mpkg file ''' expected = ['com.apple.this', 'com.salt.other'] mock = MagicMock( return_value='/tmp/dmg-X/file.pkg\n/tmp/dmg-X/other.pkg') get_pkg_id_mock.side_effect = [['com.apple.this'], ['com.salt.other']] with patch.dict(macpackage.__salt__, {'cmd.run': mock}): out = macpackage.get_mpkg_ids('/path/to/file.mpkg') mock.assert_called_once_with('find /path/to -name *.pkg', python_shell=True) calls = [call('/tmp/dmg-X/file.pkg'), call('/tmp/dmg-X/other.pkg')] get_pkg_id_mock.assert_has_calls(calls) self.assertEqual(out, expected)
def test_virtual_ha(self, mock_which, logger): mock_pkg_version = MagicMock(return_value='1.0.0') mock_pkg_version_cmp = MagicMock(return_value=-1) mock_which.side_effect = [True, True] with patch.dict( crmshmod.__salt__, { 'pkg.version': mock_pkg_version, 'pkg.version_cmp': mock_pkg_version_cmp }): assert crmshmod.__virtual__() == 'crm' logger.assert_has_calls([ mock.call('crmsh version: %s', '1.0.0'), mock.call('%s will be used', 'ha-cluster') ]) mock_which.assert_has_calls([ mock.call(crmshmod.CRM_COMMAND), mock.call(crmshmod.HA_INIT_COMMAND) ])
def test_user_chpass(self): ''' Test changing a MySQL user password in mysql exec module ''' connect_mock = MagicMock() mysql._connect = connect_mock with patch.dict(mysql.__salt__, {'config.option': MagicMock()}): mysql.user_chpass('testuser', password='******') calls = ( call().cursor().execute( 'UPDATE mysql.user SET Password=PASSWORD(%(password)s) WHERE User=%(user)s AND Host = %(host)s;', {'password': '******', 'user': '******', 'host': 'localhost', } ), call().cursor().execute('FLUSH PRIVILEGES;'), ) connect_mock.assert_has_calls(calls, any_order=True)
def test_generate_token(self): ''' Basic test for test_generate_token with approle (two vault calls) ''' mock = _mock_json_response({'auth': {'client_token': 'test'}}) with patch('requests.post', mock): result = vault.generate_token('test-minion', 'signature') log.debug('generate_token result: %s', result) self.assertTrue(isinstance(result, dict)) self.assertFalse('error' in result) self.assertTrue('token' in result) self.assertEqual(result['token'], 'test') calls = [ call("http://127.0.0.1/v1/auth/approle/login", json=ANY, verify=ANY), call("http://fake_url", headers=ANY, json=ANY, verify=ANY) ] mock.assert_has_calls(calls)
def test_get_slave_status_bad_server(self): ''' Test get_slave_status in the mysql execution module, simulating a broken server ''' connect_mock = MagicMock(return_value=None) mysql._connect = connect_mock with patch.dict(mysql.__salt__, {'config.option': MagicMock()}): rslt = mysql.get_slave_status() connect_mock.assert_has_calls([call()]) self.assertEqual(rslt, [])
def _runner(self, expected_ret, test=False, check=False, add=False, add_assertion=False): mock_check = MagicMock(return_value=check) mock_add = MagicMock(return_value=add) with patch.dict(ipset.__opts__, {'test': test}): with patch.dict(ipset.__salt__, {'ipset.check': mock_check, 'ipset.add': mock_add}): actual_ret = ipset.present(self.fake_name, self.fake_entries, set_name=self.fake_name) mock_check.assert_has_calls([call(self.fake_name, e, 'ipv4') for e in self.fake_entries], any_order=True) if add_assertion: expected_calls = [call(self.fake_name, e, 'ipv4', set_name=self.fake_name) for e in self.fake_entries] if add is not True: # if the add fails, then it will only get called once. expected_calls = expected_calls[:1] mock_add.assert_has_calls(expected_calls, any_order=True) else: self.assertTrue(mock_add.call_count == 0) self.assertDictEqual(actual_ret, expected_ret)
def test_context_manager(self): """Test whether _HistoryWrapper can be used as a context manager.""" yum_history = mock.create_autospec(dnf.yum.history.YumHistory) history = self._create_wrapper(yum_history) with history as instance: pass self.assertIs(instance, history) self.assertEqual(yum_history.close.mock_calls, [mock.call()])
def test_downgradePkgs_notfound(self, logger): with self.assertRaises(dnf.exceptions.Error) as ctx: self.base.downgradePkgs(('non-existent',)) self.assertEqual(str(ctx.exception), 'No packages marked for downgrade.') self.assertEqual(self.base.downgrade_to.mock_calls, [mock.call('non-existent', strict=False)]) self.assertEqual(logger.mock_calls, [mock.call.info('No package %s available.', 'non-existent')])
def test_get_mors_with_properties_calls(self): mock_get_mors_with_properties = MagicMock(return_value=[MagicMock()]) with patch( 'salt.utils.vmware.get_service_instance_from_managed_object', MagicMock(return_value=self.mock_si)): with patch('salt.utils.vmware.get_mors_with_properties', mock_get_mors_with_properties): salt.utils.vmware.get_properties_of_managed_object( self.fake_mo_ref, self.mock_props) mock_get_mors_with_properties.assert_has_calls( [call(self.mock_si, vim.ManagedEntity, container_ref=self.fake_mo_ref, property_list=['name'], local_properties=True), call(self.mock_si, vim.ManagedEntity, container_ref=self.fake_mo_ref, property_list=self.mock_props, local_properties=True)])
def test_set_static_dns(self): """ Test if it set static DNS configuration on a Windows NIC. """ mock_cmd = MagicMock() with patch.dict(win_ip.__salt__, {"cmd.run": mock_cmd}): self.assertDictEqual( win_ip.set_static_dns("Ethernet", "192.168.1.252", "192.168.1.253"), { "DNS Server": ("192.168.1.252", "192.168.1.253"), "Interface": "Ethernet", }, ) mock_cmd.assert_has_calls([ call( [ "netsh", "interface", "ip", "set", "dns", "name=Ethernet", "source=static", "address=192.168.1.252", "register=primary", ], python_shell=False, ), call( [ "netsh", "interface", "ip", "add", "dns", "name=Ethernet", "address=192.168.1.253", "index=2", ], python_shell=False, ), ])
def test_get_pkg_id_with_files(self): ''' Test getting a the id for a package ''' with patch('salt.modules.macpackage._get_pkg_id_from_pkginfo' ) as pkg_id_pkginfo_mock: expected = ['com.apple.this'] cmd_mock = MagicMock(side_effect=[ '/path/to/PackageInfo\n/path/to/some/other/fake/PackageInfo', '', '' ]) pkg_id_pkginfo_mock.side_effect = [['com.apple.this'], []] temp_mock = MagicMock(return_value='/tmp/dmg-ABCDEF') remove_mock = MagicMock() with patch.dict( macpackage.__salt__, { 'cmd.run': cmd_mock, 'temp.dir': temp_mock, 'file.remove': remove_mock }): out = macpackage.get_pkg_id('/path/to/file.pkg') temp_mock.assert_called_once_with(prefix='pkg-') cmd_calls = [ call('xar -t -f /path/to/file.pkg | grep PackageInfo', python_shell=True, output_loglevel='quiet'), call( 'xar -x -f /path/to/file.pkg /path/to/PackageInfo /path/to/some/other/fake/PackageInfo', cwd='/tmp/dmg-ABCDEF', output_loglevel='quiet') ] cmd_mock.assert_has_calls(cmd_calls) pkg_id_pkginfo_calls = [ call('/path/to/PackageInfo'), call('/path/to/some/other/fake/PackageInfo') ] pkg_id_pkginfo_mock.assert_has_calls(pkg_id_pkginfo_calls) remove_mock.assert_called_once_with('/tmp/dmg-ABCDEF') self.assertEqual(out, expected)
def test_generate_token(self): """ Basic test for test_generate_token with approle (two vault calls) """ mock = _mock_json_response( {"auth": {"client_token": "test", "renewable": False, "lease_duration": 0}} ) with patch("requests.post", mock): result = vault.generate_token("test-minion", "signature") log.debug("generate_token result: %s", result) self.assertTrue(isinstance(result, dict)) self.assertFalse("error" in result) self.assertTrue("token" in result) self.assertEqual(result["token"], "test") calls = [ call("http://127.0.0.1/v1/auth/approle/login", json=ANY, verify=ANY), call("http://fake_url", headers=ANY, json=ANY, verify=ANY), ] mock.assert_has_calls(calls)
def assert_last_info(self, logger, msg): self.assertEqual(logger.info.mock_calls[-1], mock.call(msg))
def dispm(m): return mock.call((PLYMOUTH, "display-message", "--text", m))
def test_downgradePkgs(self, logger): self._base.downgradePkgs(('tour',)) self.assertEqual(self._base.downgrade.mock_calls, [mock.call('tour')]) self.assertEqual(logger.mock_calls, [])
def test_downgradePkgs(self, logger): self.base.downgradePkgs(('tour',)) self.assertEqual(self.base.downgrade_to.mock_calls, [mock.call('tour', strict=False)]) self.assertEqual(logger.mock_calls, [])
def assertLastInfo(self, cmd, msg): self.assertEqual(cmd.base.logger.info.mock_calls[-1], mock.call(msg))
def hidem(m): return mock.call((PLYMOUTH, "hide-message", "--text", m))
def test_downgradePkgs(self): self._base.downgradePkgs(("tour",)) self.assertEqual(self._base.downgrade.mock_calls, [mock.call("tour")]) self.assertEqual(self._base.logger.mock_calls, [])