from contextlib import closing import importlib.util from pathlib import Path import sqlite3 import tempfile import unittest from unittest.mock import patch SPEC = importlib.util.spec_from_file_location( "limits_under_test", Path(__file__).parents[1] / "bot" / "account_limits.py") assert SPEC is not None and SPEC.loader is not None limits = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(limits) class AccountUsageQueryTests(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() self.addCleanup(self.tmp.cleanup) self.path = Path(self.tmp.name) / "usage.db" with closing(sqlite3.connect(self.path)) as con, con: con.execute("CREATE TABLE logs(type INTEGER,created_at INTEGER,token_name TEXT,quota INTEGER)") con.execute("CREATE INDEX idx_logs_top24 ON logs(type,created_at)") con.executemany("INSERT INTO logs VALUES(?,?,?,?)", [ (2, 100, "tg123", 11), (2, 101, "pm123-k2", 13), (2, 199, "sol123-k9", 17), (2, 150, "tg123-k1", None), (2, 99, "tg123", 101), (2, 200, "tg123", 103), (1, 150, "tg123", 107), (None, 150, "tg123", 109), (2, 150, "tg1234", 113), (2, 150, "tg123-k01", 127), (2, 150, "tg123-k1foreign", 131), (2, 150, "pm123-k0", 137), (2, 150, "sol123-k\u0661", 139), (2, 150, "tg0123", 149), ]) def index(self, sql): with closing(sqlite3.connect(self.path)) as con, con: con.execute(sql) def test_exact_historical_credentials_time_bounds_and_type_are_preserved(self): # No tokens table: deleted/rotated credentials must still count. self.index("CREATE INDEX idx_logs_token_name ON logs(token_name)") self.assertEqual(limits.daily_spent_units(self.path, 123, 100, 200), 41) self.assertEqual(limits.daily_spent_units(self.path, 123, 100), 144) self.assertEqual(limits.daily_spent_units(self.path, 123, 100, 100), 0) self.assertEqual(limits.daily_spent_units(self.path, 456, 100, 200), 0) def test_missing_partial_wrong_column_and_expression_index_fall_back(self): indexes = [None, "CREATE INDEX idx_logs_token_name ON logs(token_name) WHERE type=1", "CREATE INDEX idx_logs_token_name ON logs(quota)", "CREATE INDEX idx_logs_token_name ON logs(lower(token_name))"] for sql in indexes: with self.subTest(index=sql): with closing(sqlite3.connect(self.path)) as con, con: con.execute("DROP INDEX IF EXISTS idx_logs_token_name") if sql: con.execute(sql) self.assertEqual(limits.daily_spent_units(self.path, 123, 100, 200), 41) def test_indexed_usage_does_not_scan_other_accounts_daily_logs(self): self.index("CREATE INDEX idx_logs_token_name ON logs(token_name)") with closing(sqlite3.connect(self.path)) as con, con: con.executemany("INSERT INTO logs VALUES(2,150,?,1)", [("tg%d" % i,) for i in range(10000, 30000)]) real_connect = sqlite3.connect callbacks = [] def connect(*args, **kwargs): con = real_connect(*args, **kwargs) con.set_progress_handler(lambda: callbacks.append(1) or 0, 100) return con with patch.object(limits.sqlite3, "connect", side_effect=connect): self.assertEqual(limits.daily_spent_units(self.path, 123, 100, 200), 41) # SQLite instruction budget, not a load-sensitive wall-clock deadline. self.assertLess(len(callbacks), 100) def test_invalid_intervals_and_missing_database_fail_closed(self): for start, end in [(100, 99), (True, 200), (100, 200.0)]: with self.subTest(start=start, end=end), self.assertRaises(ValueError): limits.daily_spent_units(self.path, 123, start, end) missing = Path(self.tmp.name) / "missing.db" with self.assertRaises(sqlite3.DatabaseError): limits.daily_spent_units(missing, 123, 100, 200) self.assertFalse(missing.exists()) with closing(sqlite3.connect(self.path)) as con, con: con.execute("ALTER TABLE logs RENAME COLUMN quota TO missing_quota") with self.assertRaises(sqlite3.DatabaseError): limits.daily_spent_units(self.path, 123, 100, 200) if __name__ == "__main__": unittest.main()