Fix more crappy mocking

This commit is contained in:
Erik Johnson 2018-06-13 15:01:12 -05:00
parent 4eaa5789ce
commit 7427e192ba
No known key found for this signature in database
GPG key ID: 5E5583C437808F3F
5 changed files with 81 additions and 98 deletions

View file

@ -179,12 +179,12 @@ def persist(name, value, config='/etc/sysctl.conf', apply_change=False):
rest = rest[len(rest_v):]
if rest_v == value:
return 'Already set'
new_line = '{0}={1}'.format(name, value)
new_line = '{0}={1}\n'.format(name, value)
nlines.append(new_line)
nlines.append('\n')
edited = True
if not edited:
nlines.append('{0}={1}'.format(name, value))
nlines.append('{0}={1}\n'.format(name, value))
nlines.append('\n')
nlines = [salt.utils.stringutils.to_str(_l) for _l in nlines]
with salt.utils.files.fopen(config, 'w+') as ofile:

View file

@ -7,6 +7,7 @@
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import textwrap
# Import Salt Testing Libs
try:
@ -66,9 +67,8 @@ class CoreGrainsTestCase(TestCase, LoaderModuleMockMixin):
def test_parse_etc_os_release(self, path_isfile_mock):
path_isfile_mock.side_effect = lambda x: x == "/usr/lib/os-release"
with salt.utils.files.fopen(os.path.join(OS_RELEASE_DIR, "ubuntu-17.10")) as os_release_file:
os_release_content = os_release_file.readlines()
with patch("salt.utils.files.fopen", mock_open()) as os_release_file:
os_release_file.return_value.__iter__.return_value = os_release_content
os_release_content = os_release_file.read()
with patch("salt.utils.files.fopen", mock_open(read_data=os_release_content)):
os_release = core._parse_os_release(["/etc/os-release", "/usr/lib/os-release"])
self.assertEqual(os_release, {
"NAME": "Ubuntu",
@ -269,34 +269,26 @@ class CoreGrainsTestCase(TestCase, LoaderModuleMockMixin):
return orig_import(name, *args)
# Skip the first if statement
with patch.object(salt.utils.platform, 'is_proxy',
MagicMock(return_value=False)):
# Skip the selinux/systemd stuff (not pertinent)
with patch.object(core, '_linux_bin_exists',
MagicMock(return_value=False)):
# Skip the init grain compilation (not pertinent)
with patch.object(os.path, 'exists', path_isfile_mock):
# Ensure that lsb_release fails to import
with patch('{0}.__import__'.format(built_in),
side_effect=_import_mock):
# Skip all the /etc/*-release stuff (not pertinent)
with patch.object(os.path, 'isfile', path_isfile_mock):
with patch.object(core, '_parse_os_release', os_release_mock):
# Mock linux_distribution to give us the OS
# name that we want.
distro_mock = MagicMock(
return_value=os_release_map['linux_distribution']
)
with patch('salt.utils.files.fopen', mock_open()) as suse_release_file:
suse_release_file.return_value.__iter__.return_value = \
os_release_map.get('suse_release_file', '').splitlines()
with patch.object(core, 'linux_distribution', distro_mock):
with patch.object(core, '_linux_gpu_data', empty_mock):
with patch.object(core, '_linux_cpudata', empty_mock):
with patch.object(core, '_virtual', empty_mock):
# Mock the osarch
with patch.dict(core.__salt__, {'cmd.run': osarch_mock}):
os_grains = core.os_data()
# Skip the selinux/systemd stuff (not pertinent)
# Skip the init grain compilation (not pertinent)
# Ensure that lsb_release fails to import
# Skip all the /etc/*-release stuff (not pertinent)
# - Mock linux_distribution to give us the OS name that we want.
# Mock the osarch
distro_mock = MagicMock(return_value=os_release_map['linux_distribution'])
with patch.object(salt.utils.platform, 'is_proxy', MagicMock(return_value=False)), \
patch.object(core, '_linux_bin_exists', MagicMock(return_value=False)), \
patch.object(os.path, 'exists', path_isfile_mock), \
patch('{0}.__import__'.format(built_in), side_effect=_import_mock), \
patch.object(os.path, 'isfile', path_isfile_mock), \
patch.object(core, '_parse_os_release', os_release_mock), \
patch('salt.utils.files.fopen', mock_open(read_data=os_release_map.get('suse_release_file', ''))), \
patch.object(core, 'linux_distribution', distro_mock), \
patch.object(core, '_linux_gpu_data', empty_mock), \
patch.object(core, '_linux_cpudata', empty_mock), \
patch.object(core, '_virtual', empty_mock), \
patch.dict(core.__salt__, {'cmd.run': osarch_mock}):
os_grains = core.os_data()
grains = {k: v for k, v in os_grains.items()
if k in set(["os", "os_family", "osfullname", "oscodename", "osfinger",
@ -315,10 +307,11 @@ class CoreGrainsTestCase(TestCase, LoaderModuleMockMixin):
Test if OS grains are parsed correctly in SLES 11 SP3
'''
_os_release_map = {
'suse_release_file': '''SUSE Linux Enterprise Server 11 (x86_64)
VERSION = 11
PATCHLEVEL = 3
''',
'suse_release_file': textwrap.dedent('''
SUSE Linux Enterprise Server 11 (x86_64)
VERSION = 11
PATCHLEVEL = 3
'''),
'files': ["/etc/SuSE-release"],
}
expectation = {
@ -587,8 +580,9 @@ PATCHLEVEL = 3
)
empty_mock = MagicMock(return_value={})
_proc_meminfo_file = '''MemTotal: 16277028 kB
SwapTotal: 4789244 kB'''
_proc_meminfo = textwrap.dedent('''\
MemTotal: 16277028 kB
SwapTotal: 4789244 kB''')
orig_import = __import__
if six.PY2:
@ -601,49 +595,28 @@ SwapTotal: 4789244 kB'''
raise ImportError('No module named lsb_release')
return orig_import(name, *args)
# Skip the first if statement
with patch.object(salt.utils.platform, 'is_proxy',
MagicMock(return_value=False)):
# Skip the selinux/systemd stuff (not pertinent)
with patch.object(core, '_linux_bin_exists',
MagicMock(return_value=False)):
# Skip the init grain compilation (not pertinent)
with patch.object(os.path, 'exists', path_exists_mock):
# Ensure that lsb_release fails to import
with patch('{0}.__import__'.format(built_in),
side_effect=_import_mock):
# Skip all the /etc/*-release stuff (not pertinent)
with patch.object(os.path, 'isfile', path_isfile_mock):
# Make a bunch of functions return empty dicts,
# we don't care about these grains for the
# purposes of this test.
with patch.object(
core,
'_linux_cpudata',
empty_mock):
with patch.object(
core,
'_linux_gpu_data',
empty_mock):
with patch('salt.utils.files.fopen', mock_open()) as _proc_meminfo:
_proc_meminfo.return_value.__iter__.return_value = _proc_meminfo_file.splitlines()
with patch.object(
core,
'_hw_data',
empty_mock):
with patch.object(
core,
'_virtual',
empty_mock):
with patch.object(
core,
'_ps',
empty_mock):
# Mock the osarch
with patch.dict(
core.__salt__,
{'cmd.run': cmd_run_mock}):
os_grains = core.os_data()
# Mock a bunch of stuff so we can isolate the mem stuff:
# - Skip the first if statement
# - Skip the init grain compilation (not pertinent)
# - Ensure that lsb_release fails to import
# - Skip all the /etc/*-release stuff (not pertinent)
# - Make a bunch of functions return empty dicts, we don't care
# about these grains for the purposes of this test.
# - Mock the osarch
# - And most importantly, mock the contents of /proc/meminfo
with patch.object(salt.utils.platform, 'is_proxy', MagicMock(return_value=False)), \
patch.object(core, '_linux_bin_exists', MagicMock(return_value=False)), \
patch.object(os.path, 'exists', path_exists_mock), \
patch('{0}.__import__'.format(built_in), side_effect=_import_mock), \
patch.object(os.path, 'isfile', path_isfile_mock), \
patch.object(core, '_linux_cpudata', empty_mock), \
patch.object(core, '_linux_gpu_data', empty_mock), \
patch.object(core, '_hw_data', empty_mock), \
patch.object(core, '_virtual', empty_mock), \
patch.object(core, '_ps', empty_mock), \
patch.dict(core.__salt__, {'cmd.run': cmd_run_mock}), \
patch('salt.utils.files.fopen', mock_open(read_data=_proc_meminfo)):
os_grains = core.os_data()
self.assertEqual(os_grains.get('mem_total'), 15895)
self.assertEqual(os_grains.get('swap_total'), 4676)

View file

@ -5,6 +5,7 @@
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import textwrap
# Import Salt Testing Libs
from tests.support.unit import TestCase, skipIf
@ -51,15 +52,16 @@ class IscsiGrainsTestCase(TestCase):
['iqn.localhost.hostid.7f000001'])
def test_linux_iscsi_iqn_grains(self):
_iscsi_file = '## DO NOT EDIT OR REMOVE THIS FILE!\n' \
'## If you remove this file, the iSCSI daemon will not start.\n' \
'## If you change the InitiatorName, existing access control lists\n' \
'## may reject this initiator. The InitiatorName must be unique\n' \
'## for each iSCSI initiator. Do NOT duplicate iSCSI InitiatorNames.\n' \
'InitiatorName=iqn.1993-08.org.debian:01:d12f7aba36\n'
_iscsi_file = textwrap.dedent('''\
## DO NOT EDIT OR REMOVE THIS FILE!
## If you remove this file, the iSCSI daemon will not start.
## If you change the InitiatorName, existing access control lists
## may reject this initiator. The InitiatorName must be unique
## for each iSCSI initiator. Do NOT duplicate iSCSI InitiatorNames.
InitiatorName=iqn.1993-08.org.debian:01:d12f7aba36
''')
with patch('salt.utils.files.fopen', mock_open()) as iscsi_initiator_file:
iscsi_initiator_file.return_value.__iter__.return_value = _iscsi_file.splitlines()
with patch('salt.utils.files.fopen', mock_open(read_data=_iscsi_file)):
iqn = iscsi._linux_iqn()
assert isinstance(iqn, list)

View file

@ -5,6 +5,7 @@
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import textwrap
# Import Salt Testing Libs
from tests.support.mixins import LoaderModuleMockMixin
@ -98,13 +99,14 @@ class DnsmasqTestCase(TestCase, LoaderModuleMockMixin):
test for generic function for parsing dnsmasq files including includes.
'''
with patch('os.path.isfile', MagicMock(return_value=True)):
text_file_data = salt.utils.stringutils.to_str(
'\n'.join(["line here", "second line", "A=B", "#"]))
text_file_data = textwrap.dedent('''\
line here
second line
A=B
#''')
with patch('salt.utils.files.fopen',
mock_open(read_data=text_file_data),
create=True) as m:
m.return_value.__iter__.return_value = text_file_data.splitlines()
mock_open(read_data=text_file_data)):
self.assertDictEqual(dnsmasq._parse_dnamasq('filename'),
{'A': 'B',
'unparsed': ['line here',
'second line']})
'unparsed': ['line here\n',
'second line\n']})

View file

@ -91,7 +91,13 @@ class DarwinSysctlTestCase(TestCase, LoaderModuleMockMixin):
Tests successful write to existing sysctl file
'''
to_write = '#\n# Kernel sysctl configuration\n#\n'
m_calls_list = [call.writelines(['net.inet.icmp.icmplim=50', '\n'])]
m_calls_list = [call.writelines([
'#\n',
'# Kernel sysctl configuration\n',
'#\n',
'net.inet.icmp.icmplim=50\n',
'\n',
])]
with patch('salt.utils.files.fopen', mock_open(read_data=to_write)) as m_open, \
patch('os.path.isfile', MagicMock(return_value=True)):
mac_sysctl.persist('net.inet.icmp.icmplim', 50, config=to_write)