Atlas / tests /test_mongodb_connection.py
findEthics
feat: Add comprehensive database migration system for user authentication
04aa1ba
Raw
History Blame Contribute Delete
5.14 kB
#!/usr/bin/env python3
"""
Test MongoDB connection for user authentication tests
This script verifies that the MongoDB connection is working properly
for the user authentication test suite.
"""
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Load environment variables
try:
from dotenv import load_dotenv
load_dotenv()
print("βœ… Environment variables loaded")
except ImportError:
print("⚠️ dotenv not available - continuing without .env file loading")
import asyncio
from analytics.database import connect_to_database, get_database
async def test_mongodb_connection():
"""Test MongoDB connection"""
print("\nπŸ” Testing MongoDB Connection")
print("=" * 40)
# Check environment variables
mongodb_url = os.getenv("MONGODB_URL")
mongodb_db = os.getenv("MONGODB_DATABASE")
if mongodb_url:
print(f"βœ… MONGODB_URL found: {mongodb_url[:30]}...")
else:
print("❌ MONGODB_URL not found")
return False
if mongodb_db:
print(f"βœ… MONGODB_DATABASE found: {mongodb_db}")
else:
print("❌ MONGODB_DATABASE not found")
return False
# Test database connection
try:
print("\nπŸ”— Attempting to connect to MongoDB...")
database = await connect_to_database()
if database is not None:
print("βœ… MongoDB connection successful!")
# Test a simple operation
try:
# Try to list collections
collections = await database.list_collection_names()
print(f"βœ… Database accessible - found {len(collections)} collections")
if collections:
print(" Collections:", ", ".join(collections[:5]))
if len(collections) > 5:
print(f" ... and {len(collections) - 5} more")
return True
except Exception as e:
print(f"⚠️ Database accessible but operation failed: {e}")
return True # Connection works, operation might need permissions
else:
print("❌ MongoDB connection failed - falling back to JSON storage")
return False
except Exception as e:
print(f"❌ MongoDB connection error: {e}")
return False
async def test_analytics_collections():
"""Test analytics collections access"""
print("\nπŸ“Š Testing Analytics Collections")
print("=" * 40)
try:
from analytics.database import (
get_sessions_collection,
get_messages_collection,
get_search_analytics_collection
)
# Test sessions collection
sessions_collection = await get_sessions_collection()
if sessions_collection is not None:
count = await sessions_collection.count_documents({})
print(f"βœ… Sessions collection accessible - {count} documents")
else:
print("⚠️ Sessions collection not available")
# Test messages collection
messages_collection = await get_messages_collection()
if messages_collection is not None:
count = await messages_collection.count_documents({})
print(f"βœ… Messages collection accessible - {count} documents")
else:
print("⚠️ Messages collection not available")
# Test search analytics collection
search_collection = await get_search_analytics_collection()
if search_collection is not None:
count = await search_collection.count_documents({})
print(f"βœ… Search analytics collection accessible - {count} documents")
else:
print("⚠️ Search analytics collection not available")
return True
except Exception as e:
print(f"❌ Analytics collections test failed: {e}")
return False
async def main():
"""Main test function"""
print("πŸ§ͺ MongoDB Connection Test for User Authentication")
print("=" * 60)
# Test basic connection
connection_ok = await test_mongodb_connection()
# Test analytics collections
collections_ok = await test_analytics_collections()
print("\n" + "=" * 60)
if connection_ok and collections_ok:
print("πŸŽ‰ MongoDB is ready for user authentication tests!")
print("βœ… All database operations should work correctly")
elif connection_ok:
print("⚠️ MongoDB connection works but some collections may need setup")
print("βœ… Basic tests should work, some advanced tests may be limited")
else:
print("❌ MongoDB connection failed")
print("⚠️ Tests will use JSON file fallback storage")
print("βœ… Tests will still run but without persistent database storage")
return connection_ok
if __name__ == "__main__":
success = asyncio.run(main())
sys.exit(0 if success else 1)