• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2#
3# Copyright 2016 - The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#     http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17from mobly.asserts import *
18
19
20# Have an instance of unittest.TestCase so we could reuse some logic from
21# python's own unittest.
22# _ProxyTest is required because py2 does not allow instantiating
23# unittest.TestCase directly.
24class _ProxyTest(unittest.TestCase):
25    def runTest(self):
26        pass
27
28
29_pyunit_proxy = _ProxyTest()
30
31
32def assert_almost_equal(first,
33                        second,
34                        places=7,
35                        msg=None,
36                        delta=None,
37                        extras=None):
38    """
39    Assert FIRST to be within +/- DELTA to SECOND, otherwise fail the
40    test.
41    :param first: The first argument, LHS
42    :param second: The second argument, RHS
43    :param places: For floating points, how many decimal places to look into
44    :param msg: Message to display on failure
45    :param delta: The +/- first and second could be apart from each other
46    :param extras: Extra object passed to test failure handler
47    :return:
48    """
49    my_msg = None
50    try:
51        if delta:
52            _pyunit_proxy.assertAlmostEqual(
53                first, second, msg=msg, delta=delta)
54        else:
55            _pyunit_proxy.assertAlmostEqual(
56                first, second, places=places, msg=msg)
57    except Exception as e:
58        my_msg = str(e)
59        if msg:
60            my_msg = "%s %s" % (my_msg, msg)
61    # This is a hack to remove the stacktrace produced by the above exception.
62    if my_msg is not None:
63        fail(my_msg, extras=extras)
64