Files
cleveragents-core/robot/helper_security_exceptions.py
T
2026-02-25 10:05:57 +00:00

110 lines
2.7 KiB
Python

"""Robot Framework helper for exception handling tests.
Provides a CLI-style interface for Robot to invoke error
classification, redaction, and wrapping.
Usage::
python robot/helper_security_exceptions.py classify <error_type>
python robot/helper_security_exceptions.py redact <key> <value>
python robot/helper_security_exceptions.py wrap <message>
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
# Ensure the src directory is on the import path.
_SRC = str(Path(__file__).resolve().parents[1] / "src")
if _SRC not in sys.path:
sys.path.insert(0, _SRC)
from cleveragents.core.error_handling import ( # noqa: E402
classify_error,
format_error_for_cli,
redact_error_details,
wrap_unexpected,
)
from cleveragents.core.exceptions import ( # noqa: E402
AuthenticationError,
CleverAgentsError,
ConfigurationError,
DatabaseError,
ValidationError,
)
_ERROR_TYPES: dict[str, type[Exception]] = {
"validation": ValidationError,
"auth": AuthenticationError,
"config": ConfigurationError,
"database": DatabaseError,
"bare": Exception,
}
def _cmd_classify(args: list[str]) -> int:
"""Classify an error by type name."""
if len(args) < 1:
print("Usage: classify <error_type>")
return 1
etype = args[0]
exc_cls = _ERROR_TYPES.get(etype, Exception)
exc = exc_cls("test error")
info = classify_error(exc)
output = format_error_for_cli(info)
print(f"exc-classify-ok: code={info.code.value} name={info.code.name}")
print(output)
return 0
def _cmd_redact(args: list[str]) -> int:
"""Redact a key-value pair."""
if len(args) < 2:
print("Usage: redact <key> <value>")
return 1
details = {args[0]: args[1]}
redacted = redact_error_details(details)
print(f"exc-redact-ok: {json.dumps(redacted)}")
return 0
def _cmd_wrap(args: list[str]) -> int:
"""Wrap a bare Exception."""
if len(args) < 1:
print("Usage: wrap <message>")
return 1
exc = Exception(args[0])
wrapped = wrap_unexpected(exc)
is_ca = isinstance(wrapped, CleverAgentsError)
print(f"exc-wrap-ok: is_ca={is_ca} msg={wrapped.message}")
return 0
def main() -> int:
"""Entry point called by Robot Framework ``Run Process``."""
if len(sys.argv) < 2:
print("Usage: helper_security_exceptions.py <command> ...")
return 1
command = sys.argv[1]
args = sys.argv[2:]
dispatch = {
"classify": _cmd_classify,
"redact": _cmd_redact,
"wrap": _cmd_wrap,
}
handler = dispatch.get(command)
if handler is None:
print(f"Unknown command: {command}")
return 1
return handler(args)
if __name__ == "__main__":
sys.exit(main())