forked from eclipse-lsp4e/lsp4e
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLanguageServersTest.java
More file actions
823 lines (679 loc) · 34 KB
/
LanguageServersTest.java
File metadata and controls
823 lines (679 loc) · 34 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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
/*******************************************************************************
* Copyright (c) 2022-3 Cocotec Ltd and others.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Ahmed Hussain (Cocotec Ltd) - initial implementation
*
*******************************************************************************/
package org.eclipse.lsp4e.test;
import static org.eclipse.lsp4e.LanguageServiceAccessor.hasActiveLanguageServers;
import static org.eclipse.lsp4e.test.utils.TestUtils.createUniqueTestFile;
import static org.eclipse.lsp4e.test.utils.TestUtils.openEditor;
import static org.eclipse.lsp4e.test.utils.TestUtils.waitForCondition;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Vector;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;
import org.eclipse.core.resources.IFile;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.lsp4e.LanguageServerWrapper;
import org.eclipse.lsp4e.LanguageServers;
import org.eclipse.lsp4e.LanguageServers.LanguageServerDocumentExecutor;
import org.eclipse.lsp4e.internal.Pair;
import org.eclipse.lsp4e.test.utils.AbstractTestWithProject;
import org.eclipse.lsp4e.test.utils.TestUtils;
import org.eclipse.lsp4e.tests.mock.MockConnectionProvider;
import org.eclipse.lsp4e.tests.mock.MockLanguageServer;
import org.eclipse.lsp4e.tests.mock.MockTextDocumentService;
import org.eclipse.lsp4j.DidChangeTextDocumentParams;
import org.eclipse.lsp4j.Hover;
import org.eclipse.lsp4j.HoverParams;
import org.eclipse.lsp4j.Location;
import org.eclipse.lsp4j.Position;
import org.eclipse.lsp4j.Range;
import org.eclipse.lsp4j.ReferenceParams;
import org.eclipse.lsp4j.ServerCapabilities;
import org.eclipse.lsp4j.TextDocumentSyncKind;
import org.eclipse.lsp4j.jsonrpc.messages.Either;
import org.eclipse.lsp4j.services.LanguageServer;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.tests.harness.util.DisplayHelper;
import org.junit.jupiter.api.Test;
public class LanguageServersTest extends AbstractTestWithProject {
private final Predicate<ServerCapabilities> MATCH_ALL = sc -> true;
@Test
public void testCollectAll() throws Exception {
final var hoverCount = new AtomicInteger();
MockLanguageServer.INSTANCE.setTextDocumentService(new MockTextDocumentService(MockLanguageServer.INSTANCE::buildMaybeDelayedFuture) {
@Override
public synchronized void didChange(DidChangeTextDocumentParams params) {
super.didChange(params);
}
@Override
public synchronized CompletableFuture<Hover> hover(HoverParams position) {
final var hoverResponse = new Hover(List.of(Either.forLeft("HoverContent" + hoverCount.incrementAndGet())), new Range(new Position(0, 0), new Position(0, 10)));
return CompletableFuture.completedFuture(hoverResponse);
}
});
IFile testFile = TestUtils.createUniqueTestFileMultiLS(project, "Here is some content");
ITextViewer viewer = TestUtils.openTextViewer(testFile);
final IDocument document = viewer.getDocument();
final var params = new HoverParams();
final var position = new Position();
position.setCharacter(10);
position.setLine(0);
params.setPosition(position);
CompletableFuture<List<String>> result = LanguageServers.forDocument(document)
.withCapability(ServerCapabilities::getHoverProvider)
.collectAll(ls -> ls.getTextDocumentService().hover(params).thenApply(h -> h.getContents().getLeft().get(0).getLeft()));
List<String> hovers = result.join();
assertTrue(hovers.contains("HoverContent1"));
assertTrue(hovers.contains("HoverContent2"));
}
@Test
public void testCollectAllExcludesNulls() throws Exception {
final var hoverCount = new AtomicInteger();
MockLanguageServer.INSTANCE.setTextDocumentService(new MockTextDocumentService(MockLanguageServer.INSTANCE::buildMaybeDelayedFuture) {
@Override
public synchronized void didChange(DidChangeTextDocumentParams params) {
super.didChange(params);
}
@Override
public synchronized CompletableFuture<Hover> hover(HoverParams position) {
final var hoverResponse = new Hover(List.of(Either.forLeft("HoverContent" + hoverCount.incrementAndGet())), new Range(new Position(0, 0), new Position(0, 10)));
return CompletableFuture.completedFuture(hoverCount.get() == 1 ? hoverResponse : null);
}
});
IFile testFile = TestUtils.createUniqueTestFileMultiLS(project, "Here is some content");
ITextViewer viewer = TestUtils.openTextViewer(testFile);
final IDocument document = viewer.getDocument();
final var params = new HoverParams();
final var position = new Position();
position.setCharacter(10);
position.setLine(0);
params.setPosition(position);
CompletableFuture<List<String>> result = LanguageServers.forDocument(document)
.withCapability(ServerCapabilities::getHoverProvider)
.collectAll(ls -> ls.getTextDocumentService().hover(params).thenApply(h -> h == null ? null : h.getContents().getLeft().get(0).getLeft()));
List<String> hovers = result.join();
assertTrue(hovers.contains("HoverContent1"));
assertFalse(hovers.contains(null));
}
@Test
public void testComputeAll() throws Exception {
final var hoverCount = new AtomicInteger();
MockLanguageServer.INSTANCE.setTextDocumentService(new MockTextDocumentService(MockLanguageServer.INSTANCE::buildMaybeDelayedFuture) {
@Override
public synchronized void didChange(DidChangeTextDocumentParams params) {
super.didChange(params);
}
@Override
public synchronized CompletableFuture<Hover> hover(HoverParams position) {
final var hoverResponse = new Hover(List.of(Either.forLeft("HoverContent" + hoverCount.incrementAndGet())), new Range(new Position(0, 0), new Position(0, 10)));
final int currentCount = hoverCount.get();
return CompletableFuture.completedFuture(hoverResponse).thenApplyAsync(t -> {
try {
Thread.sleep(currentCount * 1000);
} catch (InterruptedException e) {
}
return t;
});
}
});
IFile testFile = TestUtils.createUniqueTestFileMultiLS(project, "Here is some content");
ITextViewer viewer = TestUtils.openTextViewer(testFile);
final IDocument document = viewer.getDocument();
final var params = new HoverParams();
final var position = new Position();
position.setCharacter(10);
position.setLine(0);
params.setPosition(position);
List<CompletableFuture<String>> result = LanguageServers.forDocument(document)
.withCapability(ServerCapabilities::getHoverProvider)
.computeAll(ls -> ls.getTextDocumentService().hover(params).thenApply(h -> h.getContents().getLeft().get(0).getLeft()));
assertEquals(2, result.size(), "Should have had two responses");
final Object first = CompletableFuture.anyOf(result.get(0), result.get(1)).join();
assertEquals("HoverContent1", first, "HoverContent1 should have returned first, independently");
List<String> hovers = result.stream().map(CompletableFuture::join).toList();
assertTrue(hovers.contains("HoverContent1"));
assertTrue(hovers.contains("HoverContent2"));
}
/**
* The raw CompletableFuture objects returned by the LSP4j layer receive their results on a dedicated listener thread which just reads responses
* from the LS output stream and dispatches them synchronously. If we compose work synchronously onto those objects then that work has
* to be done by the listener thread, which will tie it up and prevent it reading more messages. The LSExecutor API prevents the user from doing
* this by chaining <code>.thenApplyAsync(Function.identiy())</code> onto the raw objects, so that any extra work the user appends will
* run in the default executor pool, not the listener thread.
*/
@Test
public void testCollectAllUserCannotBlockListener() throws Exception {
// This test will only work if a minimum of two tasks can be run in the common pool without blocking!
assumeTrue(ForkJoinPool.commonPool().getParallelism() >= 2, "Test skipped as common thread pool does not have multiple executors");
final var hoverResponse = new Hover(List.of(Either.forLeft("HoverContent")), new Range(new Position(0, 0), new Position(0, 10)));
MockLanguageServer.INSTANCE.setHover(hoverResponse);
IFile testFile = TestUtils.createUniqueTestFile(project, "Here is some content");
ITextViewer viewer = TestUtils.openTextViewer(testFile);
final IDocument document = viewer.getDocument();
final var params = new HoverParams();
final var position = new Position();
position.setCharacter(10);
position.setLine(0);
params.setPosition(position);
final long startTime = System.currentTimeMillis();
CompletableFuture<String> resultThreadFuture = LanguageServers.forDocument(document)
.withCapability(ServerCapabilities::getHoverProvider)
.collectAll(ls -> ls.getTextDocumentService().hover(params))
// Schedule a slow 'computation' on the response, and make a note of the thread it runs in
.thenApply(hoverResult -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
return Thread.currentThread().getName();
});
CompletableFuture<?> fastHover = LanguageServers.forDocument(document)
.withCapability(ServerCapabilities::getHoverProvider)
.collectAll(ls -> ls.getTextDocumentService().hover(params));
fastHover.join();
final long secondResponseTime = System.currentTimeMillis() - startTime;
final String resultThread = resultThreadFuture.join();
assertTrue(secondResponseTime < 1000, "Second hover response should not have been blocked by the first but took " + secondResponseTime + " ms");
assertTrue(!resultThread.startsWith("LS"), "Result should not have run on an LS listener thread but ran on " + resultThread);
}
@Test
public void testComputeFirst() throws Exception {
final var hoverCount = new AtomicInteger();
final var internalResults = new Vector<CompletableFuture<?>>();
MockLanguageServer.INSTANCE.setTextDocumentService(new MockTextDocumentService(MockLanguageServer.INSTANCE::buildMaybeDelayedFuture) {
@Override
public synchronized void didChange(DidChangeTextDocumentParams params) {
super.didChange(params);
}
@Override
public synchronized CompletableFuture<Hover> hover(HoverParams position) {
final var hoverResponse = new Hover(List.of(Either.forLeft("HoverContent" + hoverCount.incrementAndGet())), new Range(new Position(0, 0), new Position(0, 10)));
final int currentCount = hoverCount.get();
CompletableFuture<Hover> result = CompletableFuture.completedFuture(hoverResponse).thenApplyAsync(t -> {
try {
Thread.sleep(currentCount * 1000);
} catch (InterruptedException e) {
}
return t;
});
internalResults.add(result);
return result;
}
});
IFile testFile = TestUtils.createUniqueTestFileMultiLS(project, "Here is some content");
ITextViewer viewer = TestUtils.openTextViewer(testFile);
final IDocument document = viewer.getDocument();
final var params = new HoverParams();
final var position = new Position();
position.setCharacter(10);
position.setLine(0);
params.setPosition(position);
CompletableFuture<Optional<String>> response = LanguageServers.forDocument(document)
.withCapability(ServerCapabilities::getHoverProvider)
.computeFirst(ls -> ls.getTextDocumentService().hover(params).thenApply(h -> h.getContents().getLeft().get(0).getLeft()));
Optional<String> result = response.join();
assertTrue(result.isPresent());
assertEquals("HoverContent1", result.get(), "HoverContent1 should have arrived first");
// It won't *normally) matter in production but because the tests run quickly, make sure the test teardown doesn't
// occur before the slower, ignored result has completed, otherwise will get a load of console noise
internalResults.forEach(CompletableFuture::join);
}
@Test
public void testComputeFirstSkipsEmptyResults() throws Exception {
final var hoverCount = new AtomicInteger();
MockLanguageServer.INSTANCE.setTextDocumentService(new MockTextDocumentService(MockLanguageServer.INSTANCE::buildMaybeDelayedFuture) {
@Override
public synchronized void didChange(DidChangeTextDocumentParams params) {
super.didChange(params);
}
@Override
public synchronized CompletableFuture<Hover> hover(HoverParams position) {
final var hoverResponse = new Hover(List.of(Either.forLeft("HoverContent" + hoverCount.incrementAndGet())), new Range(new Position(0, 0), new Position(0, 10)));
if (hoverCount.get() == 1) {
return CompletableFuture.completedFuture(null);
}
return CompletableFuture.completedFuture(hoverResponse).thenApplyAsync(t -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
return t;
});
}
});
IFile testFile = TestUtils.createUniqueTestFileMultiLS(project, "Here is some content");
ITextViewer viewer = TestUtils.openTextViewer(testFile);
final IDocument document = viewer.getDocument();
final var params = new HoverParams();
final var position = new Position();
position.setCharacter(10);
position.setLine(0);
params.setPosition(position);
CompletableFuture<Optional<String>> response = LanguageServers.forDocument(document)
.withCapability(ServerCapabilities::getHoverProvider)
.computeFirst(ls -> ls.getTextDocumentService().hover(params).thenApply(h -> h == null ? null : h.getContents().getLeft().get(0).getLeft()));
Optional<String> result = response.join();
assertTrue(result.isPresent(), "Should have returned a result");
assertEquals("HoverContent2", result.get(), "HoverContent2 should have been the result");
}
@Test
public void testComputeFirstReturnsEmptyOptionalIfNoResult() throws Exception {
MockLanguageServer.INSTANCE.setTextDocumentService(new MockTextDocumentService(MockLanguageServer.INSTANCE::buildMaybeDelayedFuture) {
@Override
public synchronized void didChange(DidChangeTextDocumentParams params) {
super.didChange(params);
}
@Override
public synchronized CompletableFuture<Hover> hover(HoverParams position) {
return CompletableFuture.completedFuture(null);
}
});
IFile testFile = TestUtils.createUniqueTestFileMultiLS(project, "Here is some content");
ITextViewer viewer = TestUtils.openTextViewer(testFile);
final IDocument document = viewer.getDocument();
final var params = new HoverParams();
final var position = new Position();
position.setCharacter(10);
position.setLine(0);
params.setPosition(position);
CompletableFuture<Optional<String>> response = LanguageServers.forDocument(document)
.withCapability(ServerCapabilities::getHoverProvider)
.computeFirst(ls -> ls.getTextDocumentService().hover(params).thenApply(h -> h == null ? null : h.getContents().getLeft().get(0).getLeft()));
Optional<String> result = response.join();
assertTrue(result.isEmpty(), "Should not have returned a result");
}
@Test
public void testComputeFirstTreatsEmptyListAsNull() throws Exception {
final var hoverCount = new AtomicInteger();
MockLanguageServer.INSTANCE.setTextDocumentService(new MockTextDocumentService(MockLanguageServer.INSTANCE::buildMaybeDelayedFuture) {
@Override
public synchronized void didChange(DidChangeTextDocumentParams params) {
super.didChange(params);
}
@Override
public synchronized CompletableFuture<Hover> hover(HoverParams position) {
final var hoverResponse = new Hover(List.of(Either.forLeft("HoverContent" + hoverCount.incrementAndGet())), new Range(new Position(0, 0), new Position(0, 10)));
if (hoverCount.get() == 1) {
return CompletableFuture.completedFuture(null);
}
return CompletableFuture.completedFuture(hoverResponse).thenApplyAsync(t -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
return t;
});
}
});
IFile testFile = TestUtils.createUniqueTestFileMultiLS(project, "Here is some content");
ITextViewer viewer = TestUtils.openTextViewer(testFile);
final IDocument document = viewer.getDocument();
final var params = new HoverParams();
final var position = new Position();
position.setCharacter(10);
position.setLine(0);
params.setPosition(position);
CompletableFuture<Optional<List<String>>> response = LanguageServers.forDocument(document)
.withCapability(ServerCapabilities::getHoverProvider)
.computeFirst(ls -> ls.getTextDocumentService().hover(params).thenApply(h -> h == null ? Collections.emptyList() : List.of(h.getContents().getLeft().get(0).getLeft())));
Optional<List<String>> result = response.join();
assertTrue(result.isPresent(), "Should have returned a result");
assertEquals("HoverContent2", result.get().get(0), "HoverContent2 should have been the result");
}
/**
* Sends a (large) series of alternating document updates and hover requests, checking that the
* ordering of events on the client side is correctly reflected in the order in which the messages
* arrive [are sent to] the server
*/
@Test
public void editInterleavingTortureTest() throws Exception {
final Vector<Integer> tooEarlyHover = new Vector<>();
final Vector<Integer> tooLateHover = new Vector<>();
MockLanguageServer.INSTANCE.getInitializeResult().getCapabilities()
.setTextDocumentSync(TextDocumentSyncKind.Incremental);
MockLanguageServer.INSTANCE.setTextDocumentService(new MockTextDocumentService(MockLanguageServer.INSTANCE::buildMaybeDelayedFuture) {
int changeVersion = 0;
@Override
public synchronized void didChange(DidChangeTextDocumentParams params) {
super.didChange(params);
changeVersion++;
}
@Override
public synchronized CompletableFuture<Hover> hover(HoverParams position) {
final int targetVersionForRequest = position.getPosition().getCharacter();
if (targetVersionForRequest < changeVersion) {
tooLateHover.add(targetVersionForRequest);
} else if (targetVersionForRequest > changeVersion){
tooEarlyHover.add(targetVersionForRequest);
}
return super.hover(position);
}
});
final var hoverResponse = new Hover(List.of(Either.forLeft("HoverContent")), new Range(new Position(0, 0), new Position(0, 10)));
MockLanguageServer.INSTANCE.setHover(hoverResponse);
CompletableFuture<?> initial = CompletableFuture.completedFuture(null);
IFile testFile = TestUtils.createUniqueTestFile(project, "");
ITextViewer viewer = TestUtils.openTextViewer(testFile);
final IDocument document = viewer.getDocument();
StyledText text = viewer.getTextWidget();
Thread.sleep(1000);
for (int i = 0; i < 5000; i++) {
final int current = i + 1;
text.append(i + "\n");
final var params = new HoverParams();
final var position = new Position();
// encode the iteration number in a suitable numeric field on the hover request params, so the
// mock server can use it to verify the requests are indeed received in the correct order
position.setCharacter(current);
position.setLine(0);
params.setPosition(position);
CompletableFuture<List<Hover>> result = LanguageServers.forDocument(document)
.withCapability(ServerCapabilities::getHoverProvider)
.collectAll(ls -> ls.getTextDocumentService().hover(params));
initial = CompletableFuture.allOf(initial, result);
}
initial.join();
final var message = new StringBuilder();
message.append("Too Early hover requests: "); message.append(tooEarlyHover.size());
message.append(System.lineSeparator());
tooEarlyHover.forEach(i -> {
message.append(" Too Early ");
message.append(i);
message.append(System.lineSeparator());
});
message.append("Too Late hover requests: "); message.append(tooLateHover.size());
message.append(System.lineSeparator());
tooLateHover.forEach(i -> {
message.append(" Too Late " );message.append(i);
message.append(System.lineSeparator());
});
assertTrue(tooEarlyHover.isEmpty() && tooLateHover.isEmpty(), message.toString());
}
/**
* Sends a sequence of bulky updates to a slow server, and checks that
* (a) Dispatch does not block, but returns an async result 'immediately'
* (b) Dispatch does not occur on the UI thread
*/
@Test
public void testBlockingServerDoesNotBlockUIThread() throws Exception {
final var uiDispatchCount = new AtomicInteger();
MockLanguageServer.INSTANCE.getInitializeResult().getCapabilities()
.setTextDocumentSync(TextDocumentSyncKind.Incremental);
MockLanguageServer.INSTANCE.setTextDocumentService(new MockTextDocumentService(MockLanguageServer.INSTANCE::buildMaybeDelayedFuture) {
@Override
public synchronized void didChange(DidChangeTextDocumentParams params) {
super.didChange(params);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public synchronized CompletableFuture<Hover> hover(HoverParams position) {
// No need for any special processing, but needs to be synchronized to
// make server block if processing a
return super.hover(position);
}
});
final var hoverResponse = new Hover(List.of(Either.forLeft("HoverContent")), new Range(new Position(0, 0), new Position(0, 10)));
MockLanguageServer.INSTANCE.setHover(hoverResponse);
CompletableFuture<?> initial = CompletableFuture.completedFuture(null);
IFile testFile = TestUtils.createUniqueTestFile(project, "");
ITextViewer viewer = TestUtils.openTextViewer(testFile);
final IDocument document = viewer.getDocument();
StyledText text = viewer.getTextWidget();
Thread.sleep(1000);
final long startTime = System.currentTimeMillis();
final var bulkyText = new StringBuilder();
// Construct a reasonably bulky payload for the document updates: if the
// payload is small then buffering will mitigate any back-pressure from the server
// (typically 8k for a unix pipe)
for (int i = 0; i < 1000; i++) {
bulkyText.append("Some Text; ");
}
final String content = bulkyText.toString();
for (int i = 0; i < 10; i++) {
final int current = i + 1;
text.append(content + "\n");
final var params = new HoverParams();
final var position = new Position();
position.setCharacter(current);
position.setLine(0);
params.setPosition(position);
CompletableFuture<?> hoverFuture = LanguageServers.forDocument(document)
.withCapability(ServerCapabilities::getHoverProvider)
.collectAll(ls -> {
try {
// If this is non-null then we're running on a/the SWT event thread
if (Display.getCurrent() != null) {
uiDispatchCount.incrementAndGet();
}
return ls.getTextDocumentService().hover(params);
} catch (Exception e) {
}
return CompletableFuture.completedFuture(null);
});
initial = CompletableFuture.allOf(initial, hoverFuture);
}
final long dispatchTime = System.currentTimeMillis() - startTime;
initial.join();
final long finishTime = System.currentTimeMillis() - startTime;
assertTrue(dispatchTime < 1000, String.format("Dispatch should not have blocked but took %d ms vs overall test time of %d ms", dispatchTime, finishTime));
assertEquals(0, uiDispatchCount.get(), "Should not have been any messages dispatched on UI thread");
}
@Test
public void testAnyMatchingIsNonBlocking() throws Exception {
// test with no LS available
long start = System.currentTimeMillis();
assertFalse(LanguageServers.forProject(project).anyMatching());
long duration = System.currentTimeMillis() - start;
assertTrue(duration < 100, "LanguageServers.anyMatching() took too long: " + duration + "ms");
// test with one slow LS available
MockLanguageServer.INSTANCE.setTimeToProceedQueries(5_000);
var testFile1 = createUniqueTestFile(project, "");
var editor1 = openEditor(testFile1);
start = System.currentTimeMillis();
try {
assertTrue(LanguageServers.forProject(project).anyMatching());
duration = System.currentTimeMillis() - start;
assertTrue(duration < 100, "LanguageServers.anyMatching() took too long: " + duration + "ms");
} finally {
editor1.getSite().getPage().closeEditor(editor1, false);
}
}
@Test
public void testNoMatchingServers() throws Exception {
final var hoverResponse = new Hover(List.of(Either.forLeft("HoverContent")), new Range(new Position(0, 0), new Position(0, 10)));
MockLanguageServer.INSTANCE.setHover(hoverResponse);
IFile testFile = TestUtils.createUniqueTestFile(project, "");
ITextViewer viewer = TestUtils.openTextViewer(testFile);
final IDocument document = viewer.getDocument();
LanguageServerDocumentExecutor executor = LanguageServers.forDocument(document).withFilter(sc -> false);
assertFalse(executor.anyMatching(), "Should not have been any valid LS");
final var params = new HoverParams();
final var position = new Position();
position.setCharacter(10);
position.setLine(0);
params.setPosition(position);
Optional<?> result = executor.computeFirst(ls -> ls.getTextDocumentService().hover(params)).get(10, TimeUnit.SECONDS);
assertFalse(result.isPresent(), "Should not have had a result");
List<?> collectedResult = executor.collectAll(ls -> ls.getTextDocumentService().hover(params)).get(10, TimeUnit.SECONDS);
assertTrue(collectedResult.isEmpty(), "Should not have had a result");
List<CompletableFuture<Hover>> allResults = executor.computeAll(ls -> ls.getTextDocumentService().hover(params));
for (CompletableFuture<Hover> f : allResults) {
Hover h = f.get(10, TimeUnit.SECONDS);
assertNull(h);
}
}
@Test
public void testComputeFirstBubblesException() throws Exception {
MockLanguageServer.INSTANCE.setTextDocumentService(new MockTextDocumentService(MockLanguageServer.INSTANCE::buildMaybeDelayedFuture) {
@Override
public synchronized void didChange(DidChangeTextDocumentParams params) {
super.didChange(params);
}
@Override
public synchronized CompletableFuture<Hover> hover(HoverParams position) {
final var result = new CompletableFuture<Hover>();
result.completeExceptionally(new IllegalStateException("No hovering here"));
return result;
}
});
IFile testFile = TestUtils.createUniqueTestFileMultiLS(project, "Here is some content");
ITextViewer viewer = TestUtils.openTextViewer(testFile);
final IDocument document = viewer.getDocument();
final var params = new HoverParams();
final var position = new Position();
position.setCharacter(10);
position.setLine(0);
params.setPosition(position);
assertThrows(CompletionException.class, () -> {
CompletableFuture<Optional<String>> response = LanguageServers.forDocument(document)
.withCapability(ServerCapabilities::getHoverProvider)
.computeFirst(ls -> ls.getTextDocumentService().hover(params)
.thenApply(h -> h == null ? null : h.getContents().getLeft().get(0).getLeft()));
response.join();
});
}
/**
* The LSExecutor request methods can optionally supply an ILSWrapper as well as the raw language server
* proxy to the consuming functions. This is intended to support constructing objects that need access to
* the same language server for follow-up calls
*/
@Test
public void testWrapperWrapsSameLS() throws Exception {
final var hoverResponse = new Hover(
List.of(Either.forLeft("HoverContent")), new Range(new Position(0, 0), new Position(0, 10)));
MockLanguageServer.INSTANCE.setHover(hoverResponse);
IFile testFile = TestUtils.createUniqueTestFileMultiLS(project, "Here is some content");
ITextViewer viewer = TestUtils.openTextViewer(testFile);
final IDocument document = viewer.getDocument();
final var params = new HoverParams();
final var position = new Position();
position.setCharacter(10);
position.setLine(0);
params.setPosition(position);
CompletableFuture<List<Pair<LanguageServerWrapper, LanguageServer>>> async = LanguageServers.forDocument(document)
.withCapability(ServerCapabilities::getHoverProvider)
.collectAll((w, ls) -> ls.getTextDocumentService().hover(params).thenApply(h -> Pair.of(w, ls)));
final List<Pair<LanguageServerWrapper, LanguageServer>> result = async.join();
final var matching = new AtomicInteger();
assertEquals(2, result.size(), "Should have had two responses");
assertNotEquals(result.get(0).second(), result.get(1).second(), "LS should have been different proxies");
result.forEach(p -> {
p.first().execute(ls -> {
if (ls == p.second()) {
matching.incrementAndGet();
}
return CompletableFuture.completedFuture(null);
}).join();
});
assertEquals(2, matching.get(), "Wrapper should have used same LS");
}
/**
* Project-level executors work slightly differently: there's (currently) no direct way
* of associating a LS with a project directly, and you can't find out a server's capabilties
* until it has started, so LSP4e relies on a document within the project having previously
* triggered a server to start. A server may shut down after inactivity, but capabilities are
* still available. Candidate LS for a project-level operation may include only currently-running LS,
* or can restart any previously-started ones that match the filter.
*/
@Test
public void testProjectExecutor() throws Exception {
var testFile1 = createUniqueTestFile(project, "");
var testFile2 = createUniqueTestFile(project, "lspt-different", "");
var editor1 = openEditor(testFile1);
var editor2 = openEditor(testFile2);
final var serverCounter = new AtomicInteger();
final List<String> serversForProject = LanguageServers.forProject(project).collectAll(ls -> CompletableFuture.completedFuture("Server" + serverCounter.incrementAndGet())).join();
assertTrue(serversForProject.contains("Server1"));
assertTrue(serversForProject.contains("Server2"));
editor1.getSite().getPage().closeEditor(editor1, false);
editor2.getSite().getPage().closeEditor(editor2, false);
waitForCondition(5_000, () -> !hasActiveLanguageServers(MATCH_ALL));
serverCounter.set(0);
final List<String> serversForProject2 = LanguageServers.forProject(project).excludeInactive().collectAll(ls -> CompletableFuture.completedFuture("Server" + serverCounter.incrementAndGet())).join();
assertTrue(serversForProject2.isEmpty());
serverCounter.set(0);
editor1 = openEditor(testFile1);
final List<String> serversForProject3 = LanguageServers.forProject(project).excludeInactive().collectAll(ls -> CompletableFuture.completedFuture("Server" + serverCounter.incrementAndGet())).join();
assertTrue(serversForProject3.contains("Server1"));
assertFalse(serversForProject3.contains("Server2"));
serverCounter.set(0);
final List<String> serversForProject4 = LanguageServers.forProject(project).collectAll(ls -> CompletableFuture.completedFuture("Server" + serverCounter.incrementAndGet())).join();
assertTrue(serversForProject4.contains("Server1"));
assertTrue(serversForProject4.contains("Server2"));
}
@Test
public void testGetDocument() throws Exception {
IFile testFile = TestUtils.createUniqueTestFile(project, "Here is some content");
ITextViewer viewer = TestUtils.openTextViewer(testFile);
final IDocument document = viewer.getDocument();
final LanguageServerDocumentExecutor executor = LanguageServers.forDocument(document);
assertEquals(document, executor.getDocument());
}
@Test
public void testCancellable() throws Exception {
IFile testFile = TestUtils.createUniqueTestFile(project, "Here is some content");
ITextViewer viewer = TestUtils.openTextViewer(testFile);
Display display = viewer.getTextWidget().getDisplay();
DisplayHelper.sleep(display, 2000);
final IDocument document = viewer.getDocument();
final LanguageServerDocumentExecutor executor = LanguageServers.forDocument(document);
MockLanguageServer.INSTANCE.setTimeToProceedQueries(3000);
// Test lsWrapper.execute() forwards cancellation
LanguageServerWrapper lsWrapper = executor.computeFirst((wrapper, ls) -> CompletableFuture.completedFuture(wrapper)).get().get();
CompletableFuture<?> request = lsWrapper.execute(ls -> ls.getTextDocumentService().references(new ReferenceParams()));
DisplayHelper.sleep(viewer.getTextWidget().getDisplay(), 500);
request.cancel(false);
assertTrue(DisplayHelper.waitForCondition(display, 3000, () -> !MockConnectionProvider.cancellations.isEmpty()));
// Test executor.computeFirst() forwards cancellation
MockConnectionProvider.cancellations.clear();
request = executor.computeFirst(ls -> ls.getTextDocumentService().references(new ReferenceParams()));
DisplayHelper.sleep(viewer.getTextWidget().getDisplay(), 500);
request.cancel(false);
DisplayHelper.sleep(viewer.getTextWidget().getDisplay(), 100);
assertTrue(DisplayHelper.waitForCondition(display, 3000, () -> !MockConnectionProvider.cancellations.isEmpty()));
// Test executor.collectAll() forwards cancellation
MockConnectionProvider.cancellations.clear();
request = executor.collectAll(ls -> ls.getTextDocumentService().references(new ReferenceParams()));
DisplayHelper.sleep(viewer.getTextWidget().getDisplay(), 500);
request.cancel(false);
DisplayHelper.sleep(viewer.getTextWidget().getDisplay(), 100);
assertTrue(DisplayHelper.waitForCondition(display, 3000, () -> !MockConnectionProvider.cancellations.isEmpty()));
// Test executor.computeAll() forwards cancellation
MockConnectionProvider.cancellations.clear();
@NonNull List<@NonNull CompletableFuture<@Nullable List<? extends Location>>> requests = executor.computeAll(ls -> ls.getTextDocumentService().references(new ReferenceParams()));
DisplayHelper.sleep(viewer.getTextWidget().getDisplay(), 500);
requests.forEach(r -> r.cancel(false));
DisplayHelper.sleep(viewer.getTextWidget().getDisplay(), 100);
assertTrue(DisplayHelper.waitForCondition(display, 3000, () -> !MockConnectionProvider.cancellations.isEmpty()));
}
}