CoolFace
Apppublic

findEthics/Atlas

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
test_mongodb_connection.py151 linesDownload Raw Back to tests
1#!/usr/bin/env python32"""3Test MongoDB connection for user authentication tests4 5This script verifies that the MongoDB connection is working properly6for the user authentication test suite.7"""8 9import sys10import os11sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))12 13# Load environment variables14try:15    from dotenv import load_dotenv16    load_dotenv()17    print("✅ Environment variables loaded")18except ImportError:19    print("⚠️  dotenv not available - continuing without .env file loading")20 21import asyncio22from analytics.database import connect_to_database, get_database23 24 25async def test_mongodb_connection():26    """Test MongoDB connection"""27    print("\n🔍 Testing MongoDB Connection")28    print("=" * 40)29    30    # Check environment variables31    mongodb_url = os.getenv("MONGODB_URL")32    mongodb_db = os.getenv("MONGODB_DATABASE")33    34    if mongodb_url:35        print(f"✅ MONGODB_URL found: {mongodb_url[:30]}...")36    else:37        print("❌ MONGODB_URL not found")38        return False39    40    if mongodb_db:41        print(f"✅ MONGODB_DATABASE found: {mongodb_db}")42    else:43        print("❌ MONGODB_DATABASE not found")44        return False45    46    # Test database connection47    try:48        print("\n🔗 Attempting to connect to MongoDB...")49        database = await connect_to_database()50        51        if database is not None:52            print("✅ MongoDB connection successful!")53            54            # Test a simple operation55            try:56                # Try to list collections57                collections = await database.list_collection_names()58                print(f"✅ Database accessible - found {len(collections)} collections")59                60                if collections:61                    print("   Collections:", ", ".join(collections[:5]))62                    if len(collections) > 5:63                        print(f"   ... and {len(collections) - 5} more")64                65                return True66                67            except Exception as e:68                print(f"⚠️  Database accessible but operation failed: {e}")69                return True  # Connection works, operation might need permissions70                71        else:72            print("❌ MongoDB connection failed - falling back to JSON storage")73            return False74            75    except Exception as e:76        print(f"❌ MongoDB connection error: {e}")77        return False78 79 80async def test_analytics_collections():81    """Test analytics collections access"""82    print("\n📊 Testing Analytics Collections")83    print("=" * 40)84    85    try:86        from analytics.database import (87            get_sessions_collection,88            get_messages_collection,89            get_search_analytics_collection90        )91        92        # Test sessions collection93        sessions_collection = await get_sessions_collection()94        if sessions_collection is not None:95            count = await sessions_collection.count_documents({})96            print(f"✅ Sessions collection accessible - {count} documents")97        else:98            print("⚠️  Sessions collection not available")99        100        # Test messages collection101        messages_collection = await get_messages_collection()102        if messages_collection is not None:103            count = await messages_collection.count_documents({})104            print(f"✅ Messages collection accessible - {count} documents")105        else:106            print("⚠️  Messages collection not available")107        108        # Test search analytics collection109        search_collection = await get_search_analytics_collection()110        if search_collection is not None:111            count = await search_collection.count_documents({})112            print(f"✅ Search analytics collection accessible - {count} documents")113        else:114            print("⚠️  Search analytics collection not available")115        116        return True117        118    except Exception as e:119        print(f"❌ Analytics collections test failed: {e}")120        return False121 122 123async def main():124    """Main test function"""125    print("🧪 MongoDB Connection Test for User Authentication")126    print("=" * 60)127    128    # Test basic connection129    connection_ok = await test_mongodb_connection()130    131    # Test analytics collections132    collections_ok = await test_analytics_collections()133    134    print("\n" + "=" * 60)135    if connection_ok and collections_ok:136        print("🎉 MongoDB is ready for user authentication tests!")137        print("✅ All database operations should work correctly")138    elif connection_ok:139        print("⚠️  MongoDB connection works but some collections may need setup")140        print("✅ Basic tests should work, some advanced tests may be limited")141    else:142        print("❌ MongoDB connection failed")143        print("⚠️  Tests will use JSON file fallback storage")144        print("✅ Tests will still run but without persistent database storage")145    146    return connection_ok147 148 149if __name__ == "__main__":150    success = asyncio.run(main())151    sys.exit(0 if success else 1)