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 unittest
6
7from telemetry import decorators
8
9_counter = 0
10
11
12class Foo(object):
13  @decorators.Cache
14  def GetCountCached(self, _):
15    global _counter
16    _counter = _counter + 1
17    return _counter
18
19
20def CreateFooUncached(_):
21  return Foo()
22
23
24@decorators.Cache
25def CreateFooCached(_):
26  return Foo()
27
28
29class DecoratorsUnitTest(unittest.TestCase):
30  # pylint: disable=C0102
31
32  def testCacheDecorator(self):
33    self.assertNotEquals(CreateFooUncached(1), CreateFooUncached(2))
34    self.assertNotEquals(CreateFooCached(1), CreateFooCached(2))
35
36    self.assertNotEquals(CreateFooUncached(1), CreateFooUncached(1))
37    self.assertEquals(CreateFooCached(1), CreateFooCached(1))
38
39  def testCacheableMemberCachesOnlyForSameArgs(self):
40    foo = Foo()
41    value_of_one = foo.GetCountCached(1)
42
43    self.assertEquals(value_of_one, foo.GetCountCached(1))
44    self.assertNotEquals(value_of_one, foo.GetCountCached(2))
45
46  def testCacheableMemberHasSeparateCachesForSiblingInstances(self):
47    foo = Foo()
48    sibling_foo = Foo()
49
50    self.assertNotEquals(foo.GetCountCached(1), sibling_foo.GetCountCached(1))
51
52  def testCacheableMemberHasSeparateCachesForNextGenerationInstances(self):
53    foo = Foo()
54    last_generation_count = foo.GetCountCached(1)
55    foo = None
56    foo = Foo()
57
58    self.assertNotEquals(last_generation_count, foo.GetCountCached(1))
59