golang.org/x/tools/gopls@v0.15.3/internal/lsprpc/commandinterceptor_test.go (about) 1 // Copyright 2021 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package lsprpc_test 6 7 import ( 8 "context" 9 "encoding/json" 10 "testing" 11 12 "golang.org/x/tools/gopls/internal/protocol" 13 jsonrpc2_v2 "golang.org/x/tools/internal/jsonrpc2_v2" 14 15 . "golang.org/x/tools/gopls/internal/lsprpc" 16 ) 17 18 func CommandInterceptor(command string, run func(*protocol.ExecuteCommandParams) (interface{}, error)) Middleware { 19 return BindHandler(func(delegate jsonrpc2_v2.Handler) jsonrpc2_v2.Handler { 20 return jsonrpc2_v2.HandlerFunc(func(ctx context.Context, req *jsonrpc2_v2.Request) (interface{}, error) { 21 if req.Method == "workspace/executeCommand" { 22 var params protocol.ExecuteCommandParams 23 if err := json.Unmarshal(req.Params, ¶ms); err == nil { 24 if params.Command == command { 25 return run(¶ms) 26 } 27 } 28 } 29 30 return delegate.Handle(ctx, req) 31 }) 32 }) 33 } 34 35 func TestCommandInterceptor(t *testing.T) { 36 const command = "foo" 37 caught := false 38 intercept := func(_ *protocol.ExecuteCommandParams) (interface{}, error) { 39 caught = true 40 return map[string]interface{}{}, nil 41 } 42 43 ctx := context.Background() 44 env := new(TestEnv) 45 defer env.Shutdown(t) 46 mw := CommandInterceptor(command, intercept) 47 l, _ := env.serve(ctx, t, mw(noopBinder)) 48 conn := env.dial(ctx, t, l.Dialer(), noopBinder, false) 49 50 params := &protocol.ExecuteCommandParams{ 51 Command: command, 52 } 53 var res interface{} 54 err := conn.Call(ctx, "workspace/executeCommand", params).Await(ctx, &res) 55 if err != nil { 56 t.Fatal(err) 57 } 58 if !caught { 59 t.Errorf("workspace/executeCommand was not intercepted") 60 } 61 }