|
| 1 | +""" |
| 2 | +Test hallucination detection in SharedMemory and OutputValidator. |
| 3 | +
|
| 4 | +These tests verify that code detection works correctly across the entire |
| 5 | +string content, not just the first 500 characters. |
| 6 | +""" |
| 7 | + |
| 8 | +import pytest |
| 9 | +from framework.graph.node import SharedMemory, MemoryWriteError |
| 10 | +from framework.graph.validator import OutputValidator, ValidationResult |
| 11 | + |
| 12 | + |
| 13 | +class TestSharedMemoryHallucinationDetection: |
| 14 | + """Test the SharedMemory hallucination detection.""" |
| 15 | + |
| 16 | + def test_detects_code_at_start(self): |
| 17 | + """Code at the start of the string should be detected.""" |
| 18 | + memory = SharedMemory() |
| 19 | + code_content = "```python\nimport os\ndef hack(): pass\n```" + "A" * 6000 |
| 20 | + |
| 21 | + with pytest.raises(MemoryWriteError) as exc_info: |
| 22 | + memory.write("output", code_content) |
| 23 | + |
| 24 | + assert "hallucinated code" in str(exc_info.value) |
| 25 | + |
| 26 | + def test_detects_code_in_middle(self): |
| 27 | + """Code in the middle of the string should be detected (was previously missed).""" |
| 28 | + memory = SharedMemory() |
| 29 | + # 600 chars of padding, then code, then more padding to exceed 5000 chars |
| 30 | + padding_start = "A" * 600 |
| 31 | + code = "\n```python\nimport os\ndef malicious(): pass\n```\n" |
| 32 | + padding_end = "B" * 5000 |
| 33 | + content = padding_start + code + padding_end |
| 34 | + |
| 35 | + with pytest.raises(MemoryWriteError) as exc_info: |
| 36 | + memory.write("output", content) |
| 37 | + |
| 38 | + assert "hallucinated code" in str(exc_info.value) |
| 39 | + |
| 40 | + def test_detects_code_at_end(self): |
| 41 | + """Code at the end of the string should be detected (was previously missed).""" |
| 42 | + memory = SharedMemory() |
| 43 | + padding = "A" * 5500 |
| 44 | + code = "\n```python\nclass Exploit:\n pass\n```" |
| 45 | + content = padding + code |
| 46 | + |
| 47 | + with pytest.raises(MemoryWriteError) as exc_info: |
| 48 | + memory.write("output", content) |
| 49 | + |
| 50 | + assert "hallucinated code" in str(exc_info.value) |
| 51 | + |
| 52 | + def test_detects_javascript_code(self): |
| 53 | + """JavaScript code patterns should be detected.""" |
| 54 | + memory = SharedMemory() |
| 55 | + padding = "A" * 600 |
| 56 | + code = "\nfunction malicious() { require('child_process'); }\n" |
| 57 | + padding_end = "B" * 5000 |
| 58 | + content = padding + code + padding_end |
| 59 | + |
| 60 | + with pytest.raises(MemoryWriteError) as exc_info: |
| 61 | + memory.write("output", content) |
| 62 | + |
| 63 | + assert "hallucinated code" in str(exc_info.value) |
| 64 | + |
| 65 | + def test_detects_sql_injection(self): |
| 66 | + """SQL patterns should be detected.""" |
| 67 | + memory = SharedMemory() |
| 68 | + padding = "A" * 600 |
| 69 | + code = "\nDROP TABLE users; SELECT * FROM passwords;\n" |
| 70 | + padding_end = "B" * 5000 |
| 71 | + content = padding + code + padding_end |
| 72 | + |
| 73 | + with pytest.raises(MemoryWriteError) as exc_info: |
| 74 | + memory.write("output", content) |
| 75 | + |
| 76 | + assert "hallucinated code" in str(exc_info.value) |
| 77 | + |
| 78 | + def test_detects_script_injection(self): |
| 79 | + """HTML script injection should be detected.""" |
| 80 | + memory = SharedMemory() |
| 81 | + padding = "A" * 600 |
| 82 | + code = "\n<script>alert('xss')</script>\n" |
| 83 | + padding_end = "B" * 5000 |
| 84 | + content = padding + code + padding_end |
| 85 | + |
| 86 | + with pytest.raises(MemoryWriteError) as exc_info: |
| 87 | + memory.write("output", content) |
| 88 | + |
| 89 | + assert "hallucinated code" in str(exc_info.value) |
| 90 | + |
| 91 | + def test_allows_short_strings_without_validation(self): |
| 92 | + """Strings under 5000 chars should not trigger validation.""" |
| 93 | + memory = SharedMemory() |
| 94 | + content = "def hello(): pass" # Contains code indicator but short |
| 95 | + |
| 96 | + # Should not raise - too short to validate |
| 97 | + memory.write("output", content) |
| 98 | + assert memory.read("output") == content |
| 99 | + |
| 100 | + def test_allows_long_strings_without_code(self): |
| 101 | + """Long strings without code indicators should be allowed.""" |
| 102 | + memory = SharedMemory() |
| 103 | + content = "This is a long text document. " * 500 # ~15000 chars, no code |
| 104 | + |
| 105 | + memory.write("output", content) |
| 106 | + assert memory.read("output") == content |
| 107 | + |
| 108 | + def test_validate_false_bypasses_check(self): |
| 109 | + """Using validate=False should bypass the check.""" |
| 110 | + memory = SharedMemory() |
| 111 | + code_content = "```python\nimport os\n```" + "A" * 6000 |
| 112 | + |
| 113 | + # Should not raise when validate=False |
| 114 | + memory.write("output", code_content, validate=False) |
| 115 | + assert memory.read("output") == code_content |
| 116 | + |
| 117 | + def test_sampling_for_very_long_strings(self): |
| 118 | + """Very long strings (>10KB) should be sampled at multiple positions.""" |
| 119 | + memory = SharedMemory() |
| 120 | + # Create a 50KB string with code at the 75% mark |
| 121 | + size = 50000 |
| 122 | + code_position = int(size * 0.75) |
| 123 | + content = "A" * code_position + "def hidden_code(): pass" + "B" * (size - code_position - 25) |
| 124 | + |
| 125 | + with pytest.raises(MemoryWriteError) as exc_info: |
| 126 | + memory.write("output", content) |
| 127 | + |
| 128 | + assert "hallucinated code" in str(exc_info.value) |
| 129 | + |
| 130 | + |
| 131 | +class TestOutputValidatorHallucinationDetection: |
| 132 | + """Test the OutputValidator hallucination detection.""" |
| 133 | + |
| 134 | + def test_detects_code_anywhere_in_output(self): |
| 135 | + """Code anywhere in the output value should trigger a warning.""" |
| 136 | + validator = OutputValidator() |
| 137 | + padding = "Normal text content. " * 50 |
| 138 | + code = "\ndef suspicious_function():\n pass\n" |
| 139 | + output = {"result": padding + code} |
| 140 | + |
| 141 | + # The method logs a warning but doesn't fail |
| 142 | + result = validator.validate_no_hallucination(output) |
| 143 | + # The warning is logged - we can't easily test logging, but the method should work |
| 144 | + assert isinstance(result, ValidationResult) |
| 145 | + |
| 146 | + def test_contains_code_indicators_full_check(self): |
| 147 | + """_contains_code_indicators should check the entire string.""" |
| 148 | + validator = OutputValidator() |
| 149 | + |
| 150 | + # Code at position 600 (was previously missed with [:500] check) |
| 151 | + padding = "A" * 600 |
| 152 | + code = "import os" |
| 153 | + content = padding + code |
| 154 | + |
| 155 | + assert validator._contains_code_indicators(content) is True |
| 156 | + |
| 157 | + def test_contains_code_indicators_sampling(self): |
| 158 | + """_contains_code_indicators should sample for very long strings.""" |
| 159 | + validator = OutputValidator() |
| 160 | + |
| 161 | + # 50KB string with code at 75% position |
| 162 | + size = 50000 |
| 163 | + code_position = int(size * 0.75) |
| 164 | + content = "A" * code_position + "class HiddenClass:" + "B" * (size - code_position - 18) |
| 165 | + |
| 166 | + assert validator._contains_code_indicators(content) is True |
| 167 | + |
| 168 | + def test_no_false_positive_for_clean_text(self): |
| 169 | + """Clean text without code should not trigger false positives.""" |
| 170 | + validator = OutputValidator() |
| 171 | + |
| 172 | + # Long text without any code indicators |
| 173 | + content = "This is a perfectly normal document. " * 300 |
| 174 | + |
| 175 | + assert validator._contains_code_indicators(content) is False |
| 176 | + |
| 177 | + def test_detects_multiple_languages(self): |
| 178 | + """Should detect code patterns from multiple programming languages.""" |
| 179 | + validator = OutputValidator() |
| 180 | + |
| 181 | + test_cases = [ |
| 182 | + "function test() {}", # JavaScript |
| 183 | + "const x = 5;", # JavaScript |
| 184 | + "SELECT * FROM users", # SQL |
| 185 | + "DROP TABLE data", # SQL |
| 186 | + "<script>", # HTML |
| 187 | + "<?php", # PHP |
| 188 | + ] |
| 189 | + |
| 190 | + for code in test_cases: |
| 191 | + assert validator._contains_code_indicators(code) is True, f"Failed to detect: {code}" |
| 192 | + |
| 193 | + |
| 194 | +class TestEdgeCases: |
| 195 | + """Test edge cases for hallucination detection.""" |
| 196 | + |
| 197 | + def test_empty_string(self): |
| 198 | + """Empty strings should not cause errors.""" |
| 199 | + memory = SharedMemory() |
| 200 | + memory.write("output", "") |
| 201 | + assert memory.read("output") == "" |
| 202 | + |
| 203 | + def test_non_string_values(self): |
| 204 | + """Non-string values should not be validated for code.""" |
| 205 | + memory = SharedMemory() |
| 206 | + |
| 207 | + # These should all work without validation |
| 208 | + memory.write("number", 12345) |
| 209 | + memory.write("list", [1, 2, 3]) |
| 210 | + memory.write("dict", {"key": "value"}) |
| 211 | + memory.write("bool", True) |
| 212 | + |
| 213 | + assert memory.read("number") == 12345 |
| 214 | + assert memory.read("list") == [1, 2, 3] |
| 215 | + |
| 216 | + def test_exactly_5000_chars(self): |
| 217 | + """String of exactly 5000 chars should not trigger validation.""" |
| 218 | + memory = SharedMemory() |
| 219 | + content = "def code(): pass" + "A" * (5000 - 16) # Exactly 5000 chars |
| 220 | + |
| 221 | + # Should not raise - exactly at threshold, not over |
| 222 | + memory.write("output", content) |
| 223 | + assert len(memory.read("output")) == 5000 |
| 224 | + |
| 225 | + def test_5001_chars_triggers_validation(self): |
| 226 | + """String of 5001 chars with code should trigger validation.""" |
| 227 | + memory = SharedMemory() |
| 228 | + content = "def code(): pass" + "A" * (5001 - 16) # 5001 chars |
| 229 | + |
| 230 | + with pytest.raises(MemoryWriteError): |
| 231 | + memory.write("output", content) |
0 commit comments