"""Tests for Storage metrics integration.""" import sys import sqlite3 import tempfile from pathlib import Path from datetime import datetime sys.path.append(str(Path(__file__).resolve().parents[1])) from storage import Storage from repositories.sqlite_repository import SQLiteOrderflowRepository def test_storage_calculates_and_stores_metrics(): """Test that Storage calculates and stores metrics during build_booktick_from_db.""" with tempfile.NamedTemporaryFile(suffix=".db", delete=False) as tmp_file: db_path = Path(tmp_file.name) try: # Create test database with minimal data with sqlite3.connect(str(db_path)) as conn: # Create tables conn.execute(""" CREATE TABLE book ( id INTEGER PRIMARY KEY, bids TEXT NOT NULL, asks TEXT NOT NULL, timestamp INTEGER NOT NULL ) """) conn.execute(""" CREATE TABLE trades ( id INTEGER PRIMARY KEY, trade_id REAL NOT NULL, price REAL NOT NULL, size REAL NOT NULL, side TEXT NOT NULL, timestamp INTEGER NOT NULL ) """) # Insert test data bids = "[(50000.0, 10.0, 0, 1), (49999.0, 5.0, 0, 1)]" # 15.0 total bid volume asks = "[(50001.0, 3.0, 0, 1), (50002.0, 2.0, 0, 1)]" # 5.0 total ask volume conn.execute("INSERT INTO book (id, bids, asks, timestamp) VALUES (?, ?, ?, ?)", (1, bids, asks, 1000)) # Add trades for CVD calculation conn.execute("INSERT INTO trades (id, trade_id, price, size, side, timestamp) VALUES (?, ?, ?, ?, ?, ?)", (1, 1.0, 50000.0, 8.0, "buy", 1000)) conn.execute("INSERT INTO trades (id, trade_id, price, size, side, timestamp) VALUES (?, ?, ?, ?, ?, ?)", (2, 2.0, 50001.0, 3.0, "sell", 1000)) conn.commit() # Test Storage metrics integration storage = Storage("BTC-USDT") storage.build_booktick_from_db(db_path, datetime.now()) # Verify metrics were calculated and stored repo = SQLiteOrderflowRepository(db_path) with repo.connect() as conn: # Check metrics table exists assert repo.table_exists(conn, "metrics") # Load calculated metrics metrics = repo.load_metrics_by_timerange(conn, 1000, 1000) assert len(metrics) == 1 metric = metrics[0] # Verify OBI calculation: (15 - 5) / (15 + 5) = 0.5 assert abs(metric.obi - 0.5) < 0.001 # Verify CVD calculation: buy(8.0) - sell(3.0) = 5.0 assert abs(metric.cvd - 5.0) < 0.001 # Verify best bid/ask assert metric.best_bid == 50000.0 assert metric.best_ask == 50001.0 # Verify book was also populated (backward compatibility) assert len(storage.book.snapshots) == 1 finally: db_path.unlink(missing_ok=True)