88 lines
2.1 KiB
Python
88 lines
2.1 KiB
Python
"""
|
|
Tests pour la couche de connexion SQLAlchemy.
|
|
"""
|
|
|
|
from dataclasses import dataclass
|
|
|
|
import pytest
|
|
from sqlalchemy import inspect
|
|
|
|
from pricewatch.app.db.connection import (
|
|
check_db_connection,
|
|
get_engine,
|
|
get_session,
|
|
init_db,
|
|
reset_engine,
|
|
)
|
|
from pricewatch.app.db.models import Product
|
|
|
|
|
|
@dataclass
|
|
class FakeDbConfig:
|
|
"""Config DB minimale pour tests SQLite."""
|
|
|
|
url: str
|
|
host: str = "sqlite"
|
|
port: int = 0
|
|
database: str = ":memory:"
|
|
|
|
|
|
@dataclass
|
|
class FakeAppConfig:
|
|
"""Config App minimale pour tests."""
|
|
|
|
db: FakeDbConfig
|
|
debug: bool = False
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def reset_db_engine():
|
|
"""Reset l'engine global entre les tests."""
|
|
reset_engine()
|
|
yield
|
|
reset_engine()
|
|
|
|
|
|
@pytest.fixture
|
|
def sqlite_config() -> FakeAppConfig:
|
|
"""Config SQLite in-memory pour tests."""
|
|
return FakeAppConfig(db=FakeDbConfig(url="sqlite:///:memory:"))
|
|
|
|
|
|
def test_get_engine_sqlite(sqlite_config: FakeAppConfig):
|
|
"""Cree un engine SQLite fonctionnel."""
|
|
engine = get_engine(sqlite_config)
|
|
assert engine.url.get_backend_name() == "sqlite"
|
|
|
|
|
|
def test_init_db_creates_tables(sqlite_config: FakeAppConfig):
|
|
"""Init DB cree toutes les tables attendues."""
|
|
init_db(sqlite_config)
|
|
engine = get_engine(sqlite_config)
|
|
inspector = inspect(engine)
|
|
tables = set(inspector.get_table_names())
|
|
assert "products" in tables
|
|
assert "price_history" in tables
|
|
assert "product_images" in tables
|
|
assert "product_specs" in tables
|
|
assert "scraping_logs" in tables
|
|
|
|
|
|
def test_get_session_commit(sqlite_config: FakeAppConfig):
|
|
"""La session permet un commit simple."""
|
|
init_db(sqlite_config)
|
|
|
|
with get_session(sqlite_config) as session:
|
|
product = Product(source="amazon", reference="B08N5WRWNW", url="https://example.com")
|
|
session.add(product)
|
|
session.commit()
|
|
|
|
with get_session(sqlite_config) as session:
|
|
assert session.query(Product).count() == 1
|
|
|
|
|
|
def test_check_db_connection(sqlite_config: FakeAppConfig):
|
|
"""Le health check DB retourne True en SQLite."""
|
|
init_db(sqlite_config)
|
|
assert check_db_connection(sqlite_config) is True
|