Example #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)
Example #2
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))
Example #3
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))
Example #4
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)
Example #5
0
 def _formatMessage(self, msg, standardMsg):
     if not self.longMessage:
         return msg or standardMsg
     if msg is None:
         return standardMsg
     try:
         return '%s : %s' % (standardMsg, msg)
     except UnicodeDecodeError:
         return '%s : %s' % (safe_repr(standardMsg), safe_repr(msg))
Example #6
0
 def assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None):
     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)
Example #7
0
 def assertMultiLineEqual(self, first, second, msg=None):
     self.assertIsInstance(first, str, 'First argument is not a string')
     self.assertIsInstance(second, str, 'Second argument is not a string')
     if first != second:
         if len(first) > self._diffThreshold or len(second) > self._diffThreshold:
             self._baseAssertEqual(first, second, msg)
         firstlines = first.splitlines(keepends=True)
         secondlines = second.splitlines(keepends=True)
         if len(firstlines) == 1 and first.strip('\r\n') == first:
             firstlines = [first + '\n']
             secondlines = [second + '\n']
         standardMsg = '%s != %s' % (safe_repr(first, True), safe_repr(second, True))
         diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines))
         standardMsg = self._truncateMessage(standardMsg, diff)
         self.fail(self._formatMessage(msg, standardMsg))
Example #8
0
    def _formatMessage(self, msg, standardMsg):
        """Honour the longMessage attribute when generating failure messages.
        If longMessage is False this means:
        * Use only an explicit message if it is provided
        * Otherwise use the standard message for the assert

        If longMessage is True:
        * Use the standard message
        * If an explicit message is provided, plus ' : ' and the explicit message
        """
        if not self.longMessage:
            return msg or standardMsg
        if msg is None:
            return standardMsg
        try:
            # don't switch to '{}' formatting in Python 2.X
            # it changes the way unicode input is handled
            return '%s : %s' % (standardMsg, msg)
        except UnicodeDecodeError:
            return '%s : %s' % (safe_repr(standardMsg), safe_repr(msg))
Example #9
0
 def assertDictContainsSubset(self, subset, dictionary, msg=None):
     warnings.warn('assertDictContainsSubset is deprecated', DeprecationWarning)
     missing = []
     mismatched = []
     for (key, value) in subset.items():
         if key not in dictionary:
             missing.append(key)
         else:
             while 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
     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))
Example #10
0
    def assertMultiLineEqual(self, first, second, msg=None):
        """Assert that two multi-line strings are equal."""
        self.assertIsInstance(first, basestring,
                              'First argument is not a string')
        self.assertIsInstance(second, basestring,
                              'Second argument is not a string')

        if first != second:
            # don't use difflib if the strings are too long
            if (len(first) > self._diffThreshold
                    or len(second) > self._diffThreshold):
                self._baseAssertEqual(first, second, msg)
            firstlines = first.splitlines(True)
            secondlines = second.splitlines(True)
            if len(firstlines) == 1 and first.strip('\r\n') == first:
                firstlines = [first + '\n']
                secondlines = [second + '\n']
            standardMsg = '%s != %s' % (safe_repr(
                first, True), safe_repr(second, True))
            diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines))
            standardMsg = self._truncateMessage(standardMsg, diff)
            self.fail(self._formatMessage(msg, standardMsg))
Example #11
0
 def assertNotIn(self, member, container, msg=None):
     """Just like self.assertTrue(a not in b), but with a nicer default message."""
     if member in container:
         standardMsg = '%s unexpectedly found in %s' % (
             safe_repr(member), safe_repr(container))
         self.fail(self._formatMessage(msg, standardMsg))
Example #12
0
 def assertIsNot(self, expr1, expr2, msg=None):
     if expr1 is expr2:
         standardMsg = 'unexpectedly identical: %s' % (safe_repr(expr1),)
         self.fail(self._formatMessage(msg, standardMsg))
Example #13
0
 def assertIs(self, expr1, expr2, msg=None):
     if expr1 is not expr2:
         standardMsg = '%s is not %s' % (safe_repr(expr1), safe_repr(expr2))
         self.fail(self._formatMessage(msg, standardMsg))
Example #14
0
 def assertNotIn(self, member, container, msg=None):
     if member in container:
         standardMsg = '%s unexpectedly found in %s' % (safe_repr(member), safe_repr(container))
         self.fail(self._formatMessage(msg, standardMsg))
Example #15
0
 def assertIsNone(self, obj, msg=None):
     if obj is not None:
         standardMsg = '%s is not None' % (safe_repr(obj),)
         self.fail(self._formatMessage(msg, standardMsg))
Example #16
0
 def assertLessEqual(self, a, b, msg=None):
     if not a <= b:
         standardMsg = '%s not less than or equal to %s' % (safe_repr(a), safe_repr(b))
         self.fail(self._formatMessage(msg, standardMsg))
Example #17
0
 def _baseAssertEqual(self, first, second, msg=None):
     if not first == second:
         standardMsg = '%s != %s' % (safe_repr(first), safe_repr(second))
         msg = self._formatMessage(msg, standardMsg)
         raise self.failureException(msg)
Example #18
0
 def _baseAssertEqual(self, first, second, msg=None):
     """The default assertEqual implementation, not type specific."""
     if not first == second:
         standardMsg = '%s != %s' % (safe_repr(first), safe_repr(second))
         msg = self._formatMessage(msg, standardMsg)
         raise self.failureException(msg)
Example #19
0
 def assertTrue(self, expr, msg=None):
     if not expr:
         msg = self._formatMessage(msg, '%s is not true' % safe_repr(expr))
         raise self.failureException(msg)
Example #20
0
 def assertIsInstance(self, obj, cls, msg=None):
     """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
     default message."""
     if not isinstance(obj, cls):
         standardMsg = '%s is not an instance of %r' % (safe_repr(obj), cls)
         self.fail(self._formatMessage(msg, standardMsg))
Example #21
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))
Example #22
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))
Example #23
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))
Example #24
0
 def assertNotEqual(self, first, second, msg=None):
     if not first != second:
         msg = self._formatMessage(msg, '%s == %s' % (safe_repr(first), safe_repr(second)))
         raise self.failureException(msg)
Example #25
0
    def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
        """An equality assertion for ordered sequences (like lists and tuples).

        For the purposes of this function, a valid ordered sequence type is one
        which can be indexed, has a length, and has an equality operator.

        Args:
            seq1: The first sequence to compare.
            seq2: The second sequence to compare.
            seq_type: The expected datatype of the sequences, or None if no
                    datatype should be enforced.
            msg: Optional message to use on failure instead of a list of
                    differences.
        """
        if seq_type is not None:
            seq_type_name = seq_type.__name__
            if not isinstance(seq1, seq_type):
                raise self.failureException('First sequence is not a %s: %s' %
                                            (seq_type_name, safe_repr(seq1)))
            if not isinstance(seq2, seq_type):
                raise self.failureException('Second sequence is not a %s: %s' %
                                            (seq_type_name, safe_repr(seq2)))
        else:
            seq_type_name = "sequence"

        differing = None
        try:
            len1 = len(seq1)
        except (TypeError, NotImplementedError):
            differing = 'First %s has no length.    Non-sequence?' % (
                seq_type_name)

        if differing is None:
            try:
                len2 = len(seq2)
            except (TypeError, NotImplementedError):
                differing = 'Second %s has no length.    Non-sequence?' % (
                    seq_type_name)

        if differing is None:
            if seq1 == seq2:
                return

            seq1_repr = safe_repr(seq1)
            seq2_repr = safe_repr(seq2)
            if len(seq1_repr) > 30:
                seq1_repr = seq1_repr[:30] + '...'
            if len(seq2_repr) > 30:
                seq2_repr = seq2_repr[:30] + '...'
            elements = (seq_type_name.capitalize(), seq1_repr, seq2_repr)
            differing = '%ss differ: %s != %s\n' % elements

            for i in xrange(min(len1, len2)):
                try:
                    item1 = seq1[i]
                except (TypeError, IndexError, NotImplementedError):
                    differing += (
                        '\nUnable to index element %d of first %s\n' %
                        (i, seq_type_name))
                    break

                try:
                    item2 = seq2[i]
                except (TypeError, IndexError, NotImplementedError):
                    differing += (
                        '\nUnable to index element %d of second %s\n' %
                        (i, seq_type_name))
                    break

                if item1 != item2:
                    differing += ('\nFirst differing element %d:\n%s\n%s\n' %
                                  (i, item1, item2))
                    break
            else:
                if (len1 == len2 and seq_type is None
                        and type(seq1) != type(seq2)):
                    # The sequences are the same, but have differing types.
                    return

            if len1 > len2:
                differing += ('\nFirst %s contains %d additional '
                              'elements.\n' % (seq_type_name, len1 - len2))
                try:
                    differing += ('First extra element %d:\n%s\n' %
                                  (len2, seq1[len2]))
                except (TypeError, IndexError, NotImplementedError):
                    differing += ('Unable to index element %d '
                                  'of first %s\n' % (len2, seq_type_name))
            elif len1 < len2:
                differing += ('\nSecond %s contains %d additional '
                              'elements.\n' % (seq_type_name, len2 - len1))
                try:
                    differing += ('First extra element %d:\n%s\n' %
                                  (len1, seq2[len1]))
                except (TypeError, IndexError, NotImplementedError):
                    differing += ('Unable to index element %d '
                                  'of second %s\n' % (len1, seq_type_name))
        standardMsg = differing
        diffMsg = '\n' + '\n'.join(
            difflib.ndiff(
                pprint.pformat(seq1).splitlines(),
                pprint.pformat(seq2).splitlines()))
        standardMsg = self._truncateMessage(standardMsg, diffMsg)
        msg = self._formatMessage(msg, standardMsg)
        self.fail(msg)
Example #26
0
 def assertIs(self, expr1, expr2, msg=None):
     """Just like self.assertTrue(a is b), but with a nicer default message."""
     if expr1 is not expr2:
         standardMsg = '%s is not %s' % (safe_repr(expr1), safe_repr(expr2))
         self.fail(self._formatMessage(msg, standardMsg))
Example #27
0
 def assertGreaterEqual(self, a, b, msg=None):
     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))
Example #28
0
 def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
     if seq_type is not None:
         seq_type_name = seq_type.__name__
         if not isinstance(seq1, seq_type):
             raise self.failureException('First sequence is not a %s: %s' % (seq_type_name, safe_repr(seq1)))
         raise self.failureException('Second sequence is not a %s: %s' % (seq_type_name, safe_repr(seq2)))
     else:
         seq_type_name = 'sequence'
     differing = None
     try:
         len1 = len(seq1)
     except (TypeError, NotImplementedError):
         differing = 'First %s has no length.    Non-sequence?' % seq_type_name
     if differing is None:
         try:
             len2 = len(seq2)
         except (TypeError, NotImplementedError):
             differing = 'Second %s has no length.    Non-sequence?' % seq_type_name
     if differing is None:
         if seq1 == seq2:
             return
         seq1_repr = safe_repr(seq1)
         seq2_repr = safe_repr(seq2)
         if len(seq1_repr) > 30:
             seq1_repr = seq1_repr[:30] + '...'
         if len(seq2_repr) > 30:
             seq2_repr = seq2_repr[:30] + '...'
         elements = (seq_type_name.capitalize(), seq1_repr, seq2_repr)
         differing = '%ss differ: %s != %s\n' % elements
         for i in range(min(len1, len2)):
             try:
                 item1 = seq1[i]
             except (TypeError, IndexError, NotImplementedError):
                 differing += '\nUnable to index element %d of first %s\n' % (i, seq_type_name)
                 break
             try:
                 item2 = seq2[i]
             except (TypeError, IndexError, NotImplementedError):
                 differing += '\nUnable to index element %d of second %s\n' % (i, seq_type_name)
                 break
             while item1 != item2:
                 differing += '\nFirst differing element %d:\n%s\n%s\n' % (i, item1, item2)
                 break
         if len1 == len2 and seq_type is None and type(seq1) != type(seq2):
             return
         if len1 > len2:
             differing += '\nFirst %s contains %d additional elements.\n' % (seq_type_name, len1 - len2)
             try:
                 differing += 'First extra element %d:\n%s\n' % (len2, seq1[len2])
             except (TypeError, IndexError, NotImplementedError):
                 differing += 'Unable to index element %d of first %s\n' % (len2, seq_type_name)
         elif len1 < len2:
             differing += '\nSecond %s contains %d additional elements.\n' % (seq_type_name, len2 - len1)
             try:
                 differing += 'First extra element %d:\n%s\n' % (len1, seq2[len1])
             except (TypeError, IndexError, NotImplementedError):
                 differing += 'Unable to index element %d of second %s\n' % (len1, seq_type_name)
     standardMsg = differing
     diffMsg = '\n' + '\n'.join(difflib.ndiff(pprint.pformat(seq1).splitlines(), pprint.pformat(seq2).splitlines()))
     standardMsg = self._truncateMessage(standardMsg, diffMsg)
     msg = self._formatMessage(msg, standardMsg)
     self.fail(msg)
Example #29
0
 def assertNotIsInstance(self, obj, cls, msg=None):
     if isinstance(obj, cls):
         standardMsg = '%s is an instance of %r' % (safe_repr(obj), cls)
         self.fail(self._formatMessage(msg, standardMsg))
Example #30
0
 def assertIsNot(self, expr1, expr2, msg=None):
     """Just like self.assertTrue(a is not b), but with a nicer default message."""
     if expr1 is expr2:
         standardMsg = 'unexpectedly identical: %s' % (safe_repr(expr1), )
         self.fail(self._formatMessage(msg, standardMsg))