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