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

test_db_manager.py 4.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. import os
  2. import asyncio
  3. import pytest
  4. from sqlmodel import Session, text, select
  5. from typing import Generator
  6. from autogenstudio.database import DatabaseManager
  7. from autogen_agentchat.agents import AssistantAgent
  8. from autogen_agentchat.teams import RoundRobinGroupChat
  9. from autogen_ext.models.openai import OpenAIChatCompletionClient
  10. from autogen_agentchat.conditions import TextMentionTermination
  11. from autogenstudio.datamodel.db import Team
  12. @pytest.fixture
  13. def test_db() -> Generator[DatabaseManager, None, None]:
  14. """Fixture for test database"""
  15. db_path = "test.db"
  16. db = DatabaseManager(f"sqlite:///{db_path}")
  17. db.reset_db()
  18. # Initialize database instead of create_db_and_tables
  19. db.initialize_database(auto_upgrade=False)
  20. yield db
  21. # Clean up
  22. asyncio.run(db.close())
  23. db.reset_db()
  24. try:
  25. if os.path.exists(db_path):
  26. os.remove(db_path)
  27. except Exception as e:
  28. print(f"Warning: Failed to remove test database file: {e}")
  29. @pytest.fixture
  30. def test_user() -> str:
  31. return "test_user@example.com"
  32. @pytest.fixture
  33. def sample_team(test_user: str) -> Team:
  34. """Create a sample team with proper config"""
  35. agent = AssistantAgent(
  36. name="weather_agent",
  37. model_client=OpenAIChatCompletionClient(
  38. model="gpt-4",
  39. ),
  40. )
  41. agent_team = RoundRobinGroupChat([agent], termination_condition=TextMentionTermination("TERMINATE"))
  42. team_component = agent_team.dump_component()
  43. return Team(
  44. user_id=test_user,
  45. component=team_component.model_dump(),
  46. )
  47. class TestDatabaseOperations:
  48. def test_basic_setup(self, test_db: DatabaseManager):
  49. """Test basic database setup and connection"""
  50. with Session(test_db.engine) as session:
  51. result = session.exec(text("SELECT 1")).first()
  52. assert result[0] == 1
  53. result = session.exec(select(1)).first()
  54. assert result == 1
  55. def test_basic_entity_creation(self, test_db: DatabaseManager, sample_team: Team):
  56. """Test creating all entity types with proper configs"""
  57. # Use upsert instead of raw session
  58. response = test_db.upsert(sample_team)
  59. assert response.status is True
  60. with Session(test_db.engine) as session:
  61. saved_team = session.get(Team, sample_team.id)
  62. assert saved_team is not None
  63. def test_upsert_operations(self, test_db: DatabaseManager, sample_team: Team):
  64. """Test upsert for both create and update scenarios"""
  65. # Test Create
  66. response = test_db.upsert(sample_team)
  67. assert response.status is True
  68. assert "Created Successfully" in response.message
  69. # Test Update
  70. team_id = sample_team.id
  71. sample_team.version = "0.0.2"
  72. response = test_db.upsert(sample_team)
  73. assert response.status is True
  74. # Verify Update
  75. result = test_db.get(Team, {"id": team_id})
  76. assert result.status is True
  77. assert result.data[0].version == "0.0.2"
  78. def test_delete_operations(self, test_db: DatabaseManager, sample_team: Team):
  79. """Test delete with various filters"""
  80. # First insert the model
  81. response = test_db.upsert(sample_team)
  82. assert response.status is True # Verify insert worked
  83. # Get the ID that was actually saved
  84. team_id = sample_team.id
  85. # Test deletion by id
  86. response = test_db.delete(Team, {"id": team_id})
  87. assert response.status is True
  88. assert "Deleted Successfully" in response.message
  89. # Verify deletion
  90. result = test_db.get(Team, {"id": team_id})
  91. assert len(result.data) == 0
  92. def test_initialize_database_scenarios(self):
  93. """Test different initialize_database parameters"""
  94. db_path = "test_init.db"
  95. db = DatabaseManager(f"sqlite:///{db_path}")
  96. try:
  97. # Test basic initialization
  98. response = db.initialize_database()
  99. assert response.status is True
  100. # Test with auto_upgrade
  101. response = db.initialize_database(auto_upgrade=True)
  102. assert response.status is True
  103. finally:
  104. asyncio.run(db.close())
  105. db.reset_db()
  106. if os.path.exists(db_path):
  107. os.remove(db_path)