• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright (c) 2013 The Chromium OS 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"""Unit tests for client/common_lib/decorators.py."""
6
7
8from __future__ import absolute_import
9from __future__ import division
10from __future__ import print_function
11
12from six.moves import range
13import threading
14import time
15import unittest
16
17import common
18from autotest_lib.client.common_lib import decorators
19
20
21class InContextTest(unittest.TestCase):
22    """ Unit tests for the in_context decorator. """
23
24    @decorators.in_context('lock')
25    def inc_count(self):
26        """ Do a slow, racy read/write. """
27        temp = self.count
28        time.sleep(0.0001)
29        self.count = temp + 1
30
31
32    def testDecorator(self):
33        """ Test that the decorator works by using it with a lock."""
34        self.count = 0
35        self.lock = threading.RLock()
36        iters = 100
37        num_threads = 20
38        # Note that it is important for us to go through all this bother to
39        # call a method in_context N times rather than call a method in_context
40        # that does something N times, because by doing the former, we acquire
41        # the context N times (1 time for the latter).
42        thread_body = lambda f, n: [f() for i in range(n)]
43        threads = [threading.Thread(target=thread_body,
44                                    args=(self.inc_count, iters))
45                   for i in range(num_threads)]
46        for thread in threads:
47            thread.start()
48        for thread in threads:
49            thread.join()
50        self.assertEquals(iters * num_threads, self.count)
51
52
53class CachedPropertyTest(unittest.TestCase):
54    """Unit tests for the cached property decorator."""
55
56    def testIt(self):
57        """cached_property."""
58        class Example(object):
59            def __init__(self, v=0):
60                self.val = v
61
62            @decorators.cached_property
63            def prop(self):
64                self.val = self.val + 1
65                return self.val
66
67        ex = Example()
68        self.assertEquals(1, ex.prop)
69        self.assertEquals(1, ex.prop)
70
71        ex2 = Example(v=5)
72        self.assertEquals(6, ex2.prop)
73
74
75if __name__ == '__main__':
76    unittest.main()
77