1#!/usr/bin/env python3
2#
3#   Copyright 2018 - 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
26    def runTest(self):
27        pass
28
29
30_pyunit_proxy = _ProxyTest()
31
32
33def assert_almost_equal(first, second, places=7, msg=None, delta=None, extras=None):
34    """
35    Assert FIRST to be within +/- DELTA to SECOND, otherwise fail the
36    test.
37    :param first: The first argument, LHS
38    :param second: The second argument, RHS
39    :param places: For floating points, how many decimal places to look into
40    :param msg: Message to display on failure
41    :param delta: The +/- first and second could be apart from each other
42    :param extras: Extra object passed to test failure handler
43    :return:
44    """
45    my_msg = None
46    try:
47        if delta:
48            _pyunit_proxy.assertAlmostEqual(first, second, msg=msg, delta=delta)
49        else:
50            _pyunit_proxy.assertAlmostEqual(first, second, places=places, msg=msg)
51    except Exception as e:
52        my_msg = str(e)
53        if msg:
54            my_msg = "%s %s" % (my_msg, msg)
55    # This is a hack to remove the stacktrace produced by the above exception.
56    if my_msg is not None:
57        fail(my_msg, extras=extras)
58