Public repository: timo / mitch

Reader

A migration stitcher (therefore mitch) for PostgreSQL, SQLite, MariaDB, and others

mitch / tests / test_helpers.py · 2.4 KB · at 76a2c3d332a1 · raw

Outline: 4 definitions
1
from pathlib import Path
2
from threading import Thread
3
from time import monotonic, sleep
4
5
from mitch.helpers import batch_transactional_migrations
6
from mitch.migration import Migration
7
from mitch.watcher import DebouncedQueue
8
9
10
def test_batch_transactional_migrations_separates_non_transactional():
11
    migrations = [
12
        Migration(id="001", up_script=Path("001.up.sql"), transactional=True),
13
        Migration(id="002", up_script=Path("002.up.sql"), transactional=False),
14
        Migration(id="003", up_script=Path("003.up.sql"), transactional=False),
15
        Migration(id="004", up_script=Path("004.up.sql"), transactional=True),
16
    ]
17
18
    batches = [(batch.transactional, list(batch.migrations)) for batch in batch_transactional_migrations(migrations)]
19
20
    assert batches == [
21
        (True, [migrations[0]]),
22
        (False, [migrations[1]]),
23
        (False, [migrations[2]]),
24
        (True, [migrations[3]]),
25
    ]
26
27
28
def test_debounce_queue_producer_consumer_sequence():
29
    debounce_time = 0.05
30
    q: DebouncedQueue[int] = DebouncedQueue(debounce_time=debounce_time)
31
32
    batches: list[list[int]] = []
33
    puts_at: list[float] = []
34
    gets_at: list[float] = []
35
    errors: list[BaseException] = []
36
37
    def producer() -> None:
38
        # First batch of items, should be received together.
39
        last_put_time: float = monotonic()
40
        for item in [1, 2, 3]:
41
            q.put(item)
42
            last_put_time = monotonic()
43
            sleep(0.01)
44
        puts_at.append(last_put_time)
45
46
        # Trigger debounce by waiting longer than debounce_time
47
        sleep(0.1)
48
49
        # Should be received after debounce time, in a separate batch.
50
        for item in [1, 2, 3]:
51
            q.put(item)
52
            last_put_time = monotonic()
53
            sleep(0.01)
54
        puts_at.append(last_put_time)
55
56
    def consumer() -> None:
57
        try:
58
            batches.append(list(q.get_all()))
59
            gets_at.append(monotonic())
60
            batches.append(list(q.get_all()))
61
            gets_at.append(monotonic())
62
        except BaseException as exc:
63
            errors.append(exc)
64
65
    consumer_thread = Thread(target=consumer)
66
    producer_thread = Thread(target=producer)
67
    consumer_thread.start()
68
    producer_thread.start()
69
    producer_thread.join(timeout=2.0)
70
    consumer_thread.join(timeout=2.0)
71
72
    if errors:
73
        raise errors[0]
74
75
    assert batches == [[1, 2, 3], [1, 2, 3]]
76
    assert all( get_at - put_at >= debounce_time - 0.01 for put_at, get_at in zip(puts_at, gets_at))