import pytest import tempfile import os from pathlib import Path from backend import create_app, db as _db @pytest.fixture(scope='session') def app(): """Create a Flask app configured for testing.""" # Create a temporary SQLite database file db_fd, db_path = tempfile.mkstemp(suffix='.db') # Override config to use SQLite in-memory (or temporary file) class TestConfig: SQLALCHEMY_DATABASE_URI = f'sqlite:///{db_path}' SQLALCHEMY_TRACK_MODIFICATIONS = False TESTING = True SECRET_KEY = 'test-secret-key' AUTH_CONFIG = { 'mode': 'single', 'jwt_secret': 'test-jwt-secret', 'jwt_expiry': 3600, } app = create_app() app.config.from_object(TestConfig) # Push an application context ctx = app.app_context() ctx.push() yield app # Teardown ctx.pop() os.close(db_fd) os.unlink(db_path) @pytest.fixture(scope='session') def db(app): """Create database tables.""" _db.create_all() yield _db _db.drop_all() @pytest.fixture(scope='function') def session(db): """Create a new database session for a test.""" connection = db.engine.connect() transaction = connection.begin() # Use a scoped session from sqlalchemy.orm import scoped_session, sessionmaker session_factory = sessionmaker(bind=connection) session = scoped_session(session_factory) db.session = session yield session # Rollback and close transaction.rollback() connection.close() session.remove() @pytest.fixture def client(app): """Test client.""" return app.test_client() @pytest.fixture def runner(app): """CLI test runner.""" return app.test_cli_runner()