Spiritual_Health_Project / tests /unit /test_consent_manager.py
DocUA's picture
feat: Complete prompt optimization system implementation
24214fc
#!/usr/bin/env python3
"""
Test script for the consent manager implementation.
Tests Task 5.1 and 5.2 implementation.
"""
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'src'))
from config.prompt_management.consent_manager import (
ConsentManager, ConsentResponse, ConsentMessageType, ConsentInteraction
)
def test_consent_manager_initialization():
"""Test that the consent manager initializes correctly."""
print("Testing consent manager initialization...")
consent_manager = ConsentManager()
# Verify approved patterns are loaded
assert hasattr(consent_manager, 'approved_patterns')
assert 'initial_request' in consent_manager.approved_patterns
assert 'clarification' in consent_manager.approved_patterns
assert 'confirmation' in consent_manager.approved_patterns
assert 'decline_acknowledgment' in consent_manager.approved_patterns
# Verify non-assumptive requirements are loaded
assert hasattr(consent_manager, 'non_assumptive_requirements')
assert 'avoid_assumptions' in consent_manager.non_assumptive_requirements
assert 'avoid_pressure' in consent_manager.non_assumptive_requirements
assert 'avoid_religious_assumptions' in consent_manager.non_assumptive_requirements
# Verify response patterns are loaded
assert hasattr(consent_manager, 'response_patterns')
assert 'accept' in consent_manager.response_patterns
assert 'decline' in consent_manager.response_patterns
assert 'ambiguous' in consent_manager.response_patterns
print("βœ“ Consent manager initializes correctly")
return True
def test_consent_message_generation():
"""Test consent message generation with approved language patterns."""
print("Testing consent message generation...")
consent_manager = ConsentManager()
# Test initial request generation
initial_message = consent_manager.generate_consent_message(ConsentMessageType.INITIAL_REQUEST)
assert len(initial_message) > 0, "Initial message should not be empty"
# Verify it uses approved patterns
approved_initial = consent_manager.approved_patterns['initial_request']
assert any(pattern in initial_message for pattern in approved_initial), \
f"Initial message should use approved pattern: {initial_message}"
# Test with context
context = {'distress_level': 'high'}
contextual_message = consent_manager.generate_consent_message(
ConsentMessageType.INITIAL_REQUEST, context
)
assert len(contextual_message) > 0, "Contextual message should not be empty"
# Test clarification message
clarification_message = consent_manager.generate_consent_message(ConsentMessageType.CLARIFICATION)
assert len(clarification_message) > 0, "Clarification message should not be empty"
approved_clarification = consent_manager.approved_patterns['clarification']
assert any(pattern in clarification_message for pattern in approved_clarification), \
f"Clarification should use approved pattern: {clarification_message}"
# Test confirmation message
confirmation_message = consent_manager.generate_consent_message(ConsentMessageType.CONFIRMATION)
assert len(confirmation_message) > 0, "Confirmation message should not be empty"
# Test decline acknowledgment
decline_message = consent_manager.generate_consent_message(ConsentMessageType.DECLINE_ACKNOWLEDGMENT)
assert len(decline_message) > 0, "Decline acknowledgment should not be empty"
print("βœ“ Consent message generation works correctly")
return True
def test_language_compliance_validation():
"""Test language compliance validation."""
print("Testing language compliance validation...")
consent_manager = ConsentManager()
# Test compliant messages
compliant_messages = [
"Would you be interested in speaking with someone from our spiritual care team?",
"Our spiritual care team is available if you'd like to connect with them.",
"I understand and respect your decision.",
"Could you help me understand what would be most helpful for you?",
"Would you find it helpful to speak with a member of our spiritual care team?"
]
for message in compliant_messages:
is_compliant, violations = consent_manager.validate_language_compliance(message)
assert is_compliant, f"Message should be compliant: '{message}'. Violations: {violations}"
assert len(violations) == 0, f"Compliant message should have no violations: {violations}"
# Test non-compliant messages
non_compliant_messages = [
"You need to speak with someone from spiritual care.",
"This will help you feel better.",
"Obviously you're struggling with faith issues.",
"You should pray about this.",
"God will help you through this.",
"You must be feeling lost without faith.",
"Clearly you need spiritual guidance."
]
for message in non_compliant_messages:
is_compliant, violations = consent_manager.validate_language_compliance(message)
assert not is_compliant, f"Message should not be compliant: '{message}'"
assert len(violations) > 0, f"Non-compliant message should have violations: '{message}'"
print("βœ“ Language compliance validation works correctly")
return True
def test_patient_response_classification():
"""Test patient response classification."""
print("Testing patient response classification...")
consent_manager = ConsentManager()
# Test acceptance responses
accept_responses = [
"Yes, I would like that",
"Yeah, that sounds good",
"Okay, please arrange that",
"Sure, I'd like to speak with someone",
"I think that would be helpful",
"I guess so, yes"
]
for response in accept_responses:
classification = consent_manager.classify_patient_response(response)
assert classification == ConsentResponse.ACCEPT, \
f"Response should be classified as ACCEPT: '{response}' -> {classification}"
# Test decline responses
decline_responses = [
"No, I'm fine",
"Not interested",
"I don't want that",
"No thanks",
"I'm okay, don't need that",
"Not right now"
]
for response in decline_responses:
classification = consent_manager.classify_patient_response(response)
assert classification == ConsentResponse.DECLINE, \
f"Response should be classified as DECLINE: '{response}' -> {classification}"
# Test ambiguous responses
ambiguous_responses = [
"I don't know",
"Maybe",
"What would that involve?",
"Tell me more about it",
"I'm not sure",
"What do you think?"
]
for response in ambiguous_responses:
classification = consent_manager.classify_patient_response(response)
assert classification in [ConsentResponse.AMBIGUOUS, ConsentResponse.UNCLEAR], \
f"Response should be classified as AMBIGUOUS/UNCLEAR: '{response}' -> {classification}"
print("βœ“ Patient response classification works correctly")
return True
def test_clarification_question_generation():
"""Test clarification question generation."""
print("Testing clarification question generation...")
consent_manager = ConsentManager()
# Test information-seeking responses
info_seeking_responses = [
"What would that involve?",
"Tell me more about it",
"How does that work?",
"What kind of support?"
]
for response in info_seeking_responses:
clarification = consent_manager.generate_clarification_question(response)
assert len(clarification) > 0, f"Clarification should not be empty for: '{response}'"
# Should contain informative content
clarification_lower = clarification.lower()
assert any(word in clarification_lower for word in ['chaplain', 'counselor', 'support', 'team']), \
f"Information-seeking clarification should be informative: '{clarification}'"
# Test uncertainty responses
uncertainty_responses = [
"I don't know",
"Maybe",
"I'm not sure",
"I need to think about it"
]
for response in uncertainty_responses:
clarification = consent_manager.generate_clarification_question(response)
assert len(clarification) > 0, f"Clarification should not be empty for: '{response}'"
# Should be supportive and non-pressuring
clarification_lower = clarification.lower()
# Should contain supportive language (this is a simplified check)
assert any(word in clarification_lower for word in ['comfortable', 'prefer', 'okay', 'pressure', 'understand', 'helpful', 'thinking']), \
f"Uncertainty clarification should be supportive: '{clarification}'"
print("βœ“ Clarification question generation works correctly")
return True
def test_consent_interaction_handling():
"""Test complete consent interaction handling."""
print("Testing consent interaction handling...")
consent_manager = ConsentManager()
# Test acceptance handling
accept_response = "Yes, I would like to speak with someone"
result = consent_manager.handle_consent_interaction(accept_response, "test_session_1")
assert result['action'] == 'proceed_with_referral', "Accept should proceed with referral"
assert result['generate_provider_summary'] == True, "Accept should generate summary"
assert result['log_referral'] == True, "Accept should log referral"
assert 'message' in result, "Result should contain response message"
assert 'interaction' in result, "Result should contain interaction record"
# Verify interaction record
interaction = result['interaction']
assert interaction['patient_response'] == accept_response, "Should record patient response"
assert interaction['response_classification'] == 'accept', "Should record classification"
# Test decline handling
decline_response = "No, I'm fine"
result = consent_manager.handle_consent_interaction(decline_response, "test_session_2")
assert result['action'] == 'return_to_medical_dialogue', "Decline should return to medical dialogue"
assert result['generate_provider_summary'] == False, "Decline should not generate summary"
assert result['log_referral'] == False, "Decline should not log referral"
# Test ambiguous handling
ambiguous_response = "I don't know, what would that involve?"
result = consent_manager.handle_consent_interaction(ambiguous_response, "test_session_3")
assert result['action'] == 'request_clarification', "Ambiguous should request clarification"
assert result['generate_provider_summary'] == False, "Ambiguous should not generate summary"
assert result['log_referral'] == False, "Ambiguous should not log referral"
assert result.get('requires_follow_up') == True, "Ambiguous should require follow-up"
print("βœ“ Consent interaction handling works correctly")
return True
def test_consent_interaction_data_model():
"""Test ConsentInteraction data model."""
print("Testing ConsentInteraction data model...")
from datetime import datetime
# Create consent interaction
interaction = ConsentInteraction(
interaction_id="test_interaction_123",
message_type=ConsentMessageType.INITIAL_REQUEST,
message_content="Would you like to speak with spiritual care?",
patient_response="Yes, I would like that",
response_classification=ConsentResponse.ACCEPT,
timestamp=datetime.now(),
session_id="test_session_456",
requires_clarification=False,
clarification_attempts=0
)
# Test serialization
interaction_dict = interaction.to_dict()
assert interaction_dict['interaction_id'] == "test_interaction_123"
assert interaction_dict['message_type'] == 'initial_request'
assert interaction_dict['response_classification'] == 'accept'
assert interaction_dict['requires_clarification'] == False
# Test deserialization
reconstructed = ConsentInteraction.from_dict(interaction_dict)
assert reconstructed.interaction_id == interaction.interaction_id
assert reconstructed.message_type == interaction.message_type
assert reconstructed.response_classification == interaction.response_classification
assert reconstructed.requires_clarification == interaction.requires_clarification
print("βœ“ ConsentInteraction data model works correctly")
return True
def test_approved_language_patterns_completeness():
"""Test that approved language patterns are complete and appropriate."""
print("Testing approved language patterns completeness...")
consent_manager = ConsentManager()
patterns = consent_manager.get_approved_language_patterns()
# Verify all required pattern types exist
required_types = ['initial_request', 'clarification', 'confirmation', 'decline_acknowledgment']
for pattern_type in required_types:
assert pattern_type in patterns, f"Missing pattern type: {pattern_type}"
assert len(patterns[pattern_type]) > 0, f"Pattern type {pattern_type} should have examples"
# Verify all patterns are compliant
for pattern_type, pattern_list in patterns.items():
for pattern in pattern_list:
is_compliant, violations = consent_manager.validate_language_compliance(pattern)
assert is_compliant, f"Approved pattern should be compliant: '{pattern}'. Violations: {violations}"
print("βœ“ Approved language patterns are complete and appropriate")
return True
def main():
"""Run all consent manager tests."""
print("=" * 60)
print("CONSENT MANAGER TESTS")
print("=" * 60)
tests = [
test_consent_manager_initialization,
test_consent_message_generation,
test_language_compliance_validation,
test_patient_response_classification,
test_clarification_question_generation,
test_consent_interaction_handling,
test_consent_interaction_data_model,
test_approved_language_patterns_completeness
]
passed = 0
failed = 0
for test in tests:
try:
print(f"\n{test.__name__.replace('_', ' ').title()}:")
print("-" * 40)
result = test()
if result:
passed += 1
print("βœ“ PASSED")
else:
failed += 1
print("βœ— FAILED")
except Exception as e:
failed += 1
print(f"βœ— FAILED: {str(e)}")
print("\n" + "=" * 60)
print(f"RESULTS: {passed} passed, {failed} failed")
print("=" * 60)
if failed == 0:
print("πŸŽ‰ All consent manager tests passed!")
print("\n**Task 5.1 & 5.2: Consent Language Compliance**")
print("βœ“ COMPLETED: Property test for consent language compliance")
print("βœ“ COMPLETED: Consent message generation with approved patterns")
print("βœ“ COMPLETED: Non-assumptive language validation")
print("βœ“ COMPLETED: Patient response classification and handling")
print("βœ“ VALIDATED: Requirements 4.1, 4.2, 4.3, 4.4, 4.5")
return True
else:
print("❌ Some tests failed. Please check the implementation.")
return False
if __name__ == "__main__":
success = main()
sys.exit(0 if success else 1)