Skip to content

Commit 2d268ba

Browse files
committed
Updated database connection validation
1 parent 79f0856 commit 2d268ba

File tree

4 files changed

+134
-118
lines changed

4 files changed

+134
-118
lines changed

.github/workflows/deploy-azure.yml

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,3 +207,29 @@ jobs:
207207
fi
208208
exit 1
209209
fi
210+
211+
#─────────────── Verify Memgraph connectivity ─────────────────
212+
- name: Set up Python for Memgraph verification
213+
uses: actions/setup-python@v4
214+
with:
215+
python-version: '3.9'
216+
217+
- name: Install dependencies for Memgraph verification
218+
run: |
219+
python -m pip install --upgrade pip
220+
pip install python-dotenv mgclient
221+
222+
- name: Export Memgraph connection details
223+
run: |
224+
# Get service IP
225+
MEMGRAPH_IP=$(kubectl get service memgraph -o jsonpath='{.status.loadBalancer.ingress[0].ip}')
226+
echo "MEMGRAPH_URI=$MEMGRAPH_IP" >> $GITHUB_ENV
227+
echo "MEMGRAPH_PORT=7687" >> $GITHUB_ENV
228+
echo "MEMGRAPH_USERNAME=${{ env.DB_USERNAME }}" >> $GITHUB_ENV
229+
echo "MEMGRAPH_PASSWORD=${{ env.DB_PASSWORD }}" >> $GITHUB_ENV
230+
echo "Memgraph connection details exported: $MEMGRAPH_IP:7687"
231+
232+
- name: Verify Memgraph connection and authentication
233+
run: |
234+
echo "Verifying Memgraph connection and authentication..."
235+
python scripts/verify_memgraph_connection.py

scripts/get_memgraph_connection.py

Lines changed: 0 additions & 118 deletions
This file was deleted.
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
from dotenv import load_dotenv
2+
import os
3+
import mgclient
4+
import sys
5+
import time
6+
from typing import Tuple, Optional
7+
8+
def verify_memgraph_connection(max_retries: int = 5, retry_delay: int = 5) -> Tuple[bool, Optional[str]]:
9+
host = os.environ.get("MEMGRAPH_URI", "127.0.0.1")
10+
port = int(os.environ.get("MEMGRAPH_PORT", "7687"))
11+
username = "test" or os.environ.get("MEMGRAPH_USERNAME", "memgraph")
12+
password = os.environ.get("MEMGRAPH_PASSWORD", "memgraph")
13+
14+
print(f"Verifying connection to Memgraph at {host}:{port}")
15+
16+
if host == "localhost":
17+
host = "127.0.0.1"
18+
19+
for attempt in range(1, max_retries + 1):
20+
try:
21+
print(f"Attempt {attempt}/{max_retries}: Connecting to Memgraph")
22+
conn = mgclient.connect(
23+
host=host,
24+
port=port,
25+
username=username,
26+
password=password
27+
)
28+
29+
conn.autocommit = True
30+
cursor = conn.cursor()
31+
32+
# Basic connectivity check
33+
cursor.execute("RETURN 'Connection successful!' AS message")
34+
result = cursor.fetchone()[0]
35+
print(f"Success: {result}")
36+
37+
# Validate authentication works
38+
cursor.execute("CREATE (n:TestNode {name: 'connection_test'}) RETURN n")
39+
cursor.execute("MATCH (n:TestNode {name: 'connection_test'}) DELETE n")
40+
print("Authentication validation successful")
41+
42+
cursor.close()
43+
conn.close()
44+
return True, None
45+
except Exception as e:
46+
error_message = f"Connection attempt {attempt} failed: {str(e)}"
47+
print(error_message)
48+
if attempt < max_retries:
49+
print(f"Retrying in {retry_delay} seconds...")
50+
time.sleep(retry_delay)
51+
else:
52+
return False, error_message
53+
54+
if __name__ == "__main__":
55+
load_dotenv(override=True)
56+
success, error = verify_memgraph_connection()
57+
58+
if not success:
59+
print(f"Failed to connect to Memgraph: {error}")
60+
sys.exit(1)
61+
62+
print("Successfully connected to and validated Memgraph")
63+
sys.exit(0)
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import unittest
2+
from unittest.mock import patch, MagicMock
3+
import sys
4+
import os
5+
6+
# Add the scripts directory to the path so we can import the module
7+
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
8+
from scripts.verify_memgraph_connection import verify_memgraph_connection
9+
10+
class TestVerifyMemgraphConnection(unittest.TestCase):
11+
12+
@patch('mgclient.connect')
13+
def test_successful_connection(self, mock_connect):
14+
# Set up mocks
15+
mock_cursor = MagicMock()
16+
mock_cursor.fetchone.return_value = ["Connection successful!"]
17+
18+
mock_conn = MagicMock()
19+
mock_conn.cursor.return_value = mock_cursor
20+
mock_connect.return_value = mock_conn
21+
22+
# Call the function
23+
success, error = verify_memgraph_connection(max_retries=1)
24+
25+
# Assertions
26+
self.assertTrue(success)
27+
self.assertIsNone(error)
28+
mock_connect.assert_called_once()
29+
self.assertEqual(mock_cursor.execute.call_count, 3)
30+
31+
@patch('mgclient.connect')
32+
def test_failed_connection(self, mock_connect):
33+
# Set up mocks
34+
mock_connect.side_effect = Exception("Connection error")
35+
36+
# Call the function
37+
success, error = verify_memgraph_connection(max_retries=1, retry_delay=0)
38+
39+
# Assertions
40+
self.assertFalse(success)
41+
self.assertIn("Connection error", error)
42+
mock_connect.assert_called_once()
43+
44+
if __name__ == '__main__':
45+
unittest.main()

0 commit comments

Comments
 (0)