File: test_rlock.py

package info (click to toggle)
textual 2.1.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 55,084 kB
  • sloc: python: 85,423; lisp: 1,669; makefile: 101
file content (56 lines) | stat: -rw-r--r-- 1,270 bytes parent folder | download | duplicates (2)
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
import asyncio

import pytest

from textual.rlock import RLock


async def test_simple_lock():
    lock = RLock()
    # Starts not locked
    assert not lock.is_locked
    # Acquire the lock
    await lock.acquire()
    assert lock.is_locked
    # Acquire a second time (should not block)
    await lock.acquire()
    assert lock.is_locked

    # Release the lock
    lock.release()
    # Should still be locked
    assert lock.is_locked
    # Release the lock
    lock.release()
    # Should be released
    assert not lock.is_locked

    # Another release is a runtime error
    with pytest.raises(RuntimeError):
        lock.release()


async def test_multiple_tasks() -> None:
    """Check RLock prevents other tasks from acquiring lock."""
    lock = RLock()

    started: list[int] = []
    done: list[int] = []

    async def test_task(n: int) -> None:
        started.append(n)
        async with lock:
            done.append(n)

    async with lock:
        assert done == []
        task1 = asyncio.create_task(test_task(1))
        assert sorted(started) == []
        task2 = asyncio.create_task(test_task(2))
        await asyncio.sleep(0)
        assert sorted(started) == [1, 2]

    await task1
    assert 1 in done
    await task2
    assert 2 in done