""" Shared pytest fixtures. Environment must be configured BEFORE `config` is imported, because config.py reads os.environ at import time. Each test then gets its own SQLite file so tests never share state. """ import os import sys import tempfile import pytest _BACKEND_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, _BACKEND_DIR) os.environ.setdefault("DB_TYPE", "sqlite") os.environ.setdefault("JWT_SECRET", "test_secret_at_least_32_bytes_long_ok") os.environ.setdefault("CORS_ORIGIN", "http://localhost:3000") # Point at a throwaway path; the db_path fixture overrides it per test. os.environ.setdefault( "DATABASE_PATH", os.path.join(tempfile.mkdtemp(), "bootstrap.db") ) import db as db_module # noqa: E402 from app import create_app # noqa: E402 @pytest.fixture def db(tmp_path, monkeypatch): """A freshly initialized, isolated SQLite database for one test.""" path = str(tmp_path / "test.db") monkeypatch.setattr(db_module, "SQLITE_PATH", path) db_module.init_db() return db_module @pytest.fixture def app(db): application = create_app() application.config.update(TESTING=True) return application @pytest.fixture def client(app): return app.test_client() @pytest.fixture def user(client): """A registered user: returns {id, email, token, password}.""" password = "secret123" resp = client.post( "/api/auth/register", json={ "email": "tester@example.com", "garminEmail": "gm@example.com", "garminPassword": password, }, ) assert resp.status_code == 201, resp.get_data(as_text=True) body = resp.get_json() return {**body, "password": password} @pytest.fixture def auth(user): """Authorization headers for the registered user.""" return {"Authorization": f"Bearer {user['token']}"} @pytest.fixture def seed_health(db, user): """Insert daily health rows. Returns the inserted records.""" def _seed(records): for r in records: db.execute( "INSERT INTO health_data (id, user_id, date, steps, heart_rate, " "heart_rate_variability, sleep_duration, sleep_quality, stress, " "calories_burned) VALUES (?,?,?,?,?,?,?,?,?,?)", [ f"{user['id']}-{r['date']}", user["id"], r["date"], r.get("steps"), r.get("heart_rate"), r.get("hrv"), r.get("sleep_duration"), r.get("sleep_quality"), r.get("stress"), r.get("calories"), ], ) return records return _seed