| OLD | NEW |
| (Empty) | |
| 1 # Copyright 2016 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 |
| 5 import unittest |
| 6 |
| 7 from libs.math.functions import Function |
| 8 from libs.math.functions import MemoizedFunction |
| 9 |
| 10 |
| 11 # Some arbitrary functions: |
| 12 _F = lambda x: x + 1 |
| 13 _G = lambda x: x * x |
| 14 |
| 15 |
| 16 class FunctionsTest(unittest.TestCase): |
| 17 |
| 18 def testFunctionCall(self): |
| 19 """``Function.__call__`` returns same value as the underlying callable.""" |
| 20 self.assertEqual(_F(5), Function(_F)(5)) |
| 21 self.assertEqual(_G(5), Function(_G)(5)) |
| 22 |
| 23 def testFunctionMap(self): |
| 24 """``Function.map`` composes functions as described in the docstring.""" |
| 25 self.assertEqual(_G(_F(5)), Function(_F).map(_G)(5)) |
| 26 self.assertEqual(_F(_G(5)), Function(_G).map(_F)(5)) |
| 27 |
| 28 def testMemoizedFunctionCall(self): |
| 29 """``MemoizedFunction.__call__`` returns same value as its callable.""" |
| 30 self.assertEqual(_F(5), MemoizedFunction(_F)(5)) |
| 31 self.assertEqual(_G(5), MemoizedFunction(_G)(5)) |
| 32 |
| 33 def testMemoizedFunctionMap(self): |
| 34 """``MemoizedFunction.map`` composes functions as described.""" |
| 35 self.assertEqual(_G(_F(5)), MemoizedFunction(_F).map(_G)(5)) |
| 36 self.assertEqual(_F(_G(5)), MemoizedFunction(_G).map(_F)(5)) |
| 37 |
| 38 def testMemoization(self): |
| 39 """``MemoizedFunction.__call__`` actually does memoize. |
| 40 |
| 41 That is, we call the underlying function once (to set the memo), then |
| 42 we discard the underlying function (to be sure the next ``__call__`` |
| 43 is handled from the memos, and finally call the function to check. |
| 44 """ |
| 45 f = MemoizedFunction(_F) |
| 46 f(5) |
| 47 del f._f |
| 48 self.assertEqual(_F(5), f(5)) |
| 49 |
| 50 def testClearMemos(self): |
| 51 """``MemoizedFunction._ClearMemos`` does actually clear the memos. |
| 52 |
| 53 That is, we call the underlying function once (to set the memo), |
| 54 then swap put the underlying function with a different one (to be |
| 55 sure we know whether the next ``__call__`` goes to the memos or to |
| 56 the function), and finally clear the memos and check. |
| 57 """ |
| 58 f = MemoizedFunction(_F) |
| 59 f(5) |
| 60 f._f = _G |
| 61 f._ClearMemos() |
| 62 self.assertEqual(_G(5), f(5)) |
| OLD | NEW |