import os import sqlite3 import sys import tempfile import pytest # Add translator/ to path so test modules can import db, translate, app sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) # Patch DB_PATH to a temp file BEFORE any test file imports `app`. # app.py calls init_db() at module load time, so this must happen here. import db as _db_module _TEST_DB_FILE = os.path.join(tempfile.gettempdir(), "rsshubtrans_test.db") _db_module.DB_PATH = _TEST_DB_FILE @pytest.fixture def db_conn(): """Fresh in-memory SQLite connection with schema for unit tests.""" conn = sqlite3.connect(":memory:") conn.row_factory = sqlite3.Row conn.executescript(""" CREATE TABLE cache ( key TEXT PRIMARY KEY, value TEXT NOT NULL, created_at REAL NOT NULL ); CREATE TABLE feeds ( key TEXT PRIMARY KEY, content BLOB NOT NULL, fetched_at REAL NOT NULL ); """) yield conn conn.close() @pytest.fixture def app_client(): """Flask test client backed by the patched temp DB, wiped between tests.""" from app import app from db import init_db init_db() # idempotent — creates tables if they don't exist yet app.config["TESTING"] = True # Clear state so each test starts clean conn = sqlite3.connect(_TEST_DB_FILE) conn.executescript("DELETE FROM cache; DELETE FROM feeds;") conn.commit() conn.close() with app.test_client() as client: yield client