Chromium Code Reviews| 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 | |
|
stgao
2016/12/05 19:30:56
style nit: for top-level definition, if it is not
| |
| 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 |