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