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. 4 5import math 6import unittest 7 8import math_utils 9 10 11class MathUtilsTest(unittest.TestCase): 12 """Tests for mathematical utility functions.""" 13 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) 18 19 def testMeanSingleNum(self): 20 """Tests the Mean function with a single number.""" 21 self.assertEqual(3.0, math_utils.Mean([3])) 22 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])) 26 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: 35 self.assertEqual( 36 AlternateMeanFunction(values), 37 math_utils.Mean(values)) 38 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)) 44 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)) 49 self.assertTrue( 50 math.isnan(math_utils.RelativeChange(0, 1))) 51 self.assertTrue( 52 math.isnan(math_utils.RelativeChange(0, -1))) 53 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)) 59 60 61if __name__ == '__main__': 62 unittest.main() 63