Skip to content

feat: add solid unit tests + batch progress output - #4

Merged
CallMarcus merged 4 commits into
mainfrom
feature/unit-tests
Jul 5, 2026
Merged

CallMarcus merged 4 commits into
mainfrom
feature/unit-tests

Conversation

@CallMarcus

Copy link
Copy Markdown
Owner

Summary

  • Solid unit tests: Added tests/ package using only stdlib unittest (97+ tests covering analyzers, scanners, utils, reporters, config, etc.). Integrated into scripts/validate_offline.py so the existing offline validation command exercises everything.
  • Header deduplication: Extracted repeated Server header logic into ssc/utils/headers.py (extract_server_header + probe helper) and updated all call sites.
  • Batch progress: Simple [N/M] progress output during batch (e.g. [3/12] 203.0.113.10 (ok)). Thread-safe, no new dependencies.
  • Docs: Added note about batch progress in README.

All changes are offline-testable and follow project constraints (stdlib + PyYAML only).

Testing

python scripts/validate_offline.py passes.

Related

Continues work from the cipher enumerator feature.

- 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

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 into scripts/validate_offline.py so 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.

Comment thread README.md
Comment on lines +74 to +78
# 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.

Comment on lines +56 to +62
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))
Comment thread cli.py Outdated
Comment on lines +910 to +915
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
Comment thread ssc/utils/headers.py Outdated
Comment on lines +3 to +25
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

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 24 out of 24 changed files in this pull request and generated 5 comments.

Comment thread ssc/utils/headers.py
Comment on lines +28 to +31
if not isinstance(probe, dict):
return None
headers = (probe.get("result") or {}).get("final", {}).get("headers", {}) or {}
return extract_server_header(headers)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread ssc/utils/headers.py
Comment on lines +14 to +18
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in commit 2ec7796 — extract_server_header now checks isinstance(key, str) and uses continue to skip non-string keys before calling key.lower().

Comment thread cli.py
Comment on lines +1019 to +1022
with progress_lock:
completed += 1
current = completed

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread cli.py
Comment on lines 993 to +997
results: List[Dict[str, Any]] = []
completed = 0
total = len(targets)
progress_lock = threading.Lock()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in commit 2ec7796 — progress_lock = threading.Lock() removed.

Comment thread cli.py
Comment on lines 17 to 19
from typing import Dict, Any, List, Optional
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in commit 2ec7796 — import threading removed.

@CallMarcus
CallMarcus merged commit 818022e into main Jul 5, 2026
3 of 4 checks passed
@CallMarcus
CallMarcus deleted the feature/unit-tests branch July 5, 2026 22:29
Copilot stopped work on behalf of CallMarcus due to an error July 5, 2026 22:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants