summaryrefslogtreecommitdiff
path: root/tests/t1_multi_lock.py
blob: eeaf0eedb83eb18bf3e4afa2b2175b2208d9939f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
'''
t1_ordered_dict.py - this file is part of S3QL (http://s3ql.googlecode.com)

Copyright (C) 2008-2009 Nikolaus Rath <Nikolaus@rath.org>

This program can be distributed under the terms of the GNU LGPL.
'''

from __future__ import division, print_function

import unittest2 as unittest
from s3ql.multi_lock import MultiLock
import time
from s3ql.common import AsyncFn
from _common import TestCase

BASE_DELAY = 1

@unittest.skip('takes too long')
class MultiLockTests(TestCase):

    def test_lock(self):
        mlock = MultiLock()
        key = (22, 'bar')

        def hold():
            mlock.acquire(key)
            time.sleep(2 * BASE_DELAY)
            mlock.release(key)

        t = AsyncFn(hold)
        t.start()
        time.sleep(BASE_DELAY)

        stamp = time.time()
        with mlock(key):
            pass
        self.assertTrue(time.time() - stamp > BASE_DELAY)

        t.join_and_raise()

    def test_nolock(self):
        mlock = MultiLock()
        key1 = (22, 'bar')
        key2 = (23, 'bar')

        def hold():
            mlock.acquire(key1)
            time.sleep(2 * BASE_DELAY)
            mlock.release(key1)

        t = AsyncFn(hold)
        t.start()
        time.sleep(BASE_DELAY)

        stamp = time.time()
        with mlock(key2):
            pass
        self.assertTrue(time.time() - stamp < BASE_DELAY)

        t.join_and_raise()

    def test_multi(self):
        mlock = MultiLock()
        key = (22, 'bar')

        def lock():
            mlock.acquire(key)

        def unlock():
            time.sleep(2 * BASE_DELAY)
            mlock.release(key)

        t1 = AsyncFn(lock)
        t1.start()
        t1.join_and_raise()

        t2 = AsyncFn(unlock)
        t2.start()

        stamp = time.time()
        with mlock(key):
            pass
        self.assertTrue(time.time() - stamp > BASE_DELAY)

        t2.join_and_raise()

def suite():
    return unittest.makeSuite(MultiLockTests)


if __name__ == "__main__":
    unittest.main()