From 556ac5660c22eb8316bff03cc3ccec5c82005b7c Mon Sep 17 00:00:00 2001 From: "Chris St. Pierre" Date: Tue, 21 Aug 2012 17:06:35 -0400 Subject: removed context managers from unit tests --- .../TestClient/TestTools/TestPOSIX/TestDevice.py | 1 - .../TestTools/TestPOSIX/TestDirectory.py | 122 +++-- .../TestClient/TestTools/TestPOSIX/TestFile.py | 61 ++- .../TestClient/TestTools/TestPOSIX/TestHardlink.py | 1 - .../TestTools/TestPOSIX/TestNonexistent.py | 95 ++-- .../TestTools/TestPOSIX/TestPermissions.py | 6 - .../TestClient/TestTools/TestPOSIX/TestSymlink.py | 1 - .../TestClient/TestTools/TestPOSIX/Test__init.py | 140 +++--- .../TestClient/TestTools/TestPOSIX/Testbase.py | 494 ++++++++++----------- testsuite/Testlib/TestOptions.py | 1 - testsuite/Testlib/TestServer/TestPlugin.py | 90 ++-- .../Testlib/TestServer/TestPlugins/TestMetadata.py | 1 - .../Testlib/TestServer/TestPlugins/TestProbes.py | 7 +- testsuite/common.py | 4 +- 14 files changed, 508 insertions(+), 516 deletions(-) (limited to 'testsuite') diff --git a/testsuite/Testlib/TestClient/TestTools/TestPOSIX/TestDevice.py b/testsuite/Testlib/TestClient/TestTools/TestPOSIX/TestDevice.py index b737cfe1e..2a935fcbc 100644 --- a/testsuite/Testlib/TestClient/TestTools/TestPOSIX/TestDevice.py +++ b/testsuite/Testlib/TestClient/TestTools/TestPOSIX/TestDevice.py @@ -1,6 +1,5 @@ import os import copy -import unittest import lxml.etree from mock import Mock, MagicMock, patch from Bcfg2.Client.Tools.POSIX.Device import * diff --git a/testsuite/Testlib/TestClient/TestTools/TestPOSIX/TestDirectory.py b/testsuite/Testlib/TestClient/TestTools/TestPOSIX/TestDirectory.py index 79879afed..34d47d8d3 100644 --- a/testsuite/Testlib/TestClient/TestTools/TestPOSIX/TestDirectory.py +++ b/testsuite/Testlib/TestClient/TestTools/TestPOSIX/TestDirectory.py @@ -1,7 +1,6 @@ import os import stat import copy -import unittest import lxml.etree from mock import Mock, MagicMock, patch from Bcfg2.Client.Tools.POSIX.Directory import * @@ -12,81 +11,80 @@ from .....common import * class TestPOSIXDirectory(TestPOSIXTool): test_obj = POSIXDirectory + @patch("os.listdir") @patch("Bcfg2.Client.Tools.POSIX.base.POSIXTool.verify") @patch("Bcfg2.Client.Tools.POSIX.Directory.%s._exists" % test_obj.__name__) - def test_verify(self, mock_exists, mock_verify): + def test_verify(self, mock_exists, mock_verify, mock_listdir): entry = lxml.etree.Element("Path", name="/test", type="directory", perms='0644', owner='root', group='root') - ptool = self.get_obj() mock_exists.return_value = False - self.assertFalse(ptool.verify(entry, [])) + self.assertFalse(self.ptool.verify(entry, [])) mock_exists.assert_called_with(entry) mock_exists.reset_mock() exists_rv = MagicMock() exists_rv.__getitem__.return_value = stat.S_IFREG | 420 # 0o644 mock_exists.return_value = exists_rv - self.assertFalse(ptool.verify(entry, [])) + self.assertFalse(self.ptool.verify(entry, [])) mock_exists.assert_called_with(entry) mock_exists.reset_mock() mock_verify.return_value = False exists_rv.__getitem__.return_value = stat.S_IFDIR | 420 # 0o644 - self.assertFalse(ptool.verify(entry, [])) + self.assertFalse(self.ptool.verify(entry, [])) mock_exists.assert_called_with(entry) - mock_verify.assert_called_with(ptool, entry, []) + mock_verify.assert_called_with(self.ptool, entry, []) mock_exists.reset_mock() mock_verify.reset_mock() mock_verify.return_value = True - self.assertTrue(ptool.verify(entry, [])) + self.assertTrue(self.ptool.verify(entry, [])) mock_exists.assert_called_with(entry) - mock_verify.assert_called_with(ptool, entry, []) + mock_verify.assert_called_with(self.ptool, entry, []) - with patch("os.listdir") as mock_listdir: - mock_exists.reset_mock() - mock_verify.reset_mock() - entry.set("prune", "true") - orig_entry = copy.deepcopy(entry) + mock_exists.reset_mock() + mock_verify.reset_mock() + entry.set("prune", "true") + orig_entry = copy.deepcopy(entry) - entries = ["foo", "bar", "bar/baz"] - mock_listdir.return_value = entries - modlist = [os.path.join(entry.get("name"), entries[0])] - self.assertFalse(ptool.verify(entry, modlist)) - mock_exists.assert_called_with(entry) - mock_verify.assert_called_with(ptool, entry, modlist) - mock_listdir.assert_called_with(entry.get("name")) - expected = [os.path.join(entry.get("name"), e) - for e in entries - if os.path.join(entry.get("name"), e) not in modlist] - actual = [e.get("path") for e in entry.findall("Prune")] - self.assertItemsEqual(expected, actual) - - mock_verify.reset_mock() - mock_exists.reset_mock() - mock_listdir.reset_mock() - entry = copy.deepcopy(orig_entry) - modlist = [os.path.join(entry.get("name"), e) - for e in entries] - self.assertTrue(ptool.verify(entry, modlist)) - mock_exists.assert_called_with(entry) - mock_verify.assert_called_with(ptool, entry, modlist) - mock_listdir.assert_called_with(entry.get("name")) - self.assertEqual(len(entry.findall("Prune")), 0) + entries = ["foo", "bar", "bar/baz"] + mock_listdir.return_value = entries + modlist = [os.path.join(entry.get("name"), entries[0])] + self.assertFalse(self.ptool.verify(entry, modlist)) + mock_exists.assert_called_with(entry) + mock_verify.assert_called_with(self.ptool, entry, modlist) + mock_listdir.assert_called_with(entry.get("name")) + expected = [os.path.join(entry.get("name"), e) + for e in entries + if os.path.join(entry.get("name"), e) not in modlist] + actual = [e.get("path") for e in entry.findall("Prune")] + self.assertItemsEqual(expected, actual) + + mock_verify.reset_mock() + mock_exists.reset_mock() + mock_listdir.reset_mock() + entry = copy.deepcopy(orig_entry) + modlist = [os.path.join(entry.get("name"), e) + for e in entries] + self.assertTrue(self.ptool.verify(entry, modlist)) + mock_exists.assert_called_with(entry) + mock_verify.assert_called_with(self.ptool, entry, modlist) + mock_listdir.assert_called_with(entry.get("name")) + self.assertEqual(len(entry.findall("Prune")), 0) @patch("os.unlink") + @patch("os.path.isdir") @patch("shutil.rmtree") @patch("Bcfg2.Client.Tools.POSIX.base.POSIXTool.install") @patch("Bcfg2.Client.Tools.POSIX.Directory.%s._exists" % test_obj.__name__) @patch("Bcfg2.Client.Tools.POSIX.Directory.%s._makedirs" % test_obj.__name__) def test_install(self, mock_makedirs, mock_exists, mock_install, - mock_rmtree, mock_unlink): + mock_rmtree, mock_isdir, mock_unlink): entry = lxml.etree.Element("Path", name="/test/foo/bar", type="directory", perms='0644', owner='root', group='root') - ptool = self.get_obj() def reset(): mock_exists.reset_mock() @@ -98,32 +96,32 @@ class TestPOSIXDirectory(TestPOSIXTool): mock_makedirs.return_value = True mock_exists.return_value = False mock_install.return_value = True - self.assertTrue(ptool.install(entry)) + self.assertTrue(self.ptool.install(entry)) mock_exists.assert_called_with(entry) - mock_install.assert_called_with(ptool, entry) + mock_install.assert_called_with(self.ptool, entry) mock_makedirs.assert_called_with(entry) reset() exists_rv = MagicMock() exists_rv.__getitem__.return_value = stat.S_IFREG | 420 # 0o644 mock_exists.return_value = exists_rv - self.assertTrue(ptool.install(entry)) + self.assertTrue(self.ptool.install(entry)) mock_unlink.assert_called_with(entry.get("name")) mock_exists.assert_called_with(entry) mock_makedirs.assert_called_with(entry) - mock_install.assert_called_with(ptool, entry) + mock_install.assert_called_with(self.ptool, entry) reset() exists_rv.__getitem__.return_value = stat.S_IFDIR | 420 # 0o644 mock_install.return_value = True - self.assertTrue(ptool.install(entry)) + self.assertTrue(self.ptool.install(entry)) mock_exists.assert_called_with(entry) - mock_install.assert_called_with(ptool, entry) + mock_install.assert_called_with(self.ptool, entry) reset() mock_install.return_value = False - self.assertFalse(ptool.install(entry)) - mock_install.assert_called_with(ptool, entry) + self.assertFalse(self.ptool.install(entry)) + mock_install.assert_called_with(self.ptool, entry) entry.set("prune", "true") prune = ["/test/foo/bar/prune1", "/test/foo/bar/prune2"] @@ -132,17 +130,17 @@ class TestPOSIXDirectory(TestPOSIXTool): reset() mock_install.return_value = True - with patch("os.path.isdir") as mock_isdir: - def isdir_rv(path): - if path.endswith("prune2"): - return True - else: - return False - mock_isdir.side_effect = isdir_rv - self.assertTrue(ptool.install(entry)) - mock_exists.assert_called_with(entry) - mock_install.assert_called_with(ptool, entry) - self.assertItemsEqual(mock_isdir.call_args_list, - [call(p) for p in prune]) - mock_unlink.assert_called_with("/test/foo/bar/prune1") - mock_rmtree.assert_called_with("/test/foo/bar/prune2") + + def isdir_rv(path): + if path.endswith("prune2"): + return True + else: + return False + mock_isdir.side_effect = isdir_rv + self.assertTrue(self.ptool.install(entry)) + mock_exists.assert_called_with(entry) + mock_install.assert_called_with(self.ptool, entry) + self.assertItemsEqual(mock_isdir.call_args_list, + [call(p) for p in prune]) + mock_unlink.assert_called_with("/test/foo/bar/prune1") + mock_rmtree.assert_called_with("/test/foo/bar/prune2") diff --git a/testsuite/Testlib/TestClient/TestTools/TestPOSIX/TestFile.py b/testsuite/Testlib/TestClient/TestTools/TestPOSIX/TestFile.py index 084268959..51deeeb52 100644 --- a/testsuite/Testlib/TestClient/TestTools/TestPOSIX/TestFile.py +++ b/testsuite/Testlib/TestClient/TestTools/TestPOSIX/TestFile.py @@ -3,7 +3,6 @@ import os import copy import difflib import binascii -import unittest import lxml.etree from Bcfg2.Bcfg2Py3k import b64encode, b64decode from mock import Mock, MagicMock, patch @@ -22,30 +21,28 @@ class TestPOSIXFile(TestPOSIXTool): def test_fully_specified(self): entry = lxml.etree.Element("Path", name="/test", type="file") - ptool = self.get_obj() - self.assertFalse(ptool.fully_specified(entry)) + self.assertFalse(self.ptool.fully_specified(entry)) entry.set("empty", "true") - self.assertTrue(ptool.fully_specified(entry)) + self.assertTrue(self.ptool.fully_specified(entry)) entry.set("empty", "false") entry.text = "text" - self.assertTrue(ptool.fully_specified(entry)) + self.assertTrue(self.ptool.fully_specified(entry)) def test_is_string(self): - ptool = self.get_obj() for char in list(range(8)) + list(range(14, 32)): - self.assertFalse(ptool._is_string("foo" + chr(char) + "bar", + self.assertFalse(self.ptool._is_string("foo" + chr(char) + "bar", 'UTF-8')) for char in list(range(9, 14)) + list(range(33, 128)): - self.assertTrue(ptool._is_string("foo" + chr(char) + "bar", + self.assertTrue(self.ptool._is_string("foo" + chr(char) + "bar", 'UTF-8')) ustr = 'é' - self.assertTrue(ptool._is_string(ustr, 'UTF-8')) + self.assertTrue(self.ptool._is_string(ustr, 'UTF-8')) if not inPy3k: - self.assertFalse(ptool._is_string("foo" + chr(128) + "bar", + self.assertFalse(self.ptool._is_string("foo" + chr(128) + "bar", 'ascii')) - self.assertFalse(ptool._is_string(ustr, 'ascii')) + self.assertFalse(self.ptool._is_string(ustr, 'ascii')) def test_get_data(self): orig_entry = lxml.etree.Element("Path", name="/test", type="file") @@ -154,7 +151,6 @@ class TestPOSIXFile(TestPOSIXTool): def test_write_tmpfile(self, mock_get_data, mock_mkstemp, mock_fdopen): entry = lxml.etree.Element("Path", name="/test", type="file", perms='0644', owner='root', group='root') - ptool = self.get_obj() newfile = "/foo/bar" def reset(): @@ -164,7 +160,7 @@ class TestPOSIXFile(TestPOSIXTool): mock_get_data.return_value = ("test", False) mock_mkstemp.return_value = (5, newfile) - self.assertEqual(ptool._write_tmpfile(entry), newfile) + self.assertEqual(self.ptool._write_tmpfile(entry), newfile) mock_get_data.assert_called_with(entry) mock_mkstemp.assert_called_with(prefix='test', dir='/') mock_fdopen.assert_called_with(5, 'w') @@ -172,13 +168,13 @@ class TestPOSIXFile(TestPOSIXTool): reset() mock_mkstemp.side_effect = OSError - self.assertFalse(ptool._write_tmpfile(entry)) + self.assertFalse(self.ptool._write_tmpfile(entry)) mock_mkstemp.assert_called_with(prefix='test', dir='/') reset() mock_mkstemp.side_effect = None mock_fdopen.side_effect = OSError - self.assertFalse(ptool._write_tmpfile(entry)) + self.assertFalse(self.ptool._write_tmpfile(entry)) mock_mkstemp.assert_called_with(prefix='test', dir='/') mock_get_data.assert_called_with(entry) mock_fdopen.assert_called_with(5, 'w') @@ -188,16 +184,15 @@ class TestPOSIXFile(TestPOSIXTool): def test_rename_tmpfile(self, mock_unlink, mock_rename): entry = lxml.etree.Element("Path", name="/test", type="file", perms='0644', owner='root', group='root') - ptool = self.get_obj() newfile = "/foo/bar" - self.assertTrue(ptool._rename_tmpfile(newfile, entry)) + self.assertTrue(self.ptool._rename_tmpfile(newfile, entry)) mock_rename.assert_called_with(newfile, entry.get("name")) mock_rename.reset_mock() mock_unlink.reset_mock() mock_rename.side_effect = OSError - self.assertFalse(ptool._rename_tmpfile(newfile, entry)) + self.assertFalse(self.ptool._rename_tmpfile(newfile, entry)) mock_rename.assert_called_with(newfile, entry.get("name")) mock_unlink.assert_called_with(newfile) @@ -205,7 +200,7 @@ class TestPOSIXFile(TestPOSIXTool): mock_rename.reset_mock() mock_unlink.reset_mock() mock_unlink.side_effect = OSError - self.assertFalse(ptool._rename_tmpfile(newfile, entry)) + self.assertFalse(self.ptool._rename_tmpfile(newfile, entry)) mock_rename.assert_called_with(newfile, entry.get("name")) mock_unlink.assert_called_with(newfile) @@ -334,7 +329,6 @@ class TestPOSIXFile(TestPOSIXTool): mock_makedirs, mock_install, mock_exists): entry = lxml.etree.Element("Path", name="/test", type="file", perms='0644', owner='root', group='root') - ptool = self.get_obj() def reset(): mock_rename.reset_mock() @@ -346,14 +340,14 @@ class TestPOSIXFile(TestPOSIXTool): mock_exists.return_value = False mock_makedirs.return_value = False - self.assertFalse(ptool.install(entry)) + self.assertFalse(self.ptool.install(entry)) mock_exists.assert_called_with("/") mock_makedirs.assert_called_with(entry, path="/") reset() mock_makedirs.return_value = True mock_write.return_value = False - self.assertFalse(ptool.install(entry)) + self.assertFalse(self.ptool.install(entry)) mock_exists.assert_called_with("/") mock_makedirs.assert_called_with(entry, path="/") mock_write.assert_called_with(entry) @@ -363,7 +357,7 @@ class TestPOSIXFile(TestPOSIXTool): mock_write.return_value = newfile mock_set_perms.return_value = False mock_rename.return_value = False - self.assertFalse(ptool.install(entry)) + self.assertFalse(self.ptool.install(entry)) mock_exists.assert_called_with("/") mock_makedirs.assert_called_with(entry, path="/") mock_write.assert_called_with(entry) @@ -373,52 +367,51 @@ class TestPOSIXFile(TestPOSIXTool): reset() mock_rename.return_value = True mock_install.return_value = False - self.assertFalse(ptool.install(entry)) + self.assertFalse(self.ptool.install(entry)) mock_exists.assert_called_with("/") mock_makedirs.assert_called_with(entry, path="/") mock_write.assert_called_with(entry) mock_set_perms.assert_called_with(entry, path=newfile) mock_rename.assert_called_with(newfile, entry) - mock_install.assert_called_with(ptool, entry) + mock_install.assert_called_with(self.ptool, entry) reset() mock_install.return_value = True - self.assertFalse(ptool.install(entry)) + self.assertFalse(self.ptool.install(entry)) mock_exists.assert_called_with("/") mock_makedirs.assert_called_with(entry, path="/") mock_write.assert_called_with(entry) mock_set_perms.assert_called_with(entry, path=newfile) mock_rename.assert_called_with(newfile, entry) - mock_install.assert_called_with(ptool, entry) + mock_install.assert_called_with(self.ptool, entry) reset() mock_set_perms.return_value = True - self.assertTrue(ptool.install(entry)) + self.assertTrue(self.ptool.install(entry)) mock_exists.assert_called_with("/") mock_makedirs.assert_called_with(entry, path="/") mock_write.assert_called_with(entry) mock_set_perms.assert_called_with(entry, path=newfile) mock_rename.assert_called_with(newfile, entry) - mock_install.assert_called_with(ptool, entry) + mock_install.assert_called_with(self.ptool, entry) reset() mock_exists.return_value = True - self.assertTrue(ptool.install(entry)) + self.assertTrue(self.ptool.install(entry)) mock_exists.assert_called_with("/") self.assertFalse(mock_makedirs.called) mock_write.assert_called_with(entry) mock_set_perms.assert_called_with(entry, path=newfile) mock_rename.assert_called_with(newfile, entry) - mock_install.assert_called_with(ptool, entry) + mock_install.assert_called_with(self.ptool, entry) def test_diff(self): - ptool = self.get_obj() content1 = "line1\nline2" content2 = "line3" rv = ["line1", "line2", "line3"] func = Mock() func.return_value = rv - self.assertItemsEqual(ptool._diff(content1, content2, func), rv) + self.assertItemsEqual(self.ptool._diff(content1, content2, func), rv) func.assert_called_with(["line1", "line2"], ["line3"]) func.reset_mock() @@ -427,5 +420,5 @@ class TestPOSIXFile(TestPOSIXTool): time.sleep(5) yield "line%s" % i func.side_effect = slow_diff - self.assertFalse(ptool._diff(content1, content2, func), rv) + self.assertFalse(self.ptool._diff(content1, content2, func), rv) func.assert_called_with(["line1", "line2"], ["line3"]) diff --git a/testsuite/Testlib/TestClient/TestTools/TestPOSIX/TestHardlink.py b/testsuite/Testlib/TestClient/TestTools/TestPOSIX/TestHardlink.py index 221da9ea5..ae48bf04e 100644 --- a/testsuite/Testlib/TestClient/TestTools/TestPOSIX/TestHardlink.py +++ b/testsuite/Testlib/TestClient/TestTools/TestPOSIX/TestHardlink.py @@ -1,6 +1,5 @@ import os import copy -import unittest import lxml.etree from mock import Mock, MagicMock, patch from Bcfg2.Client.Tools.POSIX.Hardlink import * diff --git a/testsuite/Testlib/TestClient/TestTools/TestPOSIX/TestNonexistent.py b/testsuite/Testlib/TestClient/TestTools/TestPOSIX/TestNonexistent.py index 2b46bd9e6..fbd9a11ad 100644 --- a/testsuite/Testlib/TestClient/TestTools/TestPOSIX/TestNonexistent.py +++ b/testsuite/Testlib/TestClient/TestTools/TestPOSIX/TestNonexistent.py @@ -1,6 +1,5 @@ import os import copy -import unittest import lxml.etree from mock import Mock, MagicMock, patch from Bcfg2.Client.Tools.POSIX.Nonexistent import * @@ -14,68 +13,66 @@ class TestPOSIXNonexistent(TestPOSIXTool): @patch("os.path.lexists") def test_verify(self, mock_lexists): entry = lxml.etree.Element("Path", name="/test", type="nonexistent") - ptool = self.get_obj() for val in [True, False]: mock_lexists.reset_mock() mock_lexists.return_value = val - self.assertEqual(ptool.verify(entry, []), not val) + self.assertEqual(self.ptool.verify(entry, []), not val) mock_lexists.assert_called_with(entry.get("name")) @patch("os.rmdir") @patch("os.remove") + @patch("os.path.isdir") @patch("shutil.rmtree") - def test_install(self, mock_rmtree, mock_remove, mock_rmdir): + def test_install(self, mock_rmtree, mock_isdir, mock_remove, mock_rmdir): entry = lxml.etree.Element("Path", name="/test", type="nonexistent") - ptool = self.get_obj() - with patch("os.path.isdir") as mock_isdir: - def reset(): - mock_isdir.reset_mock() - mock_remove.reset_mock() - mock_rmdir.reset_mock() - mock_rmtree.reset_mock() + def reset(): + mock_isdir.reset_mock() + mock_remove.reset_mock() + mock_rmdir.reset_mock() + mock_rmtree.reset_mock() - mock_isdir.return_value = False - self.assertTrue(ptool.install(entry)) - mock_remove.assert_called_with(entry.get("name")) + mock_isdir.return_value = False + self.assertTrue(self.ptool.install(entry)) + mock_remove.assert_called_with(entry.get("name")) - reset() - mock_remove.side_effect = OSError - self.assertFalse(ptool.install(entry)) - mock_remove.assert_called_with(entry.get("name")) + reset() + mock_remove.side_effect = OSError + self.assertFalse(self.ptool.install(entry)) + mock_remove.assert_called_with(entry.get("name")) - reset() - mock_isdir.return_value = True - self.assertTrue(ptool.install(entry)) - mock_rmdir.assert_called_with(entry.get("name")) + reset() + mock_isdir.return_value = True + self.assertTrue(self.ptool.install(entry)) + mock_rmdir.assert_called_with(entry.get("name")) - reset() - mock_rmdir.side_effect = OSError - self.assertFalse(ptool.install(entry)) - mock_rmdir.assert_called_with(entry.get("name")) - - reset() - entry.set("recursive", "true") - self.assertTrue(ptool.install(entry)) - mock_rmtree.assert_called_with(entry.get("name")) + reset() + mock_rmdir.side_effect = OSError + self.assertFalse(self.ptool.install(entry)) + mock_rmdir.assert_called_with(entry.get("name")) - reset() - mock_rmtree.side_effect = OSError - self.assertFalse(ptool.install(entry)) - mock_rmtree.assert_called_with(entry.get("name")) - - reset() - child_entry = lxml.etree.Element("Path", name="/test/foo", - type="nonexistent") - ptool = self.get_obj(posix=get_posix_object(config=get_config([child_entry]))) - mock_rmtree.side_effect = None - self.assertTrue(ptool.install(entry)) - mock_rmtree.assert_called_with(entry.get("name")) + reset() + entry.set("recursive", "true") + self.assertTrue(self.ptool.install(entry)) + mock_rmtree.assert_called_with(entry.get("name")) - reset() - child_entry = lxml.etree.Element("Path", name="/test/foo", - type="file") - ptool = self.get_obj(posix=get_posix_object(config=get_config([child_entry]))) - mock_rmtree.side_effect = None - self.assertFalse(ptool.install(entry)) + reset() + mock_rmtree.side_effect = OSError + self.assertFalse(self.ptool.install(entry)) + mock_rmtree.assert_called_with(entry.get("name")) + + reset() + child_entry = lxml.etree.Element("Path", name="/test/foo", + type="nonexistent") + ptool = self.get_obj(posix=get_posix_object(config=get_config([child_entry]))) + mock_rmtree.side_effect = None + self.assertTrue(ptool.install(entry)) + mock_rmtree.assert_called_with(entry.get("name")) + + reset() + child_entry = lxml.etree.Element("Path", name="/test/foo", + type="file") + ptool = self.get_obj(posix=get_posix_object(config=get_config([child_entry]))) + mock_rmtree.side_effect = None + self.assertFalse(ptool.install(entry)) diff --git a/testsuite/Testlib/TestClient/TestTools/TestPOSIX/TestPermissions.py b/testsuite/Testlib/TestClient/TestTools/TestPOSIX/TestPermissions.py index 008f0c839..a9b71ec2c 100644 --- a/testsuite/Testlib/TestClient/TestTools/TestPOSIX/TestPermissions.py +++ b/testsuite/Testlib/TestClient/TestTools/TestPOSIX/TestPermissions.py @@ -1,11 +1,5 @@ -import os -import unittest -import lxml.etree -from mock import Mock, MagicMock, patch from Bcfg2.Client.Tools.POSIX.Permissions import * -from .Test__init import get_posix_object from .Testbase import TestPOSIXTool -from .....common import * class TestPOSIXPermissions(TestPOSIXTool): test_obj = POSIXPermissions diff --git a/testsuite/Testlib/TestClient/TestTools/TestPOSIX/TestSymlink.py b/testsuite/Testlib/TestClient/TestTools/TestPOSIX/TestSymlink.py index 7ce8a4437..2cd10f243 100644 --- a/testsuite/Testlib/TestClient/TestTools/TestPOSIX/TestSymlink.py +++ b/testsuite/Testlib/TestClient/TestTools/TestPOSIX/TestSymlink.py @@ -1,6 +1,5 @@ import os import copy -import unittest import lxml.etree from mock import Mock, MagicMock, patch from Bcfg2.Client.Tools.POSIX.Symlink import * diff --git a/testsuite/Testlib/TestClient/TestTools/TestPOSIX/Test__init.py b/testsuite/Testlib/TestClient/TestTools/TestPOSIX/Test__init.py index e55ab4410..20577a6da 100644 --- a/testsuite/Testlib/TestClient/TestTools/TestPOSIX/Test__init.py +++ b/testsuite/Testlib/TestClient/TestTools/TestPOSIX/Test__init.py @@ -1,5 +1,4 @@ import os -import unittest import lxml.etree from mock import Mock, MagicMock, patch import Bcfg2.Client.Tools @@ -29,105 +28,110 @@ def get_posix_object(logger=None, setup=None, config=None): class TestPOSIX(Bcfg2TestCase): + def setUp(self): + self.posix = get_posix_object() + + def tearDown(self): + # just to guarantee that we start fresh each time + self.posix = None + def test__init(self): entries = [lxml.etree.Element("Path", name="test", type="file")] - p = get_posix_object(config=get_config(entries)) - self.assertIsInstance(p, Bcfg2.Client.Tools.Tool) - self.assertIsInstance(p, Bcfg2.Client.Tools.POSIX.POSIX) - self.assertIn('Path', p.__req__) - self.assertGreater(len(p.__req__['Path']), 0) - self.assertGreater(len(p.__handles__), 0) - self.assertItemsEqual(p.handled, entries) + posix = get_posix_object(config=get_config(entries)) + self.assertIsInstance(posix, Bcfg2.Client.Tools.Tool) + self.assertIsInstance(posix, Bcfg2.Client.Tools.POSIX.POSIX) + self.assertIn('Path', posix.__req__) + self.assertGreater(len(posix.__req__['Path']), 0) + self.assertGreater(len(posix.__handles__), 0) + self.assertItemsEqual(posix.handled, entries) @patch("Bcfg2.Client.Tools.Tool.canVerify") def test_canVerify(self, mock_canVerify): entry = lxml.etree.Element("Path", name="test", type="file") - p = get_posix_object() # first, test superclass canVerify failure mock_canVerify.return_value = False - self.assertFalse(p.canVerify(entry)) - mock_canVerify.assert_called_with(p, entry) + self.assertFalse(self.posix.canVerify(entry)) + mock_canVerify.assert_called_with(self.posix, entry) # next, test fully_specified failure - p.logger.error.reset_mock() + self.posix.logger.error.reset_mock() mock_canVerify.reset_mock() mock_canVerify.return_value = True mock_fully_spec = Mock() mock_fully_spec.return_value = False - p._handlers[entry.get("type")].fully_specified = mock_fully_spec - self.assertFalse(p.canVerify(entry)) - mock_canVerify.assert_called_with(p, entry) + self.posix._handlers[entry.get("type")].fully_specified = \ + mock_fully_spec + self.assertFalse(self.posix.canVerify(entry)) + mock_canVerify.assert_called_with(self.posix, entry) mock_fully_spec.assert_called_with(entry) - self.assertTrue(p.logger.error.called) + self.assertTrue(self.posix.logger.error.called) # finally, test success - p.logger.error.reset_mock() + self.posix.logger.error.reset_mock() mock_canVerify.reset_mock() mock_fully_spec.reset_mock() mock_fully_spec.return_value = True - self.assertTrue(p.canVerify(entry)) - mock_canVerify.assert_called_with(p, entry) + self.assertTrue(self.posix.canVerify(entry)) + mock_canVerify.assert_called_with(self.posix, entry) mock_fully_spec.assert_called_with(entry) - self.assertFalse(p.logger.error.called) + self.assertFalse(self.posix.logger.error.called) @patch("Bcfg2.Client.Tools.Tool.canInstall") def test_canInstall(self, mock_canInstall): entry = lxml.etree.Element("Path", name="test", type="file") - p = get_posix_object() # first, test superclass canInstall failure mock_canInstall.return_value = False - self.assertFalse(p.canInstall(entry)) - mock_canInstall.assert_called_with(p, entry) + self.assertFalse(self.posix.canInstall(entry)) + mock_canInstall.assert_called_with(self.posix, entry) # next, test fully_specified failure - p.logger.error.reset_mock() + self.posix.logger.error.reset_mock() mock_canInstall.reset_mock() mock_canInstall.return_value = True mock_fully_spec = Mock() mock_fully_spec.return_value = False - p._handlers[entry.get("type")].fully_specified = mock_fully_spec - self.assertFalse(p.canInstall(entry)) - mock_canInstall.assert_called_with(p, entry) + self.posix._handlers[entry.get("type")].fully_specified = \ + mock_fully_spec + self.assertFalse(self.posix.canInstall(entry)) + mock_canInstall.assert_called_with(self.posix, entry) mock_fully_spec.assert_called_with(entry) - self.assertTrue(p.logger.error.called) + self.assertTrue(self.posix.logger.error.called) # finally, test success - p.logger.error.reset_mock() + self.posix.logger.error.reset_mock() mock_canInstall.reset_mock() mock_fully_spec.reset_mock() mock_fully_spec.return_value = True - self.assertTrue(p.canInstall(entry)) - mock_canInstall.assert_called_with(p, entry) + self.assertTrue(self.posix.canInstall(entry)) + mock_canInstall.assert_called_with(self.posix, entry) mock_fully_spec.assert_called_with(entry) - self.assertFalse(p.logger.error.called) + self.assertFalse(self.posix.logger.error.called) def test_InstallPath(self): entry = lxml.etree.Element("Path", name="test", type="file") - p = get_posix_object() mock_install = Mock() mock_install.return_value = True - p._handlers[entry.get("type")].install = mock_install - self.assertTrue(p.InstallPath(entry)) + self.posix._handlers[entry.get("type")].install = mock_install + self.assertTrue(self.posix.InstallPath(entry)) mock_install.assert_called_with(entry) def test_VerifyPath(self): entry = lxml.etree.Element("Path", name="test", type="file") modlist = [] - p = get_posix_object() mock_verify = Mock() mock_verify.return_value = True - p._handlers[entry.get("type")].verify = mock_verify - self.assertTrue(p.VerifyPath(entry, modlist)) + self.posix._handlers[entry.get("type")].verify = mock_verify + self.assertTrue(self.posix.VerifyPath(entry, modlist)) mock_verify.assert_called_with(entry, modlist) mock_verify.reset_mock() mock_verify.return_value = False - p.setup.__getitem__.return_value = True - self.assertFalse(p.VerifyPath(entry, modlist)) + self.posix.setup.__getitem__.return_value = True + self.assertFalse(self.posix.VerifyPath(entry, modlist)) self.assertIsNotNone(entry.get('qtext')) @patch('os.remove') @@ -147,7 +151,8 @@ class TestPOSIX(Bcfg2TestCase): "_etc_test_2011-08-07T04:13:22.519978", "_etc_foo_2012-08-07T04:13:22.519978",] - with patch('os.listdir') as mock_listdir: + @patch('os.listdir') + def inner(mock_listdir): mock_listdir.side_effect = OSError posix._prune_old_backups(entry) self.assertTrue(posix.logger.error.called) @@ -178,9 +183,12 @@ class TestPOSIX(Bcfg2TestCase): for p in remove]) self.assertTrue(posix.logger.error.called) + inner() + @patch("shutil.copy") + @patch("os.path.isdir") @patch("Bcfg2.Client.Tools.POSIX.POSIX._prune_old_backups") - def test_paranoid_backup(self, mock_prune, mock_copy): + def test_paranoid_backup(self, mock_prune, mock_isdir, mock_copy): entry = lxml.etree.Element("Path", name="/etc/foo", type="file") setup = dict(ppath='/', max_copies=5, paranoid=False) posix = get_posix_object(setup=setup) @@ -206,28 +214,26 @@ class TestPOSIX(Bcfg2TestCase): self.assertFalse(mock_prune.called) self.assertFalse(mock_copy.called) - with patch("os.path.isdir") as mock_isdir: - # entry is a directory on the filesystem - mock_prune.reset_mock() - entry.set("current_exists", "true") - mock_isdir.return_value = True - posix._paranoid_backup(entry) - self.assertFalse(mock_prune.called) - self.assertFalse(mock_copy.called) - mock_isdir.assert_called_with(entry.get("name")) - - # test the actual backup now - mock_prune.reset_mock() - mock_isdir.return_value = False - posix._paranoid_backup(entry) - mock_isdir.assert_called_with(entry.get("name")) - mock_prune.assert_called_with(entry) - # it's basically impossible to test the shutil.copy() call - # exactly because the destination includes microseconds, - # so we just test it good enough - self.assertEqual(mock_copy.call_args[0][0], - entry.get("name")) - bkupnam = os.path.join(setup['ppath'], - entry.get('name').replace('/', '_')) + '_' - self.assertEqual(bkupnam, - mock_copy.call_args[0][1][:len(bkupnam)]) + # entry is a directory on the filesystem + mock_prune.reset_mock() + entry.set("current_exists", "true") + mock_isdir.return_value = True + posix._paranoid_backup(entry) + self.assertFalse(mock_prune.called) + self.assertFalse(mock_copy.called) + mock_isdir.assert_called_with(entry.get("name")) + + # test the actual backup now + mock_prune.reset_mock() + mock_isdir.return_value = False + posix._paranoid_backup(entry) + mock_isdir.assert_called_with(entry.get("name")) + mock_prune.assert_called_with(entry) + # it's basically impossible to test the shutil.copy() call + # exactly because the destination includes microseconds, so we + # just test it good enough + self.assertEqual(mock_copy.call_args[0][0], + entry.get("name")) + bkupnam = os.path.join(setup['ppath'], + entry.get('name').replace('/', '_')) + '_' + self.assertEqual(bkupnam, mock_copy.call_args[0][1][:len(bkupnam)]) diff --git a/testsuite/Testlib/TestClient/TestTools/TestPOSIX/Testbase.py b/testsuite/Testlib/TestClient/TestTools/TestPOSIX/Testbase.py index e8e5dbe23..e7772d508 100644 --- a/testsuite/Testlib/TestClient/TestTools/TestPOSIX/Testbase.py +++ b/testsuite/Testlib/TestClient/TestTools/TestPOSIX/Testbase.py @@ -1,7 +1,6 @@ import os import copy import stat -import unittest import lxml.etree from mock import Mock, MagicMock, patch import Bcfg2.Client.Tools @@ -29,137 +28,140 @@ class TestPOSIXTool(Bcfg2TestCase): posix = get_posix_object() return self.test_obj(posix.logger, posix.setup, posix.config) + def setUp(self): + self.ptool = self.get_obj() + + def tearDown(self): + # just to guarantee that we start fresh each time + self.ptool = None + def test_fully_specified(self): # fully_specified should do no checking on the abstract # POSIXTool object - ptool = self.get_obj() - self.assertTrue(ptool.fully_specified(Mock())) + self.assertTrue(self.ptool.fully_specified(Mock())) + @patch('os.stat') + @patch('os.walk') @patch("Bcfg2.Client.Tools.POSIX.base.%s._verify_metadata" % test_obj.__name__) - def test_verify(self, mock_verify): + def test_verify(self, mock_verify, mock_walk, mock_stat): entry = lxml.etree.Element("Path", name="/test", type="file") - ptool = self.get_obj() - with patch('os.stat') as mock_stat, patch('os.walk') as mock_walk: - mock_stat.return_value = MagicMock() - - mock_verify.return_value = False - self.assertFalse(ptool.verify(entry, [])) - mock_verify.assert_called_with(entry) - - mock_verify.reset_mock() - mock_verify.return_value = True - self.assertTrue(ptool.verify(entry, [])) - mock_verify.assert_called_with(entry) - - mock_verify.reset_mock() - entry.set("recursive", "true") - walk_rv = [("/", ["dir1", "dir2"], ["file1", "file2"]), - ("/dir1", ["dir3"], []), - ("/dir2", [], ["file3", "file4"])] - mock_walk.return_value = walk_rv - self.assertTrue(ptool.verify(entry, [])) - mock_walk.assert_called_with(entry.get("name")) - all_verifies = [call(entry)] - for root, dirs, files in walk_rv: - all_verifies.extend([call(entry, path=os.path.join(root, p)) - for p in dirs + files]) - self.assertItemsEqual(mock_verify.call_args_list, all_verifies) - + + mock_stat.return_value = MagicMock() + mock_verify.return_value = False + self.assertFalse(self.ptool.verify(entry, [])) + mock_verify.assert_called_with(entry) + + mock_verify.reset_mock() + mock_verify.return_value = True + self.assertTrue(self.ptool.verify(entry, [])) + mock_verify.assert_called_with(entry) + + mock_verify.reset_mock() + entry.set("recursive", "true") + walk_rv = [("/", ["dir1", "dir2"], ["file1", "file2"]), + ("/dir1", ["dir3"], []), + ("/dir2", [], ["file3", "file4"])] + mock_walk.return_value = walk_rv + self.assertTrue(self.ptool.verify(entry, [])) + mock_walk.assert_called_with(entry.get("name")) + all_verifies = [call(entry)] + for root, dirs, files in walk_rv: + all_verifies.extend([call(entry, path=os.path.join(root, p)) + for p in dirs + files]) + self.assertItemsEqual(mock_verify.call_args_list, all_verifies) + + @patch('os.walk') @patch("Bcfg2.Client.Tools.POSIX.base.%s._set_perms" % test_obj.__name__) - def test_install(self, mock_set_perms): + def test_install(self, mock_set_perms, mock_walk): entry = lxml.etree.Element("Path", name="/test", type="file") - ptool = self.get_obj() mock_set_perms.return_value = True - self.assertTrue(ptool.install(entry)) + self.assertTrue(self.ptool.install(entry)) mock_set_perms.assert_called_with(entry) mock_set_perms.reset_mock() entry.set("recursive", "true") - with patch('os.walk') as mock_walk: - walk_rv = [("/", ["dir1", "dir2"], ["file1", "file2"]), - ("/dir1", ["dir3"], []), - ("/dir2", [], ["file3", "file4"])] - mock_walk.return_value = walk_rv - - mock_set_perms.return_value = True - self.assertTrue(ptool.install(entry)) - mock_walk.assert_called_with(entry.get("name")) - all_set_perms = [call(entry)] - for root, dirs, files in walk_rv: - all_set_perms.extend([call(entry, - path=os.path.join(root, p)) - for p in dirs + files]) - self.assertItemsEqual(mock_set_perms.call_args_list, - all_set_perms) - - mock_walk.reset_mock() - mock_set_perms.reset_mock() + walk_rv = [("/", ["dir1", "dir2"], ["file1", "file2"]), + ("/dir1", ["dir3"], []), + ("/dir2", [], ["file3", "file4"])] + mock_walk.return_value = walk_rv - def set_perms_rv(entry, path=None): - if path == '/dir2/file3': - return False - else: - return True - mock_set_perms.side_effect = set_perms_rv - - self.assertFalse(ptool.install(entry)) - mock_walk.assert_called_with(entry.get("name")) - self.assertItemsEqual(mock_set_perms.call_args_list, - all_set_perms) + mock_set_perms.return_value = True + self.assertTrue(self.ptool.install(entry)) + mock_walk.assert_called_with(entry.get("name")) + all_set_perms = [call(entry)] + for root, dirs, files in walk_rv: + all_set_perms.extend([call(entry, path=os.path.join(root, p)) + for p in dirs + files]) + self.assertItemsEqual(mock_set_perms.call_args_list, + all_set_perms) + + mock_walk.reset_mock() + mock_set_perms.reset_mock() + + def set_perms_rv(entry, path=None): + if path == '/dir2/file3': + return False + else: + return True + mock_set_perms.side_effect = set_perms_rv + + self.assertFalse(self.ptool.install(entry)) + mock_walk.assert_called_with(entry.get("name")) + self.assertItemsEqual(mock_set_perms.call_args_list, all_set_perms) + @patch('os.lstat') @patch("os.unlink") + @patch("os.path.isdir") @patch("shutil.rmtree") - def test_exists(self, mock_rmtree, mock_unlink): + def test_exists(self, mock_rmtree, mock_isdir, mock_unlink, mock_lstat): entry = lxml.etree.Element("Path", name="/etc/foo", type="file") - ptool = self.get_obj() - with patch('os.lstat') as mock_lstat, \ - patch("os.path.isdir") as mock_isdir: - mock_lstat.side_effect = OSError - self.assertFalse(ptool._exists(entry)) - mock_lstat.assert_called_with(entry.get('name')) - self.assertFalse(mock_unlink.called) - - mock_lstat.reset_mock() - mock_unlink.reset_mock() - rv = MagicMock() - mock_lstat.return_value = rv - mock_lstat.side_effect = None - self.assertEqual(ptool._exists(entry), rv) - mock_lstat.assert_called_with(entry.get('name')) - self.assertFalse(mock_unlink.called) - - mock_lstat.reset_mock() - mock_unlink.reset_mock() - mock_isdir.return_value = False - self.assertFalse(ptool._exists(entry, remove=True)) - mock_isdir.assert_called_with(entry.get('name')) - mock_lstat.assert_called_with(entry.get('name')) - mock_unlink.assert_called_with(entry.get('name')) - self.assertFalse(mock_rmtree.called) - - mock_lstat.reset_mock() - mock_isdir.reset_mock() - mock_unlink.reset_mock() - mock_rmtree.reset_mock() - mock_isdir.return_value = True - self.assertFalse(ptool._exists(entry, remove=True)) - mock_isdir.assert_called_with(entry.get('name')) - mock_lstat.assert_called_with(entry.get('name')) - mock_rmtree.assert_called_with(entry.get('name')) - self.assertFalse(mock_unlink.called) - - mock_isdir.reset_mock() - mock_lstat.reset_mock() - mock_unlink.reset_mock() - mock_rmtree.reset_mock() - mock_rmtree.side_effect = OSError - self.assertEqual(ptool._exists(entry, remove=True), rv) - mock_isdir.assert_called_with(entry.get('name')) - mock_lstat.assert_called_with(entry.get('name')) - mock_rmtree.assert_called_with(entry.get('name')) - self.assertFalse(mock_unlink.called) + + mock_lstat.side_effect = OSError + self.assertFalse(self.ptool._exists(entry)) + mock_lstat.assert_called_with(entry.get('name')) + self.assertFalse(mock_unlink.called) + + mock_lstat.reset_mock() + mock_unlink.reset_mock() + rv = MagicMock() + mock_lstat.return_value = rv + mock_lstat.side_effect = None + self.assertEqual(self.ptool._exists(entry), rv) + mock_lstat.assert_called_with(entry.get('name')) + self.assertFalse(mock_unlink.called) + + mock_lstat.reset_mock() + mock_unlink.reset_mock() + mock_isdir.return_value = False + self.assertFalse(self.ptool._exists(entry, remove=True)) + mock_isdir.assert_called_with(entry.get('name')) + mock_lstat.assert_called_with(entry.get('name')) + mock_unlink.assert_called_with(entry.get('name')) + self.assertFalse(mock_rmtree.called) + + mock_lstat.reset_mock() + mock_isdir.reset_mock() + mock_unlink.reset_mock() + mock_rmtree.reset_mock() + mock_isdir.return_value = True + self.assertFalse(self.ptool._exists(entry, remove=True)) + mock_isdir.assert_called_with(entry.get('name')) + mock_lstat.assert_called_with(entry.get('name')) + mock_rmtree.assert_called_with(entry.get('name')) + self.assertFalse(mock_unlink.called) + + mock_isdir.reset_mock() + mock_lstat.reset_mock() + mock_unlink.reset_mock() + mock_rmtree.reset_mock() + mock_rmtree.side_effect = OSError + self.assertEqual(self.ptool._exists(entry, remove=True), rv) + mock_isdir.assert_called_with(entry.get('name')) + mock_lstat.assert_called_with(entry.get('name')) + mock_rmtree.assert_called_with(entry.get('name')) + self.assertFalse(mock_unlink.called) @patch("os.chown") @patch("os.chmod") @@ -173,8 +175,6 @@ class TestPOSIXTool(Bcfg2TestCase): test_obj.__name__) def test_set_perms(self, mock_set_secontext, mock_set_acls, mock_norm_gid, mock_norm_uid, mock_utime, mock_chmod, mock_chown): - ptool = self.get_obj() - def reset(): mock_set_secontext.reset_mock() mock_set_acls.reset_mock() @@ -188,7 +188,7 @@ class TestPOSIXTool(Bcfg2TestCase): type="symlink") mock_set_acls.return_value = True mock_set_secontext.return_value = True - self.assertTrue(ptool._set_perms(entry)) + self.assertTrue(self.ptool._set_perms(entry)) mock_set_secontext.assert_called_with(entry, path=entry.get("name")) mock_set_acls.assert_called_with(entry, path=entry.get("name")) @@ -198,7 +198,7 @@ class TestPOSIXTool(Bcfg2TestCase): mock_norm_gid.return_value = 100 reset() - self.assertTrue(ptool._set_perms(entry)) + self.assertTrue(self.ptool._set_perms(entry)) mock_norm_uid.assert_called_with(entry) mock_norm_gid.assert_called_with(entry) mock_chown.assert_called_with(entry.get("name"), 10, 100) @@ -211,7 +211,7 @@ class TestPOSIXTool(Bcfg2TestCase): reset() mtime = 1344459042 entry.set("mtime", str(mtime)) - self.assertTrue(ptool._set_perms(entry)) + self.assertTrue(self.ptool._set_perms(entry)) mock_norm_uid.assert_called_with(entry) mock_norm_gid.assert_called_with(entry) mock_chown.assert_called_with(entry.get("name"), 10, 100) @@ -222,7 +222,7 @@ class TestPOSIXTool(Bcfg2TestCase): mock_set_acls.assert_called_with(entry, path=entry.get("name")) reset() - self.assertTrue(ptool._set_perms(entry, path='/etc/bar')) + self.assertTrue(self.ptool._set_perms(entry, path='/etc/bar')) mock_norm_uid.assert_called_with(entry) mock_norm_gid.assert_called_with(entry) mock_chown.assert_called_with('/etc/bar', 10, 100) @@ -241,7 +241,7 @@ class TestPOSIXTool(Bcfg2TestCase): os.chown.side_effect = chown_rv entry.set("type", "device") entry.set("dev_type", list(device_map.keys())[0]) - self.assertFalse(ptool._set_perms(entry)) + self.assertFalse(self.ptool._set_perms(entry)) mock_norm_uid.assert_called_with(entry) mock_norm_gid.assert_called_with(entry) mock_chown.assert_called_with(entry.get("name"), 0, 0) @@ -257,7 +257,7 @@ class TestPOSIXTool(Bcfg2TestCase): os.chmod.side_effect = OSError entry.set("type", "file") del entry.attrib["dev_type"] - self.assertFalse(ptool._set_perms(entry)) + self.assertFalse(self.ptool._set_perms(entry)) mock_norm_uid.assert_called_with(entry) mock_norm_gid.assert_called_with(entry) mock_chown.assert_called_with(entry.get("name"), 10, 100) @@ -275,7 +275,7 @@ class TestPOSIXTool(Bcfg2TestCase): os.utime.side_effect = OSError mock_set_acls.return_value = False mock_set_secontext.return_value = False - self.assertFalse(ptool._set_perms(entry)) + self.assertFalse(self.ptool._set_perms(entry)) mock_norm_uid.assert_called_with(entry) mock_norm_gid.assert_called_with(entry) mock_chown.assert_called_with(entry.get("name"), 10, 100) @@ -286,17 +286,18 @@ class TestPOSIXTool(Bcfg2TestCase): mock_set_acls.assert_called_with(entry, path=entry.get("name")) @skipUnless(has_acls, "ACLS not found, skipping") + @patch("os.path.isdir") @patch("Bcfg2.Client.Tools.POSIX.base.%s._norm_uid" % test_obj.__name__) @patch("Bcfg2.Client.Tools.POSIX.base.%s._norm_gid" % test_obj.__name__) @patch("Bcfg2.Client.Tools.POSIX.base.%s._list_entry_acls" % test_obj.__name__) - def test_set_acls(self, mock_list_entry_acls, mock_norm_gid, mock_norm_uid): + def test_set_acls(self, mock_list_entry_acls, mock_norm_gid, mock_norm_uid, + mock_isdir): entry = lxml.etree.Element("Path", name="/etc/foo", type="file") - ptool = self.get_obj() # disable acls for the initial test Bcfg2.Client.Tools.POSIX.base.has_acls = False - self.assertTrue(ptool._set_acls(entry)) + self.assertTrue(self.ptool._set_acls(entry)) Bcfg2.Client.Tools.POSIX.base.has_acls = True # build a set of file ACLs to return from posix1e.ACL(file=...) @@ -323,9 +324,9 @@ class TestPOSIXTool(Bcfg2TestCase): mock_norm_uid.return_value = 10 mock_norm_gid.return_value = 100 - with patch("posix1e.ACL") as mock_ACL, \ - patch("posix1e.Entry") as mock_Entry, \ - patch("os.path.isdir") as mock_isdir: + @patch("posix1e.ACL") + @patch("posix1e.Entry") + def inner(mock_Entry, mock_ACL): # set up the unreasonably complex return value for # posix1e.ACL(), which has three separate uses fileacl_rv = MagicMock() @@ -364,17 +365,17 @@ class TestPOSIXTool(Bcfg2TestCase): # test fs mounted noacl mock_ACL.side_effect = IOError(95, "Operation not permitted") - self.assertFalse(ptool._set_acls(entry)) + self.assertFalse(self.ptool._set_acls(entry)) # test other error reset() mock_ACL.side_effect = IOError - self.assertFalse(ptool._set_acls(entry)) + self.assertFalse(self.ptool._set_acls(entry)) reset() mock_ACL.side_effect = mock_acl_rv mock_isdir.return_value = True - self.assertTrue(ptool._set_acls(entry)) + self.assertTrue(self.ptool._set_acls(entry)) self.assertItemsEqual(mock_ACL.call_args_list, [call(file=entry.get("name")), call(filedef=entry.get("name"))]) @@ -412,7 +413,7 @@ class TestPOSIXTool(Bcfg2TestCase): mock_norm_gid.reset_mock() mock_isdir.return_value = False acl_entries = [] - self.assertTrue(ptool._set_acls(entry, path="/bin/bar")) + self.assertTrue(self.ptool._set_acls(entry, path="/bin/bar")) mock_ACL.assert_called_with(file="/bin/bar") self.assertItemsEqual(fileacl_rv.delete_entry.call_args_list, [call(a) for a in remove_acls]) @@ -429,27 +430,29 @@ class TestPOSIXTool(Bcfg2TestCase): self.assertItemsEqual(added_acls, [(fileacl_rv, posix1e.ACL_GROUP, 100, 5)]) + inner() + @skipUnless(has_selinux, "SELinux not found, skipping") def test_set_secontext(self): entry = lxml.etree.Element("Path", name="/etc/foo", type="file") - ptool = self.get_obj() # disable selinux for the initial test Bcfg2.Client.Tools.POSIX.base.has_selinux = False - self.assertTrue(ptool._set_secontext(entry)) + self.assertTrue(self.ptool._set_secontext(entry)) Bcfg2.Client.Tools.POSIX.base.has_selinux = True - with patch("selinux.restorecon") as mock_restorecon, \ - patch("selinux.lsetfilecon") as mock_lsetfilecon: + @patch("selinux.restorecon") + @patch("selinux.lsetfilecon") + def inner(mock_lsetfilecon, mock_restorecon): # no context given - self.assertTrue(ptool._set_secontext(entry)) + self.assertTrue(self.ptool._set_secontext(entry)) self.assertFalse(mock_restorecon.called) self.assertFalse(mock_lsetfilecon.called) mock_restorecon.reset_mock() mock_lsetfilecon.reset_mock() entry.set("secontext", "__default__") - self.assertTrue(ptool._set_secontext(entry)) + self.assertTrue(self.ptool._set_secontext(entry)) mock_restorecon.assert_called_with(entry.get("name")) self.assertFalse(mock_lsetfilecon.called) @@ -457,159 +460,152 @@ class TestPOSIXTool(Bcfg2TestCase): mock_lsetfilecon.reset_mock() mock_lsetfilecon.return_value = 0 entry.set("secontext", "foo_t") - self.assertTrue(ptool._set_secontext(entry)) + self.assertTrue(self.ptool._set_secontext(entry)) self.assertFalse(mock_restorecon.called) mock_lsetfilecon.assert_called_with(entry.get("name"), "foo_t") mock_restorecon.reset_mock() mock_lsetfilecon.reset_mock() mock_lsetfilecon.return_value = 1 - self.assertFalse(ptool._set_secontext(entry)) + self.assertFalse(self.ptool._set_secontext(entry)) self.assertFalse(mock_restorecon.called) mock_lsetfilecon.assert_called_with(entry.get("name"), "foo_t") + inner() + @patch("grp.getgrnam") def test_norm_gid(self, mock_getgrnam): - ptool = self.get_obj() - self.assertEqual(5, ptool._norm_gid("5")) + self.assertEqual(5, self.ptool._norm_gid("5")) self.assertFalse(mock_getgrnam.called) mock_getgrnam.reset_mock() mock_getgrnam.return_value = ("group", "x", 5, []) - self.assertEqual(5, ptool._norm_gid("group")) + self.assertEqual(5, self.ptool._norm_gid("group")) mock_getgrnam.assert_called_with("group") @patch("Bcfg2.Client.Tools.POSIX.base.%s._norm_gid" % test_obj.__name__) def test_norm_entry_gid(self, mock_norm_gid): entry = lxml.etree.Element("Path", name="/test", type="file", group="group", owner="user") - ptool = self.get_obj() mock_norm_gid.return_value = 10 - self.assertEqual(10, ptool._norm_entry_gid(entry)) + self.assertEqual(10, self.ptool._norm_entry_gid(entry)) mock_norm_gid.assert_called_with(entry.get("group")) mock_norm_gid.reset_mock() mock_norm_gid.side_effect = KeyError - self.assertEqual(0, ptool._norm_entry_gid(entry)) + self.assertEqual(0, self.ptool._norm_entry_gid(entry)) mock_norm_gid.assert_called_with(entry.get("group")) @patch("pwd.getpwnam") def test_norm_uid(self, mock_getpwnam): - ptool = self.get_obj() - self.assertEqual(5, ptool._norm_uid("5")) + self.assertEqual(5, self.ptool._norm_uid("5")) self.assertFalse(mock_getpwnam.called) mock_getpwnam.reset_mock() mock_getpwnam.return_value = ("user", "x", 5, 5, "User", "/home/user", "/bin/zsh") - self.assertEqual(5, ptool._norm_uid("user")) + self.assertEqual(5, self.ptool._norm_uid("user")) mock_getpwnam.assert_called_with("user") @patch("Bcfg2.Client.Tools.POSIX.base.%s._norm_uid" % test_obj.__name__) def test_norm_entry_uid(self, mock_norm_uid): entry = lxml.etree.Element("Path", name="/test", type="file", group="group", owner="user") - ptool = self.get_obj() mock_norm_uid.return_value = 10 - self.assertEqual(10, ptool._norm_entry_uid(entry)) + self.assertEqual(10, self.ptool._norm_entry_uid(entry)) mock_norm_uid.assert_called_with(entry.get("owner")) mock_norm_uid.reset_mock() mock_norm_uid.side_effect = KeyError - self.assertEqual(0, ptool._norm_entry_uid(entry)) + self.assertEqual(0, self.ptool._norm_entry_uid(entry)) mock_norm_uid.assert_called_with(entry.get("owner")) def test_norm_acl_perms(self): - ptool = self.get_obj() # there's basically no reasonably way to test the Permset # object parsing feature without writing our own Mock object # that re-implements Permset.test(). silly pylibacl won't let # us create standalone Entry or Permset objects. - ptool = self.get_obj() - self.assertEqual(5, ptool._norm_acl_perms("5")) - self.assertEqual(0, ptool._norm_acl_perms("55")) - self.assertEqual(5, ptool._norm_acl_perms("rx")) - self.assertEqual(5, ptool._norm_acl_perms("r-x")) - self.assertEqual(6, ptool._norm_acl_perms("wr-")) - self.assertEqual(0, ptool._norm_acl_perms("rwrw")) - self.assertEqual(0, ptool._norm_acl_perms("-")) - self.assertEqual(0, ptool._norm_acl_perms("a")) - self.assertEqual(6, ptool._norm_acl_perms("rwa")) - self.assertEqual(4, ptool._norm_acl_perms("rr")) - - def test__gather_data(self): + self.assertEqual(5, self.ptool._norm_acl_perms("5")) + self.assertEqual(0, self.ptool._norm_acl_perms("55")) + self.assertEqual(5, self.ptool._norm_acl_perms("rx")) + self.assertEqual(5, self.ptool._norm_acl_perms("r-x")) + self.assertEqual(6, self.ptool._norm_acl_perms("wr-")) + self.assertEqual(0, self.ptool._norm_acl_perms("rwrw")) + self.assertEqual(0, self.ptool._norm_acl_perms("-")) + self.assertEqual(0, self.ptool._norm_acl_perms("a")) + self.assertEqual(6, self.ptool._norm_acl_perms("rwa")) + self.assertEqual(4, self.ptool._norm_acl_perms("rr")) + + @patch('os.stat') + def test__gather_data(self, mock_stat): path = '/test' - ptool = self.get_obj() - - # have to use context manager version of patch here because - # os.stat must be unpatched when we instantiate the object to - # make pkgutil.walk_packages() work - with patch('os.stat') as mock_stat: - mock_stat.side_effect = OSError - self.assertFalse(ptool._gather_data(path)[0]) - mock_stat.assert_called_with(path) - - mock_stat.reset_mock() - mock_stat.side_effect = None - # create a return value - stat_rv = MagicMock() - def stat_getitem(key): - if int(key) == stat.ST_UID: - return 0 - elif int(key) == stat.ST_GID: - return 10 - elif int(key) == stat.ST_MODE: - # return extra bits in the mode to emulate a device - # and ensure that they're stripped - return int('060660', 8) - stat_rv.__getitem__ = Mock(side_effect=stat_getitem) - mock_stat.return_value = stat_rv - - # disable selinux and acls for this call -- we test them - # separately so that we can skip those tests as appropriate - states = (Bcfg2.Client.Tools.POSIX.base.has_selinux, - Bcfg2.Client.Tools.POSIX.base.has_acls) - Bcfg2.Client.Tools.POSIX.base.has_selinux = False - Bcfg2.Client.Tools.POSIX.base.has_acls = False - self.assertEqual(ptool._gather_data(path), - (stat_rv, '0', '10', '0660', None, None)) - Bcfg2.Client.Tools.POSIX.base.has_selinux, \ - Bcfg2.Client.Tools.POSIX.base.has_acls = states - mock_stat.assert_called_with(path) + mock_stat.side_effect = OSError + self.assertFalse(self.ptool._gather_data(path)[0]) + mock_stat.assert_called_with(path) + + mock_stat.reset_mock() + mock_stat.side_effect = None + # create a return value + stat_rv = MagicMock() + def stat_getitem(key): + if int(key) == stat.ST_UID: + return 0 + elif int(key) == stat.ST_GID: + return 10 + elif int(key) == stat.ST_MODE: + # return extra bits in the mode to emulate a device + # and ensure that they're stripped + return int('060660', 8) + stat_rv.__getitem__ = Mock(side_effect=stat_getitem) + mock_stat.return_value = stat_rv + + # disable selinux and acls for this call -- we test them + # separately so that we can skip those tests as appropriate + states = (Bcfg2.Client.Tools.POSIX.base.has_selinux, + Bcfg2.Client.Tools.POSIX.base.has_acls) + Bcfg2.Client.Tools.POSIX.base.has_selinux = False + Bcfg2.Client.Tools.POSIX.base.has_acls = False + self.assertEqual(self.ptool._gather_data(path), + (stat_rv, '0', '10', '0660', None, None)) + Bcfg2.Client.Tools.POSIX.base.has_selinux, \ + Bcfg2.Client.Tools.POSIX.base.has_acls = states + mock_stat.assert_called_with(path) @skipUnless(has_selinux, "SELinux not found, skipping") def test__gather_data_selinux(self): context = 'system_u:object_r:root_t:s0' path = '/test' - ptool = self.get_obj() - with patch("selinux.getfilecon") as mock_getfilecon, \ - patch('os.stat') as mock_stat: + + @patch("selinux.getfilecon") + @patch('os.stat') + def inner(mock_stat, mock_getfilecon): mock_getfilecon.return_value = [len(context) + 1, context] mock_stat.return_value = MagicMock() # disable acls for this call and test them separately state = Bcfg2.Client.Tools.POSIX.base.has_acls Bcfg2.Client.Tools.POSIX.base.has_acls = False - self.assertEqual(ptool._gather_data(path)[4], 'root_t') + self.assertEqual(self.ptool._gather_data(path)[4], 'root_t') Bcfg2.Client.Tools.POSIX.base.has_acls = state mock_getfilecon.assert_called_with(path) + + inner() + @skipUnless(has_acls, "ACLS not found, skipping") + @patch('os.stat') @patch("Bcfg2.Client.Tools.POSIX.base.%s._list_file_acls" % test_obj.__name__) - @skipUnless(has_acls, "ACLS not found, skipping") - def test__gather_data_acls(self, mock_list_file_acls): + def test__gather_data_acls(self, mock_list_file_acls, mock_stat): acls = {("default", posix1e.ACL_USER, "testuser"): "rwx", ("access", posix1e.ACL_GROUP, "testgroup"): "rx"} mock_list_file_acls.return_value = acls path = '/test' - ptool = self.get_obj() - with patch('os.stat') as mock_stat: - mock_stat.return_value = MagicMock() - # disable selinux for this call and test it separately - state = Bcfg2.Client.Tools.POSIX.base.has_selinux - Bcfg2.Client.Tools.POSIX.base.has_selinux = False - self.assertItemsEqual(ptool._gather_data(path)[5], acls) - Bcfg2.Client.Tools.POSIX.base.has_selinux = state - mock_list_file_acls.assert_called_with(path) + mock_stat.return_value = MagicMock() + # disable selinux for this call and test it separately + state = Bcfg2.Client.Tools.POSIX.base.has_selinux + Bcfg2.Client.Tools.POSIX.base.has_selinux = False + self.assertItemsEqual(self.ptool._gather_data(path)[5], acls) + Bcfg2.Client.Tools.POSIX.base.has_selinux = state + mock_list_file_acls.assert_called_with(path) @patch("Bcfg2.Client.Tools.POSIX.base.%s._verify_acls" % test_obj.__name__) @patch("Bcfg2.Client.Tools.POSIX.base.%s._gather_data" % test_obj.__name__) @@ -626,18 +622,16 @@ class TestPOSIXTool(Bcfg2TestCase): # can start fresh every time orig_entry = copy.deepcopy(entry) - ptool = self.get_obj() - def reset(): mock_gather_data.reset_mock() + mock_verify_acls.reset_mock() mock_norm_uid.reset_mock() mock_norm_gid.reset_mock() return copy.deepcopy(orig_entry) - # test nonexistent file mock_gather_data.return_value = (False, None, None, None, None, None) - self.assertFalse(ptool._verify_metadata(entry)) + self.assertFalse(self.ptool._verify_metadata(entry)) self.assertEqual(entry.get("current_exists", "").lower(), "false") mock_gather_data.assert_called_with(entry.get("name")) @@ -654,7 +648,7 @@ class TestPOSIXTool(Bcfg2TestCase): entry = reset() mock_gather_data.return_value = tuple(gather_data_rv) - self.assertTrue(ptool._verify_metadata(entry)) + self.assertTrue(self.ptool._verify_metadata(entry)) mock_gather_data.assert_called_with(entry.get("name")) mock_verify_acls.assert_called_with(entry, path=entry.get("name")) self.assertEqual(entry.get("current_exists", 'true'), 'true') @@ -667,7 +661,7 @@ class TestPOSIXTool(Bcfg2TestCase): sestate = Bcfg2.Client.Tools.POSIX.base.has_selinux Bcfg2.Client.Tools.POSIX.base.has_selinux = False mock_gather_data.return_value = tuple(gather_data_rv) - self.assertTrue(ptool._verify_metadata(entry)) + self.assertTrue(self.ptool._verify_metadata(entry)) mock_gather_data.assert_called_with(entry.get("name")) mock_verify_acls.assert_called_with(entry, path=entry.get("name")) self.assertEqual(entry.get("current_exists", 'true'), 'true') @@ -688,7 +682,7 @@ class TestPOSIXTool(Bcfg2TestCase): stat_rv.__getitem__.return_value = mtime gather_data_rv[0] = stat_rv mock_gather_data.return_value = tuple(gather_data_rv) - self.assertTrue(ptool._verify_metadata(entry)) + self.assertTrue(self.ptool._verify_metadata(entry)) mock_gather_data.assert_called_with(entry.get("name")) mock_verify_acls.assert_called_with(entry, path=entry.get("name")) self.assertEqual(entry.get("current_exists", 'true'), 'true') @@ -712,7 +706,7 @@ class TestPOSIXTool(Bcfg2TestCase): gather_data_rv[idx] = val gather_data_rv[fail_idx] = fail_val mock_gather_data.return_value = tuple(gather_data_rv) - self.assertFalse(ptool._verify_metadata(entry)) + self.assertFalse(self.ptool._verify_metadata(entry)) mock_gather_data.assert_called_with(entry.get("name")) mock_verify_acls.assert_called_with(entry, path=entry.get("name")) self.assertEqual(entry.get("current_exists", 'true'), 'true') @@ -732,7 +726,7 @@ class TestPOSIXTool(Bcfg2TestCase): for attr, idx, val in expected: gather_data_rv[idx] = val mock_gather_data.return_value = tuple(gather_data_rv) - self.assertFalse(ptool._verify_metadata(entry)) + self.assertFalse(self.ptool._verify_metadata(entry)) mock_gather_data.assert_called_with(entry.get("name")) mock_verify_acls.assert_called_with(entry, path=entry.get("name")) self.assertEqual(entry.get("current_exists", 'true'), 'true') @@ -745,7 +739,9 @@ class TestPOSIXTool(Bcfg2TestCase): entry = reset() entry.set("mtime", str(mtime)) entry.set("secontext", "__default__") - with patch("selinux.matchpathcon") as mock_matchpathcon: + + @patch("selinux.matchpathcon") + def inner(entry, mock_matchpathcon): context1 = "system_u:object_r:etc_t:s0" context2 = "system_u:object_r:root_t:s0" mock_matchpathcon.return_value = [1 + len(context1), @@ -754,7 +750,7 @@ class TestPOSIXTool(Bcfg2TestCase): for attr, idx, val in expected: gather_data_rv[idx] = val mock_gather_data.return_value = tuple(gather_data_rv) - self.assertTrue(ptool._verify_metadata(entry)) + self.assertTrue(self.ptool._verify_metadata(entry)) mock_gather_data.assert_called_with(entry.get("name")) mock_verify_acls.assert_called_with(entry, path=entry.get("name")) @@ -769,7 +765,7 @@ class TestPOSIXTool(Bcfg2TestCase): entry.set("secontext", "__default__") mock_matchpathcon.return_value = [1 + len(context2), context2] - self.assertFalse(ptool._verify_metadata(entry)) + self.assertFalse(self.ptool._verify_metadata(entry)) mock_gather_data.assert_called_with(entry.get("name")) mock_verify_acls.assert_called_with(entry, path=entry.get("name")) @@ -779,6 +775,8 @@ class TestPOSIXTool(Bcfg2TestCase): self.assertEqual(entry.get(attr), val) self.assertEqual(entry.get("current_mtime"), str(mtime)) + inner(entry) + @skipUnless(has_acls, "ACLS not found, skipping") def test_list_entry_acls(self): entry = lxml.etree.Element("Path", name="/test", type="file") @@ -786,19 +784,19 @@ class TestPOSIXTool(Bcfg2TestCase): user="user", perms="rwx") lxml.etree.SubElement(entry, "ACL", scope="group", type="access", group="group", perms="5") - ptool = self.get_obj() - self.assertItemsEqual(ptool._list_entry_acls(entry), + self.assertItemsEqual(self.ptool._list_entry_acls(entry), {("default", posix1e.ACL_USER, "user"): 7, ("access", posix1e.ACL_GROUP, "group"): 5}) @skipUnless(has_acls, "ACLS not found, skipping") @patch("pwd.getpwuid") @patch("grp.getgrgid") - def test_list_file_acls(self, mock_getgrgid, mock_getpwuid): + @patch("os.path.isdir") + def test_list_file_acls(self, mock_isdir, mock_getgrgid, mock_getpwuid): path = '/test' - ptool = self.get_obj() - with patch("posix1e.ACL") as mock_ACL, \ - patch("os.path.isdir") as mock_isdir: + + @patch("posix1e.ACL") + def inner(mock_ACL): # build a set of file ACLs to return from posix1e.ACL(file=...) file_acls = [] acl = Mock() @@ -845,15 +843,15 @@ class TestPOSIXTool(Bcfg2TestCase): mock_ACL.reset_mock() mock_ACL.side_effect = IOError(95, "Operation not supported") - self.assertItemsEqual(ptool._list_file_acls(path), dict()) + self.assertItemsEqual(self.ptool._list_file_acls(path), dict()) reset() mock_ACL.side_effect = IOError - self.assertItemsEqual(ptool._list_file_acls(path), dict()) + self.assertItemsEqual(self.ptool._list_file_acls(path), dict()) reset() mock_ACL.side_effect = mock_acl_rv - self.assertItemsEqual(ptool._list_file_acls(path), acls) + self.assertItemsEqual(self.ptool._list_file_acls(path), acls) mock_isdir.assert_called_with(path) mock_getgrgid.assert_called_with(100) mock_getpwuid.assert_called_with(10) @@ -867,7 +865,7 @@ class TestPOSIXTool(Bcfg2TestCase): defacls = acls for akey, perms in acls.items(): defacls[('default', akey[1], akey[2])] = perms - self.assertItemsEqual(ptool._list_file_acls(path), defacls) + self.assertItemsEqual(self.ptool._list_file_acls(path), defacls) mock_isdir.assert_called_with(path) self.assertItemsEqual(mock_getgrgid.call_args_list, [call(100), call(100)]) @@ -876,6 +874,8 @@ class TestPOSIXTool(Bcfg2TestCase): self.assertItemsEqual(mock_ACL.call_args_list, [call(file=path), call(filedef=path)]) + inner() + @skipUnless(has_acls, "ACLS not found, skipping") @patch("Bcfg2.Client.Tools.POSIX.base.%s._list_file_acls" % test_obj.__name__) @@ -883,7 +883,6 @@ class TestPOSIXTool(Bcfg2TestCase): test_obj.__name__) def test_verify_acls(self, mock_list_entry_acls, mock_list_file_acls): entry = lxml.etree.Element("Path", name="/test", type="file") - ptool = self.get_obj() # we can't test to make sure that errors get properly sorted # into (missing, extra, wrong) without refactoring the # _verify_acls code, and I don't feel like doing that, so eff @@ -897,7 +896,7 @@ class TestPOSIXTool(Bcfg2TestCase): mock_list_entry_acls.return_value = acls mock_list_file_acls.return_value = acls - self.assertTrue(ptool._verify_acls(entry)) + self.assertTrue(self.ptool._verify_acls(entry)) mock_list_entry_acls.assert_called_with(entry) mock_list_file_acls.assert_called_with(entry.get("name")) @@ -905,7 +904,7 @@ class TestPOSIXTool(Bcfg2TestCase): mock_list_entry_acls.reset_mock() mock_list_file_acls.reset_mock() mock_list_file_acls.return_value = extra_acls - self.assertFalse(ptool._verify_acls(entry)) + self.assertFalse(self.ptool._verify_acls(entry)) mock_list_entry_acls.assert_called_with(entry) mock_list_file_acls.assert_called_with(entry.get("name")) @@ -914,7 +913,7 @@ class TestPOSIXTool(Bcfg2TestCase): mock_list_file_acls.reset_mock() mock_list_entry_acls.return_value = extra_acls mock_list_file_acls.return_value = acls - self.assertFalse(ptool._verify_acls(entry)) + self.assertFalse(self.ptool._verify_acls(entry)) mock_list_entry_acls.assert_called_with(entry) mock_list_file_acls.assert_called_with(entry.get("name")) @@ -925,7 +924,7 @@ class TestPOSIXTool(Bcfg2TestCase): mock_list_file_acls.reset_mock() mock_list_entry_acls.return_value = extra_acls mock_list_file_acls.return_value = wrong_acls - self.assertFalse(ptool._verify_acls(entry)) + self.assertFalse(self.ptool._verify_acls(entry)) mock_list_entry_acls.assert_called_with(entry) mock_list_file_acls.assert_called_with(entry.get("name")) @@ -941,7 +940,6 @@ class TestPOSIXTool(Bcfg2TestCase): mock_set_perms.reset_mock() mock_makedirs.reset_mock() - ptool = self.get_obj() mock_set_perms.return_value = True def path_exists_rv(path): if path == "/test": @@ -949,7 +947,7 @@ class TestPOSIXTool(Bcfg2TestCase): else: return False mock_exists.side_effect = path_exists_rv - self.assertTrue(ptool._makedirs(entry)) + self.assertTrue(self.ptool._makedirs(entry)) self.assertItemsEqual(mock_exists.call_args_list, [call("/test"), call("/test/foo"), call("/test/foo/bar")]) @@ -960,7 +958,7 @@ class TestPOSIXTool(Bcfg2TestCase): reset() mock_makedirs.side_effect = OSError - self.assertFalse(ptool._makedirs(entry)) + self.assertFalse(self.ptool._makedirs(entry)) self.assertItemsEqual(mock_set_perms.call_args_list, [call(entry, path="/test/foo"), call(entry, path="/test/foo/bar")]) @@ -973,7 +971,7 @@ class TestPOSIXTool(Bcfg2TestCase): else: return True mock_set_perms.side_effect = set_perms_rv - self.assertFalse(ptool._makedirs(entry)) + self.assertFalse(self.ptool._makedirs(entry)) self.assertItemsEqual(mock_exists.call_args_list, [call("/test"), call("/test/foo"), call("/test/foo/bar")]) diff --git a/testsuite/Testlib/TestOptions.py b/testsuite/Testlib/TestOptions.py index 18614e0ce..e49fe6a25 100644 --- a/testsuite/Testlib/TestOptions.py +++ b/testsuite/Testlib/TestOptions.py @@ -1,6 +1,5 @@ import os import sys -import unittest from mock import Mock, MagicMock, patch from Bcfg2.Options import * from ..common import * diff --git a/testsuite/Testlib/TestServer/TestPlugin.py b/testsuite/Testlib/TestServer/TestPlugin.py index c00a7d91d..b6d2a852b 100644 --- a/testsuite/Testlib/TestServer/TestPlugin.py +++ b/testsuite/Testlib/TestServer/TestPlugin.py @@ -2,7 +2,6 @@ import os import re import copy import logging -import unittest import lxml.etree import Bcfg2.Server from Bcfg2.Bcfg2Py3k import reduce @@ -1075,43 +1074,22 @@ class TestStructFile(TestXMLFileBacked): self.assertXMLEqual(xactual, xexpected) -# INode.__init__ and INode._load_children() call each other -# recursively, which makes this class kind of a nightmare to test. we -# have to first patch INode._load_children so that we can create an -# INode object with no children loaded, then we unpatch -# INode._load_children and patch INode.__init__ so that child objects -# aren't actually created. but in order to test things atomically, we -# do this umpteen times in order to test with different data. we -# write our own context manager to make this a little easier. fun fun -# fun. -class patch_inode(object): - def __init__(self, test_obj, data, idict): - self.test_obj = test_obj - self.data = data - self.idict = idict - self.patch_init = None - self.inode = None - - def __enter__(self): - with patch("Bcfg2.Server.Plugin.%s._load_children" % - self.test_obj.__name__): - self.inode = self.test_obj(self.data, self.idict) - self.patch_init = patch("Bcfg2.Server.Plugin.%s.__init__" % - self.inode.__class__.__name__, - new=Mock(return_value=None)) - self.patch_init.start() - self.inode._load_children(self.data, self.idict) - return (self.inode, self.patch_init.new) - - def __exit__(self, type, value, traceback): - self.patch_init.stop() - del self.patch_init - del self.inode - - class TestINode(Bcfg2TestCase): test_obj = INode + # INode.__init__ and INode._load_children() call each other + # recursively, which makes this class kind of a nightmare to test. + # we have to first patch INode._load_children so that we can + # create an INode object with no children loaded, then we unpatch + # INode._load_children and patch INode.__init__ so that child + # objects aren't actually created. but in order to test things + # atomically, we do this umpteen times in order to test with + # different data. this convenience method makes this a little + # easier. fun fun fun. + @patch("Bcfg2.Server.Plugin.%s._load_children" % test_obj.__name__, Mock()) + def _get_inode(self, data, idict): + return self.test_obj(data, idict) + def test_raw_predicates(self): metadata = Mock() metadata.groups = ["group1", "group2"] @@ -1224,12 +1202,20 @@ class TestINode(Bcfg2TestCase): child1 = lxml.etree.SubElement(data, "Client", name="foo.example.com") child2 = lxml.etree.SubElement(data, "Group", name="bar", negate="true") idict = dict() - with patch_inode(self.test_obj, data, idict) as (inode, mock_init): + + inode = self._get_inode(data, idict) + + @patch("Bcfg2.Server.Plugin.%s.__init__" % inode.__class__.__name__) + def inner(mock_init): + mock_init.return_value = None + inode._load_children(data, idict) self.assertItemsEqual(mock_init.call_args_list, [call(child1, idict, inode), call(child2, idict, inode)]) self.assertEqual(idict, dict()) self.assertItemsEqual(inode.contents, dict()) + + inner() data = lxml.etree.Element("Parent") child1 = lxml.etree.SubElement(data, "Data", name="child1", @@ -1238,7 +1224,13 @@ class TestINode(Bcfg2TestCase): subchild1 = lxml.etree.SubElement(child1, "SubChild", name="subchild") child2 = lxml.etree.SubElement(data, "Group", name="bar", negate="true") idict = dict() - with patch_inode(self.test_obj, data, idict) as (inode, mock_init): + + inode = self._get_inode(data, idict) + + @patch("Bcfg2.Server.Plugin.%s.__init__" % inode.__class__.__name__) + def inner2(mock_init): + mock_init.return_value = None + inode._load_children(data, idict) mock_init.assert_called_with(child2, idict, inode) tag = child1.tag name = child1.get("name") @@ -1250,16 +1242,26 @@ class TestINode(Bcfg2TestCase): attr=child1.get('attr'), __text__=child1.text, __children__=[subchild1])) + + inner2() # test ignore. no ignore is set on INode by default, so we # have to set one old_ignore = copy.copy(self.test_obj.ignore) self.test_obj.ignore.append("Data") idict = dict() - with patch_inode(self.test_obj, data, idict) as (inode, mock_init): + + inode = self._get_inode(data, idict) + + @patch("Bcfg2.Server.Plugin.%s.__init__" % inode.__class__.__name__) + def inner3(mock_init): + mock_init.return_value = None + inode._load_children(data, idict) mock_init.assert_called_with(child2, idict, inode) self.assertEqual(idict, dict()) self.assertItemsEqual(inode.contents, dict()) + + inner3() self.test_obj.ignore = old_ignore def test_Match(self): @@ -1423,7 +1425,9 @@ class TestPrioDir(TestPlugin, TestGenerator, TestXMLDirectoryBacked): def test_HandleEvent(self): TestXMLDirectoryBacked.test_HandleEvent(self) - with patch("Bcfg2.Server.Plugin.XMLDirectoryBacked.HandleEvent"): + + @patch("Bcfg2.Server.Plugin.XMLDirectoryBacked.HandleEvent", Mock()) + def inner(): pd = self.get_obj() test1 = Mock() test1.items = dict(Path=["/etc/foo.conf", "/etc/bar.conf"]) @@ -1439,6 +1443,8 @@ class TestPrioDir(TestPlugin, TestGenerator, TestXMLDirectoryBacked): "/etc/baz.conf": pd.BindEntry}, Package={"quux": pd.BindEntry, "xyzzy": pd.BindEntry})) + + inner() def test__matches(self): pd = self.get_obj() @@ -2120,12 +2126,16 @@ class TestGroupSpool(TestPlugin, TestGenerator): gs.entries = {"/foo": Mock(), "/bar": Mock(), "/baz/quux": Mock()} - with patch("Bcfg2.Server.Plugin.Plugin.toggle_debug") as mock_debug: + + @patch("Bcfg2.Server.Plugin.Plugin.toggle_debug") + def inner(mock_debug): gs.toggle_debug() mock_debug.assert_called_with(gs) for entry in gs.entries.values(): entry.toggle_debug.assert_any_call() + inner() + TestPlugin.test_toggle_debug(self) @patch("Bcfg2.Server.Plugin.%s.event_id" % test_obj.__name__) diff --git a/testsuite/Testlib/TestServer/TestPlugins/TestMetadata.py b/testsuite/Testlib/TestServer/TestPlugins/TestMetadata.py index 7382a4439..5dcd84a0c 100644 --- a/testsuite/Testlib/TestServer/TestPlugins/TestMetadata.py +++ b/testsuite/Testlib/TestServer/TestPlugins/TestMetadata.py @@ -3,7 +3,6 @@ import sys import copy import time import socket -import unittest import lxml.etree from mock import Mock, patch from ....common import * diff --git a/testsuite/Testlib/TestServer/TestPlugins/TestProbes.py b/testsuite/Testlib/TestServer/TestPlugins/TestProbes.py index df9248e50..38161215d 100644 --- a/testsuite/Testlib/TestServer/TestPlugins/TestProbes.py +++ b/testsuite/Testlib/TestServer/TestPlugins/TestProbes.py @@ -1,7 +1,6 @@ import os import sys import time -import unittest import lxml.etree from mock import Mock, MagicMock, patch from ....common import * @@ -228,9 +227,11 @@ text # test__init(), which relies on being able to check the calls # of load_data(), and thus on load_data() being consistently # mocked) - with patch("Bcfg2.Server.Plugins.Probes.Probes.load_data", - new=load_data): + @patch("Bcfg2.Server.Plugins.Probes.Probes.load_data", new=load_data) + def inner(): return Probes(core, datastore) + + return inner() def test__init(self): mock_load_data = Mock() diff --git a/testsuite/common.py b/testsuite/common.py index 98ee0c6f5..b49b75477 100644 --- a/testsuite/common.py +++ b/testsuite/common.py @@ -231,7 +231,7 @@ class Bcfg2TestCase(unittest.TestCase): class DBModelTestCase(Bcfg2TestCase): models = [] - @unittest.skipUnless(has_django, "Django not found, skipping") + @skipUnless(has_django, "Django not found, skipping") def test_syncdb(self): # create the test database setup_environ(Bcfg2.settings) @@ -240,7 +240,7 @@ class DBModelTestCase(Bcfg2TestCase): cmd.handle_noargs(interactive=False) self.assertTrue(os.path.exists(Bcfg2.settings.DATABASE_NAME)) - @unittest.skipUnless(has_django, "Django not found, skipping") + @skipUnless(has_django, "Django not found, skipping") def test_cleandb(self): """ ensure that we a) can connect to the database; b) start with a clean database """ -- cgit v1.2.3-1-g7c22