1# Copyright 2019 Google LLC 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# https://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15"""Tests for simple_memoizer.""" 16 17import unittest 18from compiler.util import simple_memoizer 19 20 21class SimpleMemoizerTest(unittest.TestCase): 22 23 def test_memoized_function_returns_same_values(self): 24 @simple_memoizer.memoize 25 def add_one(n): 26 return n + 1 27 28 for i in range(100): 29 self.assertEqual(i + 1, add_one(i)) 30 31 def test_memoized_function_is_only_called_once(self): 32 arguments = [] 33 34 @simple_memoizer.memoize 35 def add_one_and_add_argument_to_list(n): 36 arguments.append(n) 37 return n + 1 38 39 self.assertEqual(1, add_one_and_add_argument_to_list(0)) 40 self.assertEqual([0], arguments) 41 self.assertEqual(1, add_one_and_add_argument_to_list(0)) 42 self.assertEqual([0], arguments) 43 44 def test_memoized_function_with_multiple_arguments(self): 45 arguments = [] 46 47 @simple_memoizer.memoize 48 def sum_arguments_and_add_arguments_to_list(n, m, o): 49 arguments.append((n, m, o)) 50 return n + m + o 51 52 self.assertEqual(3, sum_arguments_and_add_arguments_to_list(0, 1, 2)) 53 self.assertEqual([(0, 1, 2)], arguments) 54 self.assertEqual(3, sum_arguments_and_add_arguments_to_list(0, 1, 2)) 55 self.assertEqual([(0, 1, 2)], arguments) 56 self.assertEqual(3, sum_arguments_and_add_arguments_to_list(2, 1, 0)) 57 self.assertEqual([(0, 1, 2), (2, 1, 0)], arguments) 58 59 def test_memoized_function_with_no_arguments(self): 60 arguments = [] 61 62 @simple_memoizer.memoize 63 def return_one_and_add_empty_tuple_to_list(): 64 arguments.append(()) 65 return 1 66 67 self.assertEqual(1, return_one_and_add_empty_tuple_to_list()) 68 self.assertEqual([()], arguments) 69 self.assertEqual(1, return_one_and_add_empty_tuple_to_list()) 70 self.assertEqual([()], arguments) 71 72if __name__ == '__main__': 73 unittest.main() 74