-
-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathhandler_migration_test.go
More file actions
291 lines (250 loc) · 8.53 KB
/
Copy pathhandler_migration_test.go
File metadata and controls
291 lines (250 loc) · 8.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
// Copyright 2026 The Go Language Server Authors
// SPDX-License-Identifier: BSD-3-Clause
package protocol
import (
"context"
"errors"
"net"
"sync"
"testing"
"time"
gocmp "github.com/google/go-cmp/cmp"
"go.lsp.dev/jsonrpc2"
)
func newJSONRPCTestStreams(t *testing.T) (jsonrpc2.Conn, jsonrpc2.Stream) {
t.Helper()
serverEnd, clientEnd := net.Pipe()
serverConn := jsonrpc2.NewConn(jsonrpc2.NewStream(serverEnd), jsonrpc2.WithCodec(lspCodec{}))
clientStream := jsonrpc2.NewStream(clientEnd)
t.Cleanup(func() {
if err := clientStream.Close(); err != nil {
t.Logf("close client stream: %v", err)
}
if err := serverConn.Close(); err != nil {
t.Logf("close server conn: %v", err)
}
})
return serverConn, clientStream
}
func TestCancelHandlerCancelsInFlightRequests(t *testing.T) {
tests := map[string]struct {
id jsonrpc2.ID
cancelParams jsonrpc2.RawMessage
}{
"success: numeric id": {
id: jsonrpc2.NewNumberID(7),
cancelParams: jsonrpc2.RawMessage(`{"id":7}`),
},
"success: string id": {
id: jsonrpc2.NewStringID("request-7"),
cancelParams: jsonrpc2.RawMessage(`{"id":"request-7"}`),
},
}
for name, tt := range tests {
t.Run(name, func(t *testing.T) {
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
serverConn, clientStream := newJSONRPCTestStreams(t)
started := make(chan struct{})
canceled := make(chan struct{})
serverConn.Go(ctx, Handlers(func(ctx context.Context, req *jsonrpc2.Request) (any, error) {
if req.Method() != "test/block" {
return nil, jsonrpc2.ErrMethodNotFound
}
close(started)
select {
case <-ctx.Done():
close(canceled)
return nil, ErrRequestCancelled
case <-time.After(2 * time.Second):
return nil, errors.New("request was not canceled")
}
}))
if _, err := clientStream.Write(ctx, jsonrpc2.NewCall(tt.id, "test/block", nil)); err != nil {
t.Fatalf("write blocking call: %v", err)
}
select {
case <-started:
case <-ctx.Done():
t.Fatalf("blocking call did not start: %v", ctx.Err())
}
if _, err := clientStream.Write(ctx, jsonrpc2.NewNotification(MethodCancelRequest, tt.cancelParams)); err != nil {
t.Fatalf("write cancel notification: %v", err)
}
select {
case <-canceled:
case <-ctx.Done():
t.Fatalf("request was not canceled: %v", ctx.Err())
}
msg, _, err := clientStream.Read(ctx)
if err != nil {
t.Fatalf("read canceled response: %v", err)
}
resp, ok := msg.(*jsonrpc2.Response)
if !ok {
t.Fatalf("canceled response type = %T, want *jsonrpc2.Response", msg)
}
if resp.ID() != tt.id {
t.Fatalf("canceled response id = %v, want %v", resp.ID(), tt.id)
}
if err := resp.Err(); !errors.Is(err, ErrRequestCancelled) {
t.Fatalf("canceled response error = %v, want wrapping %v", err, ErrRequestCancelled)
}
})
}
}
func TestCancelHandlerMalformedCancelIDCallReturnsParseError(t *testing.T) {
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
serverConn, clientStream := newJSONRPCTestStreams(t)
serverConn.Go(ctx, Handlers(jsonrpc2.MethodNotFoundHandler))
const callID int64 = 99
if _, err := clientStream.Write(ctx, jsonrpc2.NewCall(
jsonrpc2.NewNumberID(callID),
MethodCancelRequest,
jsonrpc2.RawMessage(`{"id":{}}`),
)); err != nil {
t.Fatalf("write malformed cancel call: %v", err)
}
msg, _, err := clientStream.Read(ctx)
if err != nil {
t.Fatalf("read malformed cancel response: %v", err)
}
resp, ok := msg.(*jsonrpc2.Response)
if !ok {
t.Fatalf("malformed cancel response type = %T, want *jsonrpc2.Response", msg)
}
if resp.ID() != jsonrpc2.NewNumberID(callID) {
t.Fatalf("malformed cancel response id = %v, want %v", resp.ID(), jsonrpc2.NewNumberID(callID))
}
if err := resp.Err(); !errors.Is(err, jsonrpc2.ErrParse) {
t.Fatalf("malformed cancel response error = %v, want wrapping %v", err, jsonrpc2.ErrParse)
}
}
func TestCancelHandlerMalformedCancelIDNotificationFailsConnection(t *testing.T) {
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
serverConn, clientStream := newJSONRPCTestStreams(t)
serverConn.Go(ctx, Handlers(jsonrpc2.MethodNotFoundHandler))
if _, err := clientStream.Write(ctx, jsonrpc2.NewNotification(
MethodCancelRequest,
jsonrpc2.RawMessage(`{"id":{}}`),
)); err != nil {
t.Fatalf("write malformed cancel notification: %v", err)
}
select {
case <-serverConn.Done():
case <-ctx.Done():
t.Fatalf("server connection did not fail for malformed cancel notification: %v", ctx.Err())
}
if err := serverConn.Err(); !errors.Is(err, jsonrpc2.ErrParse) {
t.Fatalf("server connection error = %v, want wrapping %v", err, jsonrpc2.ErrParse)
}
}
type fallbackRecord struct {
method string
params LSPAny
}
type fallbackRecordingServer struct {
UnimplementedServer
mu sync.Mutex
records []fallbackRecord
standardHits int
}
func (s *fallbackRecordingServer) Request(_ context.Context, method string, params any) (any, error) {
s.mu.Lock()
defer s.mu.Unlock()
record := fallbackRecord{method: method}
if p, ok := params.(LSPAny); ok {
// Store the LSPAny as received from production ServerHandler. This avoids
// hiding aliasing problems behind a test-double copy.
record.params = p
}
s.records = append(s.records, record)
// Server.Request contract: (nil, nil) is the valid "no result, no error"
// fallback return.
return nil, nil
}
func (s *fallbackRecordingServer) DidOpen(_ context.Context, _ *DidOpenTextDocumentParams) error {
s.mu.Lock()
defer s.mu.Unlock()
s.standardHits++
return nil
}
func TestServerHandlerCustomFallbackRetainsOwnedMethodAndParams(t *testing.T) {
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
serverEnd, clientEnd := net.Pipe()
server := &fallbackRecordingServer{}
_, serverConn, _ := NewServer(ctx, server, jsonrpc2.NewStream(serverEnd))
clientStream := jsonrpc2.NewStream(clientEnd)
t.Cleanup(func() {
if err := clientStream.Close(); err != nil {
t.Logf("close client stream: %v", err)
}
if err := serverConn.Close(); err != nil {
t.Logf("close server conn: %v", err)
}
})
firstMethod := "workspace/x-custom-first"
firstParams := jsonrpc2.RawMessage(`{"marker":1,"nested":{"ok":true}}`)
wantFirstParams := append(LSPAny(nil), firstParams...)
if _, err := clientStream.Write(ctx, jsonrpc2.NewCall(jsonrpc2.NewNumberID(1), firstMethod, firstParams)); err != nil {
t.Fatalf("write first custom call: %v", err)
}
if _, _, err := clientStream.Read(ctx); err != nil {
t.Fatalf("read first custom response: %v", err)
}
// The custom fallback may retain method/params beyond handler return. Mutate
// the caller-owned request bytes and then process more traffic to pin that
// ServerHandler cloned/unmarshaled borrowed jsonrpc2 data before user handoff.
for i := range firstParams {
firstParams[i] = 'x'
}
secondMethod := "workspace/x-custom-second-after-reuse"
secondParams := jsonrpc2.RawMessage(`{"marker":2,"nested":{"ok":false},"items":[1,2,3]}`)
wantSecondParams := append(LSPAny(nil), secondParams...)
if _, err := clientStream.Write(ctx, jsonrpc2.NewCall(jsonrpc2.NewNumberID(2), secondMethod, secondParams)); err != nil {
t.Fatalf("write second custom call: %v", err)
}
if _, _, err := clientStream.Read(ctx); err != nil {
t.Fatalf("read second custom response: %v", err)
}
standardParams, err := Marshal(&DidOpenTextDocumentParams{
TextDocument: TextDocumentItem{
URI: "file:///fallback.go",
LanguageID: "go",
Version: 1,
Text: "package fallback",
},
})
if err != nil {
t.Fatalf("marshal didOpen params: %v", err)
}
if _, err := clientStream.Write(ctx, jsonrpc2.NewNotification(MethodTextDocumentDidOpen, standardParams)); err != nil {
t.Fatalf("write standard notification: %v", err)
}
deadline := time.After(2 * time.Second)
for {
server.mu.Lock()
records := make([]fallbackRecord, len(server.records))
copy(records, server.records)
standardHits := server.standardHits
server.mu.Unlock()
if len(records) == 2 && standardHits == 1 {
wantRecords := []fallbackRecord{
{method: firstMethod, params: wantFirstParams},
{method: secondMethod, params: wantSecondParams},
}
if diff := gocmp.Diff(wantRecords, records, gocmp.AllowUnexported(fallbackRecord{})); diff != "" {
t.Fatalf("fallback records mismatch (-want +got):\n%s", diff)
}
return
}
select {
case <-deadline:
t.Fatalf("server hits = fallback:%d standard:%d, want fallback:2 standard:1", len(records), standardHits)
case <-time.After(10 * time.Millisecond):
}
}
}