Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

test: coverage 28% → 34.4% — snapshot, stealth, action dispatch, config, diffSnapshot

L13e7a369dc1e
diff --git a/config.go b/config.go
index 85be83a2..b55bec5d 100644
--- a/config.go
+++ b/config.go
@@ -46,23 +46,23 @@ var stealthScript string
var readabilityJS string
var (
- port = envOr("BRIDGE_PORT", "9867")
- cdpURL = os.Getenv("CDP_URL") // empty = launch Chrome ourselves
- token = os.Getenv("BRIDGE_TOKEN")
- stateDir = envOr("BRIDGE_STATE_DIR", filepath.Join(homeDir(), ".pinchtab"))
- headless = os.Getenv("BRIDGE_HEADLESS") == "true"
- noRestore = os.Getenv("BRIDGE_NO_RESTORE") == "true"
- profileDir = envOr("BRIDGE_PROFILE", filepath.Join(homeDir(), ".pinchtab", "chrome-profile"))
- chromeVersion = envOr("BRIDGE_CHROME_VERSION", "133.0.6943.98")
- timezone = os.Getenv("BRIDGE_TIMEZONE") // e.g. "America/New_York"
- blockImages = os.Getenv("BRIDGE_BLOCK_IMAGES") == "true"
- blockMedia = os.Getenv("BRIDGE_BLOCK_MEDIA") == "true" // superset: images + fonts + CSS + video
- chromeBinary = os.Getenv("CHROME_BINARY") // path to Chrome/Chromium binary
- chromeExtraFlags = os.Getenv("CHROME_FLAGS") // extra flags (space-separated)
- actionTimeout = 15 * time.Second
- navigateTimeout = 30 * time.Second
- shutdownTimeout = 10 * time.Second
- waitNavDelay = 1 * time.Second
+ port = envOr("BRIDGE_PORT", "9867")
+ cdpURL = os.Getenv("CDP_URL") // empty = launch Chrome ourselves
+ token = os.Getenv("BRIDGE_TOKEN")
+ stateDir = envOr("BRIDGE_STATE_DIR", filepath.Join(homeDir(), ".pinchtab"))
+ headless = os.Getenv("BRIDGE_HEADLESS") == "true"
+ noRestore = os.Getenv("BRIDGE_NO_RESTORE") == "true"
+ profileDir = envOr("BRIDGE_PROFILE", filepath.Join(homeDir(), ".pinchtab", "chrome-profile"))
+ chromeVersion = envOr("BRIDGE_CHROME_VERSION", "133.0.6943.98")
+ timezone = os.Getenv("BRIDGE_TIMEZONE") // e.g. "America/New_York"
+ blockImages = os.Getenv("BRIDGE_BLOCK_IMAGES") == "true"
+ blockMedia = os.Getenv("BRIDGE_BLOCK_MEDIA") == "true" // superset: images + fonts + CSS + video
+ chromeBinary = os.Getenv("CHROME_BINARY") // path to Chrome/Chromium binary
+ chromeExtraFlags = os.Getenv("CHROME_FLAGS") // extra flags (space-separated)
+ actionTimeout = 15 * time.Second
+ navigateTimeout = 30 * time.Second
+ shutdownTimeout = 10 * time.Second
+ waitNavDelay = 1 * time.Second
)
func envOr(key, fallback string) string {
diff --git a/handler_stealth_test.go b/handler_stealth_test.go
index 5b1a9d5d..87871297 100644
--- a/handler_stealth_test.go
+++ b/handler_stealth_test.go
@@ -6,7 +6,7 @@ import (
"testing"
)
-func TestHandleStealthStatus_NoTab_Returns200(t *testing.T) {
+func TestHandleStealthStatus_NoTab_ReturnsStatic(t *testing.T) {
b := &Bridge{}
b.tabs = make(map[string]*TabEntry)
req := httptest.NewRequest("GET", "/stealth/status", nil)
@@ -14,23 +14,13 @@ func TestHandleStealthStatus_NoTab_Returns200(t *testing.T) {
b.handleStealthStatus(w, req)
- // With no tab, returns static analysis (200)
if w.Code != 200 {
t.Errorf("expected 200, got %d", w.Code)
}
-}
-
-func TestHandleStealthStatus_NonexistentTab(t *testing.T) {
- b := &Bridge{}
- b.tabs = make(map[string]*TabEntry)
- req := httptest.NewRequest("GET", "/stealth/status?tabId=nonexistent", nil)
- w := httptest.NewRecorder()
-
- b.handleStealthStatus(w, req)
-
- // With explicit nonexistent tabId, still returns static (no tab found falls through)
- if w.Code != 200 {
- t.Errorf("expected 200, got %d", w.Code)
+ // Should contain level and score
+ body := w.Body.String()
+ if !searchString(body, "level") || !searchString(body, "score") {
+ t.Errorf("expected level and score in response, got: %s", body)
}
}
@@ -46,6 +36,8 @@ func TestHandleFingerprintRotate_InvalidJSON(t *testing.T) {
}
}
+// ── generateFingerprint ────────────────────────────────────
+
func TestGenerateFingerprint_Windows(t *testing.T) {
fp := generateFingerprint(fingerprintRequest{OS: "windows"})
if fp.Platform != "Win32" {
@@ -54,51 +46,139 @@ func TestGenerateFingerprint_Windows(t *testing.T) {
if fp.UserAgent == "" {
t.Error("expected non-empty user agent")
}
- if fp.ScreenWidth == 0 {
- t.Error("expected non-zero screen width")
+ if fp.ScreenWidth == 0 || fp.ScreenHeight == 0 {
+ t.Error("expected non-zero screen dimensions")
+ }
+ if fp.Vendor != "Google Inc." {
+ t.Errorf("expected Google Inc., got %q", fp.Vendor)
}
}
-func TestStaticStealthFeatures_HasEntries(t *testing.T) {
- features := staticStealthFeatures()
- if len(features) == 0 {
- t.Error("expected non-empty stealth features map")
+func TestGenerateFingerprint_Mac(t *testing.T) {
+ fp := generateFingerprint(fingerprintRequest{OS: "mac"})
+ if fp.Platform != "MacIntel" {
+ t.Errorf("expected MacIntel, got %q", fp.Platform)
}
}
-func TestGetStealthRecommendations_AllGood(t *testing.T) {
+func TestGenerateFingerprint_Random(t *testing.T) {
+ fp := generateFingerprint(fingerprintRequest{OS: "random"})
+ validPlatforms := map[string]bool{"Win32": true, "MacIntel": true}
+ if !validPlatforms[fp.Platform] {
+ t.Errorf("unexpected platform %q", fp.Platform)
+ }
+}
+
+func TestGenerateFingerprint_UnknownOS(t *testing.T) {
+ // Unknown OS — should return empty fingerprint (no match in map)
+ fp := generateFingerprint(fingerprintRequest{OS: "freebsd"})
+ // Will have screen/language/timezone from random selection below
+ // but platform/UA won't be set from the map
+ _ = fp // just ensure no panic
+}
+
+func TestGenerateFingerprint_WithBrowser(t *testing.T) {
+ fp := generateFingerprint(fingerprintRequest{OS: "windows", Browser: "chrome"})
+ if fp.UserAgent == "" {
+ t.Error("expected non-empty user agent")
+ }
+}
+
+// ── getStealthRecommendations ──────────────────────────────
+
+func TestGetStealthRecommendations_AllEnabled(t *testing.T) {
features := map[string]bool{
- "navigator.webdriver": true,
- "navigator.plugins": true,
- "navigator.languages": true,
- "chrome.runtime": true,
- "permission.notification": true,
+ "user_agent_override": true,
+ "languages_spoofed": true,
+ "webrtc_leak_prevented": true,
+ "timezone_spoofed": true,
+ "canvas_noise": true,
+ "font_spoofing": true,
+ }
+ recs := getStealthRecommendations(features)
+ if len(recs) != 1 || recs[0] != "Stealth mode is well configured" {
+ t.Errorf("expected well-configured message, got %v", recs)
}
+}
+
+func TestGetStealthRecommendations_NoneEnabled(t *testing.T) {
+ features := map[string]bool{}
recs := getStealthRecommendations(features)
- // Recommendations include general hardening tips even when features pass
- if recs == nil {
- t.Error("expected non-nil recommendations slice")
+ if len(recs) != 6 {
+ t.Errorf("expected 6 recommendations, got %d: %v", len(recs), recs)
}
}
-func TestGetStealthRecommendations_MissingFeatures(t *testing.T) {
+func TestGetStealthRecommendations_Partial(t *testing.T) {
features := map[string]bool{
- "navigator.webdriver": false,
+ "user_agent_override": true,
+ "timezone_spoofed": true,
}
recs := getStealthRecommendations(features)
- if len(recs) == 0 {
- t.Error("expected recommendations for missing features")
+ // Should have 4 recommendations (the 4 missing features)
+ if len(recs) != 4 {
+ t.Errorf("expected 4 recommendations, got %d: %v", len(recs), recs)
}
}
-func TestSendStealthResponse(t *testing.T) {
+// ── sendStealthResponse ────────────────────────────────────
+
+func TestSendStealthResponse_HighScore(t *testing.T) {
b := &Bridge{}
- features := map[string]bool{"navigator.webdriver": true}
+ b.tabs = make(map[string]*TabEntry)
+ features := map[string]bool{
+ "a": true, "b": true, "c": true, "d": true, "e": true,
+ }
w := httptest.NewRecorder()
-
b.sendStealthResponse(w, features, "TestAgent/1.0")
if w.Code != 200 {
t.Errorf("expected 200, got %d", w.Code)
}
+ body := w.Body.String()
+ if !searchString(body, `"level":"high"`) {
+ t.Errorf("expected high level for 100%% score, got: %s", body)
+ }
+}
+
+func TestSendStealthResponse_LowScore(t *testing.T) {
+ b := &Bridge{}
+ b.tabs = make(map[string]*TabEntry)
+ features := map[string]bool{
+ "a": true, "b": false, "c": false, "d": false, "e": false,
+ "f": false, "g": false, "h": false, "i": false, "j": false,
+ }
+ w := httptest.NewRecorder()
+ b.sendStealthResponse(w, features, "")
+
+ body := w.Body.String()
+ if !searchString(body, `"level":"minimal"`) {
+ t.Errorf("expected minimal level for 10%% score, got: %s", body)
+ }
+}
+
+func TestSendStealthResponse_MediumScore(t *testing.T) {
+ b := &Bridge{}
+ b.tabs = make(map[string]*TabEntry)
+ // 6/10 = 60%
+ features := map[string]bool{
+ "a": true, "b": true, "c": true, "d": true, "e": true,
+ "f": true, "g": false, "h": false, "i": false, "j": false,
+ }
+ w := httptest.NewRecorder()
+ b.sendStealthResponse(w, features, "")
+
+ body := w.Body.String()
+ if !searchString(body, `"level":"medium"`) {
+ t.Errorf("expected medium level, got: %s", body)
+ }
+}
+
+// ── staticStealthFeatures ──────────────────────────────────
+
+func TestStaticStealthFeatures_HasEntries(t *testing.T) {
+ features := staticStealthFeatures()
+ if len(features) == 0 {
+ t.Error("expected non-empty stealth features map")
+ }
}
diff --git a/handlers_extra_test.go b/handlers_extra_test.go
index 52c3a3b5..275f0c56 100644
--- a/handlers_extra_test.go
+++ b/handlers_extra_test.go
@@ -2,7 +2,10 @@ package main
import (
"bytes"
+ "context"
"net/http/httptest"
+ "os"
+ "path/filepath"
"testing"
"time"
)
@@ -12,9 +15,7 @@ func TestHandleHealth_Response(t *testing.T) {
b.tabs = make(map[string]*TabEntry)
req := httptest.NewRequest("GET", "/health", nil)
w := httptest.NewRecorder()
-
b.handleHealth(w, req)
-
if w.Code != 200 {
t.Errorf("expected 200, got %d", w.Code)
}
@@ -27,9 +28,7 @@ func TestHandleNavigate_InvalidJSON(t *testing.T) {
b := &Bridge{}
req := httptest.NewRequest("POST", "/navigate", bytes.NewReader([]byte(`not json`)))
w := httptest.NewRecorder()
-
b.handleNavigate(w, req)
-
if w.Code != 400 {
t.Errorf("expected 400, got %d", w.Code)
}
@@ -39,9 +38,7 @@ func TestHandleEvaluate_InvalidJSON(t *testing.T) {
b := &Bridge{}
req := httptest.NewRequest("POST", "/evaluate", bytes.NewReader([]byte(`not json`)))
w := httptest.NewRecorder()
-
b.handleEvaluate(w, req)
-
if w.Code != 400 {
t.Errorf("expected 400, got %d", w.Code)
}
@@ -51,9 +48,7 @@ func TestHandleTab_InvalidJSON(t *testing.T) {
b := &Bridge{}
req := httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(`not json`)))
w := httptest.NewRecorder()
-
b.handleTab(w, req)
-
if w.Code != 400 {
t.Errorf("expected 400, got %d", w.Code)
}
@@ -64,24 +59,76 @@ func TestHandleTab_InvalidAction(t *testing.T) {
body := `{"action":"invalid"}`
req := httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(body)))
w := httptest.NewRecorder()
-
b.handleTab(w, req)
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d", w.Code)
+ }
+}
+func TestHandleTab_CloseMissingID(t *testing.T) {
+ b := &Bridge{}
+ body := `{"action":"close"}`
+ req := httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(body)))
+ w := httptest.NewRecorder()
+ b.handleTab(w, req)
if w.Code != 400 {
t.Errorf("expected 400, got %d", w.Code)
}
+ if !searchString(w.Body.String(), "tabId required") {
+ t.Errorf("expected tabId required error, got %s", w.Body.String())
+ }
}
func TestHandleAction_InvalidJSON(t *testing.T) {
b := &Bridge{}
req := httptest.NewRequest("POST", "/action", bytes.NewReader([]byte(`not json`)))
w := httptest.NewRecorder()
+ b.handleAction(w, req)
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d", w.Code)
+ }
+}
+
+func TestHandleAction_RefNotCached(t *testing.T) {
+ b := newBridgeWithFakeTab()
+ body := `{"kind":"click","ref":"e99","tabId":"tab1"}`
+ req := httptest.NewRequest("POST", "/action", bytes.NewReader([]byte(body)))
+ w := httptest.NewRecorder()
+ b.handleAction(w, req)
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d", w.Code)
+ }
+ if !searchString(w.Body.String(), "not found") {
+ t.Errorf("expected 'not found' error, got %s", w.Body.String())
+ }
+}
+func TestHandleAction_MissingKindWithTab(t *testing.T) {
+ b := newBridgeWithFakeTab()
+ body := `{"selector":"#btn","tabId":"tab1"}`
+ req := httptest.NewRequest("POST", "/action", bytes.NewReader([]byte(body)))
+ w := httptest.NewRecorder()
b.handleAction(w, req)
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d", w.Code)
+ }
+ if !searchString(w.Body.String(), "kind") {
+ t.Errorf("expected 'kind' in error, got %s", w.Body.String())
+ }
+}
+func TestHandleAction_UnknownKindWithTab(t *testing.T) {
+ b := newBridgeWithFakeTab()
+ body := `{"kind":"explode","selector":"#btn","tabId":"tab1"}`
+ req := httptest.NewRequest("POST", "/action", bytes.NewReader([]byte(body)))
+ w := httptest.NewRecorder()
+ b.handleAction(w, req)
if w.Code != 400 {
t.Errorf("expected 400, got %d", w.Code)
}
+ if !searchString(w.Body.String(), "unknown action") {
+ t.Errorf("expected 'unknown action' error, got %s", w.Body.String())
+ }
}
func TestHandleShutdown_CallsFunc(t *testing.T) {
@@ -89,21 +136,103 @@ func TestHandleShutdown_CallsFunc(t *testing.T) {
doShutdown := func() { called <- true }
b := &Bridge{}
handler := b.handleShutdown(doShutdown)
-
req := httptest.NewRequest("POST", "/shutdown", nil)
w := httptest.NewRecorder()
-
handler(w, req)
-
if w.Code != 200 {
t.Errorf("expected 200, got %d", w.Code)
}
-
- // Shutdown runs in a goroutine after 100ms
select {
case <-called:
- // ok
case <-time.After(500 * time.Millisecond):
t.Error("expected doShutdown to be called within 500ms")
}
}
+
+// ── Config extra tests ─────────────────────────────────────
+
+func TestLoadConfig_TimeoutFromFile(t *testing.T) {
+ tmp := t.TempDir()
+ cfgPath := filepath.Join(tmp, "config.json")
+ _ = os.WriteFile(cfgPath, []byte(`{"timeout":"25s","navTimeout":"60s"}`), 0644)
+
+ t.Setenv("BRIDGE_CONFIG", cfgPath)
+ t.Setenv("BRIDGE_TIMEOUT", "")
+ t.Setenv("BRIDGE_NAV_TIMEOUT", "")
+
+ origAction := actionTimeout
+ origNav := navigateTimeout
+ defer func() {
+ actionTimeout = origAction
+ navigateTimeout = origNav
+ }()
+
+ loadConfig()
+ // Config uses TimeoutSec/NavigateSec (int seconds), not duration strings
+ // So "25s" won't parse as int — this tests the no-op path
+}
+
+func TestLoadConfig_ConfigFileAllFields(t *testing.T) {
+ tmp := t.TempDir()
+ cfgPath := filepath.Join(tmp, "config.json")
+ cfg := `{
+ "port": "9999",
+ "headless": true,
+ "token": "test-token",
+ "noRestore": true,
+ "timeoutSec": 20,
+ "navigateSec": 45
+ }`
+ _ = os.WriteFile(cfgPath, []byte(cfg), 0644)
+
+ origPort := port
+ origNoRestore := noRestore
+ origToken := token
+ origAction := actionTimeout
+ origNav := navigateTimeout
+ defer func() {
+ port = origPort
+ noRestore = origNoRestore
+ token = origToken
+ actionTimeout = origAction
+ navigateTimeout = origNav
+ }()
+
+ t.Setenv("BRIDGE_CONFIG", cfgPath)
+ t.Setenv("BRIDGE_PORT", "")
+ t.Setenv("BRIDGE_TOKEN", "")
+ t.Setenv("BRIDGE_NO_RESTORE", "")
+ t.Setenv("BRIDGE_TIMEOUT", "")
+ t.Setenv("BRIDGE_NAV_TIMEOUT", "")
+ loadConfig()
+
+ if port != "9999" {
+ t.Errorf("expected port 9999, got %q", port)
+ }
+ if !noRestore {
+ t.Error("expected noRestore true from config")
+ }
+ if token != "test-token" {
+ t.Errorf("expected test-token, got %q", token)
+ }
+ if actionTimeout != 20*time.Second {
+ t.Errorf("expected 20s timeout, got %v", actionTimeout)
+ }
+ if navigateTimeout != 45*time.Second {
+ t.Errorf("expected 45s navTimeout, got %v", navigateTimeout)
+ }
+}
+
+// ── helpers ────────────────────────────────────────────────
+
+// newBridgeWithFakeTab creates a Bridge with a real context.Context tab for testing
+// handler dispatch logic without needing Chrome.
+func newBridgeWithFakeTab() *Bridge {
+ b := &Bridge{}
+ b.tabs = make(map[string]*TabEntry)
+ b.snapshots = make(map[string]*refCache)
+ ctx, cancel := context.WithCancel(context.Background())
+ _ = cancel // leaked intentionally in tests
+ b.tabs["tab1"] = &TabEntry{ctx: ctx, cancel: cancel}
+ return b
+}
diff --git a/snapshot_extra_test.go b/snapshot_extra_test.go
index e89699a3..96c7715f 100644
--- a/snapshot_extra_test.go
+++ b/snapshot_extra_test.go
@@ -2,18 +2,247 @@ package main
import (
"bytes"
+ "encoding/json"
"net/http/httptest"
"testing"
)
+// ── formatSnapshotCompact ──────────────────────────────────
+
+func TestFormatSnapshotCompact_Basic(t *testing.T) {
+ nodes := []A11yNode{
+ {Ref: "e0", Role: "button", Name: "Submit"},
+ {Ref: "e1", Role: "textbox", Name: "Email", Value: "[email protected]"},
+ }
+ got := formatSnapshotCompact(nodes)
+ want := "e0:button \"Submit\"\ne1:textbox \"Email\" val=\"[email protected]\"\n"
+ if got != want {
+ t.Errorf("got:\n%s\nwant:\n%s", got, want)
+ }
+}
+
+func TestFormatSnapshotCompact_FocusedDisabled(t *testing.T) {
+ nodes := []A11yNode{
+ {Ref: "e0", Role: "button", Name: "OK", Focused: true},
+ {Ref: "e1", Role: "button", Name: "Cancel", Disabled: true},
+ {Ref: "e2", Role: "textbox", Focused: true, Disabled: true},
+ }
+ got := formatSnapshotCompact(nodes)
+ if !contains(got, "e0:button \"OK\" *\n") {
+ t.Errorf("expected focused marker *, got:\n%s", got)
+ }
+ if !contains(got, "e1:button \"Cancel\" -\n") {
+ t.Errorf("expected disabled marker -, got:\n%s", got)
+ }
+ if !contains(got, "e2:textbox * -\n") {
+ t.Errorf("expected both markers, got:\n%s", got)
+ }
+}
+
+func TestFormatSnapshotCompact_Empty(t *testing.T) {
+ got := formatSnapshotCompact(nil)
+ if got != "" {
+ t.Errorf("expected empty string, got %q", got)
+ }
+}
+
+func TestFormatSnapshotCompact_NoName(t *testing.T) {
+ nodes := []A11yNode{{Ref: "e0", Role: "generic"}}
+ got := formatSnapshotCompact(nodes)
+ if got != "e0:generic\n" {
+ t.Errorf("got %q", got)
+ }
+}
+
+// ── truncateToTokens ───────────────────────────────────────
+
+func TestTruncateToTokens_NoTruncation(t *testing.T) {
+ nodes := []A11yNode{
+ {Ref: "e0", Role: "button", Name: "OK"},
+ {Ref: "e1", Role: "link", Name: "Home"},
+ }
+ result, truncated := truncateToTokens(nodes, 1000, "compact")
+ if truncated {
+ t.Error("expected no truncation")
+ }
+ if len(result) != 2 {
+ t.Errorf("expected 2 nodes, got %d", len(result))
+ }
+}
+
+func TestTruncateToTokens_Truncates(t *testing.T) {
+ nodes := make([]A11yNode, 100)
+ for i := range nodes {
+ nodes[i] = A11yNode{Ref: "e0", Role: "button", Name: "A long button name here"}
+ }
+ result, truncated := truncateToTokens(nodes, 50, "compact")
+ if !truncated {
+ t.Error("expected truncation")
+ }
+ if len(result) >= 100 {
+ t.Errorf("expected fewer than 100 nodes, got %d", len(result))
+ }
+}
+
+func TestTruncateToTokens_Formats(t *testing.T) {
+ nodes := make([]A11yNode, 50)
+ for i := range nodes {
+ nodes[i] = A11yNode{Ref: "e0", Role: "button", Name: "Click me"}
+ }
+ // JSON format estimates more tokens per node, so should truncate sooner
+ jsonResult, _ := truncateToTokens(nodes, 100, "json")
+ compactResult, _ := truncateToTokens(nodes, 100, "compact")
+ if len(jsonResult) > len(compactResult) {
+ t.Errorf("JSON should truncate sooner: json=%d compact=%d", len(jsonResult), len(compactResult))
+ }
+}
+
+func TestTruncateToTokens_Empty(t *testing.T) {
+ result, truncated := truncateToTokens(nil, 100, "compact")
+ if truncated {
+ t.Error("expected no truncation on empty")
+ }
+ if len(result) != 0 {
+ t.Errorf("expected 0 nodes, got %d", len(result))
+ }
+}
+
+// ── filterSubtree ──────────────────────────────────────────
+
+func TestFilterSubtree_Found(t *testing.T) {
+ nodes := []rawAXNode{
+ {NodeID: "root", BackendDOMNodeID: 1, ChildIDs: []string{"child1", "child2"}},
+ {NodeID: "child1", BackendDOMNodeID: 2, ChildIDs: []string{"grandchild"}},
+ {NodeID: "child2", BackendDOMNodeID: 3},
+ {NodeID: "grandchild", BackendDOMNodeID: 4},
+ {NodeID: "other", BackendDOMNodeID: 5},
+ }
+ // Scope to child1 subtree (should include child1 + grandchild)
+ result := filterSubtree(nodes, 2)
+ if len(result) != 2 {
+ t.Errorf("expected 2 nodes, got %d", len(result))
+ }
+ ids := map[string]bool{}
+ for _, n := range result {
+ ids[n.NodeID] = true
+ }
+ if !ids["child1"] || !ids["grandchild"] {
+ t.Errorf("expected child1 and grandchild, got %v", ids)
+ }
+}
+
+func TestFilterSubtree_NotFound(t *testing.T) {
+ nodes := []rawAXNode{
+ {NodeID: "root", BackendDOMNodeID: 1},
+ {NodeID: "child", BackendDOMNodeID: 2},
+ }
+ // Non-existent scope — returns all nodes
+ result := filterSubtree(nodes, 999)
+ if len(result) != 2 {
+ t.Errorf("expected all nodes returned, got %d", len(result))
+ }
+}
+
+func TestFilterSubtree_RootScope(t *testing.T) {
+ nodes := []rawAXNode{
+ {NodeID: "root", BackendDOMNodeID: 1, ChildIDs: []string{"child"}},
+ {NodeID: "child", BackendDOMNodeID: 2, ChildIDs: []string{"grandchild"}},
+ {NodeID: "grandchild", BackendDOMNodeID: 3},
+ }
+ // Scope to root — should include everything
+ result := filterSubtree(nodes, 1)
+ if len(result) != 3 {
+ t.Errorf("expected 3 nodes, got %d", len(result))
+ }
+}
+
+// ── diffSnapshot ───────────────────────────────────────────
+
+func TestDiffSnapshot_Added(t *testing.T) {
+ prev := []A11yNode{{Ref: "e0", Role: "button", Name: "OK", NodeID: 1}}
+ curr := []A11yNode{
+ {Ref: "e0", Role: "button", Name: "OK", NodeID: 1},
+ {Ref: "e1", Role: "link", Name: "New", NodeID: 2},
+ }
+ added, changed, removed := diffSnapshot(prev, curr)
+ if len(added) != 1 || added[0].Name != "New" {
+ t.Errorf("expected 1 added node, got %v", added)
+ }
+ if len(changed) != 0 {
+ t.Errorf("expected 0 changed, got %d", len(changed))
+ }
+ if len(removed) != 0 {
+ t.Errorf("expected 0 removed, got %d", len(removed))
+ }
+}
+
+func TestDiffSnapshot_Removed(t *testing.T) {
+ prev := []A11yNode{
+ {Ref: "e0", Role: "button", Name: "OK", NodeID: 1},
+ {Ref: "e1", Role: "link", Name: "Old", NodeID: 2},
+ }
+ curr := []A11yNode{{Ref: "e0", Role: "button", Name: "OK", NodeID: 1}}
+ _, _, removed := diffSnapshot(prev, curr)
+ if len(removed) != 1 || removed[0].Name != "Old" {
+ t.Errorf("expected 1 removed node, got %v", removed)
+ }
+}
+
+func TestDiffSnapshot_Changed(t *testing.T) {
+ prev := []A11yNode{{Ref: "e0", Role: "textbox", Name: "Email", NodeID: 1, Value: "old"}}
+ curr := []A11yNode{{Ref: "e0", Role: "textbox", Name: "Email", NodeID: 1, Value: "new"}}
+ _, changed, _ := diffSnapshot(prev, curr)
+ if len(changed) != 1 || changed[0].Value != "new" {
+ t.Errorf("expected 1 changed node, got %v", changed)
+ }
+}
+
+func TestDiffSnapshot_Empty(t *testing.T) {
+ added, changed, removed := diffSnapshot(nil, nil)
+ if len(added)+len(changed)+len(removed) != 0 {
+ t.Error("expected all empty for nil inputs")
+ }
+}
+
+// ── rawAXValue.String ──────────────────────────────────────
+
+func TestRawAXValue_String_Normal(t *testing.T) {
+ v := &rawAXValue{Type: "string", Value: json.RawMessage(`"hello"`)}
+ if got := v.String(); got != "hello" {
+ t.Errorf("expected hello, got %q", got)
+ }
+}
+
+func TestRawAXValue_String_Nil(t *testing.T) {
+ var v *rawAXValue
+ if got := v.String(); got != "" {
+ t.Errorf("expected empty, got %q", got)
+ }
+}
+
+func TestRawAXValue_String_NilValue(t *testing.T) {
+ v := &rawAXValue{Type: "string"}
+ if got := v.String(); got != "" {
+ t.Errorf("expected empty, got %q", got)
+ }
+}
+
+func TestRawAXValue_String_NonString(t *testing.T) {
+ v := &rawAXValue{Type: "number", Value: json.RawMessage(`42`)}
+ // Falls back to trimming quotes
+ if got := v.String(); got != "42" {
+ t.Errorf("expected 42, got %q", got)
+ }
+}
+
+// ── handleSnapshot noTab ───────────────────────────────────
+
func TestHandleSnapshot_InvalidFilter(t *testing.T) {
b := &Bridge{}
b.tabs = make(map[string]*TabEntry)
req := httptest.NewRequest("GET", "/snapshot?filter=bogus", nil)
w := httptest.NewRecorder()
-
b.handleSnapshot(w, req)
-
if w.Code == 0 {
t.Error("expected a response code")
}
@@ -24,9 +253,7 @@ func TestHandleScreenshot_RawParam(t *testing.T) {
b.tabs = make(map[string]*TabEntry)
req := httptest.NewRequest("GET", "/screenshot?raw=true&tabId=nonexistent", nil)
w := httptest.NewRecorder()
-
b.handleScreenshot(w, req)
-
if w.Code != 404 {
t.Errorf("expected 404, got %d", w.Code)
}
@@ -38,9 +265,7 @@ func TestHandleNavigate_WithTimeout(t *testing.T) {
body := `{"url":"https://example.com","timeout":5,"tabId":"nonexistent"}`
req := httptest.NewRequest("POST", "/navigate", bytes.NewReader([]byte(body)))
w := httptest.NewRecorder()
-
b.handleNavigate(w, req)
-
if w.Code != 404 {
t.Errorf("expected 404, got %d", w.Code)
}
@@ -49,14 +274,10 @@ func TestHandleNavigate_WithTimeout(t *testing.T) {
func TestHandleNavigate_WithBlockImages(t *testing.T) {
b := &Bridge{}
b.tabs = make(map[string]*TabEntry)
- tr := true
- _ = tr
body := `{"url":"https://example.com","blockImages":true,"tabId":"nonexistent"}`
req := httptest.NewRequest("POST", "/navigate", bytes.NewReader([]byte(body)))
w := httptest.NewRecorder()
-
b.handleNavigate(w, req)
-
if w.Code != 404 {
t.Errorf("expected 404, got %d", w.Code)
}
@@ -68,10 +289,21 @@ func TestHandleNavigate_WaitTitle(t *testing.T) {
body := `{"url":"https://example.com","waitTitle":true,"tabId":"nonexistent"}`
req := httptest.NewRequest("POST", "/navigate", bytes.NewReader([]byte(body)))
w := httptest.NewRecorder()
-
b.handleNavigate(w, req)
-
if w.Code != 404 && w.Code != 400 {
t.Errorf("expected 404 or 400, got %d", w.Code)
}
}
+
+func contains(s, substr string) bool {
+ return len(s) >= len(substr) && searchString(s, substr)
+}
+
+func searchString(s, substr string) bool {
+ for i := 0; i <= len(s)-len(substr); i++ {
+ if s[i:i+len(substr)] == substr {
+ return true
+ }
+ }
+ return false
+}