desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Tests the return of successful assign function'
| def test_assign_success(self):
| with patch('os.path.exists', MagicMock(return_value=True)):
cmd = {'pid': 1337, 'retcode': 0, 'stderr': '', 'stdout': 'net.ipv4.ip_forward = 1'}
ret = {'net.ipv4.ip_forward': '1'}
mock_cmd = MagicMock(return_value=cmd)
with patch.dict(linux_sysctl.__salt__, {'cmd.run_all': mock_cmd}):
self.assertEqual(linux_sysctl.assign('net.ipv4.ip_forward', 1), ret)
|
'Tests adding of config file failure'
| def test_persist_no_conf_failure(self):
| 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.files.fopen', mock_open()) as m_open:
self.assertRaises(CommandExecutionError, linux_sysctl.persist, 'net.ipv4.ip_forward', 1, config=None)
|
'Tests successful add of config file when previously not one'
| def test_persist_no_conf_success(self):
| with patch('os.path.isfile', MagicMock(return_value=False)):
with patch('os.path.exists', MagicMock(return_value=True)):
asn_cmd = {'pid': 1337, 'retcode': 0, 'stderr': '', 'stdout': 'net.ipv4.ip_forward = 1'}
mock_asn_cmd = MagicMock(return_value=asn_cmd)
sys_cmd = 'systemd 208\n+PAM +LIBWRAP'
mock_sys_cmd = MagicMock(return_value=sys_cmd)
with patch('salt.utils.files.fopen', mock_open()) as m_open:
with patch.dict(linux_sysctl.__context__, {'salt.utils.systemd.version': 232}):
with patch.dict(linux_sysctl.__salt__, {'cmd.run_stdout': mock_sys_cmd, 'cmd.run_all': mock_asn_cmd}):
with patch.dict(systemd.__context__, {'salt.utils.systemd.booted': True, 'salt.utils.systemd.version': 232}):
linux_sysctl.persist('net.ipv4.ip_forward', 1)
helper_open = m_open()
helper_open.write.assert_called_once_with('#\n# Kernel sysctl configuration\n#\n')
|
'Tests sysctl.conf read success'
| def test_persist_read_conf_success(self):
| with patch('os.path.isfile', MagicMock(return_value=True)):
with patch('os.path.exists', MagicMock(return_value=True)):
asn_cmd = {'pid': 1337, 'retcode': 0, 'stderr': '', 'stdout': 'net.ipv4.ip_forward = 1'}
mock_asn_cmd = MagicMock(return_value=asn_cmd)
sys_cmd = 'systemd 208\n+PAM +LIBWRAP'
mock_sys_cmd = MagicMock(return_value=sys_cmd)
with patch('salt.utils.files.fopen', mock_open()):
with patch.dict(linux_sysctl.__context__, {'salt.utils.systemd.version': 232}):
with patch.dict(linux_sysctl.__salt__, {'cmd.run_stdout': mock_sys_cmd, 'cmd.run_all': mock_asn_cmd}):
with patch.dict(systemd.__context__, {'salt.utils.systemd.booted': True}):
self.assertEqual(linux_sysctl.persist('net.ipv4.ip_forward', 1), 'Updated')
|
'Test if it get current timezone (i.e. Asia/Calcutta)'
| def test_get_zone(self):
| mock_cmd = MagicMock(side_effect=['India Standard Time', 'Indian Standard Time'])
with patch.dict(win_timezone.__salt__, {'cmd.run': mock_cmd}):
self.assertEqual(win_timezone.get_zone(), 'Asia/Calcutta')
self.assertFalse(win_timezone.get_zone())
|
'Test if it get current numeric timezone offset from UCT (i.e. +0530)'
| def test_get_offset(self):
| time = '(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi\nIndia Standard Time'
mock_cmd = MagicMock(side_effect=['India Standard Time', time])
with patch.dict(win_timezone.__salt__, {'cmd.run': mock_cmd}):
self.assertEqual(win_timezone.get_offset(), '+0530')
mock_cmd = MagicMock(return_value='India Standard Time')
with patch.dict(win_timezone.__salt__, {'cmd.run': mock_cmd}):
self.assertFalse(win_timezone.get_offset())
|
'Test if it get current timezone (i.e. PST, MDT, etc)'
| def test_get_zonecode(self):
| self.assertFalse(win_timezone.get_zonecode())
|
'Test if it unlinks, then symlinks /etc/localtime to the set timezone.'
| def test_set_zone(self):
| mock_cmd = MagicMock(return_value=0)
with patch.dict(win_timezone.__salt__, {'cmd.retcode': mock_cmd}):
self.assertTrue(win_timezone.set_zone('Asia/Calcutta'))
|
'Test if it checks the md5sum between the given timezone, and
the one set in /etc/localtime. Returns True if they match,
and False if not. Mostly useful for running state checks.'
| def test_zone_compare(self):
| mock_cmd = MagicMock(return_value='India Standard Time')
with patch.dict(win_timezone.__salt__, {'cmd.run': mock_cmd}):
self.assertTrue(win_timezone.zone_compare('Asia/Calcutta'))
|
'Test if it get current hardware clock setting (UTC or localtime)'
| def test_get_hwclock(self):
| self.assertEqual(win_timezone.get_hwclock(), 'localtime')
|
'Test if it sets the hardware clock to be either UTC or localtime'
| def test_set_hwclock(self):
| self.assertFalse(win_timezone.set_hwclock('UTC'))
|
'Tests if specified group was added'
| def test_add(self):
| mock = MagicMock(return_value={'retcode': 0})
with patch.dict(groupadd.__salt__, {'cmd.run_all': mock}):
self.assertTrue(groupadd.add('test', 100))
with patch.dict(groupadd.__grains__, {'kernel': 'Linux'}):
with patch.dict(groupadd.__salt__, {'cmd.run_all': mock}):
self.assertTrue(groupadd.add('test', 100, True))
|
'Tests the return of group information'
| def test_info(self):
| getgrnam = grp.struct_group(('foo', '*', 20, ['test']))
with patch('grp.getgrnam', MagicMock(return_value=getgrnam)):
ret = {'passwd': '*', 'gid': 20, 'name': 'foo', 'members': ['test']}
self.assertEqual(groupadd.info('foo'), ret)
|
'Tests the formatting of returned group information'
| def test_format_info(self):
| group = {'passwd': '*', 'gid': 0, 'name': 'test', 'members': ['root']}
with patch('salt.modules.groupadd._format_info', MagicMock(return_value=group)):
data = grp.struct_group(('wheel', '*', 0, ['root']))
ret = {'passwd': '*', 'gid': 0, 'name': 'test', 'members': ['root']}
self.assertDictEqual(groupadd._format_info(data), ret)
|
'Tests the return of information on all groups'
| def test_getent(self):
| getgrnam = grp.struct_group(('foo', '*', 20, ['test']))
with patch('grp.getgrall', MagicMock(return_value=[getgrnam])):
ret = [{'passwd': '*', 'gid': 20, 'name': 'foo', 'members': ['test']}]
self.assertEqual(groupadd.getent(), ret)
|
'Tests if the group id is the same as argument'
| def test_chgid_gid_same(self):
| mock_pre_gid = MagicMock(return_value=10)
with patch.dict(groupadd.__salt__, {'file.group_to_gid': mock_pre_gid}):
self.assertTrue(groupadd.chgid('test', 10))
|
'Tests the gid for a named group was changed'
| def test_chgid(self):
| mock_pre_gid = MagicMock(return_value=0)
mock_cmdrun = MagicMock(return_value=0)
with patch.dict(groupadd.__salt__, {'file.group_to_gid': mock_pre_gid}):
with patch.dict(groupadd.__salt__, {'cmd.run': mock_cmdrun}):
self.assertFalse(groupadd.chgid('test', 500))
|
'Tests if the specified group was deleted'
| def test_delete(self):
| mock_ret = MagicMock(return_value={'retcode': 0})
with patch.dict(groupadd.__salt__, {'cmd.run_all': mock_ret}):
self.assertTrue(groupadd.delete('test'))
|
'Tests if specified user gets added in the group.'
| def test_adduser(self):
| os_version_list = [{'grains': {'kernel': 'Linux', 'os_family': 'RedHat', 'osmajorrelease': '5'}, 'cmd': ('gpasswd', '-a', 'root', 'test')}, {'grains': {'kernel': 'Linux', 'os_family': 'Suse', 'osmajorrelease': '11'}, 'cmd': ('usermod', '-A', 'test', 'root')}, {'grains': {'kernel': 'Linux'}, 'cmd': ('gpasswd', '--add', 'root', 'test')}, {'grains': {'kernel': 'OTHERKERNEL'}, 'cmd': ('usermod', '-G', 'test', 'root')}]
for os_version in os_version_list:
mock = MagicMock(return_value={'retcode': 0})
with patch.dict(groupadd.__grains__, os_version['grains']):
with patch.dict(groupadd.__salt__, {'cmd.retcode': mock}):
self.assertFalse(groupadd.adduser('test', 'root'))
groupadd.__salt__['cmd.retcode'].assert_called_once_with(os_version['cmd'], python_shell=False)
|
'Tests if specified user gets deleted from the group.'
| def test_deluser(self):
| os_version_list = [{'grains': {'kernel': 'Linux', 'os_family': 'RedHat', 'osmajorrelease': '5'}, 'cmd': ('gpasswd', '-d', 'root', 'test')}, {'grains': {'kernel': 'Linux', 'os_family': 'Suse', 'osmajorrelease': '11'}, 'cmd': ('usermod', '-R', 'test', 'root')}, {'grains': {'kernel': 'Linux'}, 'cmd': ('gpasswd', '--del', 'root', 'test')}, {'grains': {'kernel': 'OpenBSD'}, 'cmd': 'usermod -S foo root'}]
for os_version in os_version_list:
mock_ret = MagicMock(return_value={'retcode': 0})
mock_stdout = MagicMock(return_value='test foo')
mock_info = MagicMock(return_value={'passwd': '*', 'gid': 0, 'name': 'test', 'members': ['root']})
with patch.dict(groupadd.__grains__, os_version['grains']):
with patch.dict(groupadd.__salt__, {'cmd.retcode': mock_ret, 'group.info': mock_info, 'cmd.run_stdout': mock_stdout}):
self.assertFalse(groupadd.deluser('test', 'root'))
groupadd.__salt__['cmd.retcode'].assert_called_once_with(os_version['cmd'], python_shell=False)
|
'Tests if members of the group, get replaced with a provided list.'
| def test_members(self):
| os_version_list = [{'grains': {'kernel': 'Linux', 'os_family': 'RedHat', 'osmajorrelease': '5'}, 'cmd': ('gpasswd', '-M', 'foo', 'test')}, {'grains': {'kernel': 'Linux', 'os_family': 'Suse', 'osmajorrelease': '11'}, 'cmd': ('groupmod', '-A', 'foo', 'test')}, {'grains': {'kernel': 'Linux'}, 'cmd': ('gpasswd', '--members', 'foo', 'test')}, {'grains': {'kernel': 'OpenBSD'}, 'cmd': 'usermod -G test foo'}]
for os_version in os_version_list:
mock_ret = MagicMock(return_value={'retcode': 0})
mock_stdout = MagicMock(return_value={'cmd.run_stdout': 1})
mock_info = MagicMock(return_value={'passwd': '*', 'gid': 0, 'name': 'test', 'members': ['root']})
mock = MagicMock(return_value=True)
with patch.dict(groupadd.__grains__, os_version['grains']):
with patch.dict(groupadd.__salt__, {'cmd.retcode': mock_ret, 'group.info': mock_info, 'cmd.run_stdout': mock_stdout, 'cmd.run': mock}):
self.assertFalse(groupadd.members('test', 'foo'))
groupadd.__salt__['cmd.retcode'].assert_called_once_with(os_version['cmd'], python_shell=False)
|
'tests that given a valid instance id and valid ELB that
register_instances returns True.'
| @mock_ec2
@mock_elb
def test_register_instances_valid_id_result_true(self):
| conn_ec2 = boto.ec2.connect_to_region(region, **boto_conn_parameters)
conn_elb = boto.ec2.elb.connect_to_region(region, **boto_conn_parameters)
zones = [zone.name for zone in conn_ec2.get_all_zones()]
elb_name = 'TestRegisterInstancesValidIdResult'
conn_elb.create_load_balancer(elb_name, zones, [(80, 80, 'http')])
reservations = conn_ec2.run_instances('ami-08389d60')
register_result = boto_elb.register_instances(elb_name, reservations.instances[0].id, **conn_parameters)
self.assertEqual(True, register_result)
|
'tests that given a string containing a instance id and valid ELB that
register_instances adds the given instance to an ELB'
| @mock_ec2
@mock_elb
def test_register_instances_valid_id_string(self):
| conn_ec2 = boto.ec2.connect_to_region(region, **boto_conn_parameters)
conn_elb = boto.ec2.elb.connect_to_region(region, **boto_conn_parameters)
zones = [zone.name for zone in conn_ec2.get_all_zones()]
elb_name = 'TestRegisterInstancesValidIdResult'
conn_elb.create_load_balancer(elb_name, zones, [(80, 80, 'http')])
reservations = conn_ec2.run_instances('ami-08389d60')
boto_elb.register_instances(elb_name, reservations.instances[0].id, **conn_parameters)
load_balancer_refreshed = conn_elb.get_all_load_balancers(elb_name)[0]
registered_instance_ids = [instance.id for instance in load_balancer_refreshed.instances]
log.debug(load_balancer_refreshed.instances)
self.assertEqual([reservations.instances[0].id], registered_instance_ids)
|
'tests that given an valid id the boto_elb deregister_instances method
removes exactly one of a number of ELB registered instances'
| @mock_ec2
@mock_elb
def test_deregister_instances_valid_id_result_true(self):
| conn_ec2 = boto.ec2.connect_to_region(region, **boto_conn_parameters)
conn_elb = boto.ec2.elb.connect_to_region(region, **boto_conn_parameters)
zones = [zone.name for zone in conn_ec2.get_all_zones()]
elb_name = 'TestDeregisterInstancesValidIdResult'
load_balancer = conn_elb.create_load_balancer(elb_name, zones, [(80, 80, 'http')])
reservations = conn_ec2.run_instances('ami-08389d60')
load_balancer.register_instances(reservations.instances[0].id)
deregister_result = boto_elb.deregister_instances(elb_name, reservations.instances[0].id, **conn_parameters)
self.assertEqual(True, deregister_result)
|
'tests that given an valid id the boto_elb deregister_instances method
removes exactly one of a number of ELB registered instances'
| @mock_ec2
@mock_elb
def test_deregister_instances_valid_id_string(self):
| conn_ec2 = boto.ec2.connect_to_region(region, **boto_conn_parameters)
conn_elb = boto.ec2.elb.connect_to_region(region, **boto_conn_parameters)
zones = [zone.name for zone in conn_ec2.get_all_zones()]
elb_name = 'TestDeregisterInstancesValidIdString'
load_balancer = conn_elb.create_load_balancer(elb_name, zones, [(80, 80, 'http')])
reservations = conn_ec2.run_instances('ami-08389d60', min_count=2)
all_instance_ids = [instance.id for instance in reservations.instances]
load_balancer.register_instances(all_instance_ids)
boto_elb.deregister_instances(elb_name, reservations.instances[0].id, **conn_parameters)
load_balancer_refreshed = conn_elb.get_all_load_balancers(elb_name)[0]
expected_instances = deepcopy(all_instance_ids)
expected_instances.remove(reservations.instances[0].id)
actual_instances = [instance.id for instance in load_balancer_refreshed.instances]
self.assertEqual(actual_instances, expected_instances)
|
'tests that given an valid ids in the form of a list that the boto_elb
deregister_instances all members of the given list'
| @mock_ec2
@mock_elb
def test_deregister_instances_valid_id_list(self):
| conn_ec2 = boto.ec2.connect_to_region(region, **boto_conn_parameters)
conn_elb = boto.ec2.elb.connect_to_region(region, **boto_conn_parameters)
zones = [zone.name for zone in conn_ec2.get_all_zones()]
elb_name = 'TestDeregisterInstancesValidIdList'
load_balancer = conn_elb.create_load_balancer(elb_name, zones, [(80, 80, 'http')])
reservations = conn_ec2.run_instances('ami-08389d60', min_count=3)
all_instance_ids = [instance.id for instance in reservations.instances]
load_balancer.register_instances(all_instance_ids)
deregister_instances = [instance.id for instance in reservations.instances[:(-1)]]
expected_instances = [reservations.instances[(-1)].id]
boto_elb.deregister_instances(elb_name, deregister_instances, **conn_parameters)
load_balancer_refreshed = conn_elb.get_all_load_balancers(elb_name)[0]
actual_instances = [instance.id for instance in load_balancer_refreshed.instances]
self.assertEqual(actual_instances, expected_instances)
|
'Test if it updates the pkgutil repo database (pkgutil -U).'
| def test_refresh_db(self):
| mock = MagicMock(return_value=0)
with patch.dict(pkgutil.__salt__, {'cmd.retcode': mock}):
with patch.object(salt.utils.pkg, 'clear_rtag', Mock()):
self.assertTrue(pkgutil.refresh_db())
|
'Test if there is an upgrade available for a certain package.'
| def test_upgrade_available(self):
| mock = MagicMock(return_value='A\n B\n SAME')
with patch.dict(pkgutil.__salt__, {'cmd.run_stdout': mock}):
self.assertEqual(pkgutil.upgrade_available('CSWpython'), '')
mock = MagicMock(side_effect=['A\n B\n SALT', None])
with patch.dict(pkgutil.__salt__, {'cmd.run_stdout': mock}):
self.assertEqual(pkgutil.upgrade_available('CSWpython'), 'SALT')
self.assertEqual(pkgutil.upgrade_available('CSWpython'), '')
|
'Test if it list all available package upgrades on this system.'
| def test_list_upgrades(self):
| mock_run = MagicMock(return_value='A DCTB B DCTB SAME')
mock_ret = MagicMock(return_value=0)
with patch.dict(pkgutil.__salt__, {'cmd.run_stdout': mock_run, 'cmd.retcode': mock_ret}):
with patch.object(salt.utils.pkg, 'clear_rtag', Mock()):
self.assertDictEqual(pkgutil.list_upgrades(), {'A': ' B'})
|
'Test if it upgrade all of the packages to the latest available version.'
| def test_upgrade(self):
| mock_run = MagicMock(return_value='A DCTB B DCTB SAME')
mock_ret = MagicMock(return_value=0)
mock_pkg = MagicMock(return_value='')
with patch.dict(pkgutil.__salt__, {'cmd.run_stdout': mock_run, 'cmd.retcode': mock_ret, 'pkg_resource.stringify': mock_pkg, 'pkg_resource.sort_pkglist': mock_pkg, 'cmd.run_all': mock_ret, 'cmd.run': mock_run}):
with patch.dict(pkgutil.__context__, {'pkg.list_pkgs': mock_ret}):
with patch.object(salt.utils.pkg, 'clear_rtag', Mock()):
self.assertDictEqual(pkgutil.upgrade(), {})
|
'Test if it list the packages currently installed as a dict.'
| def test_list_pkgs(self):
| mock_run = MagicMock(return_value='A DCTB B DCTB SAME')
mock_ret = MagicMock(return_value=True)
mock_pkg = MagicMock(return_value='')
with patch.dict(pkgutil.__salt__, {'cmd.run_stdout': mock_run, 'cmd.retcode': mock_ret, 'pkg_resource.stringify': mock_pkg, 'pkg_resource.sort_pkglist': mock_pkg, 'cmd.run': mock_run}):
with patch.dict(pkgutil.__context__, {'pkg.list_pkgs': mock_ret}):
self.assertDictEqual(pkgutil.list_pkgs(versions_as_list=True, removed=True), {})
self.assertDictEqual(pkgutil.list_pkgs(), {})
with patch.dict(pkgutil.__context__, {'pkg.list_pkgs': True}):
self.assertTrue(pkgutil.list_pkgs(versions_as_list=True))
mock_pkg = MagicMock(return_value=True)
with patch.dict(pkgutil.__salt__, {'pkg_resource.stringify': mock_pkg}):
self.assertTrue(pkgutil.list_pkgs())
|
'Test if it returns a version if the package is installed.'
| def test_version(self):
| mock_ret = MagicMock(return_value=True)
with patch.dict(pkgutil.__salt__, {'pkg_resource.version': mock_ret}):
self.assertTrue(pkgutil.version('CSWpython'))
|
'Test if it return the latest version of the named package
available for upgrade or installation.'
| def test_latest_version(self):
| self.assertEqual(pkgutil.latest_version(), '')
mock_run_all = MagicMock(return_value='A DCTB B DCTB SAME')
mock_run = MagicMock(return_value={'stdout': ''})
mock_ret = MagicMock(return_value=True)
mock_pkg = MagicMock(return_value='')
with patch.dict(pkgutil.__salt__, {'cmd.retcode': mock_ret, 'pkg_resource.stringify': mock_pkg, 'pkg_resource.sort_pkglist': mock_pkg, 'cmd.run_all': mock_run, 'cmd.run': mock_run_all}):
with patch.object(salt.utils.pkg, 'clear_rtag', Mock()):
self.assertEqual(pkgutil.latest_version('CSWpython'), '')
self.assertDictEqual(pkgutil.latest_version('CSWpython', 'Python'), {'Python': '', 'CSWpython': ''})
|
'Test if it install packages using the pkgutil tool.'
| def test_install(self):
| mock_pkg = MagicMock(side_effect=MinionError)
with patch.dict(pkgutil.__salt__, {'pkg_resource.parse_targets': mock_pkg}):
self.assertRaises(CommandExecutionError, pkgutil.install)
mock_ret = MagicMock(return_value=True)
mock_pkg = MagicMock(return_value=[''])
with patch.dict(pkgutil.__salt__, {'pkg_resource.parse_targets': mock_pkg}):
with patch.dict(pkgutil.__context__, {'pkg.list_pkgs': mock_ret}):
self.assertDictEqual(pkgutil.install(), {})
mock_run = MagicMock(return_value='A DCTB B DCTB SAME')
mock_run_all = MagicMock(return_value={'stdout': ''})
mock_pkg = MagicMock(return_value=[{'bar': '1.2.3'}])
with patch.dict(pkgutil.__salt__, {'pkg_resource.parse_targets': mock_pkg, 'pkg_resource.stringify': mock_pkg, 'pkg_resource.sort_pkglist': mock_pkg, 'cmd.run_all': mock_run_all, 'cmd.run': mock_run}):
with patch.dict(pkgutil.__context__, {'pkg.list_pkgs': mock_ret}):
self.assertDictEqual(pkgutil.install(pkgs='["foo", {"bar": "1.2.3"}]'), {})
|
'Test if it remove a package and all its dependencies
which are not in use by other packages.'
| def test_remove(self):
| mock_pkg = MagicMock(side_effect=MinionError)
with patch.dict(pkgutil.__salt__, {'pkg_resource.parse_targets': mock_pkg}):
self.assertRaises(CommandExecutionError, pkgutil.remove)
mock_ret = MagicMock(return_value=True)
mock_run = MagicMock(return_value='A DCTB B DCTB SAME')
mock_run_all = MagicMock(return_value={'stdout': ''})
mock_pkg = MagicMock(return_value=[''])
with patch.dict(pkgutil.__salt__, {'pkg_resource.parse_targets': mock_pkg, 'pkg_resource.stringify': mock_pkg, 'pkg_resource.sort_pkglist': mock_pkg, 'cmd.run_all': mock_run_all, 'cmd.run': mock_run}):
with patch.dict(pkgutil.__context__, {'pkg.list_pkgs': mock_ret}):
self.assertDictEqual(pkgutil.remove(), {})
mock_pkg = MagicMock(return_value=[{'bar': '1.2.3'}])
with patch.dict(pkgutil.__salt__, {'pkg_resource.parse_targets': mock_pkg, 'pkg_resource.stringify': mock_pkg, 'pkg_resource.sort_pkglist': mock_pkg, 'cmd.run_all': mock_run_all, 'cmd.run': mock_run}):
with patch.dict(pkgutil.__context__, {'pkg.list_pkgs': mock_ret}):
with patch.object(pkgutil, 'list_pkgs', return_value={'bar': '1.2.3'}):
self.assertDictEqual(pkgutil.remove(pkgs='["foo", "bar"]'), {})
|
'Test if it package purges are not supported,
this function is identical to ``remove()``.'
| def test_purge(self):
| mock_pkg = MagicMock(side_effect=MinionError)
with patch.dict(pkgutil.__salt__, {'pkg_resource.parse_targets': mock_pkg}):
self.assertRaises(CommandExecutionError, pkgutil.purge)
|
'Test for finger'
| def test_finger(self):
| with patch.object(os.path, 'join', return_value='A'):
with patch.object(salt.utils, 'pem_finger', return_value='A'):
with patch.dict(key.__opts__, {'pki_dir': MagicMock(return_value='A'), 'hash_type': 'sha256'}):
self.assertEqual(key.finger(), 'A')
|
'Test for finger'
| def test_finger_master(self):
| with patch.object(os.path, 'join', return_value='A'):
with patch.object(salt.utils, 'pem_finger', return_value='A'):
with patch.dict(key.__opts__, {'pki_dir': 'A', 'hash_type': 'sha256'}):
self.assertEqual(key.finger_master(), 'A')
|
'Test for Run nagios plugin and return all
the data execution with cmd.run'
| def test_run(self):
| with patch.object(nagios, '_execute_cmd', return_value='A'):
self.assertEqual(nagios.run('plugin'), 'A')
|
'Test for Run one nagios plugin and return retcode of the execution'
| def test_retcode(self):
| with patch.object(nagios, '_execute_cmd', return_value='A'):
self.assertEqual(nagios.retcode('plugin', key_name='key'), {'key': {'status': 'A'}})
|
'Test for Run nagios plugin and return all
the data execution with cmd.run_all'
| def test_run_all(self):
| with patch.object(nagios, '_execute_cmd', return_value='A'):
self.assertEqual(nagios.run_all('plugin'), 'A')
|
'Test for Run one or more nagios plugins from pillar data and
get the result of cmd.retcode'
| def test_retcode_pillar(self):
| with patch.dict(nagios.__salt__, {'pillar.get': MagicMock(return_value={})}):
self.assertEqual(nagios.retcode_pillar('pillar_name'), {})
|
'Test for Run one or more nagios plugins from pillar data
and get the result of cmd.run'
| def test_run_pillar(self):
| with patch.object(nagios, '_execute_pillar', return_value='A'):
self.assertEqual(nagios.run_pillar('pillar'), 'A')
|
'Test for Run one or more nagios plugins from pillar data
and get the result of cmd.run'
| def test_run_all_pillar(self):
| with patch.object(nagios, '_execute_pillar', return_value='A'):
self.assertEqual(nagios.run_all_pillar('pillar'), 'A')
|
'Test for List all the nagios plugins'
| def test_list_plugins(self):
| with patch.object(os, 'listdir', return_value=[]):
self.assertEqual(nagios.list_plugins(), [])
|
'Test if the parsing function works'
| def test_read_file(self):
| with patch('salt.utils.files.fopen', mock_open(read_data=MOCK_FILE)):
self.assertListEqual(pam.read_file('/etc/pam.d/login'), [{'arguments': [], 'control_flag': 'ok', 'interface': 'ok', 'module': 'ignore'}])
|
'Tests to add the specified group'
| def test_add(self):
| mock = MagicMock(return_value={'retcode': 0})
with patch.dict(pw_group.__salt__, {'cmd.run_all': mock}):
self.assertTrue(pw_group.add('a'))
|
'Tests to remove the named group'
| def test_delete(self):
| mock = MagicMock(return_value={'retcode': 0})
with patch.dict(pw_group.__salt__, {'cmd.run_all': mock}):
self.assertTrue(pw_group.delete('a'))
|
'Tests to return information about a group'
| def test_info(self):
| self.assertDictEqual(pw_group.info('name'), {})
mock = MagicMock(return_value={'gr_name': 'A', 'gr_passwd': 'B', 'gr_gid': 1, 'gr_mem': ['C', 'D']})
with patch.dict(pw_group.grinfo, mock):
self.assertDictEqual(pw_group.info('name'), {})
|
'Tests for return info on all groups'
| def test_getent(self):
| mock_getent = [{'passwd': 'x', 'gid': 0, 'name': 'root'}]
with patch.dict(pw_group.__context__, {'group.getent': mock_getent}):
self.assertDictContainsSubset({'passwd': 'x', 'gid': 0, 'name': 'root'}, pw_group.getent()[0])
mock = MagicMock(return_value='A')
with patch.object(pw_group, 'info', mock):
self.assertEqual(pw_group.getent(True)[0], 'A')
|
'tests to change the gid for a named group'
| def test_chgid(self):
| mock = MagicMock(return_value=1)
with patch.dict(pw_group.__salt__, {'file.group_to_gid': mock}):
self.assertTrue(pw_group.chgid('name', 1))
mock = MagicMock(side_effect=[1, 0])
with patch.dict(pw_group.__salt__, {'file.group_to_gid': mock}):
mock = MagicMock(return_value=None)
with patch.dict(pw_group.__salt__, {'cmd.run': mock}):
self.assertTrue(pw_group.chgid('name', 0))
mock = MagicMock(side_effect=[1, 1])
with patch.dict(pw_group.__salt__, {'file.group_to_gid': mock}):
mock = MagicMock(return_value=None)
with patch.dict(pw_group.__salt__, {'cmd.run': mock}):
self.assertFalse(pw_group.chgid('name', 0))
|
'Test for retrieving cert base path'
| def test_cert_base_path(self):
| ca_path = '/etc/tls'
mock_opt = MagicMock(return_value=ca_path)
with patch.dict(tls.__salt__, {'config.option': mock_opt}):
self.assertEqual(tls.cert_base_path(), ca_path)
|
'Test for setting the cert base path'
| def test_set_ca_cert_path(self):
| ca_path = '/tmp/ca_cert_test_path'
mock_opt = MagicMock(return_value='/etc/tls')
ret = {'ca.contextual_cert_base_path': '/tmp/ca_cert_test_path'}
with patch.dict(tls.__salt__, {'config.option': mock_opt}):
tls.set_ca_path(ca_path)
self.assertEqual(tls.__context__, ret)
|
'Test to see if ca does not exist'
| def test_ca_exists(self):
| ca_path = '/tmp/test_tls'
ca_name = 'test_ca'
mock_opt = MagicMock(return_value=ca_path)
with patch.dict(tls.__salt__, {'config.option': mock_opt}):
with patch('os.path.exists', MagicMock(return_value=False)):
with patch('salt.modules.tls.maybe_fix_ssl_version', MagicMock(return_value=True)):
self.assertFalse(tls.ca_exists(ca_name))
|
'Test to see if ca exists'
| def test_ca_exists_true(self):
| ca_path = '/tmp/test_tls'
ca_name = 'test_ca'
mock_opt = MagicMock(return_value=ca_path)
with patch.dict(tls.__salt__, {'config.option': mock_opt}):
with patch('os.path.exists', MagicMock(return_value=True)):
with patch('salt.modules.tls.maybe_fix_ssl_version', MagicMock(return_value=True)):
self.assertTrue(tls.ca_exists(ca_name))
|
'Test get_ca failure'
| def test_get_ca_fail(self):
| ca_path = '/tmp/test_tls'
ca_name = 'test_ca'
mock_opt = MagicMock(return_value=ca_path)
with patch.dict(tls.__salt__, {'config.option': mock_opt}):
with patch('os.path.exists', MagicMock(return_value=False)):
with patch('salt.modules.tls.maybe_fix_ssl_version', MagicMock(return_value=True)):
self.assertRaises(ValueError, tls.get_ca, ca_name)
|
'Test get_ca text'
| def test_get_ca_text(self):
| ca_path = '/tmp/test_tls'
ca_name = 'test_ca'
mock_opt = MagicMock(return_value=ca_path)
with patch('salt.utils.files.fopen', mock_open(read_data=_TLS_TEST_DATA['ca_cert'])):
with patch.dict(tls.__salt__, {'config.option': mock_opt}):
with patch('os.path.exists', MagicMock(return_value=True)):
with patch('salt.modules.tls.maybe_fix_ssl_version', MagicMock(return_value=True)):
self.assertEqual(tls.get_ca(ca_name, as_text=True), _TLS_TEST_DATA['ca_cert'])
|
'Test get_ca'
| def test_get_ca(self):
| ca_path = '/tmp/test_tls'
ca_name = 'test_ca'
certp = '{0}/{1}/{2}_ca_cert.crt'.format(ca_path, ca_name, ca_name)
mock_opt = MagicMock(return_value=ca_path)
with patch.dict(tls.__salt__, {'config.option': mock_opt}):
with patch('os.path.exists', MagicMock(return_value=True)):
with patch('salt.modules.tls.maybe_fix_ssl_version', MagicMock(return_value=True)):
self.assertEqual(tls.get_ca(ca_name), certp)
|
'Test cert info'
| def test_cert_info(self):
| self.maxDiff = None
with patch('os.path.exists', MagicMock(return_value=True)):
with patch('salt.modules.tls.maybe_fix_ssl_version', MagicMock(return_value=True)):
ca_path = '/tmp/test_tls'
ca_name = 'test_ca'
certp = '{0}/{1}/{2}_ca_cert.crt'.format(ca_path, ca_name, ca_name)
ret = {'not_after': 1462379961, 'signature_algorithm': 'sha256WithRSAEncryption', 'extensions': None, 'fingerprint': '96:72:B3:0A:1D:34:37:05:75:57:44:7E:08:81:A7:09:0C:E1:8F:5F:4D:0C:49:CE:5B:D2:6B:45:D3:4D:FF:31', 'serial_number': 284092004844685647925744086791559203700L, 'subject': {'C': 'US', 'CN': 'localhost', 'L': 'Salt Lake City', 'O': 'SaltStack', 'ST': 'Utah', 'emailAddress': '[email protected]'}, 'not_before': 1430843961, 'issuer': {'C': 'US', 'CN': 'localhost', 'L': 'Salt Lake City', 'O': 'SaltStack', 'ST': 'Utah', 'emailAddress': '[email protected]'}}
def ignore_extensions(data):
'\n Ignore extensions pending a resolution of issue 24338\n '
if ('extensions' in data.keys()):
data['extensions'] = None
return data
def remove_not_in_result(source, reference):
if ('signature_algorithm' not in reference):
del source['signature_algorithm']
if ('extensions' not in reference):
del source['extensions']
with patch('salt.utils.files.fopen', mock_open(read_data=_TLS_TEST_DATA['ca_cert'])):
try:
result = ignore_extensions(tls.cert_info(certp))
except AttributeError as err:
if ("'_cffi_backend.CDataGCP' object has no attribute 'cert_info'" == str(err)):
log.exception(err)
self.skipTest('Encountered an upstream error with PyOpenSSL: {0}'.format(err))
if ("'_cffi_backend.CDataGCP' object has no attribute 'object'" == str(err)):
log.exception(err)
self.skipTest('Encountered an upstream error with PyOpenSSL: {0}'.format(err))
if (LooseVersion(OpenSSL.__version__) == LooseVersion('0.14')):
log.exception(err)
self.skipTest('Encountered a package conflict. OpenSSL version 0.14 cannot be used with the "junos-eznc" pip package on this test. Skipping.')
result = {}
remove_not_in_result(ret, result)
self.assertEqual(result, ret)
|
'Test creating CA cert'
| def test_create_ca(self):
| ca_path = tempfile.mkdtemp(dir=TMP)
try:
ca_name = 'test_ca'
certp = '{0}/{1}/{2}_ca_cert.crt'.format(ca_path, ca_name, ca_name)
certk = '{0}/{1}/{2}_ca_cert.key'.format(ca_path, ca_name, ca_name)
ret = 'Created Private Key: "{0}." Created CA "{1}": "{2}."'.format(certk, ca_name, certp)
mock_opt = MagicMock(return_value=ca_path)
mock_ret = MagicMock(return_value=0)
with patch.dict(tls.__salt__, {'config.option': mock_opt, 'cmd.retcode': mock_ret}):
with patch.dict(tls.__opts__, {'hash_type': 'sha256', 'cachedir': ca_path}):
with patch('salt.modules.tls.maybe_fix_ssl_version', MagicMock(return_value=True)):
self.assertEqual(tls.create_ca(ca_name, days=365, fixmode=False, **_TLS_TEST_DATA['create_ca']), ret)
finally:
if os.path.isdir(ca_path):
shutil.rmtree(ca_path)
|
'Test creating CA cert when one already exists'
| def test_recreate_ca(self):
| ca_path = tempfile.mkdtemp(dir=TMP)
try:
ca_name = 'test_ca'
certp = '{0}/{1}/{2}_ca_cert.crt'.format(ca_path, ca_name, ca_name)
certk = '{0}/{1}/{2}_ca_cert.key'.format(ca_path, ca_name, ca_name)
ret = 'Created Private Key: "{0}." Created CA "{1}": "{2}."'.format(certk, ca_name, certp)
mock_opt = MagicMock(return_value=ca_path)
mock_ret = MagicMock(return_value=0)
with patch('salt.modules.tls.maybe_fix_ssl_version', MagicMock(return_value=True)):
with patch.dict(tls.__salt__, {'config.option': mock_opt, 'cmd.retcode': mock_ret}):
with patch.dict(tls.__opts__, {'hash_type': 'sha256', 'cachedir': ca_path}):
with patch.dict(_TLS_TEST_DATA['create_ca'], {'replace': True}):
tls.create_ca(ca_name)
self.assertEqual(tls.create_ca(ca_name, days=365, fixmode=False, **_TLS_TEST_DATA['create_ca']), ret)
finally:
if os.path.isdir(ca_path):
shutil.rmtree(ca_path)
|
'Test creating certificate signing request'
| def test_create_csr(self):
| ca_path = tempfile.mkdtemp(dir=TMP)
try:
ca_name = 'test_ca'
certp = '{0}/{1}/certs/{2}.csr'.format(ca_path, ca_name, _TLS_TEST_DATA['create_ca']['CN'])
certk = '{0}/{1}/certs/{2}.key'.format(ca_path, ca_name, _TLS_TEST_DATA['create_ca']['CN'])
ret = 'Created Private Key: "{0}." Created CSR for "{1}": "{2}."'.format(certk, _TLS_TEST_DATA['create_ca']['CN'], certp)
mock_opt = MagicMock(return_value=ca_path)
mock_ret = MagicMock(return_value=0)
mock_pgt = MagicMock(return_value=False)
with patch.dict(tls.__salt__, {'config.option': mock_opt, 'cmd.retcode': mock_ret, 'pillar.get': mock_pgt}):
with patch.dict(tls.__opts__, {'hash_type': 'sha256', 'cachedir': ca_path}):
with patch('salt.modules.tls.maybe_fix_ssl_version', MagicMock(return_value=True)):
tls.create_ca(ca_name)
self.assertEqual(tls.create_csr(ca_name, **_TLS_TEST_DATA['create_ca']), ret)
finally:
if os.path.isdir(ca_path):
shutil.rmtree(ca_path)
|
'Test creating certificate signing request when one already exists'
| def test_recreate_csr(self):
| ca_path = tempfile.mkdtemp(dir=TMP)
try:
ca_name = 'test_ca'
certp = '{0}/{1}/certs/{2}.csr'.format(ca_path, ca_name, _TLS_TEST_DATA['create_ca']['CN'])
certk = '{0}/{1}/certs/{2}.key'.format(ca_path, ca_name, _TLS_TEST_DATA['create_ca']['CN'])
ret = 'Created Private Key: "{0}." Created CSR for "{1}": "{2}."'.format(certk, _TLS_TEST_DATA['create_ca']['CN'], certp)
mock_opt = MagicMock(return_value=ca_path)
mock_ret = MagicMock(return_value=0)
mock_pgt = MagicMock(return_value=False)
with patch.dict(tls.__salt__, {'config.option': mock_opt, 'cmd.retcode': mock_ret, 'pillar.get': mock_pgt}):
with patch.dict(tls.__opts__, {'hash_type': 'sha256', 'cachedir': ca_path}):
with patch.dict(_TLS_TEST_DATA['create_ca'], {'replace': True}):
with patch('salt.modules.tls.maybe_fix_ssl_version', MagicMock(return_value=True)):
tls.create_ca(ca_name)
tls.create_csr(ca_name)
self.assertEqual(tls.create_csr(ca_name, **_TLS_TEST_DATA['create_ca']), ret)
finally:
if os.path.isdir(ca_path):
shutil.rmtree(ca_path)
|
'Test creating self signed certificate'
| def test_create_self_signed_cert(self):
| ca_path = tempfile.mkdtemp(dir=TMP)
try:
tls_dir = 'test_tls'
certp = '{0}/{1}/certs/{2}.crt'.format(ca_path, tls_dir, _TLS_TEST_DATA['create_ca']['CN'])
certk = '{0}/{1}/certs/{2}.key'.format(ca_path, tls_dir, _TLS_TEST_DATA['create_ca']['CN'])
ret = 'Created Private Key: "{0}." Created Certificate: "{1}."'.format(certk, certp)
mock_opt = MagicMock(return_value=ca_path)
with patch.dict(tls.__salt__, {'config.option': mock_opt}):
with patch.dict(tls.__opts__, {'hash_type': 'sha256', 'cachedir': ca_path}):
with patch('salt.modules.tls.maybe_fix_ssl_version', MagicMock(return_value=True)):
self.assertEqual(tls.create_self_signed_cert(tls_dir=tls_dir, days=365, **_TLS_TEST_DATA['create_ca']), ret)
finally:
if os.path.isdir(ca_path):
shutil.rmtree(ca_path)
|
'Test creating self signed certificate when one already exists'
| def test_recreate_self_signed_cert(self):
| ca_path = tempfile.mkdtemp(dir=TMP)
try:
tls_dir = 'test_tls'
certp = '{0}/{1}/certs/{2}.crt'.format(ca_path, tls_dir, _TLS_TEST_DATA['create_ca']['CN'])
certk = '{0}/{1}/certs/{2}.key'.format(ca_path, tls_dir, _TLS_TEST_DATA['create_ca']['CN'])
ret = 'Created Private Key: "{0}." Created Certificate: "{1}."'.format(certk, certp)
mock_opt = MagicMock(return_value=ca_path)
with patch.dict(tls.__salt__, {'config.option': mock_opt}):
with patch.dict(tls.__opts__, {'hash_type': 'sha256', 'cachedir': ca_path}):
with patch('salt.modules.tls.maybe_fix_ssl_version', MagicMock(return_value=True)):
self.assertEqual(tls.create_self_signed_cert(tls_dir=tls_dir, days=365, **_TLS_TEST_DATA['create_ca']), ret)
finally:
if os.path.isdir(ca_path):
shutil.rmtree(ca_path)
|
'Test signing certificate from request'
| def test_create_ca_signed_cert(self):
| ca_path = tempfile.mkdtemp(dir=TMP)
try:
ca_name = 'test_ca'
certp = '{0}/{1}/certs/{2}.crt'.format(ca_path, ca_name, _TLS_TEST_DATA['create_ca']['CN'])
ret = 'Created Certificate for "{0}": "{1}"'.format(_TLS_TEST_DATA['create_ca']['CN'], certp)
mock_opt = MagicMock(return_value=ca_path)
mock_ret = MagicMock(return_value=0)
mock_pgt = MagicMock(return_value=False)
with patch.dict(tls.__salt__, {'config.option': mock_opt, 'cmd.retcode': mock_ret, 'pillar.get': mock_pgt}):
with patch.dict(tls.__opts__, {'hash_type': 'sha256', 'cachedir': ca_path}):
with patch('salt.modules.tls.maybe_fix_ssl_version', MagicMock(return_value=True)):
tls.create_ca(ca_name)
tls.create_csr(ca_name, **_TLS_TEST_DATA['create_ca'])
self.assertEqual(tls.create_ca_signed_cert(ca_name, _TLS_TEST_DATA['create_ca']['CN']), ret)
finally:
if os.path.isdir(ca_path):
shutil.rmtree(ca_path)
|
'Test signing certificate from request when certificate exists'
| def test_recreate_ca_signed_cert(self):
| ca_path = tempfile.mkdtemp(dir=TMP)
try:
ca_name = 'test_ca'
certp = '{0}/{1}/certs/{2}.crt'.format(ca_path, ca_name, _TLS_TEST_DATA['create_ca']['CN'])
ret = 'Created Certificate for "{0}": "{1}"'.format(_TLS_TEST_DATA['create_ca']['CN'], certp)
mock_opt = MagicMock(return_value=ca_path)
mock_ret = MagicMock(return_value=0)
mock_pgt = MagicMock(return_value=False)
with patch.dict(tls.__salt__, {'config.option': mock_opt, 'cmd.retcode': mock_ret, 'pillar.get': mock_pgt}):
with patch.dict(tls.__opts__, {'hash_type': 'sha256', 'cachedir': ca_path}):
with patch('salt.modules.tls.maybe_fix_ssl_version', MagicMock(return_value=True)):
tls.create_ca(ca_name)
tls.create_csr(ca_name)
tls.create_ca_signed_cert(ca_name, _TLS_TEST_DATA['create_ca']['CN'])
self.assertEqual(tls.create_ca_signed_cert(ca_name, _TLS_TEST_DATA['create_ca']['CN'], replace=True), ret)
finally:
if os.path.isdir(ca_path):
shutil.rmtree(ca_path)
|
'Test creating pkcs12'
| def test_create_pkcs12(self):
| ca_path = tempfile.mkdtemp(dir=TMP)
try:
ca_name = 'test_ca'
certp = '{0}/{1}/certs/{2}.p12'.format(ca_path, ca_name, _TLS_TEST_DATA['create_ca']['CN'])
ret = 'Created PKCS#12 Certificate for "{0}": "{1}"'.format(_TLS_TEST_DATA['create_ca']['CN'], certp)
mock_opt = MagicMock(return_value=ca_path)
mock_ret = MagicMock(return_value=0)
mock_pgt = MagicMock(return_value=False)
with patch.dict(tls.__salt__, {'config.option': mock_opt, 'cmd.retcode': mock_ret, 'pillar.get': mock_pgt}):
with patch.dict(tls.__opts__, {'hash_type': 'sha256', 'cachedir': ca_path}):
with patch('salt.modules.tls.maybe_fix_ssl_version', MagicMock(return_value=True)):
tls.create_ca(ca_name)
tls.create_csr(ca_name, **_TLS_TEST_DATA['create_ca'])
tls.create_ca_signed_cert(ca_name, _TLS_TEST_DATA['create_ca']['CN'])
self.assertEqual(tls.create_pkcs12(ca_name, _TLS_TEST_DATA['create_ca']['CN'], 'password'), ret)
finally:
if os.path.isdir(ca_path):
shutil.rmtree(ca_path)
|
'Test creating pkcs12 when it already exists'
| def test_recreate_pkcs12(self):
| ca_path = tempfile.mkdtemp(dir=TMP)
try:
ca_name = 'test_ca'
certp = '{0}/{1}/certs/{2}.p12'.format(ca_path, ca_name, _TLS_TEST_DATA['create_ca']['CN'])
ret = 'Created PKCS#12 Certificate for "{0}": "{1}"'.format(_TLS_TEST_DATA['create_ca']['CN'], certp)
mock_opt = MagicMock(return_value=ca_path)
mock_ret = MagicMock(return_value=0)
mock_pgt = MagicMock(return_value=False)
with patch.dict(tls.__salt__, {'config.option': mock_opt, 'cmd.retcode': mock_ret, 'pillar.get': mock_pgt}):
with patch.dict(tls.__opts__, {'hash_type': 'sha256', 'cachedir': ca_path}):
with patch.dict(_TLS_TEST_DATA['create_ca'], {'replace': True}):
with patch('salt.modules.tls.maybe_fix_ssl_version', MagicMock(return_value=True)):
tls.create_ca(ca_name)
tls.create_csr(ca_name)
tls.create_ca_signed_cert(ca_name, _TLS_TEST_DATA['create_ca']['CN'])
tls.create_pkcs12(ca_name, _TLS_TEST_DATA['create_ca']['CN'], 'password')
self.assertEqual(tls.create_pkcs12(ca_name, _TLS_TEST_DATA['create_ca']['CN'], 'password', replace=True), ret)
finally:
if os.path.isdir(ca_path):
shutil.rmtree(ca_path)
|
'Test extension logic with different pyOpenSSL versions'
| def test_pyOpenSSL_version(self):
| pillarval = {'csr': {'extendedKeyUsage': 'serverAuth'}}
mock_pgt = MagicMock(return_value=pillarval)
with patch.dict(tls.__dict__, {'OpenSSL_version': LooseVersion('0.1.1'), 'X509_EXT_ENABLED': False}):
self.assertEqual(tls.__virtual__(), (False, 'PyOpenSSL version 0.10 or later must be installed before this module can be used.'))
with patch.dict(tls.__salt__, {'pillar.get': mock_pgt}):
self.assertRaises(AssertionError, tls.get_extensions, 'server')
self.assertRaises(AssertionError, tls.get_extensions, 'client')
with patch.dict(tls.__dict__, {'OpenSSL_version': LooseVersion('0.14.1'), 'X509_EXT_ENABLED': True}):
self.assertTrue(tls.__virtual__())
with patch.dict(tls.__salt__, {'pillar.get': mock_pgt}):
self.assertEqual(tls.get_extensions('server'), pillarval)
self.assertEqual(tls.get_extensions('client'), pillarval)
with patch.dict(tls.__dict__, {'OpenSSL_version': LooseVersion('0.15.1'), 'X509_EXT_ENABLED': True}):
self.assertTrue(tls.__virtual__())
with patch.dict(tls.__salt__, {'pillar.get': mock_pgt}):
self.assertEqual(tls.get_extensions('server'), pillarval)
self.assertEqual(tls.get_extensions('client'), pillarval)
|
'Test extension logic with different pyOpenSSL versions'
| def test_pyOpenSSL_version_destructive(self):
| pillarval = {'csr': {'extendedKeyUsage': 'serverAuth'}}
mock_pgt = MagicMock(return_value=pillarval)
ca_path = tempfile.mkdtemp(dir=TMP)
ca_name = 'test_ca'
certp = '{0}/{1}/{2}_ca_cert.crt'.format(ca_path, ca_name, ca_name)
certk = '{0}/{1}/{2}_ca_cert.key'.format(ca_path, ca_name, ca_name)
ret = 'Created Private Key: "{0}." Created CA "{1}": "{2}."'.format(certk, ca_name, certp)
mock_opt = MagicMock(return_value=ca_path)
mock_ret = MagicMock(return_value=0)
try:
with patch.dict(tls.__salt__, {'config.option': mock_opt, 'cmd.retcode': mock_ret}):
with patch.dict(tls.__opts__, {'hash_type': 'sha256', 'cachedir': ca_path}):
with patch.dict(_TLS_TEST_DATA['create_ca'], {'replace': True}):
with patch.dict(tls.__dict__, {'OpenSSL_version': LooseVersion('0.1.1'), 'X509_EXT_ENABLED': False}):
self.assertEqual(tls.create_ca(ca_name, days=365, fixmode=False, **_TLS_TEST_DATA['create_ca']), ret)
with patch.dict(tls.__dict__, {'OpenSSL_version': LooseVersion('0.14.1'), 'X509_EXT_ENABLED': True}):
self.assertEqual(tls.create_ca(ca_name, days=365, fixmode=False, **_TLS_TEST_DATA['create_ca']), ret)
with patch.dict(tls.__dict__, {'OpenSSL_version': LooseVersion('0.15.1'), 'X509_EXT_ENABLED': True}):
self.assertEqual(tls.create_ca(ca_name, days=365, fixmode=False, **_TLS_TEST_DATA['create_ca']), ret)
finally:
if os.path.isdir(ca_path):
shutil.rmtree(ca_path)
try:
certp = '{0}/{1}/certs/{2}.csr'.format(ca_path, ca_name, _TLS_TEST_DATA['create_ca']['CN'])
certk = '{0}/{1}/certs/{2}.key'.format(ca_path, ca_name, _TLS_TEST_DATA['create_ca']['CN'])
ret = 'Created Private Key: "{0}." Created CSR for "{1}": "{2}."'.format(certk, _TLS_TEST_DATA['create_ca']['CN'], certp)
with patch.dict(tls.__salt__, {'config.option': mock_opt, 'cmd.retcode': mock_ret, 'pillar.get': mock_pgt}):
with patch.dict(tls.__opts__, {'hash_type': 'sha256', 'cachedir': ca_path}):
with patch.dict(_TLS_TEST_DATA['create_ca'], {'subjectAltName': 'DNS:foo.bar', 'replace': True}):
with patch.dict(tls.__dict__, {'OpenSSL_version': LooseVersion('0.1.1'), 'X509_EXT_ENABLED': False}):
tls.create_ca(ca_name)
tls.create_csr(ca_name)
self.assertRaises(ValueError, tls.create_csr, ca_name, **_TLS_TEST_DATA['create_ca'])
with patch.dict(tls.__dict__, {'OpenSSL_version': LooseVersion('0.14.1'), 'X509_EXT_ENABLED': True}):
tls.create_ca(ca_name)
tls.create_csr(ca_name)
self.assertEqual(tls.create_csr(ca_name, **_TLS_TEST_DATA['create_ca']), ret)
with patch.dict(tls.__dict__, {'OpenSSL_version': LooseVersion('0.15.1'), 'X509_EXT_ENABLED': True}):
tls.create_ca(ca_name)
tls.create_csr(ca_name)
self.assertEqual(tls.create_csr(ca_name, **_TLS_TEST_DATA['create_ca']), ret)
finally:
if os.path.isdir(ca_path):
shutil.rmtree(ca_path)
|
'Test for Answers to debconf questions for all packages'
| def test_get_selections(self):
| mock = MagicMock(return_value=[])
with patch.dict(debconfmod.__salt__, {'cmd.run_stdout': mock}):
with patch.object(debconfmod, '_unpack_lines', mock):
self.assertEqual(debconfmod.get_selections(False), {})
|
'Test for Answers to debconf questions for a package'
| def test_show(self):
| mock = MagicMock(return_value={})
with patch.object(debconfmod, 'get_selections', mock):
self.assertEqual(debconfmod.show('name'), None)
|
'Test for Set answers to debconf questions for a package.'
| def test_set_(self):
| mock = MagicMock(return_value=None)
with patch.object(os, 'write', mock):
with patch.object(os, 'close', mock):
with patch.object(debconfmod, '_set_file', mock):
with patch.object(os, 'unlink', mock):
self.assertTrue(debconfmod.set_('package', 'question', 'type', 'value'))
|
'Test for Set answers to debconf questions from a template.'
| def test_set_template(self):
| mock = MagicMock(return_value='A')
with patch.dict(debconfmod.__salt__, {'cp.get_template': mock}):
with patch.object(debconfmod, 'set_file', mock):
self.assertEqual(debconfmod.set_template('path', 'template', 'context', 'defaults', 'saltenv'), 'A')
|
'Test for Set answers to debconf questions from a file.'
| def test_set_file(self):
| mock = MagicMock(return_value='A')
with patch.dict(debconfmod.__salt__, {'cp.cache_file': mock}):
mock = MagicMock(return_value=None)
with patch.object(debconfmod, '_set_file', mock):
self.assertTrue(debconfmod.set_file('path'))
mock = MagicMock(return_value=False)
with patch.dict(debconfmod.__salt__, {'cp.cache_file': mock}):
mock = MagicMock(return_value=None)
with patch.object(debconfmod, '_set_file', mock):
self.assertFalse(debconfmod.set_file('path'))
|
'Mock sendmail method'
| def sendmail(self, sender, recipient, msg):
| if (self.flag == 1):
raise SMTPRecipientsRefused('All recipients were refused.')
elif (self.flag == 2):
raise SMTPHeloError('Helo error')
elif (self.flag == 3):
raise SMTPSenderRefused('Sender Refused')
elif (self.flag == 4):
raise SMTPDataError('Data error')
return (sender, recipient, msg)
|
'Mock login method'
| def login(self, username, password):
| if (self.flag == 5):
raise SMTPAuthenticationError('SMTP Authentication Failure')
return (username, password)
|
'Mock quit method'
| @staticmethod
def quit():
| return True
|
'Mock ehlo method'
| @staticmethod
def ehlo():
| return True
|
'Mock has_extn method'
| @staticmethod
def has_extn(name):
| return name
|
'Mock starttls method'
| def starttls(self):
| if (self.flag == 1):
raise SMTPHeloError('Helo error')
elif (self.flag == 2):
raise SMTPException('Exception error')
elif (self.flag == 3):
raise RuntimeError
return True
|
'Mock sendmail method'
| def sendmail(self, sender, recipient, msg):
| if (self.flag == 1):
raise SMTPRecipientsRefused('All recipients were refused.')
elif (self.flag == 2):
raise SMTPHeloError('Helo error')
elif (self.flag == 3):
raise SMTPSenderRefused('Sender Refused')
elif (self.flag == 4):
raise SMTPDataError('Data error')
return (sender, recipient, msg)
|
'Mock quit method'
| @staticmethod
def quit():
| return True
|
'Mock SMTP_SSL method'
| def SMTP_SSL(self, server):
| self.server = server
if (self.flag == 1):
raise MockGaierror('gaierror')
return MockSMTPSSL('server')
|
'Mock SMTP method'
| def SMTP(self, server):
| self.server = server
if (self.flag == 1):
raise MockGaierror('gaierror')
return MockSMTP('server')
|
'Tests if it send a message to an SMTP recipient.'
| def test_send_msg(self):
| mock = MagicMock(return_value={'smtp.server': '', 'smtp.tls': 'True', 'smtp.sender': '', 'smtp.username': '', 'smtp.password': ''})
with patch.dict(smtp.__salt__, {'config.option': mock}):
self.assertTrue(smtp.send_msg('[email protected]', 'This is a salt module test', profile='my-smtp-account'))
MockSMTPSSL.flag = 1
self.assertFalse(smtp.send_msg('[email protected]', 'This is a salt module test', profile='my-smtp-account'))
MockSMTPSSL.flag = 2
self.assertFalse(smtp.send_msg('[email protected]', 'This is a salt module test', profile='my-smtp-account'))
MockSMTPSSL.flag = 3
self.assertFalse(smtp.send_msg('[email protected]', 'This is a salt module test', profile='my-smtp-account'))
MockSMTPSSL.flag = 4
self.assertFalse(smtp.send_msg('[email protected]', 'This is a salt module test', profile='my-smtp-account'))
mock = MagicMock(return_value={'smtp.server': '', 'smtp.tls': '', 'smtp.sender': '', 'smtp.username': '', 'smtp.password': ''})
with patch.dict(smtp.__salt__, {'config.option': mock}):
MockSMTPSSL.flag = 5
self.assertFalse(smtp.send_msg('[email protected]', 'This is a salt module test', username='myuser', password='verybadpass', sender='[email protected]', server='smtp.domain.com'))
MockSMTP.flag = 1
self.assertFalse(smtp.send_msg('[email protected]', 'This is a salt module test', profile='my-smtp-account'))
MockSMTP.flag = 2
self.assertFalse(smtp.send_msg('[email protected]', 'This is a salt module test', profile='my-smtp-account'))
MockSMTP.flag = 3
self.assertFalse(smtp.send_msg('[email protected]', 'This is a salt module test', profile='my-smtp-account'))
MockSmtplib.flag = 1
self.assertFalse(smtp.send_msg('[email protected]', 'This is a salt module test', profile='my-smtp-account'))
|
'Tests checking event existence when the event already exists'
| def test_that_when_checking_if_a_rule_exists_and_a_rule_exists_the_rule_exists_method_returns_true(self):
| self.conn.list_rules.return_value = {'Rules': [rule_ret]}
result = boto_cloudwatch_event.exists(Name=rule_name, **conn_parameters)
self.assertTrue(result['exists'])
|
'Tests checking rule existence when the rule does not exist'
| def test_that_when_checking_if_a_rule_exists_and_a_rule_does_not_exist_the_exists_method_returns_false(self):
| self.conn.list_rules.return_value = {'Rules': []}
result = boto_cloudwatch_event.exists(Name=rule_name, **conn_parameters)
self.assertFalse(result['exists'])
|
'Tests checking rule existence when boto returns an error'
| def test_that_when_checking_if_a_rule_exists_and_boto3_returns_an_error_the_rule_exists_method_returns_error(self):
| self.conn.list_rules.side_effect = ClientError(error_content, 'list_rules')
result = boto_cloudwatch_event.exists(Name=rule_name, **conn_parameters)
self.assertEqual(result.get('error', {}).get('message'), error_message.format('list_rules'))
|
'Tests describe rule for an existing rule'
| def test_that_when_describing_rule_and_rule_exists_the_describe_rule_method_returns_rule(self):
| self.conn.describe_rule.return_value = rule_ret
result = boto_cloudwatch_event.describe(Name=rule_name, **conn_parameters)
self.assertEqual(result.get('rule'), rule_ret)
|
'Tests describe rule for an non existent rule'
| def test_that_when_describing_rule_and_rule_does_not_exists_the_describe_method_returns_none(self):
| self.conn.describe_rule.side_effect = not_found_error
result = boto_cloudwatch_event.describe(Name=rule_name, **conn_parameters)
self.assertNotEqual(result.get('error'), None)
|
'tests True when rule created'
| def test_that_when_creating_a_rule_succeeds_the_create_rule_method_returns_true(self):
| self.conn.put_rule.return_value = create_rule_ret
result = boto_cloudwatch_event.create_or_update(Name=rule_name, Description=rule_desc, ScheduleExpression=rule_sched, **conn_parameters)
self.assertTrue(result['created'])
|
'tests False when rule not created'
| def test_that_when_creating_a_rule_fails_the_create_method_returns_error(self):
| self.conn.put_rule.side_effect = ClientError(error_content, 'put_rule')
result = boto_cloudwatch_event.create_or_update(Name=rule_name, Description=rule_desc, ScheduleExpression=rule_sched, **conn_parameters)
self.assertEqual(result.get('error', {}).get('message'), error_message.format('put_rule'))
|
'tests True when delete rule succeeds'
| def test_that_when_deleting_a_rule_succeeds_the_delete_method_returns_true(self):
| self.conn.delete_rule.return_value = {}
result = boto_cloudwatch_event.delete(Name=rule_name, **conn_parameters)
self.assertTrue(result.get('deleted'))
self.assertEqual(result.get('error'), None)
|
'tests False when delete rule fails'
| def test_that_when_deleting_a_rule_fails_the_delete_method_returns_error(self):
| self.conn.delete_rule.side_effect = ClientError(error_content, 'delete_rule')
result = boto_cloudwatch_event.delete(Name=rule_name, **conn_parameters)
self.assertFalse(result.get('deleted'))
self.assertEqual(result.get('error', {}).get('message'), error_message.format('delete_rule'))
|
'Tests listing targets for an existing rule'
| def test_that_when_listing_targets_and_rule_exists_the_list_targets_method_returns_targets(self):
| self.conn.list_targets_by_rule.return_value = {'Targets': [target_ret]}
result = boto_cloudwatch_event.list_targets(Rule=rule_name, **conn_parameters)
self.assertEqual(result.get('targets'), [target_ret])
|
'Tests list targets for an non existent rule'
| def test_that_when_listing_targets_and_rule_does_not_exist_the_list_targets_method_returns_error(self):
| self.conn.list_targets_by_rule.side_effect = not_found_error
result = boto_cloudwatch_event.list_targets(Rule=rule_name, **conn_parameters)
self.assertNotEqual(result.get('error'), None)
|
'tests None when targets added'
| def test_that_when_putting_targets_succeeds_the_put_target_method_returns_no_failures(self):
| self.conn.put_targets.return_value = {'FailedEntryCount': 0}
result = boto_cloudwatch_event.put_targets(Rule=rule_name, Targets=[], **conn_parameters)
self.assertIsNone(result['failures'])
|
'tests False when thing type not created'
| def test_that_when_putting_targets_fails_the_put_targets_method_returns_error(self):
| self.conn.put_targets.side_effect = ClientError(error_content, 'put_targets')
result = boto_cloudwatch_event.put_targets(Rule=rule_name, Targets=[], **conn_parameters)
self.assertEqual(result.get('error', {}).get('message'), error_message.format('put_targets'))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.