Repository navigation
feat: add solid unit tests + batch progress output - #4
Conversation
- Introduce tests/ package with 97+ focused offline tests - Cover: utils (network, files, headers), analyzers (security headers, waf/cdn, cloud classifier, server tokens, remediation narrative, scan diff), scanners (cipher classifier, backport detector, evidence collector), reporters, config, scan profiles, signatures - Wire unittest suite into scripts/validate_offline.py (still the canonical 'python scripts/validate_offline.py' command) - Deduplicate Server header extraction into ssc/utils/headers.py (extract_server_header + extract_server_header_from_probe) - Update call sites in cli.py, backport_detector.py, evidence_collector.py - Update exports and CLAUDE.md All tests pass via the existing offline validation harness. No new dependencies (stdlib unittest only).
- Thread-safe counter using stdlib threading.Lock - Prints e.g. '[3/12] 203.0.113.10 (ok)' for each completed target - Added _format_batch_progress() helper (easily testable) - Updated initial batch message to show thread count - Extended scripts/validate_offline.py with test_batch_progress_format() No new dependencies. Minimal and additive.
- Added example of [N/M] progress in common commands section - Mentioned simple progress in Batch triage use case
There was a problem hiding this comment.
Pull request overview
This PR expands the project’s offline validation and testability by adding a comprehensive stdlib unittest suite, consolidating repeated Server-header extraction logic into a shared utility, and improving batch-mode UX with simple progress output.
Changes:
- Added a new
tests/unittest suite and integrated it intoscripts/validate_offline.pyso offline validation runs both the existing assertions and the unittest suite. - Introduced
ssc/utils/headers.py(extract_server_header*) and updated scanners/CLI call sites to use it instead of duplicated logic. - Added
[N/M]batch progress formatting/output and updated README usage docs.
Reviewed changes
Copilot reviewed 24 out of 24 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/init.py | Adds unittest discovery/run documentation for the new test suite. |
| tests/test_utils_network.py | New tests for IP/hostname validation and target parsing. |
| tests/test_utils_headers.py | New tests for shared Server header extraction helpers. |
| tests/test_utils_files.py | New tests for unique output file creation helper. |
| tests/test_signatures.py | New tests for signature/contact placeholder enforcement logic. |
| tests/test_scanners_evidence_collector.py | New tests for evidence collection and evidence strength scoring. |
| tests/test_scanners_cipher_enumerator.py | New tests for cipher classification rules and enumerator structure. |
| tests/test_scanners_backport_detector.py | New tests for backport detection from headers and banners. |
| tests/test_scan_profiles.py | New tests for scan profile resolution and port selection behavior. |
| tests/test_reporters.py | New tests for JSON/Markdown/CSV reporter outputs and batch summaries. |
| tests/test_config.py | New tests for config defaults and save/load roundtrips. |
| tests/test_analyzers_waf_cdn.py | New tests for WAF/CDN detection and prioritization behavior. |
| tests/test_analyzers_server_tokens.py | New tests for Server token parsing and evidence summaries. |
| tests/test_analyzers_security_headers.py | New tests for security header scoring/presence detection. |
| tests/test_analyzers_scan_diff.py | New tests for scan diff snapshot extraction and change detection. |
| tests/test_analyzers_remediation_narrative.py | New tests for remediation narrative generation across scenarios. |
| tests/test_analyzers_cloud_classifier.py | New tests for cloud gateway classification heuristics. |
| ssc/utils/headers.py | Adds shared helpers for extracting Server header from headers/probe structures. |
| ssc/utils/init.py | Exposes the new header helpers via the utils package public API. |
| ssc/scanners/evidence_collector.py | Refactors Server-header extraction to use the shared helper. |
| ssc/scanners/backport_detector.py | Refactors Server-header extraction to use the shared helper. |
| scripts/validate_offline.py | Runs unittest discovery suite and adds a batch progress formatting test. |
| cli.py | Adds batch progress formatter and prints progress with a completion counter. |
| README.md | Documents batch progress behavior and updates batch triage description. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| # Batch shows simple progress as targets complete (e.g. "[3/12] 203.0.113.10 (ok)"); uses only stdlib | ||
| ``` | ||
|
|
||
| Now, also add a short mention in the "Batch triage" use case for completeness. | ||
|
|
| def test_max_length(self): | ||
| # 253 chars total is max for DNS name | ||
| long_but_valid = "a." + ("b." * 60) + "c.com" # construct under limit | ||
| self.assertTrue(is_valid_hostname("a." * 60 + "b.com") or len("a." * 60 + "b.com") > 253) | ||
| # Explicit over limit should fail | ||
| over = "a" * 250 + ".com" | ||
| self.assertFalse(is_valid_hostname(over)) |
| def _format_batch_progress(current: int, total: int, label: str, status: str, log_path: Optional[str] = None) -> str: | ||
| """Format a simple batch progress line (e.g. '[3/12] example.com (ok)').""" | ||
| prefix = f"[+] Batch progress: [{current}/{total}] {label} ({status})" | ||
| if log_path: | ||
| return f"{prefix} log={log_path}" | ||
| return prefix |
| from typing import Any, Dict, List, Optional | ||
|
|
||
|
|
||
| def extract_server_header(headers: Dict[str, List[str]]) -> Optional[str]: | ||
| """Extract Server header value from headers dict (case-insensitive key).""" | ||
| if not headers: | ||
| return None | ||
| for key, values in headers.items(): | ||
| if key.lower() == "server" and values: | ||
| return values[0] | ||
| return None | ||
|
|
||
|
|
||
| def extract_server_header_from_probe(probe: Optional[Dict[str, Any]]) -> Optional[str]: | ||
| """Extract Server header from a full HTTP probe structure. | ||
|
|
||
| Handles the common shape: probe["result"]["final"]["headers"]. | ||
| Returns None for invalid input or missing header. | ||
| """ | ||
| if not isinstance(probe, dict): | ||
| return None | ||
| headers = (probe.get("result") or {}).get("final", {}).get("headers", {}) or {} | ||
| return extract_server_header(headers) |
- README: remove stray editorial text that broke the code block - tests: fix broken max-length hostname test (proper 253 char boundary) - _format_batch_progress: return minimal '[N/M] ...' fragment (caller adds prefix) - extract_server_header: make more defensive (accept Optional[Any], handle str values and non-dicts) - Add more test cases for the header helper robustness
| if not isinstance(probe, dict): | ||
| return None | ||
| headers = (probe.get("result") or {}).get("final", {}).get("headers", {}) or {} | ||
| return extract_server_header(headers) |
There was a problem hiding this comment.
Fixed in commit 2ec7796 — extract_server_header_from_probe now checks each intermediate (result, final) with isinstance(..., dict) and returns None early if any is not a dict, so a None final value is handled safely without raising AttributeError.
| for key, values in headers.items(): | ||
| if key.lower() == "server" and values: | ||
| if isinstance(values, (list, tuple)): | ||
| return str(values[0]) if values else None | ||
| return str(values) |
There was a problem hiding this comment.
Fixed in commit 2ec7796 — extract_server_header now checks isinstance(key, str) and uses continue to skip non-string keys before calling key.lower().
| with progress_lock: | ||
| completed += 1 | ||
| current = completed | ||
|
|
There was a problem hiding this comment.
Fixed in commit 2ec7796 — replaced with progress_lock: completed += 1; current = completed with a plain completed += 1; current = completed since as_completed yields on the main thread and no synchronization is needed.
| results: List[Dict[str, Any]] = [] | ||
| completed = 0 | ||
| total = len(targets) | ||
| progress_lock = threading.Lock() | ||
|
|
There was a problem hiding this comment.
Fixed in commit 2ec7796 — progress_lock = threading.Lock() removed.
| from typing import Dict, Any, List, Optional | ||
| import threading | ||
| from concurrent.futures import ThreadPoolExecutor, as_completed |
There was a problem hiding this comment.
Fixed in commit 2ec7796 — import threading removed.
Summary
tests/package using only stdlibunittest(97+ tests covering analyzers, scanners, utils, reporters, config, etc.). Integrated intoscripts/validate_offline.pyso the existing offline validation command exercises everything.ssc/utils/headers.py(extract_server_header+ probe helper) and updated all call sites.[N/M]progress output duringbatch(e.g.[3/12] 203.0.113.10 (ok)). Thread-safe, no new dependencies.All changes are offline-testable and follow project constraints (stdlib + PyYAML only).
Testing
python scripts/validate_offline.pypasses.Related
Continues work from the cipher enumerator feature.