Skip to content

armgit / kong

Public Imported from GitHub
0

The world's first agentic reverse engineer.

refactor tests

Amruth422ff23b061a
diff --git a/kong/agent/deobfuscator.py b/kong/agent/deobfuscator.py
index 3438857..d123dfe 100644
--- a/kong/agent/deobfuscator.py
+++ b/kong/agent/deobfuscator.py
@@ -42,10 +42,6 @@ _PATTERN_FILES: dict[ObfuscationType, str] = {
}
-# -----------------------------------------------------------------------
-# Classification heuristics
-# -----------------------------------------------------------------------
-
_CFF_LOOP_RE = re.compile(
r"while\s*\(\s*(?:1|true)\s*\)\s*\{",
re.IGNORECASE,
@@ -135,10 +131,6 @@ def _detect_vmprotect(code: str) -> bool:
return len(lines) > 200
-# -----------------------------------------------------------------------
-# Pattern library loader
-# -----------------------------------------------------------------------
-
def load_patterns(techniques: list[ObfuscationType]) -> str:
"""Load and concatenate pattern library files for the given techniques."""
parts: list[str] = []
@@ -154,10 +146,6 @@ def load_patterns(techniques: list[ObfuscationType]) -> str:
return "\n\n---\n\n".join(parts)
-# -----------------------------------------------------------------------
-# Deobfuscator
-# -----------------------------------------------------------------------
-
class Deobfuscator:
"""Orchestrates LLM-driven deobfuscation with symbolic tool access.
diff --git a/kong/ghidra/client.py b/kong/ghidra/client.py
index 40237ac..f0809a3 100644
--- a/kong/ghidra/client.py
+++ b/kong/ghidra/client.py
@@ -113,10 +113,6 @@ class GhidraClient:
def __exit__(self, *exc: object) -> None:
self.close()
- # ------------------------------------------------------------------
- # Query methods
- # ------------------------------------------------------------------
-
def get_binary_info(self) -> BinaryInfo:
"""Get metadata about the loaded binary."""
prog = self.program
@@ -279,10 +275,6 @@ class GhidraClient:
)
return entries
- # ------------------------------------------------------------------
- # Mutation methods — wrapped in transactions
- # ------------------------------------------------------------------
-
def rename_function(self, addr: int, new_name: str) -> None:
"""Rename a function at the given address."""
func = self._get_function_at(addr)
@@ -364,10 +356,6 @@ class GhidraClient:
self.program.endTransaction(tx, True)
logger.info("Added %s comment at 0x%08x", comment_type, addr)
- # ------------------------------------------------------------------
- # Type management methods
- # ------------------------------------------------------------------
-
def create_struct(self, definition: StructDefinition) -> None:
"""Create a struct data type in Ghidra's DataTypeManager.
@@ -559,10 +547,6 @@ class GhidraClient:
}
return _SIZED_DEFAULTS.get(size, Undefined4DataType.dataType)
- # ------------------------------------------------------------------
- # Control flow graph methods
- # ------------------------------------------------------------------
-
def get_basic_blocks(self, addr: int) -> list[BasicBlock]:
"""Get basic blocks for the function at addr."""
from ghidra.program.model.block import SimpleBlockModel
@@ -698,10 +682,6 @@ class GhidraClient:
return BlockEdgeType.COMPUTED
return BlockEdgeType.UNKNOWN
- # ------------------------------------------------------------------
- # Helpers
- # ------------------------------------------------------------------
-
def _to_addr(self, addr: int) -> Any:
"""Convert an integer offset to a Ghidra Address."""
return self.program.getAddressFactory().getDefaultAddressSpace().getAddress(addr)
diff --git a/kong/symbolic/simplifier.py b/kong/symbolic/simplifier.py
index 983a254..c63b080 100644
--- a/kong/symbolic/simplifier.py
+++ b/kong/symbolic/simplifier.py
@@ -105,10 +105,6 @@ def _classify_bool(original: str, z3_expr: z3.ExprRef) -> SimplificationResult:
)
-# ---------------------------------------------------------------------------
-# C expression parser → z3 AST
-# ---------------------------------------------------------------------------
-
class _ParseError(Exception):
pass
@@ -334,10 +330,6 @@ class _ExprParser:
raise _ParseError(f"Unknown binary operator: {op}")
-# ---------------------------------------------------------------------------
-# z3 AST → C-like string
-# ---------------------------------------------------------------------------
-
def _z3_to_c(expr: z3.ExprRef) -> str:
"""Best-effort conversion of a z3 expression back to C-like syntax."""
if z3.is_true(expr):
diff --git a/tests/test_agent_queue.py b/tests/test_agent_queue.py
index cc46baf..c993f1f 100644
--- a/tests/test_agent_queue.py
+++ b/tests/test_agent_queue.py
@@ -11,12 +11,6 @@ def _func(addr: int, name: str, size: int = 100, classification: FunctionClassif
class TestWorkQueueBasic:
- def test_empty_queue(self):
- q = WorkQueue()
- assert len(q) == 0
- assert not q
- assert q.next() is None
-
def test_build_simple(self):
funcs = [_func(0x1000, "a"), _func(0x2000, "b"), _func(0x3000, "c")]
q = WorkQueue()
diff --git a/tests/test_agent_supervisor.py b/tests/test_agent_supervisor.py
index 2349123..1a2d998 100644
--- a/tests/test_agent_supervisor.py
+++ b/tests/test_agent_supervisor.py
@@ -256,11 +256,6 @@ class TestAnalysisStats:
stats.confirmed = 1
assert stats.name_rate == 0.75
- def test_name_rate_zero_functions(self):
- stats = AnalysisStats(total_functions=0)
- assert stats.name_rate == 0.0
-
-
class TestSupervisorExport:
def test_export_creates_source_file(self, tmp_path):
funcs = [_func(0x1000, "a")]
diff --git a/tests/test_agent_triage.py b/tests/test_agent_triage.py
index e10afb2..a67be80 100644
--- a/tests/test_agent_triage.py
+++ b/tests/test_agent_triage.py
@@ -30,9 +30,6 @@ def _make_client(functions=None, binary_info=None, strings=None):
return client
-# ── SignatureDB ──────────────────────────────────────────────
-
-
class TestSignatureDB:
def test_load_stdlib(self):
db = SignatureDB()
@@ -110,9 +107,6 @@ class TestSignatureDB:
assert count == 0
-# ── TriageAgent ──────────────────────────────────────────────
-
-
class TestTriageAgent:
def test_run_returns_triage_result(self):
funcs = [_func(0x1000, "a"), _func(0x2000, "b")]
@@ -163,9 +157,6 @@ class TestTriageAgent:
assert result.queue_size == 2
-# ── Language Detection ───────────────────────────────────────
-
-
class TestLanguageDetection:
def test_detect_go(self):
funcs = [
@@ -236,11 +227,6 @@ class TestCallGraph:
)
assert g.edge_count == 1
- def test_empty_graph(self):
- g = CallGraph()
- assert g.edge_count == 0
-
-
class TestTriageResultCounts:
def test_classification_counts(self):
result = TriageResult(
diff --git a/tests/test_deobfuscator.py b/tests/test_deobfuscator.py
index 186061b..50797ce 100644
--- a/tests/test_deobfuscator.py
+++ b/tests/test_deobfuscator.py
@@ -21,10 +21,6 @@ from kong.agent.models import FunctionResult
from kong.ghidra.types import BinaryInfo, FunctionInfo
-# ---------------------------------------------------------------------------
-# Classification heuristic tests
-# ---------------------------------------------------------------------------
-
_CFF_CODE = """\
void FUN_004015a0(int *data, int len) {
int state = 0x3a2b;
@@ -120,9 +116,6 @@ class TestClassifyObfuscation:
assert ObfuscationType.CONTROL_FLOW_FLATTENING in techniques
assert ObfuscationType.BOGUS_CONTROL_FLOW in techniques
- def test_empty_code(self):
- assert classify_obfuscation("") == []
-
def test_vmprotect_needs_many_cases(self):
code = "void dispatch(void) {\n"
code += "while (1) {\n"
@@ -137,10 +130,6 @@ class TestClassifyObfuscation:
assert ObfuscationType.VM_PROTECTION in techniques
-# ---------------------------------------------------------------------------
-# Pattern library tests
-# ---------------------------------------------------------------------------
-
class TestPatternLibrary:
def test_load_cff_pattern(self):
content = load_patterns([ObfuscationType.CONTROL_FLOW_FLATTENING])
@@ -167,14 +156,6 @@ class TestPatternLibrary:
assert "Instruction Substitution" in content
assert "VM-Based Protection" in content
- def test_empty_techniques(self):
- content = load_patterns([])
- assert content == ""
-
-
-# ---------------------------------------------------------------------------
-# Deobfuscator orchestrator tests
-# ---------------------------------------------------------------------------
def _make_context(decompilation: str = "void foo() {}") -> AnalysisContext:
return AnalysisContext(
@@ -257,10 +238,6 @@ class TestDeobfuscator:
assert tools == DEOBFUSCATION_TOOLS
-# ---------------------------------------------------------------------------
-# Integration: Analyzer delegates to Deobfuscator
-# ---------------------------------------------------------------------------
-
class TestAnalyzerDeobfuscationIntegration:
def test_obfuscated_function_delegates(self):
from kong.agent.analyzer import Analyzer
diff --git a/tests/test_export_source.py b/tests/test_export_source.py
index 5ad3298..96c031b 100644
--- a/tests/test_export_source.py
+++ b/tests/test_export_source.py
@@ -93,24 +93,6 @@ def sample_decompilations() -> dict[int, str]:
}
-def test_export_data_instantiation(
- binary_info: BinaryInfo,
- stats: AnalysisStats,
- token_usage: TokenUsage,
-) -> None:
- data = ExportData(
- binary_info=binary_info,
- stats=stats,
- results={},
- decompilations={},
- token_usage=token_usage,
- duration_seconds=42.5,
- )
- assert data.binary_info.name == "test_binary"
- assert data.duration_seconds == 42.5
- assert data.results == {}
-
-
def test_file_creation(
tmp_path: Path,
binary_info: BinaryInfo,
diff --git a/tests/test_ghidra_client.py b/tests/test_ghidra_client.py
index 21d240e..1619872 100644
--- a/tests/test_ghidra_client.py
+++ b/tests/test_ghidra_client.py
@@ -10,10 +10,6 @@ from kong.ghidra.client import GhidraClient, GhidraClientError, _classify
from kong.ghidra.types import FunctionClassification
-# ---------------------------------------------------------------------------
-# Helpers — build mock Java objects
-# ---------------------------------------------------------------------------
-
def _mock_program():
"""Create a mock Ghidra Program with enough methods for client tests."""
prog = MagicMock()
@@ -58,10 +54,6 @@ def _mock_function(addr, name, size, is_thunk=False):
return func
-# ---------------------------------------------------------------------------
-# Fixtures
-# ---------------------------------------------------------------------------
-
@pytest.fixture
def mock_pyghidra():
"""Patch pyghidra.start and pyghidra.open_program."""
@@ -90,15 +82,7 @@ def client(mock_pyghidra, tmp_path):
return c
-# ---------------------------------------------------------------------------
-# Tests
-# ---------------------------------------------------------------------------
-
class TestConnection:
- def test_open_sets_program(self, client):
- assert client._program is not None
- assert client._flat_api is not None
-
def test_close_clears_state(self, client):
client.close()
assert client._program is None
@@ -111,7 +95,7 @@ class TestConnection:
with pytest.raises(GhidraClientError, match="Not open"):
c.program
- def test_open_nonexistent_binary_raises(self, mock_pyghidra):
+ def test_open_nonexistent_binary_raises(self, mock_pyghidra): # noqa: ARG002
c = GhidraClient("/nonexistent/binary")
with pytest.raises(GhidraClientError, match="Binary not found"):
c.open()
diff --git a/tests/test_llm_client.py b/tests/test_llm_client.py
index 18bcd77..2e56965 100644
--- a/tests/test_llm_client.py
+++ b/tests/test_llm_client.py
@@ -133,21 +133,6 @@ class TestAnthropicClient:
assert response.name == ""
assert "Failed to parse" in response.reasoning
- @patch("kong.llm.client.anthropic.Anthropic")
- def test_response_has_token_counts(self, mock_anthropic_cls):
- mock_client = MagicMock()
- mock_anthropic_cls.return_value = mock_client
- mock_client.messages.create.return_value = _mock_message(
- '{"name": "f"}', input_tokens=500, output_tokens=200
- )
-
- client = AnthropicClient(api_key="test-key")
- response = client.analyze_function("prompt")
-
- assert response.input_tokens == 500
- assert response.output_tokens == 200
-
-
class TestModelTokenUsage:
def test_cost_calculation(self):
u = ModelTokenUsage(input_tokens=1_000_000, output_tokens=1_000_000)
diff --git a/tests/test_llm_tools.py b/tests/test_llm_tools.py
index 1b174c2..fd4bc8f 100644
--- a/tests/test_llm_tools.py
+++ b/tests/test_llm_tools.py
@@ -14,10 +14,6 @@ from kong.llm.tools import (
)
-# ---------------------------------------------------------------------------
-# Tool schema tests
-# ---------------------------------------------------------------------------
-
class TestToolSchemas:
def test_all_tools_have_required_fields(self):
for tool in DEOBFUSCATION_TOOLS:
@@ -28,10 +24,6 @@ class TestToolSchemas:
assert "properties" in tool["input_schema"]
assert "required" in tool["input_schema"]
- def test_tool_names_unique(self):
- names = [t["name"] for t in DEOBFUSCATION_TOOLS]
- assert len(names) == len(set(names))
-
def test_expected_tools_present(self):
names = {t["name"] for t in DEOBFUSCATION_TOOLS}
assert "simplify_expression" in names
@@ -42,10 +34,6 @@ class TestToolSchemas:
assert "get_basic_blocks" in names
-# ---------------------------------------------------------------------------
-# ToolExecutor tests
-# ---------------------------------------------------------------------------
-
class TestToolExecutor:
@pytest.fixture
def mock_ghidra(self):
@@ -112,13 +100,6 @@ class TestToolExecutor:
result = executor.execute("nonexistent_tool", {})
assert "Unknown tool" in result
- def test_call_log(self, executor):
- executor.execute("simplify_expression", {"expression": "1 + 2"})
- executor.execute("simplify_expression", {"expression": "3 + 4"})
- assert executor.call_count == 2
- assert executor.call_log[0].tool_name == "simplify_expression"
- assert executor.call_log[1].tool_input["expression"] == "3 + 4"
-
def test_handles_execution_error(self, executor, mock_ghidra):
mock_ghidra.get_decompilation.side_effect = Exception("Ghidra crashed")
result = executor.execute("get_decompilation", {
@@ -128,10 +109,6 @@ class TestToolExecutor:
assert executor.call_count == 1
-# ---------------------------------------------------------------------------
-# Tool use loop tests (mocked Anthropic)
-# ---------------------------------------------------------------------------
-
class TestToolUseLoop:
def _mock_text_message(self, text, input_tokens=100, output_tokens=50):
msg = MagicMock()
diff --git a/tests/test_normalizer.py b/tests/test_normalizer.py
index 63b57a9..10fdcc7 100644
--- a/tests/test_normalizer.py
+++ b/tests/test_normalizer.py
@@ -5,18 +5,6 @@ import pytest
from kong.normalizer.syntactic import normalize
-class TestEmptyAndPassthrough:
- def test_empty_string(self) -> None:
- assert normalize("") == ""
-
- def test_clean_code_unchanged(self) -> None:
- code = "int x = a % 5;\nreturn x + 1;"
- assert normalize(code) == code
-
- def test_whitespace_only(self) -> None:
- assert normalize(" \n\n ") == " \n\n "
-
-
class TestNegativeLiteralCleanup:
def test_simple_plus_negative(self) -> None:
assert normalize("x + -5") == "x - 5"
diff --git a/tests/test_symbolic.py b/tests/test_symbolic.py
index 6b99931..3e589a5 100644
--- a/tests/test_symbolic.py
+++ b/tests/test_symbolic.py
@@ -123,14 +123,6 @@ class TestSimplifierParsing:
result = simplify_expression("1 << 3")
assert result.simplified == "8"
- def test_empty_expression(self):
- result = simplify_expression("")
- assert result.error != ""
-
- def test_invalid_expression(self):
- result = simplify_expression("@#$")
- assert result.error != ""
-
def test_suffix_literal(self):
result = simplify_expression("42u + 0")
assert result.simplified == "42"
@@ -156,10 +148,6 @@ class TestSimplifierParsing:
assert result.predicate_kind == PredicateKind.ALWAYS_TRUE
-# ===================================================================
-# State machine tracer tests
-# ===================================================================
-
def _make_cff_cfg() -> tuple[ControlFlowGraph, list[PcodeOp]]:
"""Build a synthetic CFF control flow graph.
@@ -229,16 +217,6 @@ class TestStateMachineTracer:
result = trace_state_machine_from_cfg(cfg, pcode, "state")
assert result.state_variable == "state"
- def test_wrong_state_var(self):
- cfg, pcode = _make_cff_cfg()
- result = trace_state_machine_from_cfg(cfg, pcode, "nonexistent")
- assert result.error != ""
-
- def test_empty_cfg(self):
- cfg = ControlFlowGraph(function_addr=0x1000)
- result = trace_state_machine_from_cfg(cfg, [], "state")
- assert result.error != ""
-
def test_linear_chains(self):
result = StateMachineResult(
states=[1, 2, 3, 4, 5],
@@ -266,10 +244,6 @@ class TestStateMachineTracer:
assert len(result.transitions_from(3)) == 0
-# ===================================================================
-# Dead code elimination tests
-# ===================================================================
-
class TestDeadCodeElimination:
def test_always_true_removes_else(self):
code = """\
diff --git a/tests/test_tui.py b/tests/test_tui.py
index 5ccedc7..cdef238 100644
--- a/tests/test_tui.py
+++ b/tests/test_tui.py
@@ -2,14 +2,6 @@
from __future__ import annotations
-from unittest.mock import MagicMock, create_autospec
-
-from textual.app import App
-from textual.widgets import Static
-
-from kong.agent.events import Event, EventType
-from kong.agent.supervisor import Supervisor
-from kong.tui.app import EVENT_STYLES, AgentEvent, KongApp
from kong.tui.widgets import BinaryHeader, ProgressWidget, StatusBar
@@ -27,15 +19,6 @@ class TestBinaryHeader:
class TestProgressWidget:
- def test_default_reactive_values(self) -> None:
- widget = ProgressWidget()
- assert widget.phase_name == "Initializing"
- assert widget.completed == 0
- assert widget.total == 0
- assert widget.high == 0
- assert widget.medium == 0
- assert widget.low == 0
-
def test_update_phase(self) -> None:
widget = ProgressWidget()
widget.update_phase("Analysis")
@@ -72,26 +55,3 @@ class TestStatusBar:
assert "PAUSED" in content
-class TestEventStyles:
- def test_event_styles_has_expected_keys(self) -> None:
- expected_keys = {
- EventType.PHASE_START,
- EventType.PHASE_COMPLETE,
- EventType.FUNCTION_COMPLETE,
- EventType.FUNCTION_SKIPPED,
- EventType.FUNCTION_ERROR,
- EventType.RUN_ERROR,
- EventType.RUN_COMPLETE,
- EventType.DEOBFUSCATION_DETECTED,
- EventType.DEOBFUSCATION_COMPLETE,
- EventType.EXPORT_FILE,
- EventType.CLEANUP_TYPE_CREATED,
- }
- assert expected_keys.issubset(EVENT_STYLES.keys())
-
-
-class TestAgentEvent:
- def test_agent_event_wraps_event(self) -> None:
- event = Event(type=EventType.RUN_START, message="test")
- msg = AgentEvent(event)
- assert msg.event is event
diff --git a/tests/test_type_recovery.py b/tests/test_type_recovery.py
index 09e39ed..8dd916d 100644
--- a/tests/test_type_recovery.py
+++ b/tests/test_type_recovery.py
@@ -49,16 +49,7 @@ def _proposal(
)
-# ---------------------------------------------------------------------------
-# StructAccumulator
-# ---------------------------------------------------------------------------
-
class TestStructAccumulator:
- def test_empty_accumulator(self):
- acc = StructAccumulator()
- assert acc.proposal_count == 0
- assert acc.unify() == []
-
def test_add_proposals(self):
acc = StructAccumulator()
acc.add_proposals(0x1000, [
@@ -171,10 +162,6 @@ class TestStructAccumulator:
assert app.struct_name == "conn_t"
-# ---------------------------------------------------------------------------
-# _pick_best_field
-# ---------------------------------------------------------------------------
-
class TestPickBestField:
def test_prefers_descriptive_name(self):
candidates = [
@@ -192,16 +179,6 @@ class TestPickBestField:
best = _pick_best_field(candidates)
assert best.data_type == "int"
- def test_single_candidate(self):
- candidates = [_field("x", "int", 0, 4)]
- best = _pick_best_field(candidates)
- assert best.name == "x"
-
-
-# ---------------------------------------------------------------------------
-# apply_unified_structs
-# ---------------------------------------------------------------------------
-
class TestApplyUnifiedStructs:
def test_creates_structs_and_applies_types(self):
client = MagicMock()
@@ -262,20 +239,6 @@ class TestApplyUnifiedStructs:
affected = apply_unified_structs(client, [us])
assert affected == []
- def test_no_applications(self):
- client = MagicMock()
- us = UnifiedStruct(
- definition=StructDefinition(name="orphan_t", size=16, fields=[]),
- )
- affected = apply_unified_structs(client, [us])
- client.create_struct.assert_called_once()
- assert affected == []
-
-
-# ---------------------------------------------------------------------------
-# _resolve_param_ordinal
-# ---------------------------------------------------------------------------
-
class TestResolveParamOrdinal:
def test_resolves_by_name(self):
client = MagicMock()
@@ -302,10 +265,6 @@ class TestResolveParamOrdinal:
assert _resolve_param_ordinal(client, 0x1000, "param_1") is None
-# ---------------------------------------------------------------------------
-# LLM JSON parsing — struct_proposals
-# ---------------------------------------------------------------------------
-
class TestParseLLMJsonStructs:
def test_parse_with_struct_proposals(self):
raw = '''{
@@ -360,10 +319,6 @@ class TestParseLLMJsonStructs:
assert f.size == 4
-# ---------------------------------------------------------------------------
-# Analyzer context — known types in prompt
-# ---------------------------------------------------------------------------
-
class TestAnalyzerContextTypes:
def test_known_types_included_in_prompt(self):
llm = MagicMock()
@@ -439,10 +394,6 @@ class TestAnalyzerContextTypes:
assert "Known Struct Types" not in prompt
-# ---------------------------------------------------------------------------
-# Analyzer — struct proposals flow through to FunctionResult
-# ---------------------------------------------------------------------------
-
class TestAnalyzerStructProposalPassthrough:
def test_struct_proposals_in_result(self):
response = LLMResponse(
@@ -487,42 +438,6 @@ class TestAnalyzerStructProposalPassthrough:
assert result.struct_proposals[0].name == "req_t"
-# ---------------------------------------------------------------------------
-# Ghidra types dataclasses
-# ---------------------------------------------------------------------------
-
-class TestStructDefinition:
- def test_field_count(self):
- sd = StructDefinition(
- name="test_t", size=16,
- fields=[
- StructField(name="a", data_type="int", offset=0, size=4),
- StructField(name="b", data_type="int", offset=4, size=4),
- ],
- )
- assert sd.field_count == 2
-
- def test_field_at_offset(self):
- sd = StructDefinition(
- name="test_t", size=16,
- fields=[
- StructField(name="a", data_type="int", offset=0, size=4),
- StructField(name="b", data_type="long", offset=8, size=8),
- ],
- )
- assert sd.field_at_offset(0).name == "a"
- assert sd.field_at_offset(8).name == "b"
- assert sd.field_at_offset(4) is None
-
- def test_struct_field_end_offset(self):
- f = StructField(name="x", data_type="int", offset=4, size=4)
- assert f.end_offset == 8
-
-
-# ---------------------------------------------------------------------------
-# Supervisor cleanup integration
-# ---------------------------------------------------------------------------
-
class TestSupervisorCleanupIntegration:
def test_cleanup_with_struct_proposals(self, tmp_path):
from kong.agent.events import EventType, Phase