Merge pull request #36146 from meaksh/tests-fixes-for-2015.8

Fixing unit tests for 2015.8
This commit is contained in:
Mike Place 2016-09-08 22:10:36 +09:00 committed by GitHub
commit 4cc8ea9577
18 changed files with 116 additions and 100 deletions

View file

@ -41,8 +41,11 @@ def _check_systemd_salt_config():
sysctl_dir = os.path.split(conf)[0]
if not os.path.exists(sysctl_dir):
os.makedirs(sysctl_dir)
with salt.utils.fopen(conf, 'w'):
pass
try:
salt.utils.fopen(conf, 'w').close()
except (IOError, OSError):
msg = 'Could not create file: {0}'
raise CommandExecutionError(msg.format(conf))
return conf

View file

@ -19,7 +19,10 @@ def __virtual__():
'''
Only run on Darwin (OS X) systems
'''
return __virtualname__ if __grains__['os'] == 'MacOS' else False
if __grains__['os'] == 'MacOS':
return __virtualname__
return (False, 'The darwin_sysctl execution module cannot be loaded: '
'only available on MacOS systems.')
def show(config_file=False):

View file

@ -48,7 +48,7 @@ class LoadAuthTestCase(TestCase):
'eauth': 'pam'
}, expected_extra_kws=auth.AUTH_INTERNAL_KEYWORDS)
ret = self.lauth.load_name(valid_eauth_load)
format_call_mock.assert_has_calls(expected_ret)
format_call_mock.assert_has_calls((expected_ret,), any_order=True)
def test_get_groups(self):
valid_eauth_load = {'username': 'test_user',
@ -63,7 +63,7 @@ class LoadAuthTestCase(TestCase):
'eauth': 'pam'
}, expected_extra_kws=auth.AUTH_INTERNAL_KEYWORDS)
self.lauth.get_groups(valid_eauth_load)
format_call_mock.assert_has_calls(expected_ret)
format_call_mock.assert_has_calls((expected_ret,), any_order=True)
@patch('zmq.Context', MagicMock())

View file

@ -118,6 +118,13 @@ def _has_required_moto():
return True
@skipIf(NO_MOCK, NO_MOCK_REASON)
@skipIf(HAS_BOTO is False, 'The boto module must be installed.')
@skipIf(HAS_MOTO is False, 'The moto module must be installed.')
@skipIf(_has_required_boto() is False, 'The boto module must be greater than'
' or equal to version {0}'
.format(required_boto_version))
@skipIf(_has_required_moto() is False, 'The moto version must be >= to version {0}'.format(required_moto_version))
class BotoVpcTestCaseBase(TestCase):
def setUp(self):
boto_vpc.__context__ = {}
@ -230,13 +237,6 @@ class BotoVpcTestCaseMixin(object):
return rtbl
@skipIf(NO_MOCK, NO_MOCK_REASON)
@skipIf(HAS_BOTO is False, 'The boto module must be installed.')
@skipIf(HAS_MOTO is False, 'The moto module must be installed.')
@skipIf(_has_required_boto() is False, 'The boto module must be greater than'
' or equal to version {0}'
.format(required_boto_version))
@skipIf(_has_required_moto() is False, 'The moto version must be >= to version {0}'.format(required_moto_version))
class BotoVpcTestCase(BotoVpcTestCaseBase, BotoVpcTestCaseMixin):
'''
TestCase for salt.modules.boto_vpc module

View file

@ -577,7 +577,7 @@ class PsTestCase(TestCase):
'# 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)
write_cron_lines_mock.assert_has_calls((expected_write_call,), any_order=True)
def test__get_cron_date_time(self):
ret = cron._get_cron_date_time(minute=STUB_CRON_TIMESTAMP['minute'],

View file

@ -84,17 +84,22 @@ class LinuxSysctlTestCase(TestCase):
self.assertEqual(linux_sysctl.assign(
'net.ipv4.ip_forward', 1), ret)
@patch('os.path.isfile', MagicMock(return_value=False))
def test_persist_no_conf_failure(self):
'''
Tests adding of config file failure
'''
with patch('salt.utils.fopen', mock_open()) as m_open:
helper_open = m_open()
helper_open.write.assertRaises(CommandExecutionError,
linux_sysctl.persist,
'net.ipv4.ip_forward',
1, config=None)
asn_cmd = {'pid': 1337, 'retcode': 0,
'stderr': "sysctl: permission denied", 'stdout': ''}
mock_asn_cmd = MagicMock(return_value=asn_cmd)
cmd = "sysctl -w net.ipv4.ip_forward=1"
mock_cmd = MagicMock(return_value=cmd)
with patch.dict(linux_sysctl.__salt__, {'cmd.run_stdout': mock_cmd,
'cmd.run_all': mock_asn_cmd}):
with patch('salt.utils.fopen', mock_open()) as m_open:
self.assertRaises(CommandExecutionError,
linux_sysctl.persist,
'net.ipv4.ip_forward',
1, config=None)
@patch('os.path.isfile', MagicMock(return_value=False))
def test_persist_no_conf_success(self):

View file

@ -7,7 +7,7 @@
from __future__ import absolute_import
# Import Salt Libs
from salt.modules import darwin_sysctl
from salt.modules import mac_sysctl
from salt.exceptions import CommandExecutionError
# Import Salt Testing Libs
@ -25,13 +25,13 @@ from salttesting.mock import (
ensure_in_syspath('../../')
# Globals
darwin_sysctl.__salt__ = {}
mac_sysctl.__salt__ = {}
@skipIf(NO_MOCK, NO_MOCK_REASON)
class DarwinSysctlTestCase(TestCase):
'''
TestCase for salt.modules.darwin_sysctl module
TestCase for salt.modules.mac_sysctl module
'''
def test_get(self):
@ -39,8 +39,8 @@ class DarwinSysctlTestCase(TestCase):
Tests the return of get function
'''
mock_cmd = MagicMock(return_value='foo')
with patch.dict(darwin_sysctl.__salt__, {'cmd.run': mock_cmd}):
self.assertEqual(darwin_sysctl.get('kern.ostype'), 'foo')
with patch.dict(mac_sysctl.__salt__, {'cmd.run': mock_cmd}):
self.assertEqual(mac_sysctl.get('kern.ostype'), 'foo')
def test_assign_cmd_failed(self):
'''
@ -49,9 +49,9 @@ class DarwinSysctlTestCase(TestCase):
cmd = {'pid': 3548, 'retcode': 1, 'stderr': '',
'stdout': 'net.inet.icmp.icmplim: 250 -> 50'}
mock_cmd = MagicMock(return_value=cmd)
with patch.dict(darwin_sysctl.__salt__, {'cmd.run_all': mock_cmd}):
with patch.dict(mac_sysctl.__salt__, {'cmd.run_all': mock_cmd}):
self.assertRaises(CommandExecutionError,
darwin_sysctl.assign,
mac_sysctl.assign,
'net.inet.icmp.icmplim', 50)
def test_assign(self):
@ -62,8 +62,8 @@ class DarwinSysctlTestCase(TestCase):
'stdout': 'net.inet.icmp.icmplim: 250 -> 50'}
ret = {'net.inet.icmp.icmplim': '50'}
mock_cmd = MagicMock(return_value=cmd)
with patch.dict(darwin_sysctl.__salt__, {'cmd.run_all': mock_cmd}):
self.assertEqual(darwin_sysctl.assign(
with patch.dict(mac_sysctl.__salt__, {'cmd.run_all': mock_cmd}):
self.assertEqual(mac_sysctl.assign(
'net.inet.icmp.icmplim', 50), ret)
@patch('os.path.isfile', MagicMock(return_value=False))
@ -72,11 +72,11 @@ class DarwinSysctlTestCase(TestCase):
Tests adding of config file failure
'''
with patch('salt.utils.fopen', mock_open()) as m_open:
helper_open = m_open()
helper_open.write.assertRaises(CommandExecutionError,
darwin_sysctl.persist,
'net.inet.icmp.icmplim',
50, config=None)
m_open.side_effect = IOError(13, 'Permission denied', '/file')
self.assertRaises(CommandExecutionError,
mac_sysctl.persist,
'net.inet.icmp.icmplim',
50, config=None)
@patch('os.path.isfile', MagicMock(return_value=False))
def test_persist_no_conf_success(self):
@ -84,7 +84,7 @@ class DarwinSysctlTestCase(TestCase):
Tests successful add of config file when previously not one
'''
with patch('salt.utils.fopen', mock_open()) as m_open:
darwin_sysctl.persist('net.inet.icmp.icmplim', 50)
mac_sysctl.persist('net.inet.icmp.icmplim', 50)
helper_open = m_open()
helper_open.write.assert_called_once_with(
'#\n# Kernel sysctl configuration\n#\n')
@ -97,7 +97,7 @@ class DarwinSysctlTestCase(TestCase):
to_write = '#\n# Kernel sysctl configuration\n#\n'
m_calls_list = [call.writelines(['net.inet.icmp.icmplim=50', '\n'])]
with patch('salt.utils.fopen', mock_open(read_data=to_write)) as m_open:
darwin_sysctl.persist('net.inet.icmp.icmplim', 50, config=to_write)
mac_sysctl.persist('net.inet.icmp.icmplim', 50, config=to_write)
helper_open = m_open()
calls_list = helper_open.method_calls
self.assertEqual(calls_list, m_calls_list)

View file

@ -102,13 +102,13 @@ class MountTestCase(TestCase):
with patch.object(mount, 'fstab', mock):
self.assertTrue(mount.rm_fstab('name', 'device'))
mock = MagicMock(return_value={'name': 'name'})
with patch.object(mount, 'fstab', mock):
mock_fstab = MagicMock(return_value={'name': 'name'})
with patch.object(mount, 'fstab', mock_fstab):
with patch('salt.utils.fopen', mock_open()) as m_open:
helper_open = m_open()
helper_open.write.assertRaises(CommandExecutionError,
mount.rm_fstab,
config=None)
m_open.side_effect = IOError(13, 'Permission denied:', '/file')
self.assertRaises(CommandExecutionError,
mount.rm_fstab,
'name', 'device')
def test_set_fstab(self):
'''
@ -144,11 +144,7 @@ class MountTestCase(TestCase):
mock = MagicMock(return_value={'name': 'name'})
with patch.object(mount, 'fstab', mock):
with patch('salt.utils.fopen', mock_open()) as m_open:
helper_open = m_open()
helper_open.write.assertRaises(CommandExecutionError,
mount.rm_automaster,
'name', 'device')
self.assertTrue(mount.rm_automaster('name', 'device'))
def test_set_automaster(self):
'''

View file

@ -293,10 +293,10 @@ class MySQLTestCase(TestCase):
with patch.dict(mysql.__salt__, {'config.option': MagicMock()}):
function(*args, **kwargs)
if isinstance(expected_sql, dict):
calls = (call().cursor().execute('{0}'.format(expected_sql['sql']), expected_sql['sql_args']))
calls = call().cursor().execute('{0}'.format(expected_sql['sql']), expected_sql['sql_args'])
else:
calls = (call().cursor().execute('{0}'.format(expected_sql)))
connect_mock.assert_has_calls(calls)
calls = call().cursor().execute('{0}'.format(expected_sql))
connect_mock.assert_has_calls((calls,), True)
if __name__ == '__main__':

View file

@ -91,10 +91,12 @@ class PuppetTestCase(TestCase):
with patch('salt.utils.fopen', mock_open()):
self.assertTrue(puppet.disable())
with patch('salt.utils.fopen', mock_open()) as m_open:
helper_open = m_open()
helper_open.write.assertRaises(CommandExecutionError,
puppet.disable)
try:
with patch('salt.utils.fopen', mock_open()) as m_open:
m_open.side_effect = IOError(13, 'Permission denied:', '/file')
self.assertRaises(CommandExecutionError, puppet.disable)
except StopIteration:
pass
def test_status(self):
'''
@ -155,9 +157,8 @@ class PuppetTestCase(TestCase):
self.assertDictEqual(puppet.summary(), {'resources': 1})
with patch('salt.utils.fopen', mock_open()) as m_open:
helper_open = m_open()
helper_open.write.assertRaises(CommandExecutionError,
puppet.summary)
m_open.side_effect = IOError(13, 'Permission denied:', '/file')
self.assertRaises(CommandExecutionError, puppet.summary)
def test_plugin_sync(self):
'''

View file

@ -326,7 +326,7 @@ class UserAddTestCase(TestCase):
'''
Test the user information
'''
self.assertEqual(useradd.info('salt'), {})
self.assertEqual(useradd.info('username-that-doesnt-exist'), {})
mock = MagicMock(return_value=pwd.struct_passwd(('_TEST_GROUP',
'*',
@ -336,9 +336,7 @@ class UserAddTestCase(TestCase):
'/var/virusmails',
'/usr/bin/false')))
with patch.object(pwd, 'getpwnam', mock):
mock = MagicMock(return_value='Group Name')
with patch.object(useradd, 'list_groups', mock):
self.assertEqual(useradd.info('salt')['name'], '_TEST_GROUP')
self.assertEqual(useradd.info('username-that-doesnt-exist')['name'], '_TEST_GROUP')
# 'list_groups' function tests: 1

View file

@ -103,7 +103,8 @@ class TestEventListener(AsyncTestCase):
event_listener = saltnado.EventListener({}, # we don't use mod_opts, don't save?
{'sock_dir': SOCK_DIR,
'transport': 'zeromq'})
event_future = event_listener.get_event(1, 'evt1', self.stop) # get an event future
self._finished = False # fit to event_listener's behavior
event_future = event_listener.get_event(self, 'evt1', self.stop) # get an event future
me.fire_event({'data': 'foo2'}, 'evt2') # fire an event we don't want
me.fire_event({'data': 'foo1'}, 'evt1') # fire an event we do want
self.wait() # wait for the future
@ -113,6 +114,27 @@ class TestEventListener(AsyncTestCase):
self.assertEqual(event_future.result()['tag'], 'evt1')
self.assertEqual(event_future.result()['data']['data'], 'foo1')
def test_set_event_handler(self):
'''
Test subscribing events using set_event_handler
'''
with eventpublisher_process():
me = event.MasterEvent(SOCK_DIR)
event_listener = saltnado.EventListener({}, # we don't use mod_opts, don't save?
{'sock_dir': SOCK_DIR,
'transport': 'zeromq'})
self._finished = False # fit to event_listener's behavior
event_future = event_listener.get_event(self,
tag='evt',
callback=self.stop,
timeout=1,
) # get an event future
me.fire_event({'data': 'foo'}, 'evt') # fire an event we do want
self.wait()
# check that we subscribed the event we wanted
self.assertEqual(len(event_listener.timeout_map), 0)
def test_timeout(self):
'''
Make sure timeouts work correctly
@ -121,7 +143,8 @@ class TestEventListener(AsyncTestCase):
event_listener = saltnado.EventListener({}, # we don't use mod_opts, don't save?
{'sock_dir': SOCK_DIR,
'transport': 'zeromq'})
event_future = event_listener.get_event(1,
self._finished = False # fit to event_listener's behavior
event_future = event_listener.get_event(self,
tag='evt1',
callback=self.stop,
timeout=1,

View file

@ -54,10 +54,18 @@ include('http')
extend_template = '''#!pyobjects
include('http')
from salt.utils.pyobjects import StateFactory
Service = StateFactory('service')
Service.running(extend('apache'), watch=[{'file': '/etc/file'}])
'''
map_template = '''#!pyobjects
from salt.utils.pyobjects import StateFactory
Service = StateFactory('service')
class Samba(Map):
__merge__ = 'samba:lookup'
@ -127,6 +135,9 @@ from salt://password.sls import password
'''
requisite_implicit_list_template = '''#!pyobjects
from salt.utils.pyobjects import StateFactory
Service = StateFactory('service')
with Pkg.installed("pkg"):
Service.running("service", watch=File("file"), require=Cmd("cmd"))
'''

View file

@ -129,12 +129,12 @@ class SPMTest(TestCase):
('summary', 'Summary: {0}')):
assert line.format(_F1['definition'][key]) in lines
# Reinstall with force=False, should fail
self.ui._error.clear()
self.ui._error = []
self.client.run(['local', 'install', pkgpath])
assert len(self.ui._error) > 0
# Reinstall with force=True, should succeed
__opts__['force'] = True
self.ui._error.clear()
self.ui._error = []
self.client.run(['local', 'install', pkgpath])
assert len(self.ui._error) == 0
__opts__['force'] = False
@ -167,7 +167,7 @@ class SPMTest(TestCase):
)
for args in fail_args:
self.ui._error.clear()
self.ui._error = []
self.client.run(args)
assert len(self.ui._error) > 0

View file

@ -20,6 +20,7 @@ def provision_state(module, fixture):
@skipIf(NO_MOCK, NO_MOCK_REASON)
@skipIf(True, 'Skipped: This module has been deprecated.')
class DockerStateTestCase(TestCase):
def test_docker_run_success(self):
from salt.states import dockerio

View file

@ -1318,26 +1318,6 @@ class FileTestCase(TestCase):
(name, source,
preserve=True), ret)
with patch.object(os.path, 'isdir', mock_t):
with patch.dict(filestate.__opts__, {'test': False}):
with patch.object(shutil, 'copy',
MagicMock(side_effect=[IOError,
True])):
comt = ('Failed to copy "{0}" to "{1}"'
.format(source, name))
ret.update({'comment': comt, 'result': False})
self.assertDictEqual(filestate.copy
(name, source,
preserve=True), ret)
comt = ('Copied "{0}" to "{1}"'.format(source,
name))
ret.update({'comment': comt, 'result': True,
'changes': {name: source}})
self.assertDictEqual(filestate.copy
(name, source,
preserve=True), ret)
# 'rename' function tests: 1
def test_rename(self):

View file

@ -150,16 +150,17 @@ class NetworkTestCase(TestCase):
interfaces = network._interfaces_ifconfig(SOLARIS)
self.assertEqual(interfaces,
{'ilbext0': {'inet': [{'address': '10.10.11.11',
'broadcast': '10.10.11.31',
'netmask': '255.255.255.224'},
{'address': '10.10.11.12',
'broadcast': '10.10.11.31',
'netmask': '255.255.255.224'}],
'inet6': [{'address': '::',
'prefixlen': '0'}],
'inet6': [],
'up': True},
'ilbint0': {'inet': [{'address': '10.6.0.11',
'broadcast': '10.6.0.255',
'netmask': '255.255.255.0'}],
'inet6': [{'address': '::',
'prefixlen': '0'}],
'inet6': [],
'up': True},
'lo0': {'inet': [{'address': '127.0.0.1',
'netmask': '255.0.0.0'}],
@ -174,8 +175,7 @@ class NetworkTestCase(TestCase):
'up': True},
'vpn0': {'inet': [{'address': '10.6.0.14',
'netmask': '255.0.0.0'}],
'inet6': [{'address': '::',
'prefixlen': '0'}],
'inet6': [],
'up': True}}
)

View file

@ -527,14 +527,9 @@ class UtilsTestCase(TestCase):
ret = utils.date_cast('Mon Dec 23 10:19:15 MST 2013')
expected_ret = datetime.datetime(2013, 12, 23, 10, 19, 15)
self.assertEqual(ret, expected_ret)
except ImportError:
try:
ret = utils.date_cast('Mon Dec 23 10:19:15 MST 2013')
expected_ret = datetime.datetime(2013, 12, 23, 10, 19, 15)
self.assertEqual(ret, expected_ret)
except RuntimeError:
# Unparseable without timelib installed
self.skipTest('\'timelib\' is not installed')
except RuntimeError:
# Unparseable without timelib installed
self.skipTest('\'timelib\' is not installed')
@skipIf(not HAS_TIMELIB, '\'timelib\' is not installed')
def test_date_format(self):