Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
"""Pytest configuration for the Speakr test suite.
This file is imported by pytest BEFORE it collects any test module, so the
environment it sets here is in place before any `from src.app import app`
binds the Flask app to a database.
Goal: isolation. Point the app at a throwaway temporary SQLite database so
the test suite never reads or mutates the developer's real
`instance/transcriptions.db`. Running the suite with `pytest` therefore
needs no services and is safe on any machine / in CI.
Note: the legacy standalone invocation (`python tests/test_foo.py`) does NOT
load conftest.py, so this changes nothing for that workflow — it only affects
`pytest` runs.
"""
import os
import tempfile
# --- Isolated database (set BEFORE src.app is imported) ---------------------
# Use a real file (not :memory:) because the app and tests open multiple
# connections / app contexts, which an in-memory SQLite DB would not share.
_TEST_DIR = tempfile.mkdtemp(prefix="speakr_pytest_")
_TEST_DB_PATH = os.path.join(_TEST_DIR, "test.db")
# PYTEST_DATABASE_URI runs the suite against another database, such as the
# PostgreSQL service of the CI job. That database must be empty and is used
# only by the tests.
os.environ["SQLALCHEMY_DATABASE_URI"] = (
os.environ.get("PYTEST_DATABASE_URI") or f"sqlite:///{_TEST_DB_PATH}"
)
# The app os.makedirs(UPLOAD_FOLDER) at import time; default is /data/uploads
# which isn't writable in CI / outside Docker. Point it at the temp dir.
os.environ["UPLOAD_FOLDER"] = os.path.join(_TEST_DIR, "uploads")
# --- No real external services ----------------------------------------------
# A developer's container or .env points at real services (an LLM, an
# embeddings API, an ASR server, a mail server). The suite must not call them:
# they bill, send mail, and make results depend on the host (with an
# embeddings API configured, the tests expecting embeddings to be unavailable
# fail). Every such setting is forced to what a clean CI checkout has. An
# empty value, not a removed one, because load_dotenv() never overrides a
# variable that is already set, but would fill a removed one from .env.
for _var in (
"TEXT_MODEL_BASE_URL", "TEXT_MODEL_NAME",
"EMBEDDING_BASE_URL", "EMBEDDING_API_KEY", "EMBEDDING_MODEL", "EMBEDDING_DIMENSIONS",
"ASR_BASE_URL", "TRANSCRIPTION_MODEL", "TRANSCRIPTION_CONNECTOR",
"SMTP_HOST", "SMTP_USERNAME", "SMTP_PASSWORD",
"SSO_CLIENT_SECRET", "SSO_DISCOVERY_URL",
):
os.environ[_var] = ""
os.environ["USE_ASR_ENDPOINT"] = "false"
# initialize_config() hard-exits at import if no text or transcription
# service is set; these are harmless placeholders that are never reached.
os.environ["TEXT_MODEL_API_KEY"] = "test-key"
os.environ["TRANSCRIPTION_API_KEY"] = "test-key"
os.environ["TRANSCRIPTION_BASE_URL"] = "https://api.openai.com/v1"
# --- Quiet, deterministic defaults for tests --------------------------------
# Only set if the caller hasn't already chosen a value.
os.environ.setdefault("SECRET_KEY", "pytest-secret-key")
os.environ.setdefault("ENABLE_AUTO_PROCESSING", "false") # no black-hole file monitor
# Run ZERO background job-queue workers during tests. These counts are read at
# job_queue import time, so they must be set before src.app is imported. With
# workers running, enqueue() auto-starts daemon threads that claim and process
# test-created jobs in the background — racing tests that exercise the queue
# directly (e.g. test_job_queue_race_condition) and spraying FileNotFound
# errors as they try to transcribe nonexistent test files. Tests that need to
# exercise claiming drive _claim_next_job themselves.
os.environ["JOB_QUEUE_WORKERS"] = "0"
os.environ["SUMMARY_QUEUE_WORKERS"] = "0"
# Force the agentic Inquire flag OFF for the suite: the legacy-pipeline tests
# (test_cov_inquire) patch the single-shot pipeline's internals and would
# silently route to the agent if the host .env enables the beta. The agent's
# own tests call run_inquire_agent directly and manage their env explicitly.
os.environ["ENABLE_INQUIRE_AGENT"] = "false"
# The voice-embedding canary sends a real clip to the configured transcription
# backend to check it still produces compatible embeddings. Left on, importing
# src.app in a test run POSTs audio to whatever ASR endpoint the host .env
# points at: slow, noisy in the logs, and it bills somebody for a transcription
# nobody asked for. The check has its own tests, which drive it explicitly.
os.environ["DISABLE_VOICE_EMBEDDING_CHECK"] = "true"
# NB: do NOT force WEBHOOK_GLOBAL_ENABLED=false here — the webhook suite needs
# delivery enabled (it mocks the actual HTTP POST), so leave the default (true).
# Disable per-endpoint rate limiting under test: several auth tests POST
# /login many times from the same client IP within one run, which the real
# "10 per minute" login limit would reject with 429. Production leaves this
# enabled (default true).
os.environ.setdefault("RATELIMIT_ENABLED", "false")
import pytest # noqa: E402
@pytest.fixture(scope="session", autouse=True)
def _initialize_test_database():
"""Create the full schema in the throwaway DB once per session."""
from src.app import app
from src.init_db import initialize_database
with app.app_context():
initialize_database(app)
yield
# Best-effort cleanup of the temp DB file after the session.
for path in (_TEST_DB_PATH, _TEST_DB_PATH + "-wal", _TEST_DB_PATH + "-shm"):
try:
os.remove(path)
except OSError:
pass