File size: 15,807 Bytes
24214fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
#!/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)