File size: 12,793 Bytes
c87f72b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
387
388
389
390
391
392
393
394
395
"""
Comprehensive tests for worker_watchdog.py

Tests cover:
- WorkerWatchdog initialization
- File hash calculation
- Change detection
- Self-healing trigger
- Workflow health checking
- State management
"""
import pytest
import json
import hashlib
from pathlib import Path
from unittest.mock import Mock, patch, MagicMock
import sys

# Add parent directory to path
sys.path.insert(0, str(Path(__file__).parent.parent))

from workers.worker_watchdog import WorkerWatchdog


class TestWorkerWatchdogInit:
    """Test WorkerWatchdog initialization"""

    def test_init_default_values(self):
        """Test that WorkerWatchdog initializes with correct defaults"""
        watchdog = WorkerWatchdog()

        assert watchdog.check_interval == 300
        assert watchdog.running == False
        assert isinstance(watchdog.file_hashes, dict)
        assert isinstance(watchdog.template_hashes, dict)
        assert isinstance(watchdog.stats, dict)

    def test_init_custom_interval(self):
        """Test initialization with custom check interval"""
        watchdog = WorkerWatchdog(check_interval=600)

        assert watchdog.check_interval == 600

    def test_init_creates_monitoring_directory(self, temp_dir, monkeypatch):
        """Test that initialization creates monitoring directory"""
        monkeypatch.chdir(temp_dir)

        watchdog = WorkerWatchdog()

        assert watchdog.monitoring_path.exists()

    def test_init_stats_structure(self):
        """Test that stats dict has correct structure"""
        watchdog = WorkerWatchdog()

        assert "total_checks" in watchdog.stats
        assert "issues_detected" in watchdog.stats
        assert "auto_repairs_triggered" in watchdog.stats
        assert "successful_repairs" in watchdog.stats
        assert "start_time" in watchdog.stats
        assert "last_check" in watchdog.stats


class TestWorkerWatchdogFileHashing:
    """Test file hashing functionality"""

    def test_calculate_file_hash(self, temp_dir):
        """Test that file hash is calculated correctly"""
        watchdog = WorkerWatchdog()

        test_file = temp_dir / "test.txt"
        test_content = b"test content"
        test_file.write_bytes(test_content)

        hash_result = watchdog.calculate_file_hash(test_file)

        # Verify it's a valid SHA256 hash
        assert len(hash_result) == 64
        assert all(c in '0123456789abcdef' for c in hash_result)

        # Verify hash is correct
        expected_hash = hashlib.sha256(test_content).hexdigest()
        assert hash_result == expected_hash

    def test_calculate_file_hash_nonexistent(self, temp_dir):
        """Test hash calculation for non-existent file"""
        watchdog = WorkerWatchdog()

        nonexistent_file = temp_dir / "nonexistent.txt"
        hash_result = watchdog.calculate_file_hash(nonexistent_file)

        assert hash_result == ""

    def test_calculate_file_hash_empty_file(self, temp_dir):
        """Test hash calculation for empty file"""
        watchdog = WorkerWatchdog()

        empty_file = temp_dir / "empty.txt"
        empty_file.write_bytes(b"")

        hash_result = watchdog.calculate_file_hash(empty_file)

        expected_hash = hashlib.sha256(b"").hexdigest()
        assert hash_result == expected_hash

    def test_scan_file_hashes(self, temp_dir, monkeypatch):
        """Test scanning directory for file hashes"""
        monkeypatch.chdir(temp_dir)
        watchdog = WorkerWatchdog()

        # Create test Python files
        scripts_dir = temp_dir / "scripts"
        scripts_dir.mkdir()
        (scripts_dir / "test1.py").write_text("content1")
        (scripts_dir / "test2.py").write_text("content2")
        (scripts_dir / "test.txt").write_text("not python")

        hashes = watchdog.scan_file_hashes(scripts_dir, "*.py")

        assert len(hashes) == 2
        assert any("test1.py" in key for key in hashes.keys())
        assert any("test2.py" in key for key in hashes.keys())

    def test_scan_file_hashes_empty_directory(self, temp_dir):
        """Test scanning empty directory"""
        watchdog = WorkerWatchdog()

        empty_dir = temp_dir / "empty"
        empty_dir.mkdir()

        hashes = watchdog.scan_file_hashes(empty_dir, "*.py")

        assert len(hashes) == 0

    def test_scan_file_hashes_nonexistent_directory(self, temp_dir):
        """Test scanning non-existent directory"""
        watchdog = WorkerWatchdog()

        nonexistent_dir = temp_dir / "nonexistent"

        hashes = watchdog.scan_file_hashes(nonexistent_dir, "*.py")

        assert len(hashes) == 0


class TestWorkerWatchdogChangeDetection:
    """Test change detection functionality"""

    def test_detect_changes_new_file(self, temp_dir, monkeypatch):
        """Test detection of new files"""
        monkeypatch.chdir(temp_dir)
        watchdog = WorkerWatchdog()

        # Initial scan
        scripts_dir = temp_dir / "scripts"
        scripts_dir.mkdir()
        watchdog.scripts_path = scripts_dir
        watchdog.file_hashes = watchdog.scan_file_hashes(scripts_dir, "*.py")

        # Add new file
        (scripts_dir / "new_file.py").write_text("new content")

        changes = watchdog.detect_changes()

        assert len(changes["new_files"]) == 1
        assert any("new_file.py" in f for f in changes["new_files"])

    def test_detect_changes_modified_file(self, temp_dir, monkeypatch):
        """Test detection of modified files"""
        monkeypatch.chdir(temp_dir)
        watchdog = WorkerWatchdog()

        scripts_dir = temp_dir / "scripts"
        scripts_dir.mkdir()
        test_file = scripts_dir / "test.py"
        test_file.write_text("original content")

        watchdog.scripts_path = scripts_dir
        watchdog.file_hashes = watchdog.scan_file_hashes(scripts_dir, "*.py")

        # Modify file
        test_file.write_text("modified content")

        changes = watchdog.detect_changes()

        assert len(changes["modified_files"]) == 1
        assert any("test.py" in f for f in changes["modified_files"])

    def test_detect_changes_deleted_file(self, temp_dir, monkeypatch):
        """Test detection of deleted files"""
        monkeypatch.chdir(temp_dir)
        watchdog = WorkerWatchdog()

        scripts_dir = temp_dir / "scripts"
        scripts_dir.mkdir()
        test_file = scripts_dir / "test.py"
        test_file.write_text("content")

        watchdog.scripts_path = scripts_dir
        watchdog.file_hashes = watchdog.scan_file_hashes(scripts_dir, "*.py")

        # Delete file
        test_file.unlink()

        changes = watchdog.detect_changes()

        assert len(changes["deleted_files"]) == 1
        assert any("test.py" in f for f in changes["deleted_files"])

    def test_detect_changes_no_changes(self, temp_dir, monkeypatch):
        """Test when no changes detected"""
        monkeypatch.chdir(temp_dir)
        watchdog = WorkerWatchdog()

        scripts_dir = temp_dir / "scripts"
        scripts_dir.mkdir()
        (scripts_dir / "test.py").write_text("content")

        watchdog.scripts_path = scripts_dir
        watchdog.file_hashes = watchdog.scan_file_hashes(scripts_dir, "*.py")

        changes = watchdog.detect_changes()

        assert len(changes["new_files"]) == 0
        assert len(changes["modified_files"]) == 0
        assert len(changes["deleted_files"]) == 0


class TestWorkerWatchdogSelfHealing:
    """Test self-healing trigger functionality"""

    def test_trigger_self_healing_success(self, temp_dir, monkeypatch):
        """Test successful self-healing trigger"""
        monkeypatch.chdir(temp_dir)
        watchdog = WorkerWatchdog()

        # Create mock healing script
        workers_dir = temp_dir / "workers"
        workers_dir.mkdir()
        healing_script = workers_dir / "self_healing_worker.py"
        healing_script.write_text("#!/usr/bin/env python3\nprint('healing')")

        watchdog.base_path = temp_dir

        with patch('subprocess.run') as mock_run:
            mock_run.return_value = Mock(returncode=0, stdout="success", stderr="")

            result = watchdog.trigger_self_healing()

            assert result == True
            assert watchdog.stats["successful_repairs"] == 1

    def test_trigger_self_healing_failure(self, temp_dir, monkeypatch):
        """Test failed self-healing trigger"""
        monkeypatch.chdir(temp_dir)
        watchdog = WorkerWatchdog()

        workers_dir = temp_dir / "workers"
        workers_dir.mkdir()
        healing_script = workers_dir / "self_healing_worker.py"
        healing_script.write_text("#!/usr/bin/env python3\nprint('healing')")

        watchdog.base_path = temp_dir

        with patch('subprocess.run') as mock_run:
            mock_run.return_value = Mock(returncode=1, stdout="", stderr="error")

            result = watchdog.trigger_self_healing()

            assert result == False

    def test_trigger_self_healing_script_not_found(self, temp_dir, monkeypatch):
        """Test self-healing when script not found"""
        monkeypatch.chdir(temp_dir)
        watchdog = WorkerWatchdog()
        watchdog.base_path = temp_dir

        result = watchdog.trigger_self_healing()

        assert result == False

    def test_trigger_self_healing_timeout(self, temp_dir, monkeypatch):
        """Test self-healing timeout"""
        monkeypatch.chdir(temp_dir)
        watchdog = WorkerWatchdog()

        workers_dir = temp_dir / "workers"
        workers_dir.mkdir()
        healing_script = workers_dir / "self_healing_worker.py"
        healing_script.write_text("#!/usr/bin/env python3\nprint('healing')")

        watchdog.base_path = temp_dir

        with patch('subprocess.run') as mock_run:
            from subprocess import TimeoutExpired
            mock_run.side_effect = TimeoutExpired("cmd", 300)

            result = watchdog.trigger_self_healing()

            assert result == False


class TestWorkerWatchdogStateManagement:
    """Test state save/load functionality"""

    def test_save_state(self, temp_dir, monkeypatch):
        """Test saving watchdog state"""
        monkeypatch.chdir(temp_dir)
        watchdog = WorkerWatchdog()

        watchdog.monitoring_path = temp_dir
        watchdog.watchdog_state_file = temp_dir / "watchdog_state.json"
        watchdog.stats["total_checks"] = 5
        watchdog.file_hashes = {"test.py": "hash123"}

        watchdog.save_state()

        assert watchdog.watchdog_state_file.exists()

        with open(watchdog.watchdog_state_file, 'r') as f:
            state = json.load(f)

        assert state["stats"]["total_checks"] == 5
        assert state["file_count"] == 1

    def test_load_state(self, temp_dir, monkeypatch):
        """Test loading watchdog state"""
        monkeypatch.chdir(temp_dir)
        watchdog = WorkerWatchdog()

        watchdog.monitoring_path = temp_dir
        watchdog.watchdog_state_file = temp_dir / "watchdog_state.json"

        # Create state file
        state = {
            "stats": {"total_checks": 10},
            "file_count": 5,
            "last_update": "2026-04-14"
        }

        with open(watchdog.watchdog_state_file, 'w') as f:
            json.dump(state, f)

        watchdog.load_state()

        assert watchdog.stats["total_checks"] == 10

    def test_load_state_file_not_exists(self, temp_dir, monkeypatch):
        """Test loading state when file doesn't exist"""
        monkeypatch.chdir(temp_dir)
        watchdog = WorkerWatchdog()

        watchdog.monitoring_path = temp_dir
        watchdog.watchdog_state_file = temp_dir / "nonexistent.json"

        # Should not raise error
        watchdog.load_state()


class TestWorkerWatchdogHealthCheck:
    """Test health check functionality"""

    def test_perform_health_check(self, temp_dir, monkeypatch):
        """Test performing a health check"""
        monkeypatch.chdir(temp_dir)
        watchdog = WorkerWatchdog()

        scripts_dir = temp_dir / "scripts"
        scripts_dir.mkdir()

        watchdog.scripts_path = scripts_dir
        watchdog.monitoring_path = temp_dir

        with patch.object(watchdog, 'trigger_self_healing') as mock_heal:
            watchdog.perform_health_check()

            assert watchdog.stats["total_checks"] == 1
            assert watchdog.stats["last_check"] is not None

    def test_run_once(self, temp_dir, monkeypatch):
        """Test running health check once"""
        monkeypatch.chdir(temp_dir)
        watchdog = WorkerWatchdog()

        scripts_dir = temp_dir / "scripts"
        scripts_dir.mkdir()

        watchdog.scripts_path = scripts_dir
        watchdog.monitoring_path = temp_dir

        with patch.object(watchdog, 'trigger_self_healing'):
            watchdog.run_once()

            assert watchdog.stats["total_checks"] == 1