File: test_db.py

package info (click to toggle)
freedombox 26.3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 83,092 kB
  • sloc: python: 48,542; javascript: 1,730; xml: 481; makefile: 290; sh: 137; php: 32
file content (68 lines) | stat: -rw-r--r-- 1,389 bytes parent folder | download | duplicates (4)
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
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
Tests for database utilities.
"""
import threading
import time

from .. import db


def test_db_lock_no_wait():
    """Test that lock is immediately by first user."""
    lock = db.DBLock()

    start_time = time.time()
    with lock:
        pass

    end_time = time.time()
    assert end_time - start_time < 0.1


def test_db_lock_max_wait():
    """Test that lock waits only for timeout period."""
    event = threading.Event()
    lock = db.DBLock()
    lock.timeout = 0.25

    def thread_func():
        with lock:
            event.set()
            time.sleep(0.3)

    thread = threading.Thread(target=thread_func)
    thread.start()

    event.wait()
    start_time = time.time()
    with lock as return_value:
        pass

    end_time = time.time()
    assert end_time - start_time < 0.27
    assert not return_value


def test_db_lock_release():
    """Test that lock is available after release."""
    event = threading.Event()
    lock = db.DBLock()
    lock.timeout = 0.25

    def thread_func():
        with lock:
            event.set()
            time.sleep(0.2)

    thread = threading.Thread(target=thread_func)
    thread.start()

    event.wait()
    start_time = time.time()
    with lock as return_value:
        pass

    end_time = time.time()
    assert return_value
    assert end_time - start_time <= 0.23