def test_cache_cache_is_not_global(self): call_count = 0 def double(x): nonlocal call_count call_count += 1 return 2 * x cached_double1 = solution.cache(double, 3) cached_double2 = solution.cache(double, 3) self.assertEqual(42 * 2, cached_double1(42)) self.assertEqual(42 * 2, cached_double2(42)) self.assertEqual(2, call_count)
def test_cache_zero_times(self): call_count = 0 def double(x): nonlocal call_count call_count += 1 return 2 * x cached_double = solution.cache(double, 0) self.assertEqual(256, cached_double(128)) self.assertEqual(256, cached_double(128)) self.assertEqual(2, call_count)
def test_cache_call_is_cached(self): call_count = 0 def double(x): nonlocal call_count call_count += 1 return 2 * x cached_double = solution.cache(double, 10) self.assertEqual(256, cached_double(128)) self.assertEqual(256, cached_double(128)) self.assertEqual(1, call_count)
def test_cache_no_cache(self): call_count = 0 def double(x): nonlocal call_count call_count += 1 return 2 * x cached_double = solution.cache(double, 0) self.assertEqual(42 * 2, cached_double(42)) self.assertEqual(5 * 2, cached_double(5)) self.assertEqual(2, call_count)
def test_cache_function_with_vargs(self): call_count = 0 def sum_varargs(*x): nonlocal call_count call_count += 1 return sum(x) cached_sum = solution.cache(sum_varargs, 10) self.assertEqual(6, cached_sum(1, 2, 3)) self.assertEqual(9, cached_sum(4, 5)) self.assertEqual(6, cached_sum(1, 2, 3)) self.assertEqual(6, cached_sum(3, 2, 1, 0)) self.assertEqual(3, call_count)
def test_cache_size_is_respected(self): call_count = 0 def double(x): nonlocal call_count call_count += 1 return 2 * x cached_double = solution.cache(double, 2) self.assertEqual(2, cached_double(1)) self.assertEqual(4, cached_double(2)) self.assertEqual(6, cached_double(3)) self.assertEqual(2, cached_double(1)) self.assertEqual(4, call_count)