test_table_creation.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import os
  2. import sys
  3. from pathlib import Path
  4. # add the parent directory to the system path
  5. sys.path.append(str(Path(__file__).resolve().parent.parent))
  6. import unittest
  7. from sqlalchemy import create_engine, inspect
  8. import database.database as db_module
  9. from database.database import create_dynamic_tables, get_dynamic_table_names
  10. class TestTableCreation(unittest.TestCase):
  11. def setUp(self):
  12. # Reset global singletons so each test gets a clean in-memory DB
  13. db_module._engine = None
  14. db_module._Session = None
  15. db_module.dynamic_model_cache.clear()
  16. # Set environment variables for in-memory SQLite
  17. os.environ["DATABASE_TYPE"] = "SQLITE"
  18. os.environ["DATABASE_STRING_CONNECTION"] = ":memory:"
  19. self.engine = create_engine("sqlite:///:memory:", echo=False, future=True)
  20. db_module._engine = self.engine
  21. def tearDown(self):
  22. self.engine.dispose()
  23. # Clean up singletons after each test
  24. db_module._engine = None
  25. db_module._Session = None
  26. db_module.dynamic_model_cache.clear()
  27. def test_table_creation(self):
  28. # Verify tables do not exist in a fresh engine
  29. inspector = inspect(self.engine)
  30. current_tables = inspector.get_table_names()
  31. table_names = get_dynamic_table_names()
  32. for table in table_names:
  33. self.assertNotIn(table, current_tables)
  34. # Trigger table creation explicitly
  35. create_dynamic_tables(self.engine)
  36. # Refresh the inspector to get the latest table names
  37. inspector = inspect(self.engine)
  38. current_tables = inspector.get_table_names()
  39. for table in table_names:
  40. self.assertIn(table, current_tables)
  41. # New quota tables must also exist
  42. for quota_table in [
  43. "quota_users",
  44. "quota_groups",
  45. "quota_rules",
  46. "quota_events",
  47. ]:
  48. self.assertIn(quota_table, current_tables)
  49. if __name__ == "__main__":
  50. unittest.main()