blob: 2d4434492707b3727cfa684472a5b01094c5c983 [file] [log] [blame]
Mike Frysingerd03e6b52019-08-03 12:49:01 -04001#!/usr/bin/env python2
Christopher Wiley8d6cd542013-03-11 11:10:44 -07002# 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
6import mox
7import threading
8import time
Alex Miller5c0a6312014-03-10 15:00:31 -07009import unittest
Christopher Wiley8d6cd542013-03-11 11:10:44 -070010
Alex Miller5c0a6312014-03-10 15:00:31 -070011import common
Alex Miller23b73662014-03-10 11:48:55 -070012from autotest_lib.client.common_lib import decorators
Christopher Wiley8d6cd542013-03-11 11:10:44 -070013
14
15class InContextTest(mox.MoxTestBase):
16 """ Unit tests for the in_context decorator. """
17
Alex Miller23b73662014-03-10 11:48:55 -070018 @decorators.in_context('lock')
Christopher Wiley8d6cd542013-03-11 11:10:44 -070019 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)
Alex Miller5c0a6312014-03-10 15:00:31 -070045
46
47class CachedPropertyTest(unittest.TestCase):
48 def testIt(self):
49 """cached_property"""
50 class Example(object):
Alex Miller82ef3df2014-03-25 16:11:40 -070051 def __init__(self, v=0):
52 self.val = v
Alex Miller5c0a6312014-03-10 15:00:31 -070053
54 @decorators.cached_property
55 def prop(self):
Alex Miller82ef3df2014-03-25 16:11:40 -070056 self.val = self.val + 1
Alex Miller5c0a6312014-03-10 15:00:31 -070057 return self.val
Alex Miller82ef3df2014-03-25 16:11:40 -070058
Alex Miller5c0a6312014-03-10 15:00:31 -070059 ex = Example()
60 self.assertEquals(1, ex.prop)
Alex Miller82ef3df2014-03-25 16:11:40 -070061 self.assertEquals(1, ex.prop)
62
63 ex2 = Example(v=5)
64 self.assertEquals(6, ex2.prop)
Alex Miller5c0a6312014-03-10 15:00:31 -070065
66
67if __name__ == '__main__':
68 unittest.main()