diff options
Diffstat (limited to 'testsuite/common.py')
-rw-r--r-- | testsuite/common.py | 265 |
1 files changed, 69 insertions, 196 deletions
diff --git a/testsuite/common.py b/testsuite/common.py index e26d0be61..04c446f67 100644 --- a/testsuite/common.py +++ b/testsuite/common.py @@ -12,9 +12,13 @@ import os import re import sys import codecs -import unittest +import lxml.etree +import Bcfg2.Options from mock import patch, MagicMock, _patch, DEFAULT -from Bcfg2.Compat import wraps +try: + from unittest import skip, skipIf, skipUnless, TestCase +except ImportError: + from unittest2 import skip, skipIf, skipUnless, TestCase #: The path to the Bcfg2 specification root for the tests. Using the #: root directory exposes a lot of potential problems with building @@ -33,16 +37,34 @@ inPy3k = False if sys.hexversion >= 0x03000000: inPy3k = True + +#: A function to set a default config option if it's not already set +def set_setup_default(option, value=None): + if not hasattr(Bcfg2.Options.setup, option): + setattr(Bcfg2.Options.setup, option, value) + try: from django.core.management import setup_environ has_django = True os.environ['DJANGO_SETTINGS_MODULE'] = "Bcfg2.settings" + set_setup_default("db_engine", "sqlite3") + set_setup_default("db_name", + os.path.join(os.path.dirname(os.path.abspath(__file__)), + "test.sqlite")) + set_setup_default("db_user") + set_setup_default("db_password") + set_setup_default("db_host") + set_setup_default("db_port") + set_setup_default("db_opts", dict()) + set_setup_default("db_schema") + set_setup_default("timezone") + set_setup_default("web_debug", False) + set_setup_default("web_prefix") + import Bcfg2.settings - Bcfg2.settings.DATABASE_NAME = \ - os.path.join(os.path.dirname(os.path.abspath(__file__)), "test.sqlite") - Bcfg2.settings.DATABASES['default']['NAME'] = Bcfg2.settings.DATABASE_NAME + Bcfg2.settings.read_config() except ImportError: has_django = False @@ -90,196 +112,46 @@ else: return codecs.unicode_escape_decode(s)[0] -#: Whether or not skipping tests is natively supported by -#: :mod:`unittest`. If it isn't, then we have to make tests that -#: would be skipped succeed instead. -can_skip = False - -if hasattr(unittest, "skip"): - can_skip = True - - #: skip decorator from :func:`unittest.skip` - skip = unittest.skip - - #: skipIf decorator from :func:`unittest.skipIf` - skipIf = unittest.skipIf - - #: skipUnless decorator from :func:`unittest.skipUnless` - skipUnless = unittest.skipUnless -else: - # we can't actually skip tests, we just make them pass - can_skip = False - - def skip(msg): - """ skip decorator used when :mod:`unittest` doesn't support - skipping tests. Replaces the decorated function with a - no-op. """ - def decorator(func): - return lambda *args, **kwargs: None - return decorator - - def skipIf(condition, msg): - """ skipIf decorator used when :mod:`unittest` doesn't support - skipping tests """ - if not condition: - return lambda f: f - else: - return skip(msg) - - def skipUnless(condition, msg): - """ skipUnless decorator used when :mod:`unittest` doesn't - support skipping tests """ - if condition: - return lambda f: f - else: - return skip(msg) - - -def _count_diff_all_purpose(actual, expected): - '''Returns list of (cnt_act, cnt_exp, elem) triples where the - counts differ''' - # elements need not be hashable - s, t = list(actual), list(expected) - m, n = len(s), len(t) - NULL = object() - result = [] - for i, elem in enumerate(s): - if elem is NULL: - continue - cnt_s = cnt_t = 0 - for j in range(i, m): - if s[j] == elem: - cnt_s += 1 - s[j] = NULL - for j, other_elem in enumerate(t): - if other_elem == elem: - cnt_t += 1 - t[j] = NULL - if cnt_s != cnt_t: - diff = (cnt_s, cnt_t, elem) - result.append(diff) - - for i, elem in enumerate(t): - if elem is NULL: - continue - cnt_t = 0 - for j in range(i, n): - if t[j] == elem: - cnt_t += 1 - t[j] = NULL - diff = (0, cnt_t, elem) - result.append(diff) - return result - - -def _assertion(predicate, default_msg=None): - @wraps(predicate) - def inner(self, *args, **kwargs): - if 'msg' in kwargs: - msg = kwargs['msg'] - del kwargs['msg'] - else: - try: - msg = default_msg % args - except TypeError: - # message passed as final (non-keyword) argument? - msg = args[-1] - args = args[:-1] - assert predicate(*args, **kwargs), msg - return inner - - -def _regex_matches(val, regex): - if hasattr(regex, 'search'): - return regex.search(val) - else: - return re.search(regex, val) - - -class Bcfg2TestCase(unittest.TestCase): +class Bcfg2TestCase(TestCase): """ Base TestCase class that inherits from - :class:`unittest.TestCase`. This class does a few things: - - * Adds :func:`assertXMLEqual`, a useful assertion method given all - the XML used by Bcfg2; - - * Defines convenience methods that were (mostly) added in Python - 2.7. + :class:`unittest.TestCase`. This class adds + :func:`assertXMLEqual`, a useful assertion method given all the + XML used by Bcfg2. """ - if not hasattr(unittest.TestCase, "assertItemsEqual"): - # TestCase in Py3k lacks assertItemsEqual, but has the other - # convenience methods. this code is (mostly) cribbed from the - # py2.7 unittest library - def assertItemsEqual(self, expected_seq, actual_seq, msg=None): - """ Implementation of - :func:`unittest.TestCase.assertItemsEqual` for python - versions that lack it """ - first_seq, second_seq = list(actual_seq), list(expected_seq) - differences = _count_diff_all_purpose(first_seq, second_seq) - - if differences: - standardMsg = 'Element counts were not equal:\n' - lines = ['First has %d, Second has %d: %r' % diff - for diff in differences] - diffMsg = '\n'.join(lines) - standardMsg = self._truncateMessage(standardMsg, diffMsg) - msg = self._formatMessage(msg, standardMsg) - self.fail(msg) - - if not hasattr(unittest.TestCase, "assertRegexpMatches"): - # Some versions of TestCase in Py3k seem to lack - # assertRegexpMatches, but have the other convenience methods. - assertRegexpMatches = _assertion(lambda s, r: _regex_matches(s, r), - "%s does not contain /%s/") - - if not hasattr(unittest.TestCase, "assertNotRegexpMatches"): - # Some versions of TestCase in Py3k seem to lack - # assertNotRegexpMatches even though they have - # assertRegexpMatches - assertNotRegexpMatches = \ - _assertion(lambda s, r: not _regex_matches(s, r), - "%s contains /%s/") - - if not hasattr(unittest.TestCase, "assertIn"): - # versions of TestCase before python 2.7 and python 3.1 lacked - # a lot of the really handy convenience methods, so we provide - # them -- at least the easy ones and the ones we use. - assertIs = _assertion(lambda a, b: a is b, "%s is not %s") - assertIsNot = _assertion(lambda a, b: a is not b, "%s is %s") - assertIsNone = _assertion(lambda x: x is None, "%s is not None") - assertIsNotNone = _assertion(lambda x: x is not None, "%s is None") - assertIn = _assertion(lambda a, b: a in b, "%s is not in %s") - assertNotIn = _assertion(lambda a, b: a not in b, "%s is in %s") - assertIsInstance = _assertion(isinstance, "%s is not instance of %s") - assertNotIsInstance = _assertion(lambda a, b: not isinstance(a, b), - "%s is instance of %s") - assertGreater = _assertion(lambda a, b: a > b, - "%s is not greater than %s") - assertGreaterEqual = _assertion(lambda a, b: a >= b, - "%s is not greater than or equal to %s") - assertLess = _assertion(lambda a, b: a < b, "%s is not less than %s") - assertLessEqual = _assertion(lambda a, b: a <= b, - "%s is not less than or equal to %s") - def assertXMLEqual(self, el1, el2, msg=None): - """ Test that the two XML trees given are equal. Both - elements and all children are expected to have ``name`` - attributes. """ - self.assertEqual(el1.tag, el2.tag, msg=msg) - self.assertEqual(el1.text, el2.text, msg=msg) - self.assertItemsEqual(el1.attrib.items(), el2.attrib.items(), msg=msg) + """ Test that the two XML trees given are equal. """ + if msg is None: + msg = "XML trees are not equal: %s" + else: + msg += ": %s" + fullmsg = msg + "\nFirst: %s" % lxml.etree.tostring(el1) + \ + "\nSecond: %s" % lxml.etree.tostring(el2) + + self.assertEqual(el1.tag, el2.tag, msg=fullmsg % "Tags differ") + self.assertEqual(el1.text, el2.text, + msg=fullmsg % "Text content differs") + self.assertItemsEqual(el1.attrib.items(), el2.attrib.items(), + msg=fullmsg % "Attributes differ") self.assertEqual(len(el1.getchildren()), - len(el2.getchildren())) + len(el2.getchildren()), + msg=fullmsg % "Different numbers of children") + matched = [] for child1 in el1.getchildren(): - cname = child1.get("name") - self.assertIsNotNone(cname, - msg="Element %s has no 'name' attribute" % - child1.tag) - children2 = el2.xpath("%s[@name='%s']" % (child1.tag, cname)) - self.assertEqual(len(children2), 1, - msg="More than one %s element named %s" % \ - (child1.tag, cname)) - self.assertXMLEqual(child1, children2[0], msg=msg) + for child2 in el2.xpath(child1.tag): + if child2 in matched: + continue + try: + self.assertXMLEqual(child1, child2) + matched.append(child2) + break + except AssertionError: + continue + else: + assert False, \ + fullmsg % ("Element %s is missing from second" % + lxml.etree.tostring(child1)) + self.assertItemsEqual(el2.getchildren(), matched, + msg=fullmsg % "Second has extra element(s)") class DBModelTestCase(Bcfg2TestCase): @@ -289,11 +161,13 @@ class DBModelTestCase(Bcfg2TestCase): @skipUnless(has_django, "Django not found, skipping") def test_syncdb(self): """ Create the test database and sync the schema """ - setup_environ(Bcfg2.settings) - import django.core.management - django.core.management.call_command("syncdb", interactive=False, - verbosity=0) - self.assertTrue(os.path.exists(Bcfg2.settings.DATABASE_NAME)) + if self.models: + setup_environ(Bcfg2.settings) + import django.core.management + django.core.management.call_command("syncdb", interactive=False, + verbosity=0) + self.assertTrue( + os.path.exists(Bcfg2.settings.DATABASES['default']['NAME'])) @skipUnless(has_django, "Django not found, skipping") def test_cleandb(self): @@ -394,4 +268,3 @@ try: re_type = re._pattern_type except AttributeError: re_type = type(re.compile("")) - |