package pluginsdk import ( "bufio" "bytes" "context" "encoding/json" "fmt" "io" "sync/atomic" "testing" "time" ) func writeRPCFrame(w io.Writer, v any) error { raw, err := json.Marshal(v) if err != nil { return err } _, err = fmt.Fprintf(w, "Content-Length: %d\r\n\r\n%s", len(raw), raw) return err } func TestServerLocaleHandshakeAndHotUpdate(t *testing.T) { inR, inW := io.Pipe() var outBuf bytes.Buffer srv := NewWithIO(inR, &outBuf) var changedCount atomic.Int32 var lastChangedLocale atomic.Value srv.OnLocaleChanged(func(ev LocaleChangedEvent) { changedCount.Add(1) lastChangedLocale.Store(ev.Locale) }) ctx, cancel := context.WithCancel(context.Background()) defer cancel() done := make(chan error, 1) go func() { done <- srv.Serve(ctx) }() if err := writeRPCFrame(inW, map[string]any{ "jsonrpc": "2.0", "id": 1, "method": "plugin/initialize", "params": map[string]any{ "pluginId": "acme.backup", "pluginApi": "1.0.0", "dataDir": t.TempDir(), "locale": "zh-CN", "fallbackChain": []string{"zh-CN", "en-US"}, "l10nBundle": map[string]string{ "backup.done": "宸插浠?{name}锛堝叡 {count} 椤癸級", "contraction": "Can't open {name}'s disk", }, }, }); err != nil { t.Fatalf("write initialize: %v", err) } deadline := time.Now().Add(2 * time.Second) for srv.InitInfo().PluginID == "" && time.Now().Before(deadline) { time.Sleep(10 * time.Millisecond) } if got := srv.Locale(); got != "zh-CN" { t.Fatalf("Locale() = %q, want zh-CN", got) } if got := srv.T("backup.done", map[string]any{"name": "Sonoma", "count": 3}); got != "宸插浠?Sonoma锛堝叡 3 椤癸級" { t.Fatalf("T(backup.done) = %q", got) } if got := srv.T("contraction", map[string]any{"name": "Sonoma"}); got != "Can't open Sonoma's disk" { t.Fatalf("T(contraction) = %q, want Can't open Sonoma's disk", got) } if got := srv.T("missing.key", nil); got != "missing.key" { t.Fatalf("T(missing.key) = %q, want missing.key", got) } // Broadcast live locale change (notification without id). if err := writeRPCFrame(inW, map[string]any{ "jsonrpc": "2.0", "method": "plugin/localeChanged", "params": map[string]any{ "locale": "ja-JP", "fallbackChain": []string{"ja-JP", "en-US", "zh-CN"}, "l10nBundle": map[string]string{ "backup.done": "{name} 銈掋儛銉冦偗銈儍銉椼仐銇俱仐銇燂紙{count} 浠讹級", }, }, }); err != nil { t.Fatalf("write localeChanged: %v", err) } deadline = time.Now().Add(2 * time.Second) for changedCount.Load() == 0 && time.Now().Before(deadline) { time.Sleep(10 * time.Millisecond) } if changedCount.Load() != 1 || lastChangedLocale.Load() != "ja-JP" { t.Fatalf("expected OnLocaleChanged(ja-JP), count=%d val=%v", changedCount.Load(), lastChangedLocale.Load()) } if got := srv.Locale(); got != "ja-JP" { t.Fatalf("Locale() after update = %q, want ja-JP", got) } if got := srv.T("backup.done", map[string]any{"name": "Sonoma", "count": 3}); got != "Sonoma 銈掋儛銉冦偗銈儍銉椼仐銇俱仐銇燂紙3 浠讹級" { t.Fatalf("T(backup.done) after ja-JP switch = %q", got) } _ = writeRPCFrame(inW, map[string]any{ "jsonrpc": "2.0", "method": "plugin/shutdown", }) _ = inW.Close() if err := <-done; err != nil { t.Fatalf("Serve returned error: %v", err) } } // fakeHost answers one reverse Host API call per entry in replies and sends // each received request on got. func fakeHost(t *testing.T, serverOut *io.PipeReader, serverIn *io.PipeWriter, replies []any, got chan<- envelope) { t.Helper() br := bufio.NewReader(serverOut) for _, result := range replies { frame, err := readFrame(br) if err != nil { t.Errorf("fake host read: %v", err) return } var req envelope if err := json.Unmarshal(frame, &req); err != nil { t.Errorf("fake host decode: %v", err) return } got <- req raw, _ := json.Marshal(result) if err := writeRPCFrame(serverIn, map[string]any{"jsonrpc": "2.0", "id": json.RawMessage(req.ID), "result": json.RawMessage(raw)}); err != nil { t.Errorf("fake host write: %v", err) return } } } func TestRefAwareHostCalls(t *testing.T) { inR, inW := io.Pipe() outR, outW := io.Pipe() srv := NewWithIO(inR, outW) ctx, cancel := context.WithCancel(context.Background()) defer cancel() go func() { _ = srv.Serve(ctx) }() got := make(chan envelope, 8) go fakeHost(t, outR, inW, []any{ map[string]any{"pid": 4242}, map[string]any{"running": true}, nil, nil, }, got) ref := VMRef{DriverID: "acme.driver.lab", Name: "dev"} pid, err := srv.SpawnVMProcessWithRef(ctx, ref, "emulator.exe", []string{"-avd", "dev"}, "", nil) if err != nil || pid != 4242 { t.Fatalf("SpawnVMProcessWithRef = %d, %v", pid, err) } spawn := <-got var sp struct { Ref VMRef `json:"ref"` VMName string `json:"vm_name"` } if spawn.Method != "host/vm.spawn" || json.Unmarshal(spawn.Params, &sp) != nil || sp.Ref != ref || sp.VMName != "dev" { t.Fatalf("spawn request = %s %s", spawn.Method, spawn.Params) } running, err := srv.IsVMProcessRunningByRef(ctx, ref) if err != nil || !running { t.Fatalf("IsVMProcessRunningByRef = %v, %v", running, err) } if req := <-got; req.Method != "host/vm.isRunning" || !bytes.Contains(req.Params, []byte(`"driver_id":"acme.driver.lab"`)) { t.Fatalf("isRunning request = %s %s", req.Method, req.Params) } ready := true report := VMStateReport{Ref: ref, State: "running", Ready: &ready, Endpoints: []VMEndpoint{{Kind: "adb", Serial: "emulator-5554", Ready: true}}, GuestOS: &GuestOSInfo{Family: "android"}} if err := srv.ReportVMState(ctx, report); err != nil { t.Fatalf("ReportVMState: %v", err) } if req := <-got; req.Method != "host/vm.reportState" || !bytes.Contains(req.Params, []byte(`"serial":"emulator-5554"`)) || !bytes.Contains(req.Params, []byte(`"family":"android"`)) { t.Fatalf("reportState request = %s %s", req.Method, req.Params) } if err := srv.StopVMProcessByRef(ctx, ref); err != nil { t.Fatalf("StopVMProcessByRef: %v", err) } if req := <-got; req.Method != "host/vm.stop" || !bytes.Contains(req.Params, []byte(`"ref"`)) { t.Fatalf("stop request = %s %s", req.Method, req.Params) } }