11import os
22import pytest
33from unittest .mock import patch ,MagicMock
4- from src .utils .mongodb_client import MongoDBClient
4+ from src .utils .mongodb_client import MongoDBClient , get_mongodb_client
55
66@pytest .fixture (autouse = True )
77def mock_env_vars ():
8- """Automatically mock environment variables for all tests."""
8+ """Mock environment variables for all tests."""
99with patch .dict (os .environ , {
1010'MONGODB_URI' :'mongodb://localhost:27017' ,
1111'MONGODB_DATABASE' :'test_db'
@@ -36,15 +36,16 @@ def mock_mongo_client():
3636@pytest .fixture
3737def mongodb_client ():
3838"""Create a fresh MongoDB client instance for each test."""
39- client = MongoDBClient ()
40- client .client = None # Reset connection
39+ client = get_mongodb_client ()
40+ client .client = None
4141client .db = None
42- return client
42+ yield client
43+ client .close ()
4344
4445def test_singleton_pattern ():
4546"""Test that MongoDBClient follows singleton pattern."""
46- client1 = MongoDBClient ()
47- client2 = MongoDBClient ()
47+ client1 = get_mongodb_client ()
48+ client2 = get_mongodb_client ()
4849assert client1 is client2
4950
5051def test_lazy_initialization (mongodb_client ):
@@ -55,7 +56,6 @@ def test_lazy_initialization(mongodb_client):
5556def test_successful_connection (mongodb_client ,mock_mongo_client ):
5657"""Test successful database connection."""
5758mongodb_client .initialize_connection ()
58-
5959mock_mongo_client ['client' ].assert_called_once_with ('mongodb://localhost:27017' )
6060assert mongodb_client .client is not None
6161assert mongodb_client .db is not None
@@ -67,28 +67,36 @@ def test_insert_one(mongodb_client, mock_mongo_client):
6767collection .insert_one .return_value .inserted_id = "test_id"
6868
6969result = mongodb_client .insert_one ("test_collection" ,test_doc )
70-
7170collection .insert_one .assert_called_once_with (test_doc )
7271assert result == "test_id"
7372
7473def test_find_one (mongodb_client ,mock_mongo_client ):
7574"""Test finding a single document."""
7675test_query = {"name" :"test" }
7776expected_doc = {"_id" :"test_id" ,"name" :"test" }
78-
7977collection = mock_mongo_client ['collection' ]
8078collection .find_one .return_value = expected_doc
8179
8280result = mongodb_client .find_one ("test_collection" ,test_query )
83-
8481collection .find_one .assert_called_once_with (test_query )
8582assert result == expected_doc
8683
87- def test_close_connection (mongodb_client ,mock_mongo_client ):
88- """Test closing the database connection."""
89- mongodb_client .initialize_connection ()
90- mongodb_client .close ()
84+ def test_connection_error (mock_mongo_client ):
85+ """Test handling of connection errors."""
86+ mock_mongo_client ['client' ].side_effect = Exception ("Connection failed" )
87+ client = get_mongodb_client ()
88+ client .client = None
9189
92- mock_mongo_client ['client_instance' ].close .assert_called_once ()
93- assert mongodb_client .client is None
94- assert mongodb_client .db is None
90+ with pytest .raises (Exception )as exc_info :
91+ client .initialize_connection ()
92+ assert "Failed to connect to MongoDB" in str (exc_info .value )
93+
94+ def test_missing_env_vars ():
95+ """Test handling of missing environment variables."""
96+ with patch .dict (os .environ , {},clear = True ):
97+ client = get_mongodb_client ()
98+ client .client = None
99+
100+ with pytest .raises (ValueError )as exc_info :
101+ client .initialize_connection ()
102+ assert "MongoDB connection details not found" in str (exc_info .value )