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