summaryrefslogtreecommitdiff
path: root/yoyo/tests/conftest.py
blob: 1bf8d4a26c2bcff08d6a54264fdf38fc35a03bc1 (plain)
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
import pytest

import yoyo.backends.core
from yoyo.connections import get_backend
from yoyo.tests import dburi_sqlite3
from yoyo.tests import get_test_backends
from yoyo.tests import get_test_dburis


def _backend(dburi):
    """
    Return a backend configured in ``test_databases.ini``
    """
    backend = get_backend(dburi)
    with backend.transaction():
        if backend.__class__ is yoyo.backends.core.MySQLBackend:
            backend.execute(
                "CREATE TABLE yoyo_t (id CHAR(1) primary key) ENGINE=InnoDB"
            )
        else:
            backend.execute("CREATE TABLE yoyo_t " "(id CHAR(1) primary key)")
    try:
        yield backend
    finally:
        backend.rollback()
        with backend.transaction():
            drop_all_tables(backend)


@pytest.fixture(params=get_test_dburis())
def backend(request):
    """
    Return all backends configured in ``test_databases.ini``
    """
    yield from _backend(request.param)


@pytest.fixture()
def backend_sqlite3(request):
    yield from _backend(dburi_sqlite3)


@pytest.fixture(params=get_test_dburis())
def dburi(request):
    try:
        yield request.param
    finally:
        backend = get_backend(request.param)
        with backend.transaction():
            drop_all_tables(backend)


def drop_all_tables(backend):
    for t in backend.list_tables():
        backend.execute(f"DROP TABLE {backend.quote_identifier(t)}")


def drop_yoyo_tables(backend):
    for table in backend.list_tables():
        if table.startswith("yoyo") or table.startswith("_yoyo"):
            with backend.transaction():
                backend.execute("DROP TABLE {}".format(table))


def pytest_configure(config):
    for backend in get_test_backends():
        drop_yoyo_tables(backend)