1 # Copyright 2014 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
11 class MathUtilsTest(unittest
.TestCase
):
12 """Tests for mathematical utility functions."""
14 def testTruncatedMeanRaisesError(self
):
15 """TruncatedMean should raise an error when passed an empty list."""
16 with self
.assertRaises(TypeError):
17 math_utils
.TruncatedMean([], 0)
19 def testMeanSingleNum(self
):
20 """Tests the Mean function with a single number."""
21 self
.assertEqual(3.0, math_utils
.Mean([3]))
23 def testMeanShortList(self
):
24 """Tests the Mean function with a short list."""
25 self
.assertEqual(0.5, math_utils
.Mean([-3, 0, 1, 4]))
27 def testMeanCompareAlternateImplementation(self
):
28 """Tests Mean by comparing against an alternate implementation."""
29 def AlternateMeanFunction(values
):
30 """Simple arithmetic mean function."""
31 return sum(values
) / float(len(values
))
32 test_values_lists
= [[1], [5, 6.5, 1.2, 3], [-3, 0, 1, 4],
33 [-3, -1, 0.12, 0.752, 3.33, 8, 16, 32, 439]]
34 for values
in test_values_lists
:
36 AlternateMeanFunction(values
),
37 math_utils
.Mean(values
))
39 def testRelativeChange(self
):
40 """Tests the common cases for calculating relative change."""
41 # The change is relative to the first value, regardless of which is bigger.
42 self
.assertEqual(0.5, math_utils
.RelativeChange(1.0, 1.5))
43 self
.assertEqual(0.5, math_utils
.RelativeChange(2.0, 1.0))
45 def testRelativeChangeFromZero(self
):
46 """Tests what happens when relative change from zero is calculated."""
47 # If the first number is zero, then the result is not a number.
48 self
.assertEqual(0, math_utils
.RelativeChange(0, 0))
50 math
.isnan(math_utils
.RelativeChange(0, 1)))
52 math
.isnan(math_utils
.RelativeChange(0, -1)))
54 def testRelativeChangeWithNegatives(self
):
55 """Tests that relative change given is always positive."""
56 self
.assertEqual(3.0, math_utils
.RelativeChange(-1, 2))
57 self
.assertEqual(3.0, math_utils
.RelativeChange(1, -2))
58 self
.assertEqual(1.0, math_utils
.RelativeChange(-1, -2))
61 if __name__
== '__main__':