mirror of
https://github.com/trustgraph-ai/trustgraph.git
synced 2026-04-26 00:46:22 +02:00
Structured query support (#492)
* Tweak the structured query schema * Structure query service * Gateway support for nlp-query and structured-query * API support * Added CLI * Update tests * More tests
This commit is contained in:
parent
8d4aa0069c
commit
a6d9f5e849
22 changed files with 2813 additions and 31 deletions
356
tests/unit/test_retrieval/test_nlp_query.py
Normal file
356
tests/unit/test_retrieval/test_nlp_query.py
Normal file
|
|
@ -0,0 +1,356 @@
|
|||
"""
|
||||
Unit tests for NLP Query service
|
||||
Following TEST_STRATEGY.md approach for service testing
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import json
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
from typing import Dict, Any
|
||||
|
||||
from trustgraph.schema import (
|
||||
QuestionToStructuredQueryRequest, QuestionToStructuredQueryResponse,
|
||||
PromptRequest, PromptResponse, Error, RowSchema, Field as SchemaField
|
||||
)
|
||||
from trustgraph.retrieval.nlp_query.service import Processor
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_prompt_client():
|
||||
"""Mock prompt service client"""
|
||||
return AsyncMock()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_pulsar_client():
|
||||
"""Mock Pulsar client"""
|
||||
return AsyncMock()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_schemas():
|
||||
"""Sample schemas for testing"""
|
||||
return {
|
||||
"customers": RowSchema(
|
||||
name="customers",
|
||||
description="Customer data",
|
||||
fields=[
|
||||
SchemaField(name="id", type="string", primary=True),
|
||||
SchemaField(name="name", type="string"),
|
||||
SchemaField(name="email", type="string"),
|
||||
SchemaField(name="state", type="string")
|
||||
]
|
||||
),
|
||||
"orders": RowSchema(
|
||||
name="orders",
|
||||
description="Order data",
|
||||
fields=[
|
||||
SchemaField(name="order_id", type="string", primary=True),
|
||||
SchemaField(name="customer_id", type="string"),
|
||||
SchemaField(name="total", type="float"),
|
||||
SchemaField(name="status", type="string")
|
||||
]
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def processor(mock_pulsar_client, sample_schemas):
|
||||
"""Create processor with mocked dependencies"""
|
||||
proc = Processor(
|
||||
taskgroup=MagicMock(),
|
||||
pulsar_client=mock_pulsar_client,
|
||||
config_type="schema"
|
||||
)
|
||||
|
||||
# Set up schemas
|
||||
proc.schemas = sample_schemas
|
||||
|
||||
# Mock the client method
|
||||
proc.client = MagicMock()
|
||||
|
||||
return proc
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestNLPQueryProcessor:
|
||||
"""Test NLP Query service processor"""
|
||||
|
||||
async def test_phase1_select_schemas_success(self, processor, mock_prompt_client):
|
||||
"""Test successful schema selection (Phase 1)"""
|
||||
# Arrange
|
||||
question = "Show me customers from California"
|
||||
expected_schemas = ["customers"]
|
||||
|
||||
mock_response = PromptResponse(
|
||||
text=json.dumps(expected_schemas),
|
||||
error=None
|
||||
)
|
||||
|
||||
processor.client.return_value.request = AsyncMock(return_value=mock_response)
|
||||
|
||||
# Act
|
||||
result = await processor.phase1_select_schemas(question)
|
||||
|
||||
# Assert
|
||||
assert result == expected_schemas
|
||||
processor.client.assert_called_once_with("prompt-request")
|
||||
|
||||
async def test_phase1_select_schemas_prompt_error(self, processor):
|
||||
"""Test schema selection with prompt service error"""
|
||||
# Arrange
|
||||
question = "Show me customers"
|
||||
error = Error(type="prompt-error", message="Template not found")
|
||||
mock_response = PromptResponse(text="", error=error)
|
||||
|
||||
processor.client.return_value.request = AsyncMock(return_value=mock_response)
|
||||
|
||||
# Act & Assert
|
||||
with pytest.raises(Exception, match="Prompt service error"):
|
||||
await processor.phase1_select_schemas(question)
|
||||
|
||||
async def test_phase2_generate_graphql_success(self, processor):
|
||||
"""Test successful GraphQL generation (Phase 2)"""
|
||||
# Arrange
|
||||
question = "Show me customers from California"
|
||||
selected_schemas = ["customers"]
|
||||
expected_result = {
|
||||
"query": "query { customers(where: {state: {eq: \"California\"}}) { id name email state } }",
|
||||
"variables": {},
|
||||
"confidence": 0.95
|
||||
}
|
||||
|
||||
mock_response = PromptResponse(
|
||||
text=json.dumps(expected_result),
|
||||
error=None
|
||||
)
|
||||
|
||||
processor.client.return_value.request = AsyncMock(return_value=mock_response)
|
||||
|
||||
# Act
|
||||
result = await processor.phase2_generate_graphql(question, selected_schemas)
|
||||
|
||||
# Assert
|
||||
assert result == expected_result
|
||||
processor.client.assert_called_once_with("prompt-request")
|
||||
|
||||
async def test_phase2_generate_graphql_prompt_error(self, processor):
|
||||
"""Test GraphQL generation with prompt service error"""
|
||||
# Arrange
|
||||
question = "Show me customers"
|
||||
selected_schemas = ["customers"]
|
||||
error = Error(type="prompt-error", message="Generation failed")
|
||||
mock_response = PromptResponse(text="", error=error)
|
||||
|
||||
processor.client.return_value.request = AsyncMock(return_value=mock_response)
|
||||
|
||||
# Act & Assert
|
||||
with pytest.raises(Exception, match="Prompt service error"):
|
||||
await processor.phase2_generate_graphql(question, selected_schemas)
|
||||
|
||||
async def test_on_message_full_flow_success(self, processor):
|
||||
"""Test complete message processing flow"""
|
||||
# Arrange
|
||||
request = QuestionToStructuredQueryRequest(
|
||||
question="Show me customers from California",
|
||||
max_results=100
|
||||
)
|
||||
|
||||
msg = MagicMock()
|
||||
msg.value.return_value = request
|
||||
msg.properties.return_value = {"id": "test-123"}
|
||||
|
||||
consumer = MagicMock()
|
||||
flow = MagicMock()
|
||||
flow_response = AsyncMock()
|
||||
flow.return_value = flow_response
|
||||
|
||||
# Mock Phase 1 response
|
||||
phase1_response = PromptResponse(
|
||||
text=json.dumps(["customers"]),
|
||||
error=None
|
||||
)
|
||||
|
||||
# Mock Phase 2 response
|
||||
phase2_response = PromptResponse(
|
||||
text=json.dumps({
|
||||
"query": "query { customers(where: {state: {eq: \"California\"}}) { id name email } }",
|
||||
"variables": {},
|
||||
"confidence": 0.9
|
||||
}),
|
||||
error=None
|
||||
)
|
||||
|
||||
# Set up mock to return different responses for each call
|
||||
processor.client.return_value.request = AsyncMock(
|
||||
side_effect=[phase1_response, phase2_response]
|
||||
)
|
||||
|
||||
# Act
|
||||
await processor.on_message(msg, consumer, flow)
|
||||
|
||||
# Assert
|
||||
assert processor.client.return_value.request.call_count == 2
|
||||
flow_response.send.assert_called_once()
|
||||
|
||||
# Verify response structure
|
||||
response_call = flow_response.send.call_args
|
||||
response = response_call[0][0] # First argument is the response object
|
||||
|
||||
assert isinstance(response, QuestionToStructuredQueryResponse)
|
||||
assert response.error is None
|
||||
assert "customers" in response.graphql_query
|
||||
assert response.detected_schemas == ["customers"]
|
||||
assert response.confidence == 0.9
|
||||
|
||||
async def test_on_message_phase1_error(self, processor):
|
||||
"""Test message processing with Phase 1 failure"""
|
||||
# Arrange
|
||||
request = QuestionToStructuredQueryRequest(
|
||||
question="Show me customers",
|
||||
max_results=100
|
||||
)
|
||||
|
||||
msg = MagicMock()
|
||||
msg.value.return_value = request
|
||||
msg.properties.return_value = {"id": "test-123"}
|
||||
|
||||
consumer = MagicMock()
|
||||
flow = MagicMock()
|
||||
flow_response = AsyncMock()
|
||||
flow.return_value = flow_response
|
||||
|
||||
# Mock Phase 1 error
|
||||
phase1_response = PromptResponse(
|
||||
text="",
|
||||
error=Error(type="template-error", message="Template not found")
|
||||
)
|
||||
|
||||
processor.client.return_value.request = AsyncMock(return_value=phase1_response)
|
||||
|
||||
# Act
|
||||
await processor.on_message(msg, consumer, flow)
|
||||
|
||||
# Assert
|
||||
flow_response.send.assert_called_once()
|
||||
|
||||
# Verify error response
|
||||
response_call = flow_response.send.call_args
|
||||
response = response_call[0][0]
|
||||
|
||||
assert isinstance(response, QuestionToStructuredQueryResponse)
|
||||
assert response.error is not None
|
||||
assert response.error.type == "nlp-query-error"
|
||||
assert "Prompt service error" in response.error.message
|
||||
|
||||
async def test_schema_config_loading(self, processor):
|
||||
"""Test schema configuration loading"""
|
||||
# Arrange
|
||||
config = {
|
||||
"schema": {
|
||||
"test_schema": json.dumps({
|
||||
"name": "test_schema",
|
||||
"description": "Test schema",
|
||||
"fields": [
|
||||
{
|
||||
"name": "id",
|
||||
"type": "string",
|
||||
"primary_key": True,
|
||||
"required": True
|
||||
},
|
||||
{
|
||||
"name": "name",
|
||||
"type": "string",
|
||||
"description": "User name"
|
||||
}
|
||||
]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
# Act
|
||||
await processor.on_schema_config(config, "v1")
|
||||
|
||||
# Assert
|
||||
assert "test_schema" in processor.schemas
|
||||
schema = processor.schemas["test_schema"]
|
||||
assert schema.name == "test_schema"
|
||||
assert schema.description == "Test schema"
|
||||
assert len(schema.fields) == 2
|
||||
assert schema.fields[0].name == "id"
|
||||
assert schema.fields[0].primary == True
|
||||
assert schema.fields[1].name == "name"
|
||||
|
||||
async def test_schema_config_loading_invalid_json(self, processor):
|
||||
"""Test schema configuration loading with invalid JSON"""
|
||||
# Arrange
|
||||
config = {
|
||||
"schema": {
|
||||
"bad_schema": "invalid json{"
|
||||
}
|
||||
}
|
||||
|
||||
# Act
|
||||
await processor.on_schema_config(config, "v1")
|
||||
|
||||
# Assert - bad schema should be ignored
|
||||
assert "bad_schema" not in processor.schemas
|
||||
|
||||
def test_processor_initialization(self, mock_pulsar_client):
|
||||
"""Test processor initialization with correct specifications"""
|
||||
# Act
|
||||
processor = Processor(
|
||||
taskgroup=MagicMock(),
|
||||
pulsar_client=mock_pulsar_client,
|
||||
schema_selection_template="custom-schema-select",
|
||||
graphql_generation_template="custom-graphql-gen"
|
||||
)
|
||||
|
||||
# Assert
|
||||
assert processor.schema_selection_template == "custom-schema-select"
|
||||
assert processor.graphql_generation_template == "custom-graphql-gen"
|
||||
assert processor.config_key == "schema"
|
||||
assert processor.schemas == {}
|
||||
|
||||
def test_add_args(self):
|
||||
"""Test command-line argument parsing"""
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
Processor.add_args(parser)
|
||||
|
||||
# Test default values
|
||||
args = parser.parse_args([])
|
||||
assert args.config_type == "schema"
|
||||
assert args.schema_selection_template == "schema-selection"
|
||||
assert args.graphql_generation_template == "graphql-generation"
|
||||
|
||||
# Test custom values
|
||||
args = parser.parse_args([
|
||||
"--config-type", "custom",
|
||||
"--schema-selection-template", "my-selector",
|
||||
"--graphql-generation-template", "my-generator"
|
||||
])
|
||||
assert args.config_type == "custom"
|
||||
assert args.schema_selection_template == "my-selector"
|
||||
assert args.graphql_generation_template == "my-generator"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestNLPQueryHelperFunctions:
|
||||
"""Test helper functions and data transformations"""
|
||||
|
||||
def test_schema_info_formatting(self, sample_schemas):
|
||||
"""Test schema info formatting for prompts"""
|
||||
# This would test any helper functions for formatting schema data
|
||||
# Currently the formatting is inline, but good to test if extracted
|
||||
|
||||
customers_schema = sample_schemas["customers"]
|
||||
expected_fields = ["id", "name", "email", "state"]
|
||||
|
||||
actual_fields = [f.name for f in customers_schema.fields]
|
||||
assert actual_fields == expected_fields
|
||||
|
||||
# Test primary key detection
|
||||
primary_fields = [f.name for f in customers_schema.fields if f.primary]
|
||||
assert primary_fields == ["id"]
|
||||
522
tests/unit/test_retrieval/test_structured_query.py
Normal file
522
tests/unit/test_retrieval/test_structured_query.py
Normal file
|
|
@ -0,0 +1,522 @@
|
|||
"""
|
||||
Unit tests for Structured Query Service
|
||||
Following TEST_STRATEGY.md approach for service testing
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import json
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
from trustgraph.schema import (
|
||||
StructuredQueryRequest, StructuredQueryResponse,
|
||||
QuestionToStructuredQueryRequest, QuestionToStructuredQueryResponse,
|
||||
ObjectsQueryRequest, ObjectsQueryResponse,
|
||||
Error, GraphQLError
|
||||
)
|
||||
from trustgraph.retrieval.structured_query.service import Processor
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_pulsar_client():
|
||||
"""Mock Pulsar client"""
|
||||
return AsyncMock()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def processor(mock_pulsar_client):
|
||||
"""Create processor with mocked dependencies"""
|
||||
proc = Processor(
|
||||
taskgroup=MagicMock(),
|
||||
pulsar_client=mock_pulsar_client
|
||||
)
|
||||
|
||||
# Mock the client method
|
||||
proc.client = MagicMock()
|
||||
|
||||
return proc
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestStructuredQueryProcessor:
|
||||
"""Test Structured Query service processor"""
|
||||
|
||||
async def test_successful_end_to_end_query(self, processor):
|
||||
"""Test successful end-to-end query processing"""
|
||||
# Arrange
|
||||
request = StructuredQueryRequest(
|
||||
question="Show me all customers from New York"
|
||||
)
|
||||
|
||||
msg = MagicMock()
|
||||
msg.value.return_value = request
|
||||
msg.properties.return_value = {"id": "test-123"}
|
||||
|
||||
consumer = MagicMock()
|
||||
flow = MagicMock()
|
||||
flow_response = AsyncMock()
|
||||
flow.return_value = flow_response
|
||||
|
||||
# Mock NLP query service response
|
||||
nlp_response = QuestionToStructuredQueryResponse(
|
||||
error=None,
|
||||
graphql_query='query { customers(where: {state: {eq: "NY"}}) { id name email } }',
|
||||
variables={"state": "NY"},
|
||||
detected_schemas=["customers"],
|
||||
confidence=0.95
|
||||
)
|
||||
|
||||
# Mock objects query service response
|
||||
objects_response = ObjectsQueryResponse(
|
||||
error=None,
|
||||
data='{"customers": [{"id": "1", "name": "John", "email": "john@example.com"}]}',
|
||||
errors=None,
|
||||
extensions={}
|
||||
)
|
||||
|
||||
# Set up mock clients
|
||||
mock_nlp_client = AsyncMock()
|
||||
mock_nlp_client.request.return_value = nlp_response
|
||||
|
||||
mock_objects_client = AsyncMock()
|
||||
mock_objects_client.request.return_value = objects_response
|
||||
|
||||
processor.client.side_effect = lambda name: (
|
||||
mock_nlp_client if name == "nlp-query-request" else mock_objects_client
|
||||
)
|
||||
|
||||
# Act
|
||||
await processor.on_message(msg, consumer, flow)
|
||||
|
||||
# Assert
|
||||
# Verify NLP query service was called correctly
|
||||
mock_nlp_client.request.assert_called_once()
|
||||
nlp_call_args = mock_nlp_client.request.call_args[0][0]
|
||||
assert isinstance(nlp_call_args, QuestionToStructuredQueryRequest)
|
||||
assert nlp_call_args.question == "Show me all customers from New York"
|
||||
assert nlp_call_args.max_results == 100
|
||||
|
||||
# Verify objects query service was called correctly
|
||||
mock_objects_client.request.assert_called_once()
|
||||
objects_call_args = mock_objects_client.request.call_args[0][0]
|
||||
assert isinstance(objects_call_args, ObjectsQueryRequest)
|
||||
assert objects_call_args.query == 'query { customers(where: {state: {eq: "NY"}}) { id name email } }'
|
||||
assert objects_call_args.variables == {"state": "NY"}
|
||||
assert objects_call_args.user == "default"
|
||||
assert objects_call_args.collection == "default"
|
||||
|
||||
# Verify response
|
||||
flow_response.send.assert_called_once()
|
||||
response_call = flow_response.send.call_args
|
||||
response = response_call[0][0]
|
||||
|
||||
assert isinstance(response, StructuredQueryResponse)
|
||||
assert response.error is None
|
||||
assert response.data == '{"customers": [{"id": "1", "name": "John", "email": "john@example.com"}]}'
|
||||
assert len(response.errors) == 0
|
||||
|
||||
async def test_nlp_query_service_error(self, processor):
|
||||
"""Test handling of NLP query service errors"""
|
||||
# Arrange
|
||||
request = StructuredQueryRequest(
|
||||
question="Invalid query"
|
||||
)
|
||||
|
||||
msg = MagicMock()
|
||||
msg.value.return_value = request
|
||||
msg.properties.return_value = {"id": "test-error"}
|
||||
|
||||
consumer = MagicMock()
|
||||
flow = MagicMock()
|
||||
flow_response = AsyncMock()
|
||||
flow.return_value = flow_response
|
||||
|
||||
# Mock NLP query service error response
|
||||
nlp_response = QuestionToStructuredQueryResponse(
|
||||
error=Error(type="nlp-query-error", message="Failed to parse question"),
|
||||
graphql_query="",
|
||||
variables={},
|
||||
detected_schemas=[],
|
||||
confidence=0.0
|
||||
)
|
||||
|
||||
mock_nlp_client = AsyncMock()
|
||||
mock_nlp_client.request.return_value = nlp_response
|
||||
|
||||
processor.client.return_value = mock_nlp_client
|
||||
|
||||
# Act
|
||||
await processor.on_message(msg, consumer, flow)
|
||||
|
||||
# Assert
|
||||
flow_response.send.assert_called_once()
|
||||
response_call = flow_response.send.call_args
|
||||
response = response_call[0][0]
|
||||
|
||||
assert isinstance(response, StructuredQueryResponse)
|
||||
assert response.error is not None
|
||||
assert response.error.type == "structured-query-error"
|
||||
assert "NLP query service error" in response.error.message
|
||||
|
||||
async def test_empty_graphql_query_error(self, processor):
|
||||
"""Test handling of empty GraphQL query from NLP service"""
|
||||
# Arrange
|
||||
request = StructuredQueryRequest(
|
||||
question="Ambiguous question"
|
||||
)
|
||||
|
||||
msg = MagicMock()
|
||||
msg.value.return_value = request
|
||||
msg.properties.return_value = {"id": "test-empty"}
|
||||
|
||||
consumer = MagicMock()
|
||||
flow = MagicMock()
|
||||
flow_response = AsyncMock()
|
||||
flow.return_value = flow_response
|
||||
|
||||
# Mock NLP query service response with empty query
|
||||
nlp_response = QuestionToStructuredQueryResponse(
|
||||
error=None,
|
||||
graphql_query="", # Empty query
|
||||
variables={},
|
||||
detected_schemas=[],
|
||||
confidence=0.1
|
||||
)
|
||||
|
||||
mock_nlp_client = AsyncMock()
|
||||
mock_nlp_client.request.return_value = nlp_response
|
||||
|
||||
processor.client.return_value = mock_nlp_client
|
||||
|
||||
# Act
|
||||
await processor.on_message(msg, consumer, flow)
|
||||
|
||||
# Assert
|
||||
flow_response.send.assert_called_once()
|
||||
response_call = flow_response.send.call_args
|
||||
response = response_call[0][0]
|
||||
|
||||
assert response.error is not None
|
||||
assert "empty GraphQL query" in response.error.message
|
||||
|
||||
async def test_objects_query_service_error(self, processor):
|
||||
"""Test handling of objects query service errors"""
|
||||
# Arrange
|
||||
request = StructuredQueryRequest(
|
||||
question="Show me customers"
|
||||
)
|
||||
|
||||
msg = MagicMock()
|
||||
msg.value.return_value = request
|
||||
msg.properties.return_value = {"id": "test-objects-error"}
|
||||
|
||||
consumer = MagicMock()
|
||||
flow = MagicMock()
|
||||
flow_response = AsyncMock()
|
||||
flow.return_value = flow_response
|
||||
|
||||
# Mock successful NLP response
|
||||
nlp_response = QuestionToStructuredQueryResponse(
|
||||
error=None,
|
||||
graphql_query='query { customers { id name } }',
|
||||
variables={},
|
||||
detected_schemas=["customers"],
|
||||
confidence=0.9
|
||||
)
|
||||
|
||||
# Mock objects query service error
|
||||
objects_response = ObjectsQueryResponse(
|
||||
error=Error(type="graphql-execution-error", message="Table 'customers' not found"),
|
||||
data=None,
|
||||
errors=None,
|
||||
extensions={}
|
||||
)
|
||||
|
||||
mock_nlp_client = AsyncMock()
|
||||
mock_nlp_client.request.return_value = nlp_response
|
||||
|
||||
mock_objects_client = AsyncMock()
|
||||
mock_objects_client.request.return_value = objects_response
|
||||
|
||||
processor.client.side_effect = lambda name: (
|
||||
mock_nlp_client if name == "nlp-query-request" else mock_objects_client
|
||||
)
|
||||
|
||||
# Act
|
||||
await processor.on_message(msg, consumer, flow)
|
||||
|
||||
# Assert
|
||||
flow_response.send.assert_called_once()
|
||||
response_call = flow_response.send.call_args
|
||||
response = response_call[0][0]
|
||||
|
||||
assert response.error is not None
|
||||
assert "Objects query service error" in response.error.message
|
||||
assert "Table 'customers' not found" in response.error.message
|
||||
|
||||
async def test_graphql_errors_handling(self, processor):
|
||||
"""Test handling of GraphQL validation/execution errors"""
|
||||
# Arrange
|
||||
request = StructuredQueryRequest(
|
||||
question="Show invalid field"
|
||||
)
|
||||
|
||||
msg = MagicMock()
|
||||
msg.value.return_value = request
|
||||
msg.properties.return_value = {"id": "test-graphql-errors"}
|
||||
|
||||
consumer = MagicMock()
|
||||
flow = MagicMock()
|
||||
flow_response = AsyncMock()
|
||||
flow.return_value = flow_response
|
||||
|
||||
# Mock successful NLP response
|
||||
nlp_response = QuestionToStructuredQueryResponse(
|
||||
error=None,
|
||||
graphql_query='query { customers { invalid_field } }',
|
||||
variables={},
|
||||
detected_schemas=["customers"],
|
||||
confidence=0.8
|
||||
)
|
||||
|
||||
# Mock objects response with GraphQL errors
|
||||
graphql_errors = [
|
||||
GraphQLError(
|
||||
message="Cannot query field 'invalid_field' on type 'Customer'",
|
||||
path=["customers", "0", "invalid_field"], # All path elements must be strings
|
||||
extensions={}
|
||||
)
|
||||
]
|
||||
|
||||
objects_response = ObjectsQueryResponse(
|
||||
error=None,
|
||||
data=None,
|
||||
errors=graphql_errors,
|
||||
extensions={}
|
||||
)
|
||||
|
||||
mock_nlp_client = AsyncMock()
|
||||
mock_nlp_client.request.return_value = nlp_response
|
||||
|
||||
mock_objects_client = AsyncMock()
|
||||
mock_objects_client.request.return_value = objects_response
|
||||
|
||||
processor.client.side_effect = lambda name: (
|
||||
mock_nlp_client if name == "nlp-query-request" else mock_objects_client
|
||||
)
|
||||
|
||||
# Act
|
||||
await processor.on_message(msg, consumer, flow)
|
||||
|
||||
# Assert
|
||||
flow_response.send.assert_called_once()
|
||||
response_call = flow_response.send.call_args
|
||||
response = response_call[0][0]
|
||||
|
||||
assert response.error is None
|
||||
assert len(response.errors) == 1
|
||||
assert "Cannot query field 'invalid_field'" in response.errors[0]
|
||||
assert "customers" in response.errors[0]
|
||||
|
||||
async def test_complex_query_with_variables(self, processor):
|
||||
"""Test processing complex queries with variables"""
|
||||
# Arrange
|
||||
request = StructuredQueryRequest(
|
||||
question="Show customers with orders over $100 from last month"
|
||||
)
|
||||
|
||||
msg = MagicMock()
|
||||
msg.value.return_value = request
|
||||
msg.properties.return_value = {"id": "test-complex"}
|
||||
|
||||
consumer = MagicMock()
|
||||
flow = MagicMock()
|
||||
flow_response = AsyncMock()
|
||||
flow.return_value = flow_response
|
||||
|
||||
# Mock NLP response with complex query and variables
|
||||
nlp_response = QuestionToStructuredQueryResponse(
|
||||
error=None,
|
||||
graphql_query='''
|
||||
query GetCustomersWithLargeOrders($minTotal: Float!, $startDate: String!) {
|
||||
customers {
|
||||
id
|
||||
name
|
||||
orders(where: {total: {gt: $minTotal}, date: {gte: $startDate}}) {
|
||||
id
|
||||
total
|
||||
date
|
||||
}
|
||||
}
|
||||
}
|
||||
''',
|
||||
variables={
|
||||
"minTotal": "100.0", # Convert to string for Pulsar schema
|
||||
"startDate": "2024-01-01"
|
||||
},
|
||||
detected_schemas=["customers", "orders"],
|
||||
confidence=0.88
|
||||
)
|
||||
|
||||
# Mock objects response
|
||||
objects_response = ObjectsQueryResponse(
|
||||
error=None,
|
||||
data='{"customers": [{"id": "1", "name": "Alice", "orders": [{"id": "100", "total": 150.0}]}]}',
|
||||
errors=None
|
||||
)
|
||||
|
||||
mock_nlp_client = AsyncMock()
|
||||
mock_nlp_client.request.return_value = nlp_response
|
||||
|
||||
mock_objects_client = AsyncMock()
|
||||
mock_objects_client.request.return_value = objects_response
|
||||
|
||||
processor.client.side_effect = lambda name: (
|
||||
mock_nlp_client if name == "nlp-query-request" else mock_objects_client
|
||||
)
|
||||
|
||||
# Act
|
||||
await processor.on_message(msg, consumer, flow)
|
||||
|
||||
# Assert
|
||||
# Verify variables were passed correctly (converted to strings)
|
||||
objects_call_args = mock_objects_client.request.call_args[0][0]
|
||||
assert objects_call_args.variables["minTotal"] == "100.0" # Should be converted to string
|
||||
assert objects_call_args.variables["startDate"] == "2024-01-01"
|
||||
|
||||
# Verify response
|
||||
response_call = flow_response.send.call_args
|
||||
response = response_call[0][0]
|
||||
assert response.error is None
|
||||
assert "Alice" in response.data
|
||||
|
||||
async def test_null_data_handling(self, processor):
|
||||
"""Test handling of null/empty data responses"""
|
||||
# Arrange
|
||||
request = StructuredQueryRequest(
|
||||
question="Show nonexistent data"
|
||||
)
|
||||
|
||||
msg = MagicMock()
|
||||
msg.value.return_value = request
|
||||
msg.properties.return_value = {"id": "test-null"}
|
||||
|
||||
consumer = MagicMock()
|
||||
flow = MagicMock()
|
||||
flow_response = AsyncMock()
|
||||
flow.return_value = flow_response
|
||||
|
||||
# Mock responses
|
||||
nlp_response = QuestionToStructuredQueryResponse(
|
||||
error=None,
|
||||
graphql_query='query { customers { id } }',
|
||||
variables={},
|
||||
detected_schemas=["customers"],
|
||||
confidence=0.9
|
||||
)
|
||||
|
||||
objects_response = ObjectsQueryResponse(
|
||||
error=None,
|
||||
data=None, # Null data
|
||||
errors=None,
|
||||
extensions={}
|
||||
)
|
||||
|
||||
mock_nlp_client = AsyncMock()
|
||||
mock_nlp_client.request.return_value = nlp_response
|
||||
|
||||
mock_objects_client = AsyncMock()
|
||||
mock_objects_client.request.return_value = objects_response
|
||||
|
||||
processor.client.side_effect = lambda name: (
|
||||
mock_nlp_client if name == "nlp-query-request" else mock_objects_client
|
||||
)
|
||||
|
||||
# Act
|
||||
await processor.on_message(msg, consumer, flow)
|
||||
|
||||
# Assert
|
||||
response_call = flow_response.send.call_args
|
||||
response = response_call[0][0]
|
||||
|
||||
assert response.error is None
|
||||
assert response.data == "null" # Should convert None to "null" string
|
||||
|
||||
async def test_exception_handling(self, processor):
|
||||
"""Test general exception handling"""
|
||||
# Arrange
|
||||
request = StructuredQueryRequest(
|
||||
question="Test exception"
|
||||
)
|
||||
|
||||
msg = MagicMock()
|
||||
msg.value.return_value = request
|
||||
msg.properties.return_value = {"id": "test-exception"}
|
||||
|
||||
consumer = MagicMock()
|
||||
flow = MagicMock()
|
||||
flow_response = AsyncMock()
|
||||
flow.return_value = flow_response
|
||||
|
||||
# Mock client to raise exception
|
||||
mock_client = AsyncMock()
|
||||
mock_client.request.side_effect = Exception("Network timeout")
|
||||
processor.client.return_value = mock_client
|
||||
|
||||
# Act
|
||||
await processor.on_message(msg, consumer, flow)
|
||||
|
||||
# Assert
|
||||
flow_response.send.assert_called_once()
|
||||
response_call = flow_response.send.call_args
|
||||
response = response_call[0][0]
|
||||
|
||||
assert response.error is not None
|
||||
assert response.error.type == "structured-query-error"
|
||||
assert "Network timeout" in response.error.message
|
||||
assert response.data == "null"
|
||||
assert len(response.errors) == 0
|
||||
|
||||
def test_processor_initialization(self, mock_pulsar_client):
|
||||
"""Test processor initialization with correct specifications"""
|
||||
# Act
|
||||
processor = Processor(
|
||||
taskgroup=MagicMock(),
|
||||
pulsar_client=mock_pulsar_client
|
||||
)
|
||||
|
||||
# Assert - Test default ID
|
||||
assert processor.id == "structured-query"
|
||||
|
||||
# Verify specifications were registered (we can't directly access them,
|
||||
# but we know they were registered if initialization succeeded)
|
||||
assert processor is not None
|
||||
|
||||
def test_add_args(self):
|
||||
"""Test command-line argument parsing"""
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
Processor.add_args(parser)
|
||||
|
||||
# Test that it doesn't crash (no additional args)
|
||||
args = parser.parse_args([])
|
||||
# No specific assertions since no custom args are added
|
||||
assert args is not None
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestStructuredQueryHelperFunctions:
|
||||
"""Test helper functions and data transformations"""
|
||||
|
||||
def test_service_logging_integration(self):
|
||||
"""Test that logging is properly configured"""
|
||||
# Import the logger
|
||||
from trustgraph.retrieval.structured_query.service import logger
|
||||
|
||||
assert logger.name == "trustgraph.retrieval.structured_query.service"
|
||||
|
||||
def test_default_values(self):
|
||||
"""Test default configuration values"""
|
||||
from trustgraph.retrieval.structured_query.service import default_ident
|
||||
|
||||
assert default_ident == "structured-query"
|
||||
Loading…
Add table
Add a link
Reference in a new issue