Пример #1
0
    def assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None):
        """Fail if the two objects are equal as determined by their
           difference rounded to the given number of decimal places
           (default 7) and comparing to zero, or by comparing that the
           between the two objects is less than the given delta.

           Note that decimal places (from zero) are usually not the same
           as significant digits (measured from the most signficant digit).

           Objects that are equal automatically fail.
        """
        if delta is not None and places is not None:
            raise TypeError("specify delta or places not both")
        if delta is not None:
            if not (first == second) and abs(first - second) > delta:
                return
            standardMsg = '%s == %s within %s delta' % (safe_repr(first),
                                                        safe_repr(second),
                                                        safe_repr(delta))
        else:
            if places is None:
                places = 7
            if not (first == second) and round(abs(second-first), places) != 0:
                return
            standardMsg = '%s == %s within %r places' % (safe_repr(first),
                                                         safe_repr(second),
                                                         places)

        msg = self._formatMessage(msg, standardMsg)
        raise self.failureException(msg)
Пример #2
0
    def assertItemsEqual(self, expected_seq, actual_seq, msg=None):
        missing = unexpected = None
        try:
            expected = sorted(expected_seq)
            actual = sorted(actual_seq)
        except TypeError:
            # Unsortable items (example: set(), complex(), ...)
            expected = list(expected_seq)
            actual = list(actual_seq)
            missing, unexpected = unorderable_list_difference(
                expected, actual)
        else:
            return self.assertSequenceEqual(expected, actual, msg=msg)

        errors = []
        if missing:
            errors.append(
                'Expected, but missing:\n    %s' % (safe_repr(missing), )
            )
        if unexpected:
            errors.append(
                'Unexpected, but present:\n    %s' % (safe_repr(unexpected), )
            )
        if errors:
            standardMsg = '\n'.join(errors)
            self.fail(self._formatMessage(msg, standardMsg))
Пример #3
0
    def assertDictContainsSubset(self, expected, actual, msg=None):
        missing, mismatched = [], []

        for key, value in items(expected):
            if key not in actual:
                missing.append(key)
            elif value != actual[key]:
                mismatched.append('%s, expected: %s, actual: %s' % (
                    safe_repr(key), safe_repr(value),
                    safe_repr(actual[key])))

        if not (missing or mismatched):
            return

        standard_msg = ''
        if missing:
            standard_msg = 'Missing: %s' % ','.join(map(safe_repr, missing))

        if mismatched:
            if standard_msg:
                standard_msg += '; '
            standard_msg += 'Mismatched values: %s' % (
                ','.join(mismatched))

        self.fail(self._formatMessage(msg, standard_msg))
Пример #4
0
    def assertDictContainsSubset(self, expected, actual, msg=None):
        """Checks whether actual is a superset of expected."""
        missing = []
        mismatched = []
        for key, value in expected.iteritems():
            if key not in actual:
                missing.append(key)
            elif value != actual[key]:
                mismatched.append('%s, expected: %s, actual: %s' %
                                  (safe_repr(key), safe_repr(value),
                                   safe_repr(actual[key])))

        if not (missing or mismatched):
            return

        standardMsg = ''
        if missing:
            standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in
                                                    missing)
        if mismatched:
            if standardMsg:
                standardMsg += '; '
            standardMsg += 'Mismatched values: %s' % ','.join(mismatched)

        self.fail(self._formatMessage(msg, standardMsg))
Пример #5
0
 def assertGreaterEqual(self, a, b, msg=None):
     """Just like self.assertTrue(a >= b), but with a nicer default
     message.
     """
     if not a >= b:
         standardMsg = '%s not greater than or equal to %s' % (safe_repr(a), safe_repr(b))
         self.fail(self._formatMessage(msg, standardMsg))
Пример #6
0
    def test_diff_output(self):
        self._create_conf()
        self._create_rpmnew()
        self._create_rpmsave()

        with self.rpmconf_plugin as rpmconf, mock.patch("sys.stdout", new_callable=StringIO) as stdout:
            rpmconf.diff = True
            rpmconf.run()

            lines = stdout.getvalue().splitlines()

        expected_lines = [
            "--- {0}".format(*self.conf_file),
            "+++ {0}".format(*self.conf_file_rpmnew),
            "@@ -1,3 +1,2 @@",
            " package = good",
            " true = false",
            '-what = "tahw"',
            "--- {0}".format(*self.conf_file_rpmsave),
            "+++ {0}".format(*self.conf_file),
            "@@ -1,2 +1,3 @@",
            "-package = bad",
            "-true = true",
            "+package = good",
            "+true = false",
            '+what = "tahw"',
        ]

        msg_tmpl = "{0} does not start with {1}"
        for line, expected_line in zip_longest(lines, expected_lines, fillvalue=""):
            if not line.startswith(expected_line):
                self.fail(msg_tmpl.format(safe_repr(line), safe_repr(expected_line)))
Пример #7
0
    def assertIsClose(self,
                      first,
                      second,
                      rel_tol=None,
                      abs_tol=None,
                      msg=None):
        ''' Fails if the two objects are unequal as determined by their
        absolute and relative difference

        If the two objects compare equal then they will automatically
        compare relative almost equal. '''

        if first == second:
            # shortcut
            return

        if rel_tol is None:
            rel_tol = 1e-09
        if abs_tol is None:
            abs_tol = 0.0

        if isclose(first, second, rel_tol, abs_tol):
            return

        standardMsg = '%s != %s within %s rel-tol and %s abs-tol' % (
            safe_repr(first), safe_repr(second), rel_tol, abs_tol)
        msg = self._formatMessage(msg, standardMsg)
        raise self.failureException(msg)
Пример #8
0
 def simple_equality(cls, first, second, msg=None):
     """
     Classmethod equivalent to unittest.TestCase method (longMessage = False.)
     """
     if not first==second:
         standardMsg = '%s != %s' % (safe_repr(first), safe_repr(second))
         raise cls.failureException(msg or standardMsg)
Пример #9
0
    def assertItemsEqual(self, expected_seq, actual_seq, msg=None):
        missing = unexpected = None
        try:
            expected = sorted(expected_seq)
            actual = sorted(actual_seq)
        except TypeError:
            # Unsortable items (example: set(), complex(), ...)
            expected = list(expected_seq)
            actual = list(actual_seq)
            missing, unexpected = unorderable_list_difference(
                expected, actual)
        else:
            return self.assertSequenceEqual(expected, actual, msg=msg)

        errors = []
        if missing:
            errors.append(
                'Expected, but missing:\n    %s' % (safe_repr(missing), )
            )
        if unexpected:
            errors.append(
                'Unexpected, but present:\n    %s' % (safe_repr(unexpected), )
            )
        if errors:
            standardMsg = '\n'.join(errors)
            self.fail(self._formatMessage(msg, standardMsg))
Пример #10
0
    def assertDictContainsSubset(self, dictionary, subset, msg=None):
        """Checks whether dictionary is a superset of subset."""

        missing = []
        mismatched = []
        for key, value in subset.items():
            if key not in dictionary:
                missing.append(key)
            elif value != dictionary[key]:
                mismatched.append('%s, expected: %s, actual: %s' %
                                  (safe_repr(key), safe_repr(value),
                                   safe_repr(dictionary[key])))

        if not (missing or mismatched):
            return

        standard_message = ''
        if missing:
            standard_message = 'Missing: %s' % ','.join(
                safe_repr(m) for m in missing)
        if mismatched:
            if standard_message:
                standard_message += '; '
            standard_message += 'Mismatched values: %s' % ','.join(mismatched)

        self.fail(self._formatMessage(msg, standard_message))
Пример #11
0
    def assertDictContainsSubset(self, expected, actual, msg=None):
        missing, mismatched = [], []

        for key, value in items(expected):
            if key not in actual:
                missing.append(key)
            elif value != actual[key]:
                mismatched.append('%s, expected: %s, actual: %s' % (
                    safe_repr(key), safe_repr(value),
                    safe_repr(actual[key])))

        if not (missing or mismatched):
            return

        standard_msg = ''
        if missing:
            standard_msg = 'Missing: %s' % ','.join(map(safe_repr, missing))

        if mismatched:
            if standard_msg:
                standard_msg += '; '
            standard_msg += 'Mismatched values: %s' % (
                ','.join(mismatched))

        self.fail(self._formatMessage(msg, standard_msg))
Пример #12
0
 def simple_equality(cls, first, second, msg=None):
     """
     Classmethod equivalent to unittest.TestCase method (longMessage = False.)
     """
     if not first == second:
         standardMsg = '%s != %s' % (safe_repr(first), safe_repr(second))
         raise cls.failureException(msg or standardMsg)
Пример #13
0
 def assertJson(self, expected, actual, assertType=1, msg=None):
     """
     Checks whether actual is a superset of expected. \n
     :param expected:  \n
     :param actual:  \n
     :param assertType: 0 模糊匹配  1 精确匹配  \n
     :param msg:  \n
     :return:  \n
     """
     expected = json.loads(expected)
     actual = json.loads(actual)
     assertType = int(assertType)
     missing = []
     mismatched = []
     for key, value in expected.iteritems():
         if key not in actual:
             missing.append(key)
         elif value != actual[key]:
             if assertType == 0 and type(value) == type(actual[key]):
                 continue
             mismatched.append(
                 '%s(expected: %s, actual: %s)' % (safe_repr(key), safe_repr(value), safe_repr(actual[key])))
     if not (missing or mismatched):
         return
     standardMsg = ''
     if missing:
         standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in missing)
     if mismatched:
         if standardMsg:
             standardMsg += '; '
         standardMsg += 'Mismatched values: %s' % ','.join(mismatched)
     raise AssertionError(self._formatMessage(msg, standardMsg))
Пример #14
0
 def assertLess(self, a, b, msg=None):
     """Just like self.assertTrue(a < b), but with a nicer default
     message.
     """
     if not a < b:
         standardMsg = '%s not less than %s' % (safe_repr(a), safe_repr(b))
         self.fail(self._formatMessage(msg, standardMsg))
Пример #15
0
 def assertAllIn(self, iterable, container, msg=None):
     """Check for all the item in iterable to be in the given container"""
     for member in iterable:
         if member not in container:
             if member not in container:
                 standardMsg = '%s not found in %s' % (safe_repr(member), safe_repr(container))
                 self.fail(self._formatMessage(msg, standardMsg))
Пример #16
0
def dicts_almost_equal(dict1, dict2, delta=None, places=None, default_value=0):
    """Test if two dictionaries with numeric values are almost equal.

    Fail if the two dictionaries are unequal as determined by
    comparing that the difference between values with the same key are
    not greater than delta (default 1e-8), or that difference rounded
    to the given number of decimal places is not zero. If a key in one
    dictionary is not in the other the default_value keyword argument
    will be used for the missing value (default 0). If the two objects
    compare equal then they will automatically compare almost equal.

    Args:
        dict1 (dict): a dictionary.
        dict2 (dict): a dictionary.
        delta (number): threshold for comparison (defaults to 1e-8).
        places (int): number of decimal places for comparison.
        default_value (number): default value for missing keys.

    Raises:
        TypeError: if the arguments are not valid (both `delta` and
            `places` are specified).

    Returns:
        String: Empty string if dictionaries are almost equal. A description
            of their difference if they are deemed not almost equal.
    """

    def valid_comparison(value):
        """compare value to delta, within places accuracy"""
        if places is not None:
            return round(value, places) == 0
        else:
            return value < delta

    # Check arguments.
    if dict1 == dict2:
        return ''
    if places is not None:
        if delta is not None:
            raise TypeError("specify delta or places not both")
        msg_suffix = ' within %s places' % places
    else:
        delta = delta or 1e-8
        msg_suffix = ' within %s delta' % delta

    # Compare all keys in both dicts, populating error_msg.
    error_msg = ''
    for key in set(dict1.keys()) | set(dict2.keys()):
        val1 = dict1.get(key, default_value)
        val2 = dict2.get(key, default_value)
        if not valid_comparison(abs(val1 - val2)):
            error_msg += '(%s: %s != %s), ' % (safe_repr(key),
                                               safe_repr(val1),
                                               safe_repr(val2))

    if error_msg:
        return error_msg[:-2] + msg_suffix
    else:
        return ''
Пример #17
0
 def assertAnyIn(self, iterable, container, msg=None):
     """Check for at least a one of the item in iterable to be in the given container"""
     for member in iterable:
         if member in container:
             break
     else:
         standardMsg = 'no item of %s found in %s' % (safe_repr(iterable), safe_repr(container))
         self.fail(self._formatMessage(msg, standardMsg))
Пример #18
0
 def assertAllIn(self, iterable, container, msg=None):
     """Check for all the item in iterable to be in the given container"""
     for member in iterable:
         if member not in container:
             if member not in container:
                 standardMsg = '%s not found in %s' % (safe_repr(member),
                                                       safe_repr(container))
                 self.fail(self._formatMessage(msg, standardMsg))
Пример #19
0
    def assertHTMLNotEqual(self, html1, html2, msg=None):
        """Asserts that two HTML snippets are not semantically equivalent."""
        dom1 = assert_and_parse_html(self, html1, msg, "First argument is not valid HTML:")
        dom2 = assert_and_parse_html(self, html2, msg, "Second argument is not valid HTML:")

        if dom1 == dom2:
            standardMsg = "%s == %s" % (safe_repr(dom1, True), safe_repr(dom2, True))
            self.fail(self._formatMessage(msg, standardMsg))
Пример #20
0
 def assertNotEqual(self, first, second, msg=None):
     """Fail if the two objects are equal as determined by the '=='
        operator.
     """
     if not first != second:
         msg = self._formatMessage(msg, '%s == %s' % (safe_repr(first),
                                                       safe_repr(second)))
         raise self.failureException(msg)
Пример #21
0
    def assertDictAlmostEqual(self,
                              dict1,
                              dict2,
                              delta=None,
                              msg=None,
                              places=None,
                              default_value=0):
        """Assert two dictionaries with numeric values are almost equal.

        Fail if the two dictionaries are unequal as determined by
        comparing that the difference between values with the same key are
        not greater than delta (default 1e-8), or that difference rounded
        to the given number of decimal places is not zero. If a key in one
        dictionary is not in the other the default_value keyword argument
        will be used for the missing value (default 0). If the two objects
        compare equal then they will automatically compare almost equal.

        Args:
            dict1 (dict): a dictionary.
            dict2 (dict): a dictionary.
            delta (number): threshold for comparison (defaults to 1e-8).
            msg (str): return a custom message on failure.
            places (int): number of decimal places for comparison.
            default_value (number): default value for missing keys.

        Raises:
            TypeError: raises TestCase failureException if the test fails.
        """
        def valid_comparison(value):
            """compare value to delta, within places accuracy"""
            if places is not None:
                return round(value, places) == 0
            else:
                return value < delta

        # Check arguments.
        if dict1 == dict2:
            return
        if places is not None:
            if delta is not None:
                raise TypeError("specify delta or places not both")
            msg_suffix = ' within %s places' % places
        else:
            delta = delta or 1e-8
            msg_suffix = ' within %s delta' % delta

        # Compare all keys in both dicts, populating error_msg.
        error_msg = ''
        for key in set(dict1.keys()) | set(dict2.keys()):
            val1 = dict1.get(key, default_value)
            val2 = dict2.get(key, default_value)
            if not valid_comparison(abs(val1 - val2)):
                error_msg += '(%s: %s != %s), ' % (
                    safe_repr(key), safe_repr(val1), safe_repr(val2))

        if error_msg:
            msg = self._formatMessage(msg, error_msg[:-2] + msg_suffix)
            raise self.failureException(msg)
Пример #22
0
 def assertIn(self, member, container, msg=None):
     """
     Just like self.assertTrue(a in b), but with a nicer default message.
     Backported from Python 2.7 unittest library.
     """
     if member not in container:
         standardMsg = '%s not found in %s' % (safe_repr(member),
                                               safe_repr(container))
         self.fail(self._formatMessage(msg, standardMsg))
Пример #23
0
 def assertAnyIn(self, iterable, container, msg=None):
     """Check for at least a one of the item in iterable to be in the given container"""
     for member in iterable:
         if member in container:
             break
     else:
         standardMsg = 'no item of %s found in %s' % (safe_repr(iterable),
                                                      safe_repr(container))
         self.fail(self._formatMessage(msg, standardMsg))
Пример #24
0
 def test_bugfix_release(self):
     self.version.release_bugfix_version()
     expected_reference = str(self.BUGFIX_RELEASE_TEST[0]) + '.' + \
                          str(self.BUGFIX_RELEASE_TEST[1]) + '.' + \
                          str(self.BUGFIX_RELEASE_TEST[2])
     self.assertTrue(self.version.major_version == self.BUGFIX_RELEASE_TEST[0] and
                     self.version.minor_version == self.BUGFIX_RELEASE_TEST[1] and
                     self.version.bugfix_version == self.BUGFIX_RELEASE_TEST[2],
                     msg='Major release of object %s is expected to be %s.' %
                         (safe_repr(self.version), safe_repr(expected_reference)))
Пример #25
0
 def assertInLog(self, member, container, level="INFO", msg=None):
     """Just like self.assertIn(member, container), but with a log level check."""
     self.assertIn(member, container)
     if not container.startswith(f"{level}:"):
         # This implementation is consistent with similar functions in unittest.case.
         standardMsg = "%s does not start with %s" % (
             safe_repr(container),
             safe_repr(level),
         )
         self.fail(self._formatMessage(msg, standardMsg))
Пример #26
0
    def assertDictEqual(self, d1, d2, excluded_keys=[], **kwargs):
        """
        Overrides super.assertDictEqual fn to remove certain keys from either list before the comparison
        (uses "**kwargs" b/c sometimes this gets called by built-in Django fns)
        """

        self.assertIsInstance(d1, dict, 'First argument is not a dictionary')
        self.assertIsInstance(d2, dict, 'Second argument is not a dictionary')

        d1_copy = d1.copy()
        d2_copy = d2.copy()
        for key_to_exclude in excluded_keys:
            d1_copy.pop(key_to_exclude, None)
            d2_copy.pop(key_to_exclude, None)

        msg = "{0} != {1}".format(safe_repr(d1_copy, True),
                                  safe_repr(d2_copy, True))
        diff = ('\n' + '\n'.join(
            ndiff(
                pprint.pformat(d1_copy).splitlines(),
                pprint.pformat(d2_copy).splitlines())))
        msg = self._truncateMessage(msg, diff)

        d1_keys = d1_copy.keys()
        d2_keys = d2_copy.keys()
        self.assertSetEqual(
            set(d1_keys), set(d2_keys),
            msg=msg)  # comparing as a set b/c order is irrelevant

        for key in d1_keys:
            d1_value = d1_copy[key]
            d2_value = d2_copy[key]
            # I am doing this instead of just calling super()
            # b/c Django doesn't consider querysets to be equal even if they point to the same thing
            # (see http://stackoverflow.com/questions/16058571/comparing-querysets-in-django-testcase)
            d1_type = type(d1_value)
            d2_type = type(d2_value)

            try:
                self.assertEqual(d1_type, d2_type, msg=msg)
            except AssertionError:
                # If I was checking strings & unicode objects or querysets & lists then the above assertion would have failed
                # so check those 2 special cases here...
                # string_types = [str, unicode, ]
                # if d1_type in string_types and d2_type in string_types:
                #     self.assertEqual(str(d1_value), str(d2_value))
                if QuerySet in inspect.getmro(
                        d1_type
                ) or QuerySet in inspect.getmro(
                        d2_type
                ):  # lil bit of indirection here b/c custom managers acting as querysets might have been created dynamically
                    self.assertQuerysetEqual(d1_value, d2_value)
                else:
                    # ...and if it still fails, then go ahead and raise the original error
                    raise AssertionError(msg)
Пример #27
0
        def assert_datatype_equal(self, dt1, dt2, msg=None):
            if not isinstance(dt1, DataType):
                dt1 = DataType(dt1)
            if not isinstance(dt2, DataType):
                dt2 = DataType(dt2)

            if dt1 != dt2:
                standard_msg = '{} != {}'.format(safe_repr(dt1, True), safe_repr(dt2, True))
                diff = '\n' + '\n'.join(difflib.ndiff(dt1.pretty_repr(), dt2.pretty_repr()))
                standard_msg = self._truncateMessage(standard_msg, diff)
                self.fail(self._formatMessage(msg, standard_msg))
Пример #28
0
 def assertEqual(self, val1, val2, msg=None, exact=False):
     if val1 == val2:
         return
     if not exact and isinstance(val1, str) and isinstance(val2, str):
         self.assertSimilarStrings(val1, val2, msg)
     elif (not exact and isinstance(val1, (int, float)) and
           isinstance(val2, (int, float))):
         if abs(val2 - val1) <= UnitTestedAssignment.DELTA:
             return
     standardMsg = "{} != {}".format(safe_repr(val1), safe_repr(val2))
     self.fail(msg, standardMsg)
Пример #29
0
    def assertHTMLNotEqual(self, html1, html2, msg=None):
        """Asserts that two HTML snippets are not semantically equivalent."""
        dom1 = assert_and_parse_html(self, html1, msg,
            'First argument is not valid HTML:')
        dom2 = assert_and_parse_html(self, html2, msg,
            'Second argument is not valid HTML:')

        if dom1 == dom2:
            standardMsg = '%s == %s' % (
                safe_repr(dom1, True), safe_repr(dom2, True))
            self.fail(self._formatMessage(msg, standardMsg))
Пример #30
0
    def assertDictEqual(self, d1, d2, msg=None):
        self.assertIsInstance(d1, dict, 'First argument is not a dictionary')
        self.assertIsInstance(d2, dict, 'Second argument is not a dictionary')

        if d1 != d2:
            standardMsg = '%s != %s' % (safe_repr(d1, True), safe_repr(d2, True))
            diff = ('\n' + '\n'.join(difflib.ndiff(
                           pprint.pformat(d1).splitlines(),
                           pprint.pformat(d2).splitlines())))
            standardMsg = self._truncateMessage(standardMsg, diff)
            self.fail(self._formatMessage(msg, standardMsg))
Пример #31
0
    def assertFound(self, x, string, msg=None):
        idx = string.find(x)

        if idx == -1:
            std_msg = '{sub} not found in {string}'.format(
                sub=safe_repr(x),
                string=safe_repr(string),
            )
            self.fail(self._formatMessage(msg, std_msg))

        return idx
Пример #32
0
 def assertEqual(self, val1, val2, msg=None, exact=False):
     if val1 == val2:
         return
     if not exact and isinstance(val1, str) and isinstance(val2, str):
         self.assertSimilarStrings(val1, val2, msg)
     elif (not exact and isinstance(val1, (int, float))
           and isinstance(val2, (int, float))):
         if abs(val2 - val1) <= UnitTestedAssignment.DELTA:
             return
     standardMsg = "{} != {}".format(safe_repr(val1), safe_repr(val2))
     self.fail(msg, standardMsg)
Пример #33
0
 def assertcountmessage(self, request, nb, liste=False):
     messages = get_messages(request)
     actual = len([e.message for e in messages])
     if actual != nb:
         if liste:
             messages_str = "[\n"
             for m in messages:
                 messages_str += "\t'" + m.message + "',\n"
                 messages_str += "]"
             self.fail('Message count was %s, expected %s. list of messages: \n %s' % (actual, nb, messages_str))
         else:
             self.fail('Message count was %s, expected %s' % (safe_repr(actual), safe_repr(nb)))
Пример #34
0
    def assertDOMEqual(self, dom1, dom2, msg=None):
        if dom1 != dom2:
            standard_msg = '{} != {}'.format(
                safe_repr(dom1, True),
                safe_repr(dom2, True)
            )
            diff = ('\n' + '\n'.join(difflib.ndiff(
                str(dom1).splitlines(),
                str(dom2).splitlines(),
            )))

            self.fail(self._formatMessage(msg, self._truncateMessage(standard_msg, diff)))
Пример #35
0
 def assertRedirect(self, response, relative_url):
     if not (response and isinstance(response, Response)):
         self.fail('No Response instance found')
     if response.status_code != 302:
         self.fail('Unexpected return code ' + str(response.status_code))
     location = response.headers.get('Location')
     if not re.match(relative_url, location, re.RegexFlag.IGNORECASE):
         loc = safe_repr(location)
         url = safe_repr(relative_url)
         msg = self._formatMessage(f'{loc} does not start with {url}',
                                   'unexpected redirect target')
         raise self.failureException(msg)
    def assertArrayEqual(self, first, second, msg=None):
        '''Fail if a is not a numpy array or if it is not equal to b'''

        if not isinstance(first, np.ndarray):
            std_msg = '%s is %s, not numpy array' % (safe_repr(first),
                                                     type(first))
            self.fail(self._formatMessage(msg, std_msg))

        if not np.all(first == second):
            std_msg = '%s is not equal to %s' % (safe_repr(first),
                                                 safe_repr(second))
            self.fail(self._formatMessage(msg, std_msg))
Пример #37
0
 def assertDeltaWithin(self,
                       expected_value,
                       actual_value,
                       acceptable_delta,
                       message=""):
     actual_delta = abs(expected_value - actual_value)
     self.logger.debug(
         f"Delta: {actual_delta:.3f}, Acceptable: {acceptable_delta:.3f}")
     if not actual_delta <= acceptable_delta:
         standard_msg = "%s is not within %s +- %s" % (
             safe_repr(actual_value), safe_repr(expected_value),
             safe_repr(acceptable_delta))
         self.fail(self._formatMessage(message, standard_msg))
Пример #38
0
 def SetModuleInfoEqual(self, first_inst, second_inst):
     """
     自定义断言:用于判断两个对象的属性值是否相等
     """
     if not (first_inst.set_name == second_inst.set_name
             and first_inst.set_id == second_inst.set_id
             and first_inst.module_name == second_inst.module_name
             and first_inst.module_id == second_inst.module_id and
             first_inst.flat__module_id == second_inst.flat__module_id and
             first_inst.flat__module_name == second_inst.flat__module_name):
         msg = self._formatMessage(
             "%s == %s" % (safe_repr(first_inst), safe_repr(second_inst)))
         raise self.failureException(msg)
Пример #39
0
    def assertSpyCalledWith(self, spy_or_call, *expected_args,
                            **expected_kwargs):
        """Assert that a function was called with the given arguments.

        If a spy is provided, all calls will be checked for a match.

        This will imply :py:meth:`assertHasSpy`.

        Args:
            spy_or_call (callable or kgb.spies.FunctionSpy):
                The function, spy, or call to check.

            *expected_args (tuple):
                Position arguments expected to be provided in any of the calls.

            **expected_kwargs (dict):
                Keyword arguments expected to be provided in any of the calls.

        Raises:
            AssertionError:
                The function was not called with the provided arguments.
        """
        if isinstance(spy_or_call, FunctionSpy):
            self.assertSpyCalled(spy_or_call)

        if not spy_or_call.called_with(*expected_args, **expected_kwargs):
            if isinstance(spy_or_call, SpyCall):
                self._kgb_assert_fail(
                    'This call to %s was not passed args=%s, kwargs=%s.\n'
                    '\n'
                    'It was called with:\n'
                    '\n'
                    '%s' % (
                        self._format_spy_or_call(spy_or_call),
                        safe_repr(expected_args),
                        format_spy_kwargs(expected_kwargs),
                        self._format_spy_call_args(spy_or_call),
                    ))
            else:
                self._kgb_assert_fail(
                    'No call to %s was passed args=%s, kwargs=%s.\n'
                    '\n'
                    'The following calls were recorded:\n'
                    '\n'
                    '%s' % (
                        self._format_spy_or_call(spy_or_call),
                        safe_repr(expected_args),
                        format_spy_kwargs(expected_kwargs),
                        self._format_spy_calls(spy_or_call,
                                               self._format_spy_call_args),
                    ))
Пример #40
0
    def assertCountOccurrences(self, member, container, count, msg=None):
        """Like self.assertEqual(count, container.count(member),
        but with a nicer default message.
        """
        occ_count = container.count(member)

        if occ_count != count:
            std_msg = '{member} found {occ} time(s) in {container} ({exp} expected)'.format(
                            member=safe_repr(member),
                            container=safe_repr(container),
                            occ=occ_count,
                            exp=count,
            )
            self.fail(self._formatMessage(msg, std_msg))
Пример #41
0
    def assertSize(self, obj, size, msg=None):  # pylint: disable=invalid-name
        """Same as ``self.assertEqual(len(obj), size)``, with a nicer default
        message."""
        try:
            obj_size = len(obj)
        except Exception:  # pylint: disable=broad-except
            logging.exception("Couldn't get object size")
            self.fail('Could not get {} size.'.format(safe_repr(obj)))
            return

        if size != obj_size:
            standard_msg = "{}'s size is {} != {}".format(safe_repr(obj),
                                                          obj_size, size)
            self.fail(self._formatMessage(msg, standard_msg))
Пример #42
0
    def assertHTMLEqual(self, html1, html2, msg=None):
        """
        Asserts that two HTML snippets are semantically the same.
        Whitespace in most cases is ignored, and attribute ordering is not
        significant. The passed-in arguments must be valid HTML.
        """
        dom1 = assert_and_parse_html(self, html1, msg, "First argument is not valid HTML:")
        dom2 = assert_and_parse_html(self, html2, msg, "Second argument is not valid HTML:")

        if dom1 != dom2:
            standardMsg = "%s != %s" % (safe_repr(dom1, True), safe_repr(dom2, True))
            diff = "\n" + "\n".join(difflib.ndiff(six.text_type(dom1).splitlines(), six.text_type(dom2).splitlines()))
            standardMsg = self._truncateMessage(standardMsg, diff)
            self.fail(self._formatMessage(msg, standardMsg))
Пример #43
0
def assertDictContainsSubsetRecursive(self,
                                      expected,
                                      actual,
                                      depth=0,
                                      msg=None):
    assert isinstance(self, TestCase)
    self.assertIsInstance(expected, collections.Mapping)
    self.assertIsInstance(actual, collections.Mapping)
    missing = []
    mismatched = []
    for key, value in expected.iteritems():
        if isinstance(value, datetime.datetime):
            value = datetime.datetime.strftime(value, '%Y-%m-%d %H:%M:%S%z')
        if isinstance(actual[key], datetime.datetime):
            actual[key] = datetime.datetime.strftime(actual[key],
                                                     '%Y-%m-%d %H:%M:%S%z')
        if key not in actual:
            missing.append(key)
        elif isinstance(actual[key], collections.Mapping):
            missing_1, mismatched_1 = self.assertDictContainsSubsetRecursive(
                value, actual[key], depth=depth + 1)
            missing.extend(missing_1)
            mismatched.extend(mismatched_1)
        elif isinstance(actual[key], collections.Sequence) and hasattr(
                actual[key], '__iter__'):
            missing_1, mismatched_1 = self.assertSequenceRecursive(
                value, actual[key], depth=depth + 1)
            missing.extend(missing_1)
            mismatched.extend(mismatched_1)
        elif value != actual[key]:
            mismatched.append(
                '%s, expected: %s, actual: %s' %
                (safe_repr(key), safe_repr(value), safe_repr(actual[key])))

    if depth > 0:
        return missing, mismatched

    if not (missing or mismatched):
        return

    standardMsg = ''
    if missing:
        standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in missing)
    if mismatched:
        if standardMsg:
            standardMsg += '; '
        standardMsg += 'Mismatched values: %s' % ','.join(mismatched)

    self.fail(self._formatMessage(msg, standardMsg))
Пример #44
0
 def assertcountmessage(self, request, nb, liste=False):
     messages = get_messages(request)
     actual = len([e.message for e in messages])
     if actual != nb:
         if liste:
             messages_str = "[\n"
             for m in messages:
                 messages_str += "\t'" + m.message + "',\n"
                 messages_str += "]"
             self.fail(
                 'Message count was %s, expected %s. list of messages: \n %s'
                 % (actual, nb, messages_str))
         else:
             self.fail('Message count was %s, expected %s' %
                       (safe_repr(actual), safe_repr(nb)))
Пример #45
0
 def assertXMLNotEqual(self, xml1, xml2, msg=None):
     """
     Asserts that two XML snippets are not semantically equivalent.
     Whitespace in most cases is ignored, and attribute ordering is not
     significant. The passed-in arguments must be valid XML.
     """
     try:
         result = compare_xml(xml1, xml2)
     except Exception as e:
         standardMsg = 'First or second argument is not valid XML\n%s' % e
         self.fail(self._formatMessage(msg, standardMsg))
     else:
         if result:
             standardMsg = '%s == %s' % (safe_repr(xml1, True), safe_repr(xml2, True))
             self.fail(self._formatMessage(msg, standardMsg))
Пример #46
0
 def assertXMLNotEqual(self, xml1, xml2, msg=None):
     """
     Asserts that two XML snippets are not semantically equivalent.
     Whitespace in most cases is ignored, and attribute ordering is not
     significant. The passed-in arguments must be valid XML.
     """
     try:
         result = compare_xml(xml1, xml2)
     except Exception as e:
         standardMsg = 'First or second argument is not valid XML\n%s' % e
         self.fail(self._formatMessage(msg, standardMsg))
     else:
         if result:
             standardMsg = '%s == %s' % (safe_repr(xml1, True), safe_repr(xml2, True))
             self.fail(self._formatMessage(msg, standardMsg))
Пример #47
0
 def assertNotAlmostEqualRelativePopulation(self,
                                            actual,
                                            reference,
                                            precision=1E-3,
                                            msg=''):
     for level_index in range(actual.atomic_db.atomic_levels):
         level = 'rel.pop ' + actual.atomic_db.inv_atomic_dict[level_index]
         status, statement = self._areSeriesAlmostEqual(
             actual.profiles[level], reference.profiles[level], precision)
         if status:
             standardMsg = 'Relative population evolution on level %s are within relative error of %s. ' \
                           'This is not expected. Series 1 = actual, Series 2 = reference. \n' % \
                           (safe_repr(level), safe_repr(precision)) + statement
             msg = self._formatMessage(msg, standardMsg)
             self.fail(msg)
Пример #48
0
def assertSequenceRecursive(self, expected, actual, depth=0, msg=None):
    assert isinstance(self, TestCase)
    missing = []
    mismatched = []
    self.assertIsInstance(expected, collections.Sequence)
    self.assertIsInstance(actual, collections.Sequence)
    self.assertEqual(len(expected),
                     len(actual),
                     msg='Lengths are different: {} vs {}'.format(
                         expected, actual))
    for expected_item, actual_item in zip(expected, actual):
        if isinstance(actual_item, datetime.datetime):
            actual_item = datetime.datetime.strftime(actual_item,
                                                     '%Y-%m-%d %H:%M:%S%z')
        if isinstance(expected_item, datetime.datetime):
            expected_item = datetime.datetime.strftime(expected_item,
                                                       '%Y-%m-%d %H:%M:%S%z')
        if isinstance(actual_item, collections.Mapping):
            missing_1, mismatched_1 = self.assertDictContainsSubsetRecursive(
                expected_item, actual_item, depth=depth + 1)
            missing.extend(missing_1)
            mismatched.extend(mismatched_1)
        elif isinstance(actual_item, collections.Sequence) and hasattr(
                actual_item, '__iter__'):
            missing_1, mismatched_1 = self.assertSequenceRecursive(
                expected_item, actual_item, depth=depth + 1)
            missing.extend(missing_1)
            mismatched.extend(mismatched_1)
        elif expected_item != actual_item:
            mismatched.append(
                'expected: %s, actual: %s' %
                (safe_repr(expected_item), safe_repr(actual_item)))

    if depth > 0:
        return missing, mismatched

    if not (missing or mismatched):
        return

    standardMsg = ''
    if missing:
        standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in missing)
    if mismatched:
        if standardMsg:
            standardMsg += '; '
        standardMsg += 'Mismatched values: %s' % ','.join(mismatched)

    self.fail(self._formatMessage(msg, standardMsg))
Пример #49
0
    def _format_msg_existence(self, obj_path, obj_type,
                              msg=None, should_exists=True):

        exists_error_txt = (should_exists and "doesn't") or "does"
        return self._formatMessage(
            msg, '{} {} {} exist'.format(
                obj_type, safe_repr(obj_path), exists_error_txt))
Пример #50
0
 def assert5XX(self, status_code, msg=None):
     """
     Assert that the given value is a server error status (between 500 and 599)
     """
     if not 500 <= status_code < 600:
         msg = self._formatMessage(msg, "%s is not a server error status" % safe_repr(status_code))
         raise self.failureExecption(msg)
Пример #51
0
 def assert4XX(self, status_code, msg=None):
     """
     Assert that the given value is a client error status (between 400 and 499)
     """
     if not 400 <= status_code < 500:
         msg = self._formatMessage(msg, "%s is not a client error status" % safe_repr(status_code))
         raise self.failureExecption(msg)
Пример #52
0
 def assert3XX(self, status_code, msg=None):
     """
     Assert that the given value is a redirection status (between 300 and 399)
     """
     if not 300 <= status_code < 400:
         msg = self._formatMessage(msg, "%s is not a redirection status" % safe_repr(status_code))
         raise self.failureExecption(msg)
Пример #53
0
 def assertIsNone(self, obj, msg=None):
     """Same as self.assertTrue(obj is None), with a nicer default
     message.
     """
     if obj is not None:
         standardMsg = '%s is not None' % (safe_repr(obj),)
         self.fail(self._formatMessage(msg, standardMsg))
Пример #54
0
 def assert2XX(self, status_code, msg=None):
     """
     Assert that the given value is a success status (between 200 and 299)
     """
     if not 200 <= status_code < 300:
         msg = self._formatMessage(msg, "%s is not a success status" % safe_repr(status_code))
         raise self.failureExecption(msg)
    def test_frontend_none(self):
        c_path, c_content = self._create_conf()
        new_path, new_content = self._create_rpmnew()

        with self.rpmconf_plugin as rpmconf,\
                mock.patch("rpmconf.rpmconf.RpmConf.flush_input", return_value='M'),\
                mock.patch("sys.stdout", new_callable=StringIO),\
                mock.patch.dict("os.environ"):
            if os.environ.get("MERGE"):
                del os.environ["MERGE"]
            try:
                rpmconf.frontend = 'env'
                rpmconf.run()
            except SystemExit as e:
                if e.code in (errno.ENOENT, errno.EINTR):
                    self.fail("rpmconf has exited prematurely in the merge phase")
                else:
                    self.fail(
                        "rpmconf has exited prematurely"
                        "with unknown exit code {0}".format(safe_repr(e.code)))

        self.assertTrue(os.access(c_path, os.F_OK))
        with open(c_path, 'rb') as f:
            c_result = f.read()

        self.assertEqual(c_result, c_content)

        self.assertTrue(os.access(new_path, os.F_OK))
        with open(new_path, 'rb') as f:
            new_result = f.read()

        self.assertEqual(new_result, new_content)
Пример #56
0
    def assertDictEqual(self, d1, d2, excluded_keys=[], **kwargs):
        """
        Overrides super.assertDictEqual fn to remove certain keys from either list before the comparison
        (uses "**kwargs" b/c sometimes this gets called by built-in Django fns)
        """

        self.assertIsInstance(d1, dict, 'First argument is not a dictionary')
        self.assertIsInstance(d2, dict, 'Second argument is not a dictionary')

        d1_copy = d1.copy()
        d2_copy = d2.copy()
        for key_to_exclude in excluded_keys:
            d1_copy.pop(key_to_exclude, None)
            d2_copy.pop(key_to_exclude, None)

        msg = "{0} != {1}".format(safe_repr(d1_copy, True), safe_repr(d2_copy, True))
        diff = ('\n' + '\n'.join(ndiff(
            pprint.pformat(d1_copy).splitlines(),
            pprint.pformat(d2_copy).splitlines())))
        msg = self._truncateMessage(msg, diff)

        d1_keys = d1_copy.keys()
        d2_keys = d2_copy.keys()
        self.assertSetEqual(set(d1_keys), set(d2_keys), msg=msg)  # comparing as a set b/c order is irrelevant

        for key in d1_keys:
            d1_value = d1_copy[key]
            d2_value = d2_copy[key]
            # I am doing this instead of just calling super()
            # b/c Django doesn't consider querysets to be equal even if they point to the same thing
            # (see http://stackoverflow.com/questions/16058571/comparing-querysets-in-django-testcase)
            d1_type = type(d1_value)
            d2_type = type(d2_value)

            try:
                self.assertEqual(d1_value, d2_value, msg=msg)
            except AssertionError:
                # If I was checking strings & unicode objects or querysets & lists then the above assertion would have failed
                # so check those 2 special cases here...
                string_types = [str, unicode, ]
                if d1_type in string_types and d2_type in string_types:
                    self.assertEqual(str(d1_value), str(d2_value))
                elif QuerySet in inspect.getmro(d1_type) or QuerySet in inspect.getmro(d2_type): # lil bit of indirection here b/c custom managers acting as querysets might have been created dynamically
                    self.assertQuerysetEqual(d1_value, d2_value)
                else:
                    # ...and if it still fails, then go ahead and raise the original error
                    raise AssertionError(msg)
Пример #57
0
 def describe(self):
     msg = ""
     if self.symmetric_diff:
         only_expected = helpers.dict_subtract(self.expected, self.actual)
         only_actual = helpers.dict_subtract(self.actual, self.expected)
         if only_expected:
             msg += "Only in expected:\n  %s\n" % \
                    util.safe_repr(only_expected)
         if only_actual:
             msg += "Only in actual:\n  %s\n" % \
                    util.safe_repr(only_actual)
     diff_set = set(o for o in self.intersect if
                    self.expected[o] != self.actual[o])
     if diff_set:
         msg += "Differences:\n"
     for o in diff_set:
         msg += "  %s: expected %s, actual %s\n" % (
             o, self.expected[o], self.actual[o])
     return msg
Пример #58
0
 def _assert_valid_import(self, line, filename):
     if not line.strip():
         return
     for tag in DISALLOWED_TAGS:
         self.assertNotRegexpMatches(tag[0], line.strip(), tag[1])
     if 'src' not in line and 'href' not in line:
         return
     self.assertIn(
         'new_static', line, msg='new_static not found in %s in file %s' % (safe_repr(line), filename)
     )
Пример #59
0
def assertDictContainsSubsetRecursive(self, expected, actual, depth=0, msg=None):
    assert isinstance(self, TestCase)
    self.assertIsInstance(expected, collections.Mapping)
    self.assertIsInstance(actual, collections.Mapping)
    missing = []
    mismatched = []
    for key, value in expected.iteritems():
        if isinstance(value, datetime.datetime):
            value = datetime.datetime.strftime(value, '%Y-%m-%d %H:%M:%S%z')
        if isinstance(actual[key], datetime.datetime):
            actual[key] = datetime.datetime.strftime(actual[key], '%Y-%m-%d %H:%M:%S%z')
        if key not in actual:
            missing.append(key)
        elif isinstance(actual[key], collections.Mapping):
            missing_1, mismatched_1 = self.assertDictContainsSubsetRecursive(value, actual[key], depth=depth + 1)
            missing.extend(missing_1)
            mismatched.extend(mismatched_1)
        elif isinstance(actual[key], collections.Sequence) and hasattr(actual[key], '__iter__'):
            missing_1, mismatched_1 = self.assertSequenceRecursive(value, actual[key], depth=depth + 1)
            missing.extend(missing_1)
            mismatched.extend(mismatched_1)
        elif value != actual[key]:
            mismatched.append('%s, expected: %s, actual: %s' %
                              (safe_repr(key), safe_repr(value),
                               safe_repr(actual[key])))

    if depth > 0:
        return missing, mismatched

    if not (missing or mismatched):
        return

    standardMsg = ''
    if missing:
        standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in
                                               missing)
    if mismatched:
        if standardMsg:
            standardMsg += '; '
        standardMsg += 'Mismatched values: %s' % ','.join(mismatched)

    self.fail(self._formatMessage(msg, standardMsg))