Skip to content

Commit a069c53

Browse files
committed
updated test_connection method
1 parent fde69d8 commit a069c53

File tree

7 files changed

+136
-64
lines changed

7 files changed

+136
-64
lines changed

.github/workflows/test.yaml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ jobs:
9292
env:
9393
GITHUB_ACTIONS: 'true'
9494
run: |
95-
nohup /tmp/stackql -v --pgsrv.port=5444 srv &
95+
nohup /tmp/stackql -v --pgsrv.port=5466 srv &
9696
sleep 5
9797
python3 run_server_tests.py
9898
@@ -101,7 +101,7 @@ jobs:
101101
shell: pwsh
102102
run: |
103103
Start-Process -FilePath "C:\Temp\stackql.exe" `
104-
-ArgumentList "-v", "--pgsrv.port=5444", "srv"
104+
-ArgumentList "-v", "--pgsrv.port=5466", "srv"
105105
Start-Sleep -Seconds 5
106106
107107
- name: Stop StackQL server (Linux/macOS)

pystackql/core/stackql.py

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -432,4 +432,29 @@ async def executeQueriesAsync(self, queries):
432432
"or switch to local mode if you need to run multiple queries concurrently."
433433
)
434434

435-
return await self.async_executor.execute_queries(queries)
435+
return await self.async_executor.execute_queries(queries)
436+
437+
def test_connection(self):
438+
"""Tests if the server connection is working by executing a simple query.
439+
440+
This method is only valid when server_mode=True.
441+
442+
Returns:
443+
bool: True if the connection is working, False otherwise.
444+
445+
Raises:
446+
ValueError: If called when not in server mode.
447+
"""
448+
if not self.server_mode:
449+
raise ValueError("The test_connectivity method is only available in server mode.")
450+
451+
try:
452+
result = self.server_connection.execute_query("SELECT 'test' as test_value")
453+
return (isinstance(result, list) and
454+
len(result) == 1 and
455+
'test_value' in result[0] and
456+
result[0]['test_value'] == 'test')
457+
except Exception as e:
458+
if self.debug:
459+
print(f"Connection test failed: {str(e)}")
460+
return False

start-stackql-server.sh

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# start server if not running
22
echo "checking if server is running"
33
if [ -z "$(ps | grep stackql)" ]; then
4-
nohup ./stackql -v --pgsrv.port=5444 srv &
4+
nohup ./stackql -v --pgsrv.port=5466 srv &
55
sleep 5
66
else
77
echo "server is already running"

tests/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ Server tests are skipped by default because they require a running StackQL serve
5252

5353
1. Start a StackQL server:
5454
```bash
55-
stackql srv --pgsrv.address 127.0.0.1 --pgsrv.port 5444
55+
stackql srv --pgsrv.address 127.0.0.1 --pgsrv.port 5466
5656
```
5757

5858
2. Run the server tests:

tests/conftest.py

Lines changed: 0 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -48,51 +48,6 @@ def setup_stackql():
4848
# Return the StackQL instance for use in tests
4949
return stackql
5050

51-
# def stackql_process_running():
52-
# try:
53-
# if platform.system() == "Windows":
54-
# # Use `tasklist` to look for stackql.exe with correct port in args (may not include args, so fallback is loose match)
55-
# output = subprocess.check_output(['tasklist', '/FI', 'IMAGENAME eq stackql.exe'], text=True)
56-
# return "stackql.exe" in output
57-
# else:
58-
# # Use `ps aux` to search for 'stackql' process with the correct port
59-
# output = subprocess.check_output(['ps', 'aux'], text=True)
60-
# return f"--pgsrv.port={SERVER_PORT}" in output and "stackql" in output
61-
# except subprocess.CalledProcessError:
62-
# return False
63-
64-
def stackql_process_running():
65-
try:
66-
if platform.system() == "Windows":
67-
output = subprocess.check_output(
68-
['tasklist', '/FI', 'IMAGENAME eq stackql.exe'], text=True
69-
)
70-
return "stackql.exe" in output
71-
else:
72-
# More reliable: use pgrep + full argument check
73-
output = subprocess.check_output(
74-
f"ps aux | grep '[s]tackql' | grep -- '--pgsrv.port={SERVER_PORT}'",
75-
shell=True,
76-
text=True
77-
)
78-
return bool(output.strip())
79-
except subprocess.CalledProcessError:
80-
return False
81-
82-
@pytest.fixture(scope="session")
83-
def stackql_server():
84-
"""
85-
Verifies that a StackQL server process is running with the expected port.
86-
Does not attempt to start or stop the process.
87-
"""
88-
print(f"\n🔍 Checking for running StackQL server process (port {SERVER_PORT})...")
89-
90-
if not stackql_process_running():
91-
pytest.exit(f"❌ No running StackQL server process found for port {SERVER_PORT}", returncode=1)
92-
93-
print("✅ StackQL server process is running.")
94-
yield
95-
9651
@pytest.fixture
9752
def mock_interactive_shell():
9853
"""Create a mock IPython shell for testing."""

tests/test_constants.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
import pandas as pd
1515

1616
# Server connection settings
17-
SERVER_PORT = 5444
17+
SERVER_PORT = 5466
1818
SERVER_ADDRESS = "127.0.0.1"
1919

2020
# Expected properties and patterns for validation

tests/test_server.py

Lines changed: 105 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
"""
88

99
import re
10+
import os
1011
import pytest
1112
import pandas as pd
1213
from unittest.mock import patch
@@ -20,29 +21,80 @@
2021
pystackql_test_setup
2122
)
2223

23-
@pytest.mark.usefixtures("stackql_server")
24+
# @pytest.mark.usefixtures("stackql_server")
2425
class TestServerMode:
2526
"""Tests for PyStackQL server mode functionality."""
2627

2728
StackQL = StackQL # For use with pystackql_test_setup decorator
28-
29+
server_available = False # Class-level flag to track server availability
30+
31+
# @pystackql_test_setup(server_mode=True)
32+
# def test_server_mode_connectivity(self):
33+
# """Test that server mode connects successfully."""
34+
# # Check server_mode flag is set correctly
35+
# assert self.stackql.server_mode, "StackQL should be in server mode"
36+
37+
# # Check server connection object exists
38+
# assert hasattr(self.stackql, 'server_connection'), "StackQL should have a server_connection attribute"
39+
# assert self.stackql.server_connection is not None, "Server connection object should not be None"
40+
41+
# # IMPORTANT: Actually test the connection works
42+
# connection_working = self.stackql.test_connection()
43+
44+
# # Print detailed results for debugging
45+
# if not connection_working:
46+
# print("⚠️ Server connection test failed: unable to execute a simple query")
47+
# print(f"Server address: {self.stackql.server_address}")
48+
# print(f"Server port: {self.stackql.server_port}")
49+
# print("\n❌ SERVER CONNECTION FAILED - SKIPPING REMAINING SERVER TESTS")
50+
# else:
51+
# # Set flag indicating server is available
52+
# TestServerMode.server_available = True
53+
54+
# print_test_result("Server mode connectivity test",
55+
# self.stackql.server_mode and
56+
# hasattr(self.stackql, 'server_connection') and
57+
# self.stackql.server_connection is not None and
58+
# connection_working, # Include connection check in the pass criteria
59+
# True)
60+
61+
# # Add additional output about the actual connection status
62+
# print(f" - Connection status: {'✅ WORKING' if connection_working else '❌ NOT WORKING'}")
63+
# print(f" - Expected status: ✅ WORKING") # Always expected to be working
64+
65+
# # Always assert that the connection is working
66+
# assert connection_working, "Server connection should be working"
67+
2968
@pystackql_test_setup(server_mode=True)
3069
def test_server_mode_connectivity(self):
3170
"""Test that server mode connects successfully."""
32-
assert self.stackql.server_mode, "StackQL should be in server mode"
33-
# Updated assertion to check server_connection attribute instead of _conn
34-
assert hasattr(self.stackql, 'server_connection'), "StackQL should have a server_connection attribute"
35-
assert self.stackql.server_connection is not None, "Server connection object should not be None"
36-
37-
print_test_result("Server mode connectivity test",
38-
self.stackql.server_mode and
39-
hasattr(self.stackql, 'server_connection') and
40-
self.stackql.server_connection is not None,
41-
True)
42-
71+
# Initialize class variable
72+
TestServerMode.server_available = False
73+
74+
# Perform basic server connection test
75+
connection_working = self.stackql.test_connection()
76+
77+
if not connection_working:
78+
# Log minimal diagnostic info
79+
print("\n⚠️ Server connection failed")
80+
print(f"Address: {self.stackql.server_address}:{self.stackql.server_port}")
81+
print("❌ Skipping remaining server tests")
82+
83+
# Fail with a concise message - this will be what shows in the error summary
84+
pytest.fail("Server connection failed - please start stackql server")
85+
86+
# Connection succeeded
87+
TestServerMode.server_available = True
88+
print("✅ Server connection successful")
89+
4390
@pystackql_test_setup(server_mode=True)
4491
def test_server_mode_execute_stmt(self):
4592
"""Test executeStmt in server mode."""
93+
94+
# Skip if server is not available
95+
if not TestServerMode.server_available:
96+
pytest.skip("Server is not available, skipping test")
97+
4698
result = self.stackql.executeStmt(REGISTRY_PULL_HOMEBREW_QUERY)
4799

48100
# Check result structure
@@ -60,6 +112,11 @@ def test_server_mode_execute_stmt(self):
60112
@pystackql_test_setup(server_mode=True, output='pandas')
61113
def test_server_mode_execute_stmt_pandas(self):
62114
"""Test executeStmt in server mode with pandas output."""
115+
116+
# Skip if server is not available
117+
if not TestServerMode.server_available:
118+
pytest.skip("Server is not available, skipping test")
119+
63120
result = self.stackql.executeStmt(REGISTRY_PULL_HOMEBREW_QUERY)
64121

65122
# Check result structure
@@ -77,6 +134,11 @@ def test_server_mode_execute_stmt_pandas(self):
77134
@pystackql_test_setup(server_mode=True)
78135
def test_server_mode_execute(self):
79136
"""Test execute in server mode."""
137+
138+
# Skip if server is not available
139+
if not TestServerMode.server_available:
140+
pytest.skip("Server is not available, skipping test")
141+
80142
result = self.stackql.execute(LITERAL_INT_QUERY)
81143

82144
# Check result structure
@@ -98,6 +160,11 @@ def test_server_mode_execute(self):
98160
@pystackql_test_setup(server_mode=True, output='pandas')
99161
def test_server_mode_execute_pandas(self):
100162
"""Test execute in server mode with pandas output."""
163+
164+
# Skip if server is not available
165+
if not TestServerMode.server_available:
166+
pytest.skip("Server is not available, skipping test")
167+
101168
result = self.stackql.execute(LITERAL_STRING_QUERY)
102169

103170
# Check result structure
@@ -115,6 +182,11 @@ def test_server_mode_execute_pandas(self):
115182
@pystackql_test_setup(server_mode=True)
116183
def test_server_mode_provider_query(self):
117184
"""Test querying a provider in server mode."""
185+
186+
# Skip if server is not available
187+
if not TestServerMode.server_available:
188+
pytest.skip("Server is not available, skipping test")
189+
118190
result = self.stackql.execute(HOMEBREW_FORMULA_QUERY)
119191

120192
# Check result structure
@@ -135,6 +207,11 @@ def test_server_mode_provider_query(self):
135207
@patch('pystackql.core.server.ServerConnection.execute_query')
136208
def test_server_mode_execute_mocked(self, mock_execute_query):
137209
"""Test execute in server mode with mocked server response."""
210+
211+
# Skip if server is not available
212+
if not TestServerMode.server_available:
213+
pytest.skip("Server is not available, skipping test")
214+
138215
# Create a StackQL instance in server mode
139216
stackql = StackQL(server_mode=True)
140217

@@ -158,6 +235,11 @@ def test_server_mode_execute_mocked(self, mock_execute_query):
158235
@patch('pystackql.core.server.ServerConnection.execute_query')
159236
def test_server_mode_execute_pandas_mocked(self, mock_execute_query):
160237
"""Test execute in server mode with pandas output and mocked server response."""
238+
239+
# Skip if server is not available
240+
if not TestServerMode.server_available:
241+
pytest.skip("Server is not available, skipping test")
242+
161243
# Create a StackQL instance in server mode with pandas output
162244
stackql = StackQL(server_mode=True, output='pandas')
163245

@@ -186,6 +268,11 @@ def test_server_mode_execute_pandas_mocked(self, mock_execute_query):
186268
@patch('pystackql.core.server.ServerConnection.execute_query')
187269
def test_server_mode_execute_stmt_mocked(self, mock_execute_query):
188270
"""Test executeStmt in server mode with mocked server response."""
271+
272+
# Skip if server is not available
273+
if not TestServerMode.server_available:
274+
pytest.skip("Server is not available, skipping test")
275+
189276
# Create a StackQL instance in server mode
190277
stackql = StackQL(server_mode=True)
191278

@@ -208,6 +295,11 @@ def test_server_mode_execute_stmt_mocked(self, mock_execute_query):
208295

209296
def test_server_mode_csv_output_error(self):
210297
"""Test that server mode with csv output raises an error."""
298+
299+
# Skip if server is not available
300+
if not TestServerMode.server_available:
301+
pytest.skip("Server is not available, skipping test")
302+
211303
with pytest.raises(ValueError) as exc_info:
212304
StackQL(server_mode=True, output='csv')
213305

0 commit comments

Comments
 (0)