import os import tempfile import unittest from datetime import datetime, timezone from unittest.mock import patch import database class DatabaseCacheTests(unittest.TestCase): def test_intraday_snapshot_never_rolls_to_next_session(self): before_open = datetime(2026, 10, 10, 3, 0, tzinfo=timezone.utc) with patch("datetime.datetime") as clock, patch.object(database, "_conn") as connection: clock.now.return_value = before_open snapshot = database.save_prediction_snapshot( "TEST.NS", "INTRADAY", "BULLISH", "HIGH", 101, 103, 1, 3, 100) self.assertIsNone(snapshot) connection.assert_not_called() def test_prediction_sources_do_not_share_snapshot_ids(self): with tempfile.TemporaryDirectory() as tmpdir: with patch.object(database, "DB_PATH", os.path.join(tmpdir, "paper_trading.db")): database.init_db() arguments = ("TEST.NS", "1D", "BULLISH", "HIGH", 101, 103, 1, 3, 100) ai_id = database.save_prediction_snapshot(*arguments, snapshot_source="watchlist") ml_id = database.save_prediction_snapshot(*arguments, snapshot_source="ml") self.assertNotEqual(ai_id, ml_id) self.assertEqual(ai_id, database.save_prediction_snapshot( *arguments, snapshot_source="watchlist")) with database._conn() as connection: connection.execute("ALTER TABLE prediction_snapshots DROP COLUMN grading_version") database.init_db() self.assertEqual(len(database.get_prediction_snapshots()), 2) validated = database.validate_prediction(ai_id, 102, 2, True, 103, 99, hit_grade="MIDPOINT_HIT", grading_version=2) self.assertEqual(validated["grading_version"], 2) def test_watchlist_prediction_cache_round_trip_and_removal(self): with tempfile.TemporaryDirectory() as tmpdir: database_path = os.path.join(tmpdir, "paper_trading.db") with patch.object(database, "DB_PATH", database_path): database.init_db() database.add_to_watchlist("RELIANCE.NS", "Reliance Industries Limited") database.save_watchlist_prediction_cache( "RELIANCE.NS", "1D", {"direction": "BULLISH"}, saved_at=123.0 ) cached = database.get_watchlist_prediction_cache("RELIANCE.NS", "1D") self.assertEqual(cached["pred"]["direction"], "BULLISH") self.assertEqual(cached["saved_at"], 123.0) self.assertTrue(database.remove_from_watchlist("RELIANCE.NS")) self.assertIsNone(database.get_watchlist_prediction_cache("RELIANCE.NS", "1D")) def test_app_result_cache_round_trip(self): with tempfile.TemporaryDirectory() as tmpdir: database_path = os.path.join(tmpdir, "paper_trading.db") with patch.object(database, "DB_PATH", database_path): database.init_db() result = {"picks": [{"ticker": "RELIANCE.NS", "price": 2500.0}]} database.save_app_result_cache("top5", result, saved_at=456.0) cached = database.get_app_result_cache("top5") self.assertEqual(cached["result"], result) self.assertEqual(cached["saved_at"], 456.0) if __name__ == "__main__": unittest.main()