Пример #1
0
 def _assertPandasEqual(self, func, first, second, msg=None, **kwargs):
     try:
         func(first, second, **kwargs)
     except AssertionError:
         standardMsg = '{} != {}'.format(
             *_common_shorten_repr(first, second))
         msg = self._formatMessage(msg, standardMsg)
         raise self.failureException(msg)
Пример #2
0
def withfailure(call, format):
    try:
        call()
    except AssertionError:
        standardMsg = format.format(
            *_common_shorten_repr(call.first, call.second))
        msg = call.self._formatMessage(call.msg, standardMsg)
        raise call.self.fail(msg)
Пример #3
0
 def assertArrayEqual(self, first, second, msg=None):
     try:
         npt.assert_array_equal(first, second, verbose=False)
     except AssertionError:
         standardMsg = '{} != {}'.format(
             *_common_shorten_repr(first, second))
         msg = self._formatMessage(msg, standardMsg)
         raise self.failureException(msg)
Пример #4
0
    def assertArrayNotAlmostEqual(
            self, first, second, places=6, msg=None, delta=None):
        if delta is not None:
            places = int(-np.log10(delta) + np.log10(1.5))

        try:
            npt.assert_array_almost_equal(
                first, second, decimal=places, verbose=False)
        except AssertionError:
            pass
        else:
            standardMsg = '{} == {}'.format(
                *_common_shorten_repr(first, second))
            msg = self._formatMessage(msg, standardMsg)
            raise self.failureException(msg)
Пример #5
0
def assert_pandas_object_equal(first, second, **kwargs):
    """Test that arbitrary Pandas objects first and second are equal"""
    if _is_pdobj(first) and _is_pdobj(second):
        if isinstance(first, type(second)):
            if isinstance(first, pd.DataFrame):
                assert_frame_equal(first, second, **kwargs)
            elif isinstance(first, pd.Series):
                assert_series_equal(first, second, **kwargs)
            elif isinstance(first, pd.Index):
                assert_index_equal(first, second, **kwargs)
            else:
                # unreachable?
                raise AssertionError('you found a bug: unreachable code')
    else:
        msg = '{} and {} are uncomparable types'.format(
            *_common_shorten_repr(first, second))
        raise AssertionError(msg)
Пример #6
0
 def assertPandasObjectEqual(self, first, second, msg=None, **kwargs):
     is_pdobj = funcy.isa(pd.core.base.PandasObject)
     if is_pdobj(first) and is_pdobj(second):
         if isinstance(first, type(second)):
             if isinstance(first, pd.DataFrame):
                 self.assertFrameEqual(first, second, msg=msg, **kwargs)
             elif isinstance(first, pd.Series):
                 self.assertSeriesEqual(first, second, msg=msg, **kwargs)
             elif isinstance(first, pd.Index):
                 self.assertIndexEqual(first, second, msg=msg, **kwargs)
             else:
                 # unreachable?
                 raise AssertionError('you found a bug: unreachable code')
     else:
         standardMsg = '{} and {} are uncomparable types'.format(
             *_common_shorten_repr(first, second))
         msg = self._formatMessage(msg, standardMsg)
         raise self.failureException(msg)
    def compare_results(self, expected: dict):
        if self._results_normalized:
            expected_ = {k: self._normalize(v) for k, v in expected.items()}
        else:
            expected_ = {**expected}

        if expected_.keys() != self.results.keys():
            raise ResultsDifferError(
                f'Expected file structure\n{list(expected_.keys())}\n'
                f'differs from resulting file structure {list(self.results.keys())}'
            )

        for e_file, e_content in expected.items():
            f1 = self._normalize(e_content)
            f2 = self.results[e_file]
            if self._normalize(e_content) != self.results[e_file]:
                raise ResultsDifferError(
                    f'File {e_file} contents differ from expected:\n'
                    '{}\n!=\n{}'.format(*_common_shorten_repr(f2, f1)))
Пример #8
0
    def assertArrayAlmostEqual(
            self, first, second, places=6, msg=None, delta=None):

        # convert between both "places" and "delta" allowed to just "decimal"
        # numpy says abs(desired-actual) < 1.5 * 10**(-decimal)
        # => delta = 1.5 * 10**(-decimal)
        # => delta / 1.5 = 10**(-decimal)
        # => log10(delta/1.5) = -decimal
        # => decimal = -log10(delta) + log10(1.5)
        if delta is not None:
            places = int(-np.log10(delta) + np.log10(1.5))

        try:
            npt.assert_array_almost_equal(
                first, second, decimal=places, verbose=False)
        except AssertionError:
            standardMsg = '{} != {}'.format(
                *_common_shorten_repr(first, second))
            msg = self._formatMessage(msg, standardMsg)
            raise self.failureException(msg)
Пример #9
0
    def assertValSequenceEqual(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:

        :param seq1: can contain instance of values or nested list of them
        :param seq2: items are not converted
        :param seq_type: The expected datatype of the sequences, or None if no
            datatype should be enforced.
        :param msg: Optional message to use on failure instead of a list of
            differences.
        """
        seq1 = allValuesToInts(seq1)
        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

            differing = '%ss differ: %s != %s\n' % (
                (seq_type_name.capitalize(), ) +
                _common_shorten_repr(seq1, seq2))

            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

                if item1 != item2:
                    differing += ('\nFirst differing element %d:\n%s\n%s\n' %
                                  ((i, ) + _common_shorten_repr(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, safe_repr(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, safe_repr(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)
Пример #10
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 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))

            tmp_differing = ''
            for ind, (item1, item2) in enumerate(zip(seq1, seq2)):
                try:
                    self.assertEqual(item1, item2)
                except AssertionError as e:
                    tmp_differing += ('\nFirst differing element %d: %s\n' %
                                      (ind, e.args[0]))
                    break
            if tmp_differing:
                differing = '%ss differ: %s != %s\n%s' % (
                    (seq_type_name.capitalize(), ) +
                    _common_shorten_repr(seq1, seq2) + (tmp_differing, ))
            else:
                return

        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)
Пример #11
0
def assertPulseSequenceEqual(test, seq1, seq2, msg=None):
    """An equality assertion for ordered sequences of pulses.

    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.
    msg: Optional message to use on failure instead of a list of
                    differences.
    """
    import difflib
    import pprint
    from unittest.util import safe_repr, _common_shorten_repr
    seq_type = list
    if seq_type is not None:
        seq_type_name = seq_type.__name__
        if not isinstance(seq1, seq_type):
            raise test.failureException('First sequence is not a %s: %s' %
                                        (seq_type_name, safe_repr(seq1)))
        if not isinstance(seq2, seq_type):
            raise test.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

        differing = '%ss differ: %s != %s\n' % (
            (seq_type_name.capitalize(), ) + _common_shorten_repr(seq1, seq2))

        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

            if item1 != item2:
                differing += ('\nFirst differing element %d:\n%s\n%s\n' %
                              (i, str(item1), str(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(),
        # FIXME: I wish I could get pprint.pformat to use str on pulses not repr
        difflib.unified_diff(
            pprint.pformat(seq1).splitlines(),
            pprint.pformat(seq2).splitlines()))

    standardMsg = test._truncateMessage(standardMsg, diffMsg)
    msg = test._formatMessage(msg, standardMsg)
    test.fail(msg)