Completed
Push — master ( 95d8d5...80ebcd )
by Ionel Cristian
6s
created

cb_no_overlap()   A

Complexity

Conditions 2

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 2
dl 0
loc 3
rs 10
1
from __future__ import print_function, division
2
3
import logging
4
import os
5
import sys
6
import time
7
8
from process_tests import setup_coverage
9
from redis import StrictRedis
10
11
from redis_lock import Lock
12
13
from conf import TIMEOUT
14
from conf import UDS_PATH
15
16
17
if __name__ == '__main__':
18
    logging.basicConfig(
19
        level=logging.DEBUG,
20
        format='%(process)d %(asctime)s,%(msecs)05d %(name)s %(levelname)s %(message)s',
21
        datefmt="%x~%X"
22
    )
23
    test_name = sys.argv[1]
24
25
    setup_coverage()
26
27
    if test_name == 'test_simple':
28
        conn = StrictRedis(unix_socket_path=UDS_PATH)
29
        with Lock(conn, "foobar"):
30
            time.sleep(0.1)
31
    elif test_name == 'test_no_block':
32
        conn = StrictRedis(unix_socket_path=UDS_PATH)
33
        lock = Lock(conn, "foobar")
34
        res = lock.acquire(blocking=False)
35
        logging.info("acquire=>%s", res)
36
    elif test_name == 'test_timeout':
37
        conn = StrictRedis(unix_socket_path=UDS_PATH)
38
        with Lock(conn, "foobar"):
39
            time.sleep(1)
40
    elif test_name == 'test_expire':
41
        conn = StrictRedis(unix_socket_path=UDS_PATH)
42
        with Lock(conn, "foobar", expire=TIMEOUT/4):
43
            time.sleep(0.1)
44
        with Lock(conn, "foobar", expire=TIMEOUT/4):
45
            time.sleep(0.1)
46
    elif test_name == 'test_no_overlap':
47
        from sched import scheduler
48
        sched = scheduler(time.time, time.sleep)
49
        start = time.time() + TIMEOUT/2
50
        # the idea is to start all the lock at the same time - we use the scheduler to start everything in TIMEOUT/2 seconds, by
51
        # that time all the forks should be ready
52
53
        def cb_no_overlap():
54
            with Lock(conn, "foobar"):
55
                time.sleep(0.001)
56
        sched.enterabs(start, 0, cb_no_overlap, ())
57
        pids = []
58
59
        for _ in range(125):
60
            pid = os.fork()
61
            if pid:
62
                pids.append(pid)
63
            else:
64
                try:
65
                    conn = StrictRedis(unix_socket_path=UDS_PATH)
66
                    sched.run()
67
                finally:
68
                    os._exit(0)
69
        for pid in pids:
70
            os.waitpid(pid, 0)
71
    else:
72
        raise RuntimeError('Invalid test spec %r.' % test_name)
73
    logging.info('DIED.')
74