from pathlib import Path

import pytest
from sqlmodel import select

from kfs import db


@pytest.fixture()
def base_dir(tmp_path: Path) -> Path:
    return tmp_path


@pytest.fixture()
def sql_file_path(base_dir: Path) -> Path:
    return base_dir / "kfs.db"


@pytest.fixture()
def sqlite_url(sql_file_path: Path) -> str:
    return f"sqlite:///{sql_file_path}"


@pytest.fixture(autouse=True)
def database(sqlite_url: str) -> None:
    db.init(sqlite_url)


def test_init(sql_file_path: Path) -> None:
    """After init, the database has been created and the file exists"""
    assert sql_file_path.exists()


def test_database() -> None:
    with db.get_session() as session:
        # Create a new file with a tag
        tag = db.Tag(category="vendor", value="chevron")
        file = db.File(name="test_file.csv", path="/some/directory", tags=[tag])
        session.add(file)
        session.commit()

    with db.get_session() as session:
        # Retrieve the file from database
        read_file = session.exec(select(db.File)).one()

        assert file is not read_file
        assert read_file.name == "test_file.csv"
        assert read_file.path == "/some/directory"
        assert len(read_file.tags) == 1

        read_tag = read_file.tags[0]
        assert read_tag.category == "vendor"
        assert read_tag.value == "chevron"
        assert len(read_tag.files) == 1

kfs.db.get_session kfs.db.File kfs.db.init sqlmodel.select kfs.db.Tag pytest.fixture
[((91, 107), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (105, 107), False, 'import pytest\n'), ((169, 185), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (183, 185), False, 'import pytest\n'), ((263, 279), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (277, 279), False, 'import pytest\n'), ((367, 395), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (381, 395), False, 'import pytest\n'), ((439, 458), 'kfs.db.init', 'db.init', (['sqlite_url'], {}), '(sqlite_url)\n', (446, 458), False, 'from kfs import db\n'), ((651, 667), 'kfs.db.get_session', 'db.get_session', ([], {}), '()\n', (665, 667), False, 'from kfs import db\n'), ((733, 775), 'kfs.db.Tag', 'db.Tag', ([], {'category': '"""vendor"""', 'value': '"""chevron"""'}), "(category='vendor', value='chevron')\n", (739, 775), False, 'from kfs import db\n'), ((791, 856), 'kfs.db.File', 'db.File', ([], {'name': '"""test_file.csv"""', 'path': '"""/some/directory"""', 'tags': '[tag]'}), "(name='test_file.csv', path='/some/directory', tags=[tag])\n", (798, 856), False, 'from kfs import db\n'), ((918, 934), 'kfs.db.get_session', 'db.get_session', ([], {}), '()\n', (932, 934), False, 'from kfs import db\n'), ((1022, 1037), 'sqlmodel.select', 'select', (['db.File'], {}), '(db.File)\n', (1028, 1037), False, 'from sqlmodel import select\n')]