test_postgres.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. from unittest.mock import MagicMock
  2. import psycopg
  3. import pytest
  4. from embedchain.loaders.postgres import PostgresLoader
  5. @pytest.fixture
  6. def postgres_loader(mocker):
  7. with mocker.patch.object(psycopg, "connect"):
  8. config = {"url": "postgres://user:password@localhost:5432/database"}
  9. loader = PostgresLoader(config=config)
  10. yield loader
  11. def test_postgres_loader_initialization(postgres_loader):
  12. assert postgres_loader.connection is not None
  13. assert postgres_loader.cursor is not None
  14. def test_postgres_loader_invalid_config():
  15. with pytest.raises(ValueError, match="Must provide the valid config. Received: None"):
  16. PostgresLoader(config=None)
  17. def test_load_data(postgres_loader, monkeypatch):
  18. mock_cursor = MagicMock()
  19. monkeypatch.setattr(postgres_loader, "cursor", mock_cursor)
  20. query = "SELECT * FROM table"
  21. mock_cursor.fetchall.return_value = [(1, "data1"), (2, "data2")]
  22. result = postgres_loader.load_data(query)
  23. assert "doc_id" in result
  24. assert "data" in result
  25. assert len(result["data"]) == 2
  26. assert result["data"][0]["meta_data"]["url"] == query
  27. assert result["data"][1]["meta_data"]["url"] == query
  28. assert mock_cursor.execute.called_with(query)
  29. def test_load_data_exception(postgres_loader, monkeypatch):
  30. mock_cursor = MagicMock()
  31. monkeypatch.setattr(postgres_loader, "cursor", mock_cursor)
  32. _ = "SELECT * FROM table"
  33. mock_cursor.execute.side_effect = Exception("Mocked exception")
  34. with pytest.raises(
  35. ValueError, match=r"Failed to load data using query=SELECT \* FROM table with: Mocked exception"
  36. ):
  37. postgres_loader.load_data("SELECT * FROM table")
  38. def test_close_connection(postgres_loader):
  39. postgres_loader.close_connection()
  40. assert postgres_loader.cursor is None
  41. assert postgres_loader.connection is None