File: test_nameregistry.py

package info (click to toggle)
python-dogpile.cache 1.3.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 772 kB
  • sloc: python: 5,462; makefile: 155; sh: 104
file content (53 lines) | stat: -rw-r--r-- 1,495 bytes parent folder | download
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
import logging
import random
import threading
import time

from dogpile.util import NameRegistry

log = logging.getLogger(__name__)


class NameRegistryTest:
    def test_name_registry(self):
        success = [True]
        num_operations = [0]

        def create(identifier):
            log.debug("Creator running for id: " + identifier)
            return threading.Lock()

        registry = NameRegistry(create)

        baton = {"beans": False, "means": False, "please": False}

        def do_something(name):
            for iteration in range(20):
                name = list(baton)[random.randint(0, 2)]
                lock = registry.get(name)
                lock.acquire()
                try:
                    if baton[name]:
                        success[0] = False
                        log.debug("Baton is already populated")
                        break
                    baton[name] = True
                    try:
                        time.sleep(random.random() * 0.01)
                    finally:
                        num_operations[0] += 1
                        baton[name] = False
                finally:
                    lock.release()
            log.debug("thread completed operations")

        threads = []
        for id_ in range(1, 20):
            t = threading.Thread(target=do_something, args=("somename",))
            t.start()
            threads.append(t)

        for t in threads:
            t.join()

        assert success[0]