forked from The-XSS-Rat/subScraper
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_main.py
More file actions
2297 lines (1881 loc) · 79.1 KB
/
Copy pathtest_main.py
File metadata and controls
2297 lines (1881 loc) · 79.1 KB
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Unit and Integration Tests for SubScraper
Tests cover:
1. Job scheduling and slot management
2. Filter logic for reports
3. API endpoints
4. Thread safety and race conditions
"""
import copy
import json
import os
import pytest
import sqlite3
import tempfile
import threading
import time
from collections import deque
from datetime import datetime, timezone
from pathlib import Path
from unittest.mock import Mock, patch, MagicMock
# Import functions from main.py
# We'll need to structure this carefully to avoid running the main script
import sys
sys.path.insert(0, os.path.dirname(__file__))
# Mock global state before importing
with patch('main.ensure_dirs'), \
patch('main.init_database'), \
patch('main.migrate_json_to_sqlite'):
import main
class TestJobScheduling:
"""Tests for job scheduling and slot management"""
def setup_method(self):
"""Setup test fixtures"""
# Save original state
self.original_running_jobs = main.RUNNING_JOBS.copy()
self.original_queue = deque(main.JOB_QUEUE)
self.original_max_jobs = main.MAX_RUNNING_JOBS
# Clear state for tests
main.RUNNING_JOBS.clear()
main.JOB_QUEUE.clear()
main.MAX_RUNNING_JOBS = 2
def teardown_method(self):
"""Restore original state"""
main.RUNNING_JOBS = self.original_running_jobs
main.JOB_QUEUE = self.original_queue
main.MAX_RUNNING_JOBS = self.original_max_jobs
def test_count_active_jobs_locked_empty(self):
"""Test counting active jobs when none are running"""
with main.JOB_LOCK:
count = main.count_active_jobs_locked()
assert count == 0
def test_count_active_jobs_locked_with_jobs(self):
"""Test counting active jobs with running threads"""
# Create mock threads
mock_thread1 = Mock()
mock_thread1.is_alive.return_value = True
mock_thread2 = Mock()
mock_thread2.is_alive.return_value = True
mock_thread3 = Mock()
mock_thread3.is_alive.return_value = False # Dead thread
with main.JOB_LOCK:
main.RUNNING_JOBS['domain1.com'] = {'thread': mock_thread1}
main.RUNNING_JOBS['domain2.com'] = {'thread': mock_thread2}
main.RUNNING_JOBS['domain3.com'] = {'thread': mock_thread3}
count = main.count_active_jobs_locked()
assert count == 2 # Only alive threads count
def test_count_active_jobs_locked_no_thread(self):
"""Test counting when jobs exist but have no thread"""
with main.JOB_LOCK:
main.RUNNING_JOBS['domain1.com'] = {'status': 'queued'}
count = main.count_active_jobs_locked()
assert count == 0
def test_schedule_jobs_respects_max_limit(self):
"""Test that schedule_jobs respects MAX_RUNNING_JOBS limit"""
main.MAX_RUNNING_JOBS = 1
# Add jobs to queue
with main.JOB_LOCK:
main.RUNNING_JOBS['domain1.com'] = {
'domain': 'domain1.com',
'thread': None,
'status': 'queued',
'wordlist': None,
'skip_nikto': False,
'interval': 30
}
main.RUNNING_JOBS['domain2.com'] = {
'domain': 'domain2.com',
'thread': None,
'status': 'queued',
'wordlist': None,
'skip_nikto': False,
'interval': 30
}
main.JOB_QUEUE.append('domain1.com')
main.JOB_QUEUE.append('domain2.com')
# Mock _start_job_thread to avoid actually starting threads
started_jobs = []
def mock_start(job):
mock_thread = Mock()
mock_thread.is_alive.return_value = True
with main.JOB_LOCK:
job['thread'] = mock_thread
started_jobs.append(job['domain'])
with patch('main._start_job_thread', side_effect=mock_start):
main.schedule_jobs()
# Should only start 1 job due to MAX_RUNNING_JOBS = 1
assert len(started_jobs) == 1
assert started_jobs[0] == 'domain1.com'
with main.JOB_LOCK:
assert len(main.JOB_QUEUE) == 1 # Second job still queued
assert main.JOB_QUEUE[0] == 'domain2.com'
def test_schedule_jobs_starts_multiple_if_slots_available(self):
"""Test that schedule_jobs can start multiple jobs if slots available"""
main.MAX_RUNNING_JOBS = 3
# Add jobs to queue
with main.JOB_LOCK:
for i in range(3):
domain = f'domain{i}.com'
main.RUNNING_JOBS[domain] = {
'domain': domain,
'thread': None,
'status': 'queued',
'wordlist': None,
'skip_nikto': False,
'interval': 30
}
main.JOB_QUEUE.append(domain)
started_jobs = []
def mock_start(job):
mock_thread = Mock()
mock_thread.is_alive.return_value = True
with main.JOB_LOCK:
job['thread'] = mock_thread
started_jobs.append(job['domain'])
with patch('main._start_job_thread', side_effect=mock_start):
main.schedule_jobs()
# Should start all 3 jobs
assert len(started_jobs) == 3
assert set(started_jobs) == {'domain0.com', 'domain1.com', 'domain2.com'}
with main.JOB_LOCK:
assert len(main.JOB_QUEUE) == 0
def test_schedule_jobs_thread_safety(self):
"""Test that schedule_jobs is thread-safe under concurrent access"""
main.MAX_RUNNING_JOBS = 2
# Add many jobs to queue
with main.JOB_LOCK:
for i in range(10):
domain = f'domain{i}.com'
main.RUNNING_JOBS[domain] = {
'domain': domain,
'thread': None,
'status': 'queued',
'wordlist': None,
'skip_nikto': False,
'interval': 30
}
main.JOB_QUEUE.append(domain)
started_jobs = []
start_lock = threading.Lock()
def mock_start(job):
# Simulate some work
time.sleep(0.01)
mock_thread = Mock()
mock_thread.is_alive.return_value = True
with main.JOB_LOCK:
job['thread'] = mock_thread
with start_lock:
started_jobs.append(job['domain'])
with patch('main._start_job_thread', side_effect=mock_start):
# Call schedule_jobs from multiple threads
threads = []
for _ in range(5):
t = threading.Thread(target=main.schedule_jobs)
threads.append(t)
t.start()
for t in threads:
t.join()
# Should respect MAX_RUNNING_JOBS limit even with concurrent calls
with main.JOB_LOCK:
active_count = sum(1 for job in main.RUNNING_JOBS.values()
if job.get('thread') and job['thread'].is_alive())
# With MAX_RUNNING_JOBS=2, the active count should be at most 2
# (it might be less if some threads complete quickly, but should never exceed the limit)
assert active_count <= main.MAX_RUNNING_JOBS
# At least 2 jobs should have been started
assert len(started_jobs) >= 2
# No duplicates should have been started
assert len(set(started_jobs)) == len(started_jobs)
class TestFilterLogic:
"""Tests for report filtering logic"""
def test_severity_comparison(self):
"""Test severity level comparison"""
severity_levels = ['NONE', 'INFO', 'LOW', 'MEDIUM', 'HIGH', 'CRITICAL']
# Test that higher severities come after lower ones
for i, level in enumerate(severity_levels):
assert severity_levels.index(level) == i
# Test filtering logic
filter_severity = 'MEDIUM'
filter_index = severity_levels.index(filter_severity)
# These should pass the filter (>= MEDIUM)
assert severity_levels.index('MEDIUM') >= filter_index
assert severity_levels.index('HIGH') >= filter_index
assert severity_levels.index('CRITICAL') >= filter_index
# These should not pass the filter (< MEDIUM)
assert severity_levels.index('LOW') < filter_index
assert severity_levels.index('INFO') < filter_index
assert severity_levels.index('NONE') < filter_index
def test_domain_search_filter(self):
"""Test domain search filtering"""
test_cases = [
('example.com', 'example', True),
('example.com', 'EXAMPLE', True), # Case insensitive
('subdomain.example.com', 'example', True),
('example.com', 'test', False),
('test.com', 'example', False),
]
for domain, search, should_match in test_cases:
result = search.lower() in domain.lower()
assert result == should_match, f"Failed for domain={domain}, search={search}"
class TestAPIEndpoints:
"""Integration tests for API endpoints"""
def setup_method(self):
"""Setup test fixtures"""
# Create temporary data directory
self.temp_dir = tempfile.mkdtemp()
self.original_data_dir = main.DATA_DIR
main.DATA_DIR = Path(self.temp_dir)
main.DB_FILE = main.DATA_DIR / "test_recon.db"
# Initialize test database
main.ensure_dirs()
main.init_database()
def teardown_method(self):
"""Cleanup test fixtures"""
# Restore original data dir
main.DATA_DIR = self.original_data_dir
main.DB_FILE = main.DATA_DIR / "recon.db"
# Clean up temp directory
import shutil
if os.path.exists(self.temp_dir):
shutil.rmtree(self.temp_dir)
def test_build_state_payload_structure(self):
"""Test that build_state_payload returns correct structure"""
with patch('main.load_state', return_value={'targets': {}, 'last_updated': '2024-01-01'}):
with patch('main.get_config', return_value={}):
with patch('main.snapshot_running_jobs', return_value=[]):
with patch('main.job_queue_snapshot', return_value=[]):
with patch('main.snapshot_workers', return_value={}):
with patch('main.list_monitors', return_value=[]):
with patch('main.load_completed_jobs', return_value={}):
payload = main.build_state_payload()
# Check required keys
assert 'last_updated' in payload
assert 'targets' in payload
assert 'running_jobs' in payload
assert 'queued_jobs' in payload
assert 'config' in payload
assert 'tools' in payload
assert 'workers' in payload
assert 'monitors' in payload
def test_build_state_payload_includes_completed_jobs(self):
"""Test that completed jobs are merged into targets"""
test_state = {
'targets': {
'active.com': {
'subdomains': {'sub1.active.com': {}},
'flags': {},
'options': {}
}
},
'last_updated': '2024-01-01'
}
test_completed_jobs = {
'completed.com_123456': {
'state': {
'subdomains': {'sub1.completed.com': {}},
'flags': {},
},
'options': {},
'completed_at': '2024-01-01T12:00:00Z'
}
}
with patch('main.load_state', return_value=test_state):
with patch('main.get_config', return_value={}):
with patch('main.snapshot_running_jobs', return_value=[]):
with patch('main.job_queue_snapshot', return_value=[]):
with patch('main.snapshot_workers', return_value={}):
with patch('main.list_monitors', return_value=[]):
with patch('main.load_completed_jobs', return_value=test_completed_jobs):
payload = main.build_state_payload()
# Should have both active and completed domains
assert 'active.com' in payload['targets']
assert 'completed.com' in payload['targets']
assert payload['targets']['completed.com']['from_completed_jobs'] == True
assert payload['targets']['active.com'].get('from_completed_jobs') != True
class TestDatabaseOperations:
"""Tests for SQLite database operations"""
def setup_method(self):
"""Setup test database"""
self.temp_dir = tempfile.mkdtemp()
self.db_path = Path(self.temp_dir) / "test.db"
self.conn = sqlite3.connect(str(self.db_path), isolation_level=None)
self.conn.row_factory = sqlite3.Row
# Enable foreign keys - CRITICAL for cascade delete tests
self.conn.execute("PRAGMA foreign_keys=ON")
# Create tables
cursor = self.conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS targets (
domain TEXT PRIMARY KEY,
data TEXT NOT NULL,
flags TEXT,
options TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS subdomains (
id INTEGER PRIMARY KEY AUTOINCREMENT,
domain TEXT NOT NULL,
subdomain TEXT NOT NULL,
data TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
UNIQUE(domain, subdomain),
FOREIGN KEY (domain) REFERENCES targets(domain) ON DELETE CASCADE
)
""")
self.conn.commit()
def teardown_method(self):
"""Cleanup test database"""
self.conn.close()
import shutil
if os.path.exists(self.temp_dir):
shutil.rmtree(self.temp_dir)
def test_insert_target(self):
"""Test inserting a target into database"""
cursor = self.conn.cursor()
now = datetime.now(timezone.utc).isoformat()
cursor.execute(
"""INSERT INTO targets
(domain, data, flags, options, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?)""",
('example.com', '{}', '{}', '{}', now, now)
)
self.conn.commit()
cursor.execute("SELECT * FROM targets WHERE domain = ?", ('example.com',))
row = cursor.fetchone()
assert row is not None
assert row['domain'] == 'example.com'
def test_insert_subdomain(self):
"""Test inserting subdomains into database"""
cursor = self.conn.cursor()
now = datetime.now(timezone.utc).isoformat()
# First insert target
cursor.execute(
"""INSERT INTO targets
(domain, data, flags, options, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?)""",
('example.com', '{}', '{}', '{}', now, now)
)
# Then insert subdomain
sub_data = json.dumps({'sources': ['amass'], 'httpx': {}})
cursor.execute(
"""INSERT INTO subdomains
(domain, subdomain, data, created_at, updated_at)
VALUES (?, ?, ?, ?, ?)""",
('example.com', 'sub1.example.com', sub_data, now, now)
)
self.conn.commit()
cursor.execute("SELECT * FROM subdomains WHERE domain = ?", ('example.com',))
row = cursor.fetchone()
assert row is not None
assert row['subdomain'] == 'sub1.example.com'
data = json.loads(row['data'])
assert 'sources' in data
assert 'amass' in data['sources']
def test_cascade_delete(self):
"""Test that deleting a target deletes its subdomains"""
cursor = self.conn.cursor()
now = datetime.now(timezone.utc).isoformat()
# Insert target and subdomain
cursor.execute(
"""INSERT INTO targets
(domain, data, flags, options, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?)""",
('example.com', '{}', '{}', '{}', now, now)
)
cursor.execute(
"""INSERT INTO subdomains
(domain, subdomain, data, created_at, updated_at)
VALUES (?, ?, ?, ?, ?)""",
('example.com', 'sub1.example.com', '{}', now, now)
)
self.conn.commit()
# Delete target
cursor.execute("DELETE FROM targets WHERE domain = ?", ('example.com',))
self.conn.commit()
# Check subdomain is also deleted
cursor.execute("SELECT * FROM subdomains WHERE domain = ?", ('example.com',))
row = cursor.fetchone()
assert row is None
class TestThreadSafety:
"""Tests for thread safety and race conditions"""
def test_job_lock_prevents_race_conditions(self):
"""Test that JOB_LOCK prevents concurrent modifications"""
main.RUNNING_JOBS.clear()
counter = {'value': 0}
errors = []
def increment_with_lock():
try:
for _ in range(100):
with main.JOB_LOCK:
# Simulate some work
temp = counter['value']
time.sleep(0.0001) # Small delay to encourage race conditions
counter['value'] = temp + 1
except Exception as e:
errors.append(e)
# Run from multiple threads
threads = []
for _ in range(10):
t = threading.Thread(target=increment_with_lock)
threads.append(t)
t.start()
for t in threads:
t.join()
# Should be exactly 1000 (10 threads * 100 increments each)
assert counter['value'] == 1000
assert len(errors) == 0
def test_tool_gate_limits_concurrent_access(self):
"""Test that ToolGate limits concurrent access"""
gate = main.ToolGate(2) # Allow max 2 concurrent
active_count = {'value': 0, 'max_seen': 0}
lock = threading.Lock()
def worker():
with gate:
with lock:
active_count['value'] += 1
if active_count['value'] > active_count['max_seen']:
active_count['max_seen'] = active_count['value']
time.sleep(0.01) # Simulate work
with lock:
active_count['value'] -= 1
# Run many workers
threads = []
for _ in range(20):
t = threading.Thread(target=worker)
threads.append(t)
t.start()
for t in threads:
t.join()
# Max concurrent should never exceed gate limit
assert active_count['max_seen'] <= 2
assert active_count['value'] == 0 # All workers finished
class TestUtilityFunctions:
"""Tests for utility functions"""
def test_is_subdomain_input(self):
"""Test subdomain detection"""
assert main.is_subdomain_input('sub.example.com') == True
assert main.is_subdomain_input('deep.sub.example.com') == True
assert main.is_subdomain_input('example.com') == False
assert main.is_subdomain_input('com') == False
assert main.is_subdomain_input('') == False
def test_sanitize_domain_input(self):
"""Test domain input sanitization"""
assert main._sanitize_domain_input('EXAMPLE.COM') == 'example.com'
assert main._sanitize_domain_input(' example.com ') == 'example.com'
assert main._sanitize_domain_input('example.com\n') == 'example.com'
def test_is_rate_limit_error(self):
"""Test rate limit error detection"""
from urllib.error import HTTPError
# Test HTTP 429
error_429 = HTTPError('http://test.com', 429, 'Too Many Requests', {}, None)
assert main.is_rate_limit_error(error_429) == True
# Test HTTP 503
error_503 = HTTPError('http://test.com', 503, 'Service Unavailable', {}, None)
assert main.is_rate_limit_error(error_503) == True
# Test timeout message
error_timeout = Exception('Connection timed out')
assert main.is_rate_limit_error(error_timeout) == True
# Test rate limit keyword
error_rate = Exception('rate limit exceeded')
assert main.is_rate_limit_error(error_rate) == True
# Test normal error
error_normal = Exception('Some other error')
assert main.is_rate_limit_error(error_normal) == False
class TestToolConcurrencyLimits:
"""Tests for tool concurrency limits and gates"""
def test_all_tools_have_gates(self):
"""Test that all tools in TOOLS have corresponding TOOL_GATES"""
# All tools should have gates
expected_tools = set(main.TOOLS.keys())
actual_gates = set(main.TOOL_GATES.keys())
# Check that all expected tools have gates
assert expected_tools == actual_gates, \
f"Missing gates: {expected_tools - actual_gates}, Extra gates: {actual_gates - expected_tools}"
def test_all_tools_have_config_settings(self):
"""Test that all tools have max_parallel_* config settings"""
config = main.default_config()
for tool in main.TOOLS.keys():
# Convert tool name to config key (e.g., "github-subdomains" -> "max_parallel_github_subdomains")
config_key = f"max_parallel_{tool.replace('-', '_')}"
assert config_key in config, f"Missing config setting: {config_key}"
assert isinstance(config[config_key], int), f"Config {config_key} should be an integer"
assert config[config_key] >= 1, f"Config {config_key} should be >= 1"
def test_apply_concurrency_limits_updates_gates(self):
"""Test that apply_concurrency_limits properly updates tool gates"""
# Create test config with custom limits
test_config = main.default_config()
test_config['max_parallel_amass'] = 5
test_config['max_parallel_subfinder'] = 3
test_config['max_parallel_httpx'] = 7
# Apply limits
main.apply_concurrency_limits(test_config)
# Verify gates were updated
assert main.TOOL_GATES['amass'].snapshot()['limit'] == 5
assert main.TOOL_GATES['subfinder'].snapshot()['limit'] == 3
assert main.TOOL_GATES['httpx'].snapshot()['limit'] == 7
def test_gate_snapshot_returns_correct_data(self):
"""Test that gate snapshot returns limit and active count"""
gate = main.ToolGate(3)
snapshot = gate.snapshot()
assert 'limit' in snapshot
assert 'active' in snapshot
assert 'queued' in snapshot
assert snapshot['limit'] == 3
assert snapshot['active'] == 0
assert snapshot['queued'] == 0
# Acquire and check again
gate.acquire()
snapshot = gate.snapshot()
assert snapshot['active'] == 1
gate.release()
snapshot = gate.snapshot()
assert snapshot['active'] == 0
# Clean up
gate.stop_worker()
def test_gate_enqueue_executes_work(self):
"""Test that enqueued work items are executed"""
gate = main.ToolGate(1)
results = []
def work_func():
results.append('executed')
return 'result'
def result_callback(result):
results.append(result)
gate.enqueue(work_func, result_callback)
# Wait for execution
time.sleep(0.5)
assert 'executed' in results
assert 'result' in results
# Clean up
gate.stop_worker()
def test_gate_queue_respects_capacity(self):
"""Test that queue doesn't exceed capacity limit"""
gate = main.ToolGate(2)
active_count = []
lock = threading.Lock()
def work_func():
with lock:
active_count.append(1)
time.sleep(0.3) # Simulate work
with lock:
active_count.pop()
return 'done'
# Enqueue more work than capacity
for _ in range(5):
gate.enqueue(work_func)
# Give worker time to start processing
time.sleep(0.1)
# Check that active count never exceeds limit
snapshot = gate.snapshot()
assert snapshot['active'] <= 2
# Wait for all work to complete
time.sleep(2)
# Clean up
gate.stop_worker()
def test_gate_handles_errors_in_work(self):
"""Test that errors in work items are handled gracefully"""
gate = main.ToolGate(1)
errors = []
def failing_work():
raise ValueError("Test error")
def error_callback(exc):
errors.append(str(exc))
gate.enqueue(failing_work, error_callback=error_callback)
# Wait for execution
time.sleep(0.5)
assert len(errors) == 1
assert "Test error" in errors[0]
# Gate should still be functional
snapshot = gate.snapshot()
assert snapshot['active'] == 0
# Clean up
gate.stop_worker()
def test_gate_multiple_queued_items(self):
"""Test that multiple items can be queued and processed in order"""
gate = main.ToolGate(1)
results = []
lock = threading.Lock()
def make_work_func(value):
def work():
with lock:
results.append(value)
time.sleep(0.1)
return value
return work
# Enqueue multiple items
for i in range(5):
gate.enqueue(make_work_func(i))
# Wait for all to complete
time.sleep(1.5)
# All items should have been processed
assert len(results) == 5
# Results should contain all values 0-4
assert set(results) == {0, 1, 2, 3, 4}
# Clean up
gate.stop_worker()
def test_gate_backward_compatibility_context_manager(self):
"""Test that context manager (with statement) still works"""
gate = main.ToolGate(2)
results = []
def worker():
with gate:
results.append('in_context')
time.sleep(0.1)
threads = []
for _ in range(3):
t = threading.Thread(target=worker)
t.start()
threads.append(t)
for t in threads:
t.join()
assert len(results) == 3
# Clean up
gate.stop_worker()
class TestToolGateQueuing:
"""Integration tests for tool gate queuing mechanism"""
def test_job_can_proceed_when_tool_at_capacity(self):
"""Test that a job can proceed with other tools when one tool is at capacity"""
gate1 = main.ToolGate(1)
gate2 = main.ToolGate(1)
results = []
lock = threading.Lock()
def long_work():
with lock:
results.append('tool1_started')
time.sleep(0.5)
with lock:
results.append('tool1_finished')
return 'tool1_done'
def quick_work():
with lock:
results.append('tool2_executed')
return 'tool2_done'
# Fill tool1 capacity
gate1.enqueue(long_work)
# Enqueue more work to tool1 (will be queued)
gate1.enqueue(long_work)
# Execute work on tool2 (should not be blocked)
gate2.enqueue(quick_work)
# Give time for execution
time.sleep(0.2)
# Tool2 should have executed quickly
with lock:
assert 'tool2_executed' in results
assert 'tool1_started' in results
# Wait for all work to complete
time.sleep(1)
# Clean up
gate1.stop_worker()
gate2.stop_worker()
def test_multiple_jobs_share_tool_queue(self):
"""Test that multiple jobs can share the same tool queue"""
gate = main.ToolGate(1)
results = []
lock = threading.Lock()
def job_work(job_id):
def work():
with lock:
results.append(f'job_{job_id}')
time.sleep(0.1)
return f'job_{job_id}_done'
return work
# Simulate 3 jobs each trying to use the same tool
for i in range(3):
gate.enqueue(job_work(i))
# Wait for all to complete
time.sleep(1)
# All jobs should have been processed
with lock:
assert len(results) == 3
assert 'job_0' in results
assert 'job_1' in results
assert 'job_2' in results
# Clean up
gate.stop_worker()
class TestConfigurationManagement:
"""Tests for configuration management functions"""
def setup_method(self):
"""Setup test fixtures"""
self.temp_dir = tempfile.mkdtemp()
self.original_data_dir = main.DATA_DIR
self.original_config_file = main.CONFIG_FILE
self.original_db_file = main.DB_FILE
self.original_db_conn = main.DB_CONN
main.DATA_DIR = Path(self.temp_dir)
main.CONFIG_FILE = main.DATA_DIR / "config.json"
main.DB_FILE = main.DATA_DIR / "test_recon.db"
main.DB_CONN = None
main.ensure_dirs()
main.init_database()
# Clear config cache
with main.CONFIG_LOCK:
main.CONFIG.clear()
def teardown_method(self):
"""Cleanup"""
if main.DB_CONN:
main.DB_CONN.close()
main.DATA_DIR = self.original_data_dir
main.CONFIG_FILE = self.original_config_file
main.DB_FILE = self.original_db_file
main.DB_CONN = self.original_db_conn
import shutil
if os.path.exists(self.temp_dir):
shutil.rmtree(self.temp_dir)
with main.CONFIG_LOCK:
main.CONFIG.clear()
def test_default_config_has_all_required_keys(self):
"""Test that default_config returns all necessary keys"""
config = main.default_config()
required_keys = [
'data_dir', 'state_file', 'dashboard_file', 'default_interval',
'max_running_jobs', 'enable_amass', 'enable_subfinder',
'tool_flag_templates', 'setup_completed'
]
for key in required_keys:
assert key in config, f"Missing key: {key}"
def test_get_config_returns_default_on_first_call(self):
"""Test that get_config returns defaults when no config exists"""
config = main.get_config()
assert isinstance(config, dict)
assert config.get('max_running_jobs') == 1
assert config.get('default_interval') == 30
def test_save_and_load_config(self):
"""Test saving and loading configuration"""
test_config = main.default_config()
test_config['max_running_jobs'] = 5
test_config['custom_key'] = 'custom_value'
main.save_config(test_config)
# Clear cache
with main.CONFIG_LOCK:
main.CONFIG.clear()
# Load should return saved config
loaded = main.get_config()
assert loaded['max_running_jobs'] == 5
assert loaded['custom_key'] == 'custom_value'
def test_update_config_settings(self):
"""Test updating configuration settings"""
updates = {
'max_running_jobs': '3',
'global_rate_limit': '2.5',
'skip_nikto_by_default': 'true'
}
success, message, config = main.update_config_settings(updates)
assert success == True
assert config['max_running_jobs'] == 3
assert config['global_rate_limit'] == 2.5
assert config['skip_nikto_by_default'] == True
def test_bool_from_value(self):
"""Test boolean conversion from various input types"""
assert main.bool_from_value(True, False) == True
assert main.bool_from_value(False, True) == False
assert main.bool_from_value('true', False) == True
assert main.bool_from_value('True', False) == True
assert main.bool_from_value('yes', False) == True
assert main.bool_from_value('1', False) == True
assert main.bool_from_value('false', True) == False
assert main.bool_from_value('no', True) == False
assert main.bool_from_value('0', True) == False
assert main.bool_from_value(None, True) == True # default
assert main.bool_from_value('', True) == True # default
def test_apply_concurrency_limits_from_config(self):
"""Test that concurrency limits are applied from config"""
config = main.default_config()
config['max_running_jobs'] = 10
config['global_rate_limit'] = 1.5
config['max_parallel_amass'] = 3
original_max_jobs = main.MAX_RUNNING_JOBS
original_rate_limit = main.GLOBAL_RATE_LIMIT_DELAY
main.apply_concurrency_limits(config)
assert main.MAX_RUNNING_JOBS == 10
assert main.GLOBAL_RATE_LIMIT_DELAY == 1.5
assert main.TOOL_GATES['amass'].snapshot()['limit'] == 3
# Restore
main.MAX_RUNNING_JOBS = original_max_jobs
main.GLOBAL_RATE_LIMIT_DELAY = original_rate_limit
class TestStateManagement:
"""Tests for state management functions"""
def setup_method(self):
"""Setup test fixtures"""
self.temp_dir = tempfile.mkdtemp()
self.original_data_dir = main.DATA_DIR
self.original_db_file = main.DB_FILE