File size: 4,523 Bytes
0786686
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
"""

Test script for MongoDB integration.

Run this script to verify the MongoDB connection and user management.

"""
import os
import sys
from dotenv import load_dotenv
from database import db, initialize_users

# Load environment variables from .env file
load_dotenv()

def test_connection():
    """Test MongoDB connection"""
    try:
        # Test the connection by pinging the database
        db.client.admin.command('ping')
        print("βœ… Successfully connected to MongoDB")
        return True
    except Exception as e:
        print(f"❌ Failed to connect to MongoDB: {e}")
        return False

def test_user_management():
    """Test user management functions"""
    test_username = "test_user_123"
    test_password = "test_password_123"
    test_role = "test_role"
    
    # Clean up test user if exists
    db.users.delete_one({"username": test_username})
    
    # Test add_user
    print("\nTesting add_user...")
    if db.add_user(test_username, test_password, test_role):
        print(f"βœ… Successfully added test user: {test_username}")
    else:
        print("❌ Failed to add test user")
        return False
    
    # Test verify_user with correct password
    print("\nTesting verify_user with correct password...")
    user = db.verify_user(test_username, test_password)
    if user and user["username"] == test_username and user["role"] == test_role:
        print("βœ… Successfully verified user with correct password")
    else:
        print("❌ Failed to verify user with correct password")
        return False
    
    # Test verify_user with incorrect password
    print("\nTesting verify_user with incorrect password...")
    user = db.verify_user(test_username, "wrong_password")
    if user is None:
        print("βœ… Correctly rejected incorrect password")
    else:
        print("❌ Incorrectly accepted wrong password")
        return False
    
    # Test get_user
    print("\nTesting get_user...")
    user = db.get_user(test_username)
    if user and user["username"] == test_username and user["role"] == test_role:
        print("βœ… Successfully retrieved user details")
    else:
        print("❌ Failed to retrieve user details")
        return False
    
    # Clean up
    db.users.delete_one({"username": test_username})
    return True

def test_initialize_users():
    """Test user initialization"""
    print("\nTesting user initialization...")
    try:
        # Clean up any existing test users
        test_usernames = ["Tony", "Bruce", "Sam", "Peter", "Sid", "Natasha"]
        db.users.delete_many({"username": {"$in": test_usernames}})
        
        success_count, total_users, errors = initialize_users()
        
        if errors:
            print(f"⚠️  Encountered {len(errors)} errors during user initialization:")
            for error in errors:
                print(f"   - {error}")
        
        if success_count == total_users:
            print(f"βœ… Successfully initialized {success_count}/{total_users} users")
            return True
        else:
            print(f"❌ Only initialized {success_count}/{total_users} users")
            return False
    except Exception as e:
        print(f"❌ Error during user initialization test: {str(e)}")
        return False

if __name__ == "__main__":
    print("=== Testing MongoDB Integration ===")
    
    # Check if required environment variables are set
    required_vars = ['MONGO_URI']
    missing_vars = [var for var in required_vars if not os.getenv(var)]
    
    if missing_vars:
        print("❌ Missing required environment variables:")
        for var in missing_vars:
            print(f"   - {var}")
        print("\nPlease create a .env file with these variables. See .env.example")
        sys.exit(1)
    
    # Run tests
    connection_ok = test_connection()
    
    if connection_ok:
        print("\n=== Running User Management Tests ===")
        user_tests_ok = test_user_management()
        
        print("\n=== Running User Initialization Test ===")
        init_ok = test_initialize_users()
        
        if user_tests_ok and init_ok:
            print("\nβœ… All tests passed!")
            sys.exit(0)
        else:
            print("\n❌ Some tests failed")
            sys.exit(1)
    else:
        print("\n❌ Connection test failed. Please check your MongoDB connection details.")
        sys.exit(1)