You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

116 lines
3.1 KiB
Python

"""
Test configuration and fixtures
"""
import pytest
import asyncio
from typing import Generator, AsyncGenerator
from fastapi.testclient import TestClient
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
import tempfile
import os
from app.main import app
from app.core.database import get_db, Base
from app.core.config import settings
# Test database URL (use in-memory SQLite for tests)
TEST_DATABASE_URL = "sqlite+aiosqlite:///:memory:"
# Create test engine
test_engine = create_async_engine(
TEST_DATABASE_URL,
echo=False,
future=True
)
# Create test session factory
TestSessionLocal = sessionmaker(
test_engine,
class_=AsyncSession,
expire_on_commit=False
)
@pytest.fixture(scope="session")
def event_loop():
"""Create an instance of the default event loop for the test session."""
loop = asyncio.get_event_loop_policy().new_event_loop()
yield loop
loop.close()
@pytest.fixture(scope="function")
async def db_session() -> AsyncGenerator[AsyncSession, None]:
"""Create a fresh database session for each test."""
# Create tables
async with test_engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
# Create session
async with TestSessionLocal() as session:
yield session
# Drop tables
async with test_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
@pytest.fixture(scope="function")
def client() -> Generator[TestClient, None, None]:
"""Create a test client with in-memory database."""
# Create test engine and session
test_engine = create_async_engine("sqlite+aiosqlite:///:memory:", echo=False)
TestSession = sessionmaker(test_engine, class_=AsyncSession, expire_on_commit=False)
async def override_get_db():
async with test_engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
async with TestSession() as session:
yield session
app.dependency_overrides[get_db] = override_get_db
with TestClient(app) as test_client:
yield test_client
app.dependency_overrides.clear()
@pytest.fixture
def sample_financial_data():
"""Sample financial data for testing"""
return {
"ticker": "AAPL",
"start_date": "2023-01-01T00:00:00",
"end_date": "2023-12-31T23:59:59",
"period_type": "quarterly",
"include_metrics": True,
"force_refresh": False
}
@pytest.fixture
def sample_ohlcv_data():
"""Sample OHLCV data for testing"""
return {
"ticker": "AAPL",
"start_date": "2023-01-01T00:00:00",
"end_date": "2023-12-31T23:59:59",
"interval": "1d"
}
@pytest.fixture
def valid_migration_key():
"""Valid migration API key for testing"""
return settings.MIGRATION_API_KEY
@pytest.fixture
def mock_company_data():
"""Mock company data for testing"""
return {
"ticker": "AAPL",
"name": "Apple Inc.",
"cik": "0000320193",
"sector": "Technology",
"industry": "Consumer Electronics",
"business_description": "Technology company"
}