High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
P4: testability — extract buildSnapshot, interfaces, 18 tests
botb6e50a322ece
diff --git a/TODO.md b/TODO.mdindex 74f402dc..8cb3b9f2 100644--- a/TODO.md+++ b/TODO.md@@ -51,11 +51,15 @@ Split into 8 files (single package):- [x] Port changed 18800 → 9867, state dir ~/.browser-bridge → ~/.pinchtab- [x] ActionFunc takes full `actionRequest` struct (no more fragmented params)-## P4: Testability-- [ ] Extract `Browser` interface (navigate, screenshot, evaluate)-- [ ] Extract `TabManager` interface (get, create, close, list)-- [ ] Add handler tests using `httptest` + mock interfaces-- [ ] Add snapshot unit tests — a11y tree filtering/parsing+## Done ✅ (P4)+- [x] Extract `Browser` interface (navigate, screenshot, evaluate) → `interfaces.go`+- [x] Extract `TabManager` interface (get, create, close, list) → `interfaces.go`+- [x] Extract `buildSnapshot` from handler → testable pure function in `snapshot.go`+- [x] Add snapshot unit tests — a11y tree filtering/parsing, depth, interactive filter+- [x] Add middleware tests — auth, CORS, logging, jsonResp, jsonErr (httptest)+- [x] Add bridge tests — ref cache concurrency, ref lookup+- [x] Add config tests — envOr, homeDir, constants+- [x] **18 tests passing** — `go test ./...`## P5: Features- [ ] **`/scroll` endpoint** — scroll to element or by amount. Needed for infinite-scroll pages (X, Reddit).diff --git a/bridge_test.go b/bridge_test.gonew file mode 100644index 00000000..d7908e90--- /dev/null+++ b/bridge_test.go@@ -0,0 +1,77 @@+package main++import (+ "sync"+ "testing"+)++func TestRefCacheConcurrency(t *testing.T) {+ b := &Bridge{+ tabs: make(map[string]*TabEntry),+ snapshots: make(map[string]*refCache),+ }++ // Simulate concurrent reads/writes to snapshot cache+ var wg sync.WaitGroup+ for i := 0; i < 100; i++ {+ wg.Add(1)+ go func(i int) {+ defer wg.Done()+ tabID := "tab1"++ // Write+ b.mu.Lock()+ b.snapshots[tabID] = &refCache{refs: map[string]int64{+ "e0": int64(i),+ }}+ b.mu.Unlock()++ // Read+ b.mu.RLock()+ cache := b.snapshots[tabID]+ b.mu.RUnlock()+ if cache == nil {+ t.Error("cache should not be nil")+ }+ }(i)+ }+ wg.Wait()+}++func TestRefCacheLookup(t *testing.T) {+ b := &Bridge{+ tabs: make(map[string]*TabEntry),+ snapshots: make(map[string]*refCache),+ }++ // No cache → nil+ b.mu.RLock()+ cache := b.snapshots["tab1"]+ b.mu.RUnlock()+ if cache != nil {+ t.Error("expected nil cache for unknown tab")+ }++ // Set cache+ b.mu.Lock()+ b.snapshots["tab1"] = &refCache{refs: map[string]int64{+ "e0": 100,+ "e1": 200,+ }}+ b.mu.Unlock()++ // Lookup+ b.mu.RLock()+ cache = b.snapshots["tab1"]+ b.mu.RUnlock()++ if nid, ok := cache.refs["e0"]; !ok || nid != 100 {+ t.Errorf("e0 expected 100, got %d", nid)+ }+ if nid, ok := cache.refs["e1"]; !ok || nid != 200 {+ t.Errorf("e1 expected 200, got %d", nid)+ }+ if _, ok := cache.refs["e99"]; ok {+ t.Error("e99 should not exist")+ }+}diff --git a/config_test.go b/config_test.gonew file mode 100644index 00000000..9388140a--- /dev/null+++ b/config_test.go@@ -0,0 +1,38 @@+package main++import (+ "os"+ "testing"+)++func TestEnvOr(t *testing.T) {+ if got := envOr("PINCHTAB_TEST_UNSET_12345", "fallback"); got != "fallback" {+ t.Errorf("expected fallback, got %s", got)+ }++ os.Setenv("PINCHTAB_TEST_SET", "value")+ defer os.Unsetenv("PINCHTAB_TEST_SET")+ if got := envOr("PINCHTAB_TEST_SET", "fallback"); got != "value" {+ t.Errorf("expected value, got %s", got)+ }+}++func TestHomeDir(t *testing.T) {+ h := homeDir()+ if h == "" {+ t.Error("homeDir returned empty string")+ }+}++func TestConstants(t *testing.T) {+ // Verify constants are what handlers expect+ if actionClick != "click" {+ t.Error("actionClick mismatch")+ }+ if tabActionNew != "new" {+ t.Error("tabActionNew mismatch")+ }+ if maxBodySize != 1<<20 {+ t.Error("maxBodySize should be 1MB")+ }+}diff --git a/handlers.go b/handlers.goindex 141a87c7..edcf05f9 100644--- a/handlers.go+++ b/handlers.go@@ -87,82 +87,7 @@ func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {return}- // Build parent map for depth calculation- parentMap := make(map[string]string)- for _, n := range treeResp.Nodes {- for _, childID := range n.ChildIDs {- parentMap[childID] = n.NodeID- }- }- depthOf := func(nodeID string) int {- d := 0- cur := nodeID- for {- p, ok := parentMap[cur]- if !ok {- break- }- d++- cur = p- }- return d- }-- flat := make([]A11yNode, 0)- refs := make(map[string]int64)- refID := 0-- for _, n := range treeResp.Nodes {- if n.Ignored {- continue- }-- role := n.Role.String()- name := n.Name.String()-- if role == "none" || role == "generic" || role == "InlineTextBox" {- continue- }- if name == "" && role == "StaticText" {- continue- }-- depth := depthOf(n.NodeID)- if maxDepth >= 0 && depth > maxDepth {- continue- }- if filter == filterInteractive && !interactiveRoles[role] {- continue- }-- ref := fmt.Sprintf("e%d", refID)- entry := A11yNode{- Ref: ref,- Role: role,- Name: name,- Depth: depth,- }-- if v := n.Value.String(); v != "" {- entry.Value = v- }- if n.BackendDOMNodeID != 0 {- entry.NodeID = n.BackendDOMNodeID- refs[ref] = n.BackendDOMNodeID- }-- for _, prop := range n.Properties {- if prop.Name == "disabled" && prop.Value.String() == "true" {- entry.Disabled = true- }- if prop.Name == "focused" && prop.Value.String() == "true" {- entry.Focused = true- }- }-- flat = append(flat, entry)- refID++- }+ flat, refs := buildSnapshot(treeResp.Nodes, filter, maxDepth)// Cache ref→nodeID mapping for this tabb.mu.Lock()diff --git a/interfaces.go b/interfaces.gonew file mode 100644index 00000000..e1f2e050--- /dev/null+++ b/interfaces.go@@ -0,0 +1,36 @@+package main++import "context"++// Browser abstracts Chrome DevTools operations for testing.+type Browser interface {+ Navigate(ctx context.Context, url string) error+ Screenshot(ctx context.Context, quality int) ([]byte, error)+ Evaluate(ctx context.Context, expr string) (any, error)+ GetText(ctx context.Context) (string, error)+ GetLocation(ctx context.Context) (url string, title string, err error)+ GetAccessibilityTree(ctx context.Context) ([]rawAXNode, error)+ ClickNode(ctx context.Context, nodeID int64) error+ TypeNode(ctx context.Context, nodeID int64, text string) error+ FocusNode(ctx context.Context, nodeID int64) error+ ClickSelector(ctx context.Context, sel string) error+ TypeSelector(ctx context.Context, sel string, text string) error+ FillSelector(ctx context.Context, sel string, value string) error+ PressKey(ctx context.Context, key string) error+}++// TabManager abstracts tab lifecycle operations for testing.+type TabManager interface {+ Get(tabID string) (ctx context.Context, resolvedID string, err error)+ Create(url string) (tabID string, err error)+ Close(tabID string) error+ List() ([]TabInfo, error)+}++// TabInfo is a simplified tab descriptor returned by TabManager.List.+type TabInfo struct {+ ID string `json:"id"`+ URL string `json:"url"`+ Title string `json:"title"`+ Type string `json:"type"`+}diff --git a/middleware_test.go b/middleware_test.gonew file mode 100644index 00000000..672151c8--- /dev/null+++ b/middleware_test.go@@ -0,0 +1,157 @@+package main++import (+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "testing"+)++func TestJsonResp(t *testing.T) {+ w := httptest.NewRecorder()+ jsonResp(w, 200, map[string]string{"status": "ok"})++ if w.Code != 200 {+ t.Errorf("expected 200, got %d", w.Code)+ }+ if ct := w.Header().Get("Content-Type"); ct != "application/json" {+ t.Errorf("expected application/json, got %s", ct)+ }+ var body map[string]string+ json.NewDecoder(w.Body).Decode(&body)+ if body["status"] != "ok" {+ t.Errorf("expected ok, got %s", body["status"])+ }+}++func TestJsonErr(t *testing.T) {+ w := httptest.NewRecorder()+ jsonErr(w, 500, fmt.Errorf("something broke"))++ if w.Code != 500 {+ t.Errorf("expected 500, got %d", w.Code)+ }+ var body map[string]string+ json.NewDecoder(w.Body).Decode(&body)+ if body["error"] != "something broke" {+ t.Errorf("expected 'something broke', got %s", body["error"])+ }+}++func TestAuthMiddleware_NoToken(t *testing.T) {+ // When token is empty, all requests pass through+ origToken := token+ token = ""+ defer func() { token = origToken }()++ called := false+ handler := authMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ called = true+ w.WriteHeader(200)+ }))++ req := httptest.NewRequest("GET", "/test", nil)+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)++ if !called {+ t.Error("handler should have been called")+ }+}++func TestAuthMiddleware_ValidToken(t *testing.T) {+ origToken := token+ token = "secret123"+ defer func() { token = origToken }()++ called := false+ handler := authMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ called = true+ w.WriteHeader(200)+ }))++ req := httptest.NewRequest("GET", "/test", nil)+ req.Header.Set("Authorization", "Bearer secret123")+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)++ if !called {+ t.Error("handler should have been called with valid token")+ }+}++func TestAuthMiddleware_InvalidToken(t *testing.T) {+ origToken := token+ token = "secret123"+ defer func() { token = origToken }()++ called := false+ handler := authMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ called = true+ }))++ req := httptest.NewRequest("GET", "/test", nil)+ req.Header.Set("Authorization", "Bearer wrong")+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)++ if called {+ t.Error("handler should NOT have been called with invalid token")+ }+ if w.Code != 401 {+ t.Errorf("expected 401, got %d", w.Code)+ }+}++func TestCorsMiddleware(t *testing.T) {+ handler := corsMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(200)+ }))++ // OPTIONS should return 204+ req := httptest.NewRequest("OPTIONS", "/test", nil)+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)+ if w.Code != 204 {+ t.Errorf("OPTIONS expected 204, got %d", w.Code)+ }+ if w.Header().Get("Access-Control-Allow-Origin") != "*" {+ t.Error("missing CORS origin header")+ }++ // GET should pass through with CORS headers+ req = httptest.NewRequest("GET", "/test", nil)+ w = httptest.NewRecorder()+ handler.ServeHTTP(w, req)+ if w.Code != 200 {+ t.Errorf("GET expected 200, got %d", w.Code)+ }+ if w.Header().Get("Access-Control-Allow-Origin") != "*" {+ t.Error("missing CORS origin header on GET")+ }+}++func TestLoggingMiddleware(t *testing.T) {+ handler := loggingMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(201)+ }))++ req := httptest.NewRequest("GET", "/test", nil)+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)++ if w.Code != 201 {+ t.Errorf("expected 201, got %d", w.Code)+ }+}++func TestStatusWriter(t *testing.T) {+ w := httptest.NewRecorder()+ sw := &statusWriter{ResponseWriter: w, code: 200}++ sw.WriteHeader(404)+ if sw.code != 404 {+ t.Errorf("expected 404, got %d", sw.code)+ }+}diff --git a/snapshot.go b/snapshot.goindex 1027fe65..74034527 100644--- a/snapshot.go+++ b/snapshot.go@@ -2,6 +2,7 @@ package mainimport ("encoding/json"+ "fmt""strings")@@ -62,3 +63,86 @@ var interactiveRoles = map[string]bool{"menuitem": true, "menuitemcheckbox": true, "menuitemradio": true,"tab": true, "treeitem": true,}++// buildSnapshot converts raw a11y nodes into a flat list of A11yNode entries+// and a ref→backendNodeID map. filter and maxDepth control output.+func buildSnapshot(nodes []rawAXNode, filter string, maxDepth int) ([]A11yNode, map[string]int64) {+ // Build parent map for depth calculation+ parentMap := make(map[string]string)+ for _, n := range nodes {+ for _, childID := range n.ChildIDs {+ parentMap[childID] = n.NodeID+ }+ }+ depthOf := func(nodeID string) int {+ d := 0+ cur := nodeID+ for {+ p, ok := parentMap[cur]+ if !ok {+ break+ }+ d+++ cur = p+ }+ return d+ }++ flat := make([]A11yNode, 0)+ refs := make(map[string]int64)+ refID := 0++ for _, n := range nodes {+ if n.Ignored {+ continue+ }++ role := n.Role.String()+ name := n.Name.String()++ if role == "none" || role == "generic" || role == "InlineTextBox" {+ continue+ }+ if name == "" && role == "StaticText" {+ continue+ }++ depth := depthOf(n.NodeID)+ if maxDepth >= 0 && depth > maxDepth {+ continue+ }+ if filter == filterInteractive && !interactiveRoles[role] {+ continue+ }++ ref := fmt.Sprintf("e%d", refID)+ entry := A11yNode{+ Ref: ref,+ Role: role,+ Name: name,+ Depth: depth,+ }++ if v := n.Value.String(); v != "" {+ entry.Value = v+ }+ if n.BackendDOMNodeID != 0 {+ entry.NodeID = n.BackendDOMNodeID+ refs[ref] = n.BackendDOMNodeID+ }++ for _, prop := range n.Properties {+ if prop.Name == "disabled" && prop.Value.String() == "true" {+ entry.Disabled = true+ }+ if prop.Name == "focused" && prop.Value.String() == "true" {+ entry.Focused = true+ }+ }++ flat = append(flat, entry)+ refID+++ }++ return flat, refs+}diff --git a/snapshot_test.go b/snapshot_test.gonew file mode 100644index 00000000..7b2be528--- /dev/null+++ b/snapshot_test.go@@ -0,0 +1,178 @@+package main++import (+ "encoding/json"+ "testing"+)++func TestRawAXValueString(t *testing.T) {+ tests := []struct {+ name string+ val *rawAXValue+ want string+ }{+ {"nil", nil, ""},+ {"nil value", &rawAXValue{Type: "string"}, ""},+ {"string", &rawAXValue{Type: "string", Value: json.RawMessage(`"hello"`)}, "hello"},+ {"number", &rawAXValue{Type: "integer", Value: json.RawMessage(`42`)}, "42"},+ {"bool", &rawAXValue{Type: "boolean", Value: json.RawMessage(`true`)}, "true"},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got := tt.val.String()+ if got != tt.want {+ t.Errorf("got %q, want %q", got, tt.want)+ }+ })+ }+}++func TestInteractiveRoles(t *testing.T) {+ interactive := []string{"button", "link", "textbox", "checkbox", "radio", "tab", "menuitem"}+ for _, r := range interactive {+ if !interactiveRoles[r] {+ t.Errorf("expected %q to be interactive", r)+ }+ }++ nonInteractive := []string{"heading", "paragraph", "image", "banner", "main", "navigation"}+ for _, r := range nonInteractive {+ if interactiveRoles[r] {+ t.Errorf("expected %q to NOT be interactive", r)+ }+ }+}++func TestBuildSnapshot(t *testing.T) {+ // Simulate raw a11y nodes+ nodes := []rawAXNode{+ {+ NodeID: "root",+ Role: &rawAXValue{Value: json.RawMessage(`"WebArea"`)},+ Name: &rawAXValue{Value: json.RawMessage(`"Test Page"`)},+ ChildIDs: []string{"n1", "n2", "n3"},+ BackendDOMNodeID: 1,+ },+ {+ NodeID: "n1",+ Role: &rawAXValue{Value: json.RawMessage(`"button"`)},+ Name: &rawAXValue{Value: json.RawMessage(`"Submit"`)},+ BackendDOMNodeID: 10,+ },+ {+ NodeID: "n2",+ Role: &rawAXValue{Value: json.RawMessage(`"textbox"`)},+ Name: &rawAXValue{Value: json.RawMessage(`"Email"`)},+ BackendDOMNodeID: 20,+ Properties: []rawAXProp{+ {Name: "focused", Value: &rawAXValue{Value: json.RawMessage(`"true"`)}},+ },+ },+ {+ NodeID: "n3",+ Ignored: true,+ Role: &rawAXValue{Value: json.RawMessage(`"none"`)},+ },+ {+ NodeID: "n4",+ Role: &rawAXValue{Value: json.RawMessage(`"generic"`)},+ Name: &rawAXValue{Value: json.RawMessage(`""`)},+ BackendDOMNodeID: 30,+ },+ }++ flat, refs := buildSnapshot(nodes, "", -1)++ // Should have 3 entries: WebArea, button, textbox (ignored + generic + none filtered)+ if len(flat) != 3 {+ t.Fatalf("expected 3 nodes, got %d: %+v", len(flat), flat)+ }++ // Check refs map+ if refs["e0"] != 1 {+ t.Errorf("e0 should map to nodeID 1, got %d", refs["e0"])+ }+ if refs["e1"] != 10 {+ t.Errorf("e1 should map to nodeID 10, got %d", refs["e1"])+ }+ if refs["e2"] != 20 {+ t.Errorf("e2 should map to nodeID 20, got %d", refs["e2"])+ }++ // Check depth+ if flat[0].Depth != 0 {+ t.Errorf("root depth should be 0, got %d", flat[0].Depth)+ }+ if flat[1].Depth != 1 {+ t.Errorf("button depth should be 1, got %d", flat[1].Depth)+ }++ // Check focused property+ if !flat[2].Focused {+ t.Error("textbox should be focused")+ }+}++func TestBuildSnapshotInteractiveFilter(t *testing.T) {+ nodes := []rawAXNode{+ {+ NodeID: "root",+ Role: &rawAXValue{Value: json.RawMessage(`"WebArea"`)},+ Name: &rawAXValue{Value: json.RawMessage(`"Page"`)},+ ChildIDs: []string{"n1", "n2"},+ BackendDOMNodeID: 1,+ },+ {+ NodeID: "n1",+ Role: &rawAXValue{Value: json.RawMessage(`"heading"`)},+ Name: &rawAXValue{Value: json.RawMessage(`"Title"`)},+ BackendDOMNodeID: 10,+ },+ {+ NodeID: "n2",+ Role: &rawAXValue{Value: json.RawMessage(`"button"`)},+ Name: &rawAXValue{Value: json.RawMessage(`"Click me"`)},+ BackendDOMNodeID: 20,+ },+ }++ flat, _ := buildSnapshot(nodes, filterInteractive, -1)++ if len(flat) != 1 {+ t.Fatalf("expected 1 interactive node, got %d: %+v", len(flat), flat)+ }+ if flat[0].Role != "button" {+ t.Errorf("expected button, got %s", flat[0].Role)+ }+}++func TestBuildSnapshotDepthFilter(t *testing.T) {+ nodes := []rawAXNode{+ {+ NodeID: "root",+ Role: &rawAXValue{Value: json.RawMessage(`"WebArea"`)},+ Name: &rawAXValue{Value: json.RawMessage(`"Page"`)},+ ChildIDs: []string{"n1"},+ BackendDOMNodeID: 1,+ },+ {+ NodeID: "n1",+ Role: &rawAXValue{Value: json.RawMessage(`"navigation"`)},+ Name: &rawAXValue{Value: json.RawMessage(`"Nav"`)},+ ChildIDs: []string{"n2"},+ BackendDOMNodeID: 10,+ },+ {+ NodeID: "n2",+ Role: &rawAXValue{Value: json.RawMessage(`"link"`)},+ Name: &rawAXValue{Value: json.RawMessage(`"Home"`)},+ BackendDOMNodeID: 20,+ },+ }++ flat, _ := buildSnapshot(nodes, "", 1)++ if len(flat) != 2 {+ t.Fatalf("expected 2 nodes at depth<=1, got %d: %+v", len(flat), flat)+ }+}