def test_module_utils_basic_ansible_module_find_mount_point(self): from ansible.module_utils import basic basic._ANSIBLE_ARGS = None am = basic.AnsibleModule(argument_spec=dict(), ) def _mock_ismount(path): if path == b'/': return True return False with patch('os.path.ismount', side_effect=_mock_ismount): self.assertEqual( am.find_mount_point('/root/fs/../mounted/path/to/whatever'), '/') def _mock_ismount(path): if path == b'/subdir/mount': return True if path == b'/': return True return False with patch('os.path.ismount', side_effect=_mock_ismount): self.assertEqual( am.find_mount_point('/subdir/mount/path/to/whatever'), '/subdir/mount')
def test_module_utils_basic_ansible_module_selinux_enabled(self): from ansible.module_utils import basic basic._ANSIBLE_ARGS = None am = basic.AnsibleModule(argument_spec=dict(), ) # we first test the cases where the python selinux lib is # not installed, which has two paths: one in which the system # does have selinux installed (and the selinuxenabled command # is present and returns 0 when run), or selinux is not installed basic.HAVE_SELINUX = False am.get_bin_path = MagicMock() am.get_bin_path.return_value = '/path/to/selinuxenabled' am.run_command = MagicMock() am.run_command.return_value = (0, '', '') self.assertRaises(SystemExit, am.selinux_enabled) am.get_bin_path.return_value = None self.assertEqual(am.selinux_enabled(), False) # finally we test the case where the python selinux lib is installed, # and both possibilities there (enabled vs. disabled) basic.HAVE_SELINUX = True basic.selinux = Mock() with patch.dict('sys.modules', {'selinux': basic.selinux}): with patch('selinux.is_selinux_enabled', return_value=0): self.assertEqual(am.selinux_enabled(), False) with patch('selinux.is_selinux_enabled', return_value=1): self.assertEqual(am.selinux_enabled(), True) delattr(basic, 'selinux')
def test_not_linux(self): # if neither match, the fallback should be the top-level class with patch('platform.system', return_value="Foo"): with patch('ansible.module_utils.common.sys_info.get_distribution', return_value=None): assert isinstance(load_platform_subclass(self.LinuxTest), self.LinuxTest)
def test_module_utils_basic_ansible_module_selinux_context(self): from ansible.module_utils import basic basic._ANSIBLE_ARGS = None am = basic.AnsibleModule(argument_spec=dict(), ) am.selinux_initial_context = MagicMock( return_value=[None, None, None, None]) am.selinux_enabled = MagicMock(return_value=True) # we first test the cases where the python selinux lib is not installed basic.HAVE_SELINUX = False self.assertEqual(am.selinux_context(path='/foo/bar'), [None, None, None, None]) # all following tests assume the python selinux bindings are installed basic.HAVE_SELINUX = True basic.selinux = Mock() with patch.dict('sys.modules', {'selinux': basic.selinux}): # next, we test with a mocked implementation of selinux.lgetfilecon_raw to simulate # an actual context being found with patch('selinux.lgetfilecon_raw', return_value=[0, 'unconfined_u:object_r:default_t:s0']): self.assertEqual( am.selinux_context(path='/foo/bar'), ['unconfined_u', 'object_r', 'default_t', 's0']) # we also test the case where matchpathcon returned a failure with patch('selinux.lgetfilecon_raw', return_value=[-1, '']): self.assertEqual(am.selinux_context(path='/foo/bar'), [None, None, None, None]) # finally, we test where an OSError occurred during matchpathcon's call e = OSError() e.errno = errno.ENOENT with patch('selinux.lgetfilecon_raw', side_effect=e): self.assertRaises(SystemExit, am.selinux_context, path='/foo/bar') e = OSError() with patch('selinux.lgetfilecon_raw', side_effect=e): self.assertRaises(SystemExit, am.selinux_context, path='/foo/bar') delattr(basic, 'selinux')
def test_etc_lsb_release_no_decimal_release(self): module = self._mock_module() module.get_bin_path = Mock(return_value=None) with patch('ansible.module_utils.facts.system.lsb.os.path.exists', return_value=True): with patch('ansible.module_utils.facts.system.lsb.get_file_lines', return_value=etc_lsb_release_no_decimal.splitlines()): fact_collector = self.collector_class() facts_dict = fact_collector.collect(module=module) self.assertIsInstance(facts_dict, dict) self.assertEqual(facts_dict['lsb']['release'], '11') self.assertEqual(facts_dict['lsb']['id'], 'AwesomeOS') self.assertEqual(facts_dict['lsb']['description'], 'AwesomeÖS 11') self.assertEqual(facts_dict['lsb']['codename'], 'stonehenge')
def test_etc_lsb_release(self): module = self._mock_module() module.get_bin_path = Mock(return_value=None) with patch('ansible.module_utils.facts.system.lsb.os.path.exists', return_value=True): with patch('ansible.module_utils.facts.system.lsb.get_file_lines', return_value=etc_lsb_release_ubuntu14.splitlines()): fact_collector = self.collector_class() facts_dict = fact_collector.collect(module=module) self.assertIsInstance(facts_dict, dict) self.assertEqual(facts_dict['lsb']['release'], '14.04') self.assertEqual(facts_dict['lsb']['id'], 'Ubuntu') self.assertEqual(facts_dict['lsb']['description'], 'Ubuntu 14.04.3 LTS') self.assertEqual(facts_dict['lsb']['codename'], 'trusty')
def test_tmpdir_property(self, monkeypatch, args, expected, stat_exists): makedirs = {'called': False} def mock_mkdtemp(prefix, dir): return os.path.join(dir, prefix) def mock_makedirs(path, mode): makedirs['called'] = True makedirs['path'] = path makedirs['mode'] = mode return monkeypatch.setattr(tempfile, 'mkdtemp', mock_mkdtemp) monkeypatch.setattr(os.path, 'exists', lambda x: stat_exists) monkeypatch.setattr(os, 'makedirs', mock_makedirs) monkeypatch.setattr(shutil, 'rmtree', lambda x: None) monkeypatch.setattr(basic, '_ANSIBLE_ARGS', to_bytes(json.dumps({'ANSIBLE_MODULE_ARGS': args}))) with patch('time.time', return_value=42): am = basic.AnsibleModule(argument_spec={}) actual_tmpdir = am.tmpdir assert actual_tmpdir == expected # verify subsequent calls always produces the same tmpdir assert am.tmpdir == actual_tmpdir if not stat_exists: assert makedirs['called'] expected = os.path.expanduser(os.path.expandvars(am._remote_tmp)) assert makedirs['path'] == expected assert makedirs['mode'] == 0o700
def test_module_utils_basic_ansible_module_selinux_mls_enabled(self): from ansible.module_utils import basic basic._ANSIBLE_ARGS = None am = basic.AnsibleModule(argument_spec=dict(), ) basic.HAVE_SELINUX = False self.assertEqual(am.selinux_mls_enabled(), False) basic.HAVE_SELINUX = True basic.selinux = Mock() with patch.dict('sys.modules', {'selinux': basic.selinux}): with patch('selinux.is_selinux_mls_enabled', return_value=0): self.assertEqual(am.selinux_mls_enabled(), False) with patch('selinux.is_selinux_mls_enabled', return_value=1): self.assertEqual(am.selinux_mls_enabled(), True) delattr(basic, 'selinux')
def test_module_utils_basic_ansible_module_set_owner_if_different(self): from ansible.module_utils import basic basic._ANSIBLE_ARGS = None am = basic.AnsibleModule(argument_spec=dict(), ) self.assertEqual( am.set_owner_if_different('/path/to/file', None, True), True) self.assertEqual( am.set_owner_if_different('/path/to/file', None, False), False) am.user_and_group = MagicMock(return_value=(500, 500)) with patch('os.lchown', return_value=None) as m: self.assertEqual( am.set_owner_if_different('/path/to/file', 0, False), True) m.assert_called_with(b'/path/to/file', 0, -1) def _mock_getpwnam(*args, **kwargs): mock_pw = MagicMock() mock_pw.pw_uid = 0 return mock_pw m.reset_mock() with patch('pwd.getpwnam', side_effect=_mock_getpwnam): self.assertEqual( am.set_owner_if_different('/path/to/file', 'root', False), True) m.assert_called_with(b'/path/to/file', 0, -1) with patch('pwd.getpwnam', side_effect=KeyError): self.assertRaises(SystemExit, am.set_owner_if_different, '/path/to/file', 'root', False) m.reset_mock() am.check_mode = True self.assertEqual( am.set_owner_if_different('/path/to/file', 0, False), True) self.assertEqual(m.called, False) am.check_mode = False with patch('os.lchown', side_effect=OSError) as m: self.assertRaises(SystemExit, am.set_owner_if_different, '/path/to/file', 'root', False)
def setUp(self): self.mock_module = patch.multiple(basic.AnsibleModule, exit_json=exit_json, fail_json=fail_json) self.mock_module.start() self.mock_sleep = patch('time.sleep') self.mock_sleep.start() set_module_args({}) self.addCleanup(self.mock_module.stop) self.addCleanup(self.mock_sleep.stop)
def test_no_selinux(self): with patch('ansible.module_utils.facts.system.selinux.HAVE_SELINUX', False): module = self._mock_module() fact_collector = self.collector_class() facts_dict = fact_collector.collect(module=module) self.assertIsInstance(facts_dict, dict) self.assertEqual(facts_dict['selinux']['status'], 'Missing selinux Python library') return facts_dict
def setUp(self): super(TestNiosApi, self).setUp() self.module = MagicMock(name='AnsibleModule') self.module.check_mode = False self.module.params = {'provider': None} self.mock_connector = patch( 'ansible.module_utils.net_tools.nios.api.get_connector') self.mock_connector.start()
def test_module_utils_basic_ansible_module_user_and_group(self): from ansible.module_utils import basic basic._ANSIBLE_ARGS = None am = basic.AnsibleModule(argument_spec=dict(), ) mock_stat = MagicMock() mock_stat.st_uid = 0 mock_stat.st_gid = 0 with patch('os.lstat', return_value=mock_stat): self.assertEqual(am.user_and_group('/path/to/file'), (0, 0))
def setUp(self): self.patcher = patch('platform.system') mock_platform = self.patcher.start() mock_platform.return_value = 'OpenBSD' mock_module = self._mock_module() collectors = self._collectors(mock_module) fact_collector = \ ansible_collector.AnsibleFactCollector(collectors=collectors, namespace=ns) self.facts = fact_collector.collect(module=mock_module)
def test_validate_credentials_file(self): # TODO(supertom): Only dealing with p12 here, check the other states # of this function module = FakeModule() with mock.patch("ansible.module_utils.gcp.open", mock.mock_open(read_data='foobar'), create=True): # pem condition, warning is suppressed with the return_value credentials_file = '/foopath/pem.pem' with self.assertRaises(ValueError): _validate_credentials_file(module, credentials_file=credentials_file, require_valid_json=False, check_libcloud=False)
def test_distro_unknown(self): with patch('ansible.module_utils.distro.id', return_value=""): assert get_distribution() == "OtherLinux"
def test_distro_known(self): with patch('ansible.module_utils.distro.id', return_value="alpine"): assert get_distribution() == "Alpine" with patch('ansible.module_utils.distro.id', return_value="arch"): assert get_distribution() == "Arch" with patch('ansible.module_utils.distro.id', return_value="centos"): assert get_distribution() == "Centos" with patch('ansible.module_utils.distro.id', return_value="clear-linux-os"): assert get_distribution() == "Clear-linux-os" with patch('ansible.module_utils.distro.id', return_value="coreos"): assert get_distribution() == "Coreos" with patch('ansible.module_utils.distro.id', return_value="debian"): assert get_distribution() == "Debian" with patch('ansible.module_utils.distro.id', return_value="linuxmint"): assert get_distribution() == "Linuxmint" with patch('ansible.module_utils.distro.id', return_value="opensuse"): assert get_distribution() == "Opensuse" with patch('ansible.module_utils.distro.id', return_value="oracle"): assert get_distribution() == "Oracle" with patch('ansible.module_utils.distro.id', return_value="raspian"): assert get_distribution() == "Raspian" with patch('ansible.module_utils.distro.id', return_value="rhel"): assert get_distribution() == "Redhat" with patch('ansible.module_utils.distro.id', return_value="ubuntu"): assert get_distribution() == "Ubuntu" with patch('ansible.module_utils.distro.id', return_value="virtuozzo"): assert get_distribution() == "Virtuozzo" with patch('ansible.module_utils.distro.id', return_value="foo"): assert get_distribution() == "Foo"
def test_get_distribution_not_linux(): """If it's not Linux, then it has no distribution""" with patch('platform.system', return_value='Foo'): assert get_distribution() is None
def test_get_platform(): with patch('platform.system', return_value='foo'): assert get_platform() == 'foo'
def test_get_distribution_found(self): # match both the distribution and platform class with patch('ansible.module_utils.common.sys_info.get_distribution', return_value="Bar"): assert isinstance(load_platform_subclass(self.LinuxTest), self.Bar)
def test_get_distribution_none(self): # match just the platform class, not a specific distribution with patch('ansible.module_utils.common.sys_info.get_distribution', return_value=None): assert isinstance(load_platform_subclass(self.LinuxTest), self.Foo)
def test_module_utils_basic_ansible_module_set_context_if_different(self): from ansible.module_utils import basic basic._ANSIBLE_ARGS = None am = basic.AnsibleModule(argument_spec=dict(), ) basic.HAVE_SELINUX = False am.selinux_enabled = MagicMock(return_value=False) self.assertEqual( am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], True), True) self.assertEqual( am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], False), False) basic.HAVE_SELINUX = True am.selinux_enabled = MagicMock(return_value=True) am.selinux_context = MagicMock( return_value=['bar_u', 'bar_r', None, None]) am.is_special_selinux_path = MagicMock(return_value=(False, None)) basic.selinux = Mock() with patch.dict('sys.modules', {'selinux': basic.selinux}): with patch('selinux.lsetfilecon', return_value=0) as m: self.assertEqual( am.set_context_if_different( '/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], False), True) m.assert_called_with('/path/to/file', 'foo_u:foo_r:foo_t:s0') m.reset_mock() am.check_mode = True self.assertEqual( am.set_context_if_different( '/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], False), True) self.assertEqual(m.called, False) am.check_mode = False with patch('selinux.lsetfilecon', return_value=1) as m: self.assertRaises(SystemExit, am.set_context_if_different, '/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], True) with patch('selinux.lsetfilecon', side_effect=OSError) as m: self.assertRaises(SystemExit, am.set_context_if_different, '/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], True) am.is_special_selinux_path = MagicMock( return_value=(True, ['sp_u', 'sp_r', 'sp_t', 's0'])) with patch('selinux.lsetfilecon', return_value=0) as m: self.assertEqual( am.set_context_if_different( '/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], False), True) m.assert_called_with('/path/to/file', 'sp_u:sp_r:sp_t:s0') delattr(basic, 'selinux')
def test_distro_found(): with patch('ansible.module_utils.distro.version', return_value="1"): assert get_distribution_version() == "1"
def test_distro_amazon_linux_long(self): with patch('ansible.module_utils.distro.id', return_value="amazon"): assert get_distribution() == "Amazon"
def test_module_utils_basic_get_module_path(self): from ansible.module_utils.basic import get_module_path with patch('os.path.realpath', return_value='/path/to/foo/'): self.assertEqual(get_module_path(), '/path/to/foo')