~javiljoen/shopping-list

ref: 17b65e62833b4c3fa4abcd60ba61cbc1eb232fa0 shopping-list/tests/conftest.py -rw-r--r-- 1.9 KiB
17b65e62JA Viljoen Explicitly use UTF-8 for text files 1 year, 1 month ago
                                                                                
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import sqlite3
from pathlib import Path

import pytest

from groceries import todotxt
from groceries.model import Item
from groceries.sqldb import SqliteDB


@pytest.fixture()
def items():
    return [
        Item("granola", "pantry", 1, "woolworths"),
        Item("cheese", "dairy", 0, None),
        Item("baking powder", "pantry", 1, None),
        Item("apples", "produce", 0, None),
        Item("coffee beans", "pantry", 2, None),
    ]


@pytest.fixture()
def groceries_file(tmpdir, items):
    path = Path(tmpdir) / "groceries.txt"

    with path.open("w", encoding="utf-8") as fh:
        todotxt.dump(items, fh)

    return path


def create(conn):
    conn.execute(
        "CREATE TABLE items ("
        "name TEXT, "
        "section TEXT, "
        "priority INTEGER, "
        "shop TEXT) "
    )


def insert(conn, items):
    for item in items:
        conn.execute(
            "INSERT INTO items "
            "(name, section, priority, shop) "
            "VALUES (?, ?, ?, ?)",
            tuple(item),
        )


def populate_db(db_path, items):
    conn = sqlite3.connect(db_path)
    create(conn)
    insert(conn, items)
    conn.commit()
    conn.close()


@pytest.fixture()
def sqldb_file(tmpdir, items):
    path = Path(tmpdir) / "groceries.db"
    populate_db(path, items)
    return path


@pytest.fixture()
def sqldb_mem(items, monkeypatch):
    db = SqliteDB(":memory:")
    conn = sqlite3.connect(":memory:")
    monkeypatch.setattr(db, "_connect", lambda: conn)
    create(conn)
    insert(conn, items)
    return db


@pytest.fixture()
def new_sqldb_mem(monkeypatch):
    conn = sqlite3.connect(":memory:")
    db = SqliteDB(":memory:")
    monkeypatch.setattr(db, "_connect", lambda: conn)
    create(conn)
    return db


def pytest_configure(config):
    """The presence of this fn registers the 'slow' marker with pytest."""
    config.addinivalue_line("markers", "slow: mark test as slow to run")