-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
Copy pathServiceHubServicesTests.cs
944 lines (772 loc) · 41.4 KB
/
ServiceHubServicesTests.cs
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
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.DesignerAttribute;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Remote.Testing;
using Microsoft.CodeAnalysis.Serialization;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.UnitTests;
using Microsoft.VisualStudio.Threading;
using Roslyn.Test.Utilities;
using Roslyn.Test.Utilities.TestGenerators;
using Roslyn.Utilities;
using Xunit;
using Xunit.Sdk;
namespace Roslyn.VisualStudio.Next.UnitTests.Remote
{
[UseExportProvider]
[Trait(Traits.Feature, Traits.Features.RemoteHost)]
public class ServiceHubServicesTests
{
private static TestWorkspace CreateWorkspace(Type[] additionalParts = null)
=> new(composition: FeaturesTestCompositions.Features.WithTestHostParts(TestHost.OutOfProcess).AddParts(additionalParts));
[Fact]
public async Task TestRemoteHostSynchronize()
{
var code = @"class Test { void Method() { } }";
using var workspace = CreateWorkspace();
workspace.InitializeDocuments(LanguageNames.CSharp, files: [code], openDocuments: false);
using var client = await InProcRemoteHostClient.GetTestClientAsync(workspace).ConfigureAwait(false);
var solution = workspace.CurrentSolution;
await UpdatePrimaryWorkspace(client, solution);
await VerifyAssetStorageAsync(client, solution);
var remoteWorkpace = client.GetRemoteWorkspace();
Assert.Equal(
await solution.CompilationState.GetChecksumAsync(CancellationToken.None),
await remoteWorkpace.CurrentSolution.CompilationState.GetChecksumAsync(CancellationToken.None));
}
[Fact]
public async Task TestRemoteHostTextSynchronize()
{
var code = @"class Test { void Method() { } }";
using var workspace = CreateWorkspace();
workspace.InitializeDocuments(LanguageNames.CSharp, files: [code], openDocuments: false);
var client = await InProcRemoteHostClient.GetTestClientAsync(workspace).ConfigureAwait(false);
var solution = workspace.CurrentSolution;
// sync base solution
await UpdatePrimaryWorkspace(client, solution);
await VerifyAssetStorageAsync(client, solution);
// get basic info
var oldDocument = solution.Projects.First().Documents.First();
var oldState = await oldDocument.State.GetStateChecksumsAsync(CancellationToken.None);
var oldText = await oldDocument.GetTextAsync();
// update text
var newText = oldText.WithChanges(new TextChange(TextSpan.FromBounds(0, 0), "/* test */"));
// sync
await client.TryInvokeAsync<IRemoteAssetSynchronizationService>(
(service, cancellationToken) => service.SynchronizeTextAsync(oldDocument.Id, oldState.Text, newText.GetTextChanges(oldText), cancellationToken),
CancellationToken.None);
// apply change to solution
var newDocument = oldDocument.WithText(newText);
var newState = await newDocument.State.GetStateChecksumsAsync(CancellationToken.None);
// check that text already exist in remote side
Assert.True(client.TestData.WorkspaceManager.SolutionAssetCache.TryGetAsset<SerializableSourceText>(newState.Text, out var serializableRemoteText));
Assert.Equal(newText.ToString(), (await serializableRemoteText.GetTextAsync(CancellationToken.None)).ToString());
}
private static async Task<AssetProvider> GetAssetProviderAsync(Workspace workspace, Workspace remoteWorkspace, Solution solution, Dictionary<Checksum, object> map = null)
{
// make sure checksum is calculated
await solution.CompilationState.GetChecksumAsync(CancellationToken.None);
map ??= [];
await solution.AppendAssetMapAsync(map, CancellationToken.None);
var sessionId = Checksum.Create(ImmutableArray.CreateRange(Guid.NewGuid().ToByteArray()));
var storage = new SolutionAssetCache();
var assetSource = new SimpleAssetSource(workspace.Services.GetService<ISerializerService>(), map);
return new AssetProvider(sessionId, storage, assetSource, remoteWorkspace.Services.GetService<ISerializerService>());
}
[Fact]
public async Task TestDesignerAttributes()
{
var source = @"[System.ComponentModel.DesignerCategory(""Form"")] class Test { }";
using var workspace = CreateWorkspace();
workspace.InitializeDocuments(LanguageNames.CSharp, files: [source], openDocuments: false);
using var client = await InProcRemoteHostClient.GetTestClientAsync(workspace).ConfigureAwait(false);
var remoteWorkspace = client.GetRemoteWorkspace();
var cancellationTokenSource = new CancellationTokenSource();
var solution = workspace.CurrentSolution;
// Ensure remote workspace is in sync with normal workspace.
var assetProvider = await GetAssetProviderAsync(workspace, remoteWorkspace, solution);
var solutionChecksum = await solution.CompilationState.GetChecksumAsync(CancellationToken.None);
await remoteWorkspace.UpdatePrimaryBranchSolutionAsync(assetProvider, solutionChecksum, solution.WorkspaceVersion, CancellationToken.None);
var callback = new DesignerAttributeComputerCallback();
using var connection = client.CreateConnection<IRemoteDesignerAttributeDiscoveryService>(callback);
// Actually pass in the document to scan. Otherwise the test takes several seconds waiting to do the slow
// sweep of the entire solution.
var priorityDocumentId = solution.Projects.Single().Documents.Single().Id;
var invokeTask = connection.TryInvokeAsync(
solution,
(service, checksum, callbackId, cancellationToken) => service.DiscoverDesignerAttributesAsync(
callbackId, checksum, priorityDocumentId, cancellationToken),
cancellationTokenSource.Token);
var infos = await callback.Infos;
Assert.Equal(1, infos.Length);
var info = infos[0];
Assert.Equal("Form", info.Category);
Assert.Equal(solution.Projects.Single().Documents.Single().Id, info.DocumentId);
// Let the discovery know it can stop processing.
cancellationTokenSource.Cancel();
try
{
await invokeTask;
}
catch (OperationCanceledException)
{
}
}
[Fact]
public async Task TestDesignerAttributesUnsupportedLanguage()
{
var source = @"// TS code";
using var workspace = CreateWorkspace();
workspace.InitializeDocuments("TypeScript", files: [source], openDocuments: true);
using var client = await InProcRemoteHostClient.GetTestClientAsync(workspace).ConfigureAwait(false);
var remoteWorkspace = client.GetRemoteWorkspace();
var cancellationTokenSource = new CancellationTokenSource();
var solution = workspace.CurrentSolution;
// Ensure remote workspace is in sync with normal workspace.
var assetProvider = await GetAssetProviderAsync(workspace, remoteWorkspace, solution);
var solutionChecksum = await solution.CompilationState.GetChecksumAsync(CancellationToken.None);
await remoteWorkspace.UpdatePrimaryBranchSolutionAsync(assetProvider, solutionChecksum, solution.WorkspaceVersion, CancellationToken.None);
var callback = new DesignerAttributeComputerCallback();
var listenerProvider = workspace.ExportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>();
await DesignerAttributeDiscoveryService.DiscoverDesignerAttributesAsync(
workspace.CurrentSolution,
workspace.CurrentSolution.Projects.Single().Documents.Single(),
client,
listenerProvider.GetListener(FeatureAttribute.DesignerAttributes),
callback,
CancellationToken.None);
}
private class DesignerAttributeComputerCallback : IDesignerAttributeDiscoveryService.ICallback
{
private readonly TaskCompletionSource<ImmutableArray<DesignerAttributeData>> _infosSource = new();
public Task<ImmutableArray<DesignerAttributeData>> Infos => _infosSource.Task;
public ValueTask ReportDesignerAttributeDataAsync(ImmutableArray<DesignerAttributeData> infos, CancellationToken cancellationToken)
{
_infosSource.SetResult(infos);
return ValueTaskFactory.CompletedTask;
}
}
[Fact]
public async Task TestUnknownProject()
{
var workspace = CreateWorkspace([typeof(NoCompilationLanguageService)]);
var solution = workspace.CurrentSolution.AddProject("unknown", "unknown", NoCompilationConstants.LanguageName).Solution;
using var client = await InProcRemoteHostClient.GetTestClientAsync(workspace).ConfigureAwait(false);
var remoteWorkspace = client.GetRemoteWorkspace();
await UpdatePrimaryWorkspace(client, solution);
await VerifyAssetStorageAsync(client, solution);
// Only C# and VB projects are supported in Remote workspace.
// See "RemoteSupportedLanguages.IsSupported"
Assert.Empty(remoteWorkspace.CurrentSolution.Projects);
// No serializable remote options affect options checksum, so the checksums should match.
Assert.Equal(
await solution.CompilationState.GetChecksumAsync(CancellationToken.None),
await remoteWorkspace.CurrentSolution.CompilationState.GetChecksumAsync(CancellationToken.None));
solution = solution.RemoveProject(solution.ProjectIds.Single());
Assert.Equal(
await solution.CompilationState.GetChecksumAsync(CancellationToken.None),
await remoteWorkspace.CurrentSolution.CompilationState.GetChecksumAsync(CancellationToken.None));
}
[Theory]
[CombinatorialData]
[WorkItem("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1365014")]
public async Task TestRemoteHostSynchronizeIncrementalUpdate(bool applyInBatch)
{
using var workspace = CreateWorkspace();
using var client = await InProcRemoteHostClient.GetTestClientAsync(workspace).ConfigureAwait(false);
var remoteWorkspace = client.GetRemoteWorkspace();
var solution = Populate(workspace.CurrentSolution);
// verify initial setup
await workspace.ChangeSolutionAsync(solution);
solution = workspace.CurrentSolution;
await UpdatePrimaryWorkspace(client, solution);
await VerifyAssetStorageAsync(client, solution);
Assert.Equal(
await solution.CompilationState.GetChecksumAsync(CancellationToken.None),
await remoteWorkspace.CurrentSolution.CompilationState.GetChecksumAsync(CancellationToken.None));
// incrementally update
solution = await VerifyIncrementalUpdatesAsync(
workspace, remoteWorkspace, client, solution, applyInBatch, csAddition: " ", vbAddition: " ");
Assert.Equal(
await solution.CompilationState.GetChecksumAsync(CancellationToken.None),
await remoteWorkspace.CurrentSolution.CompilationState.GetChecksumAsync(CancellationToken.None));
// incrementally update
solution = await VerifyIncrementalUpdatesAsync(
workspace, remoteWorkspace, client, solution, applyInBatch, csAddition: "\r\nclass Addition { }", vbAddition: "\r\nClass VB\r\nEnd Class");
Assert.Equal(
await solution.CompilationState.GetChecksumAsync(CancellationToken.None),
await remoteWorkspace.CurrentSolution.CompilationState.GetChecksumAsync(CancellationToken.None));
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/52578")]
public async Task TestIncrementalUpdateHandlesReferenceReversal()
{
using var workspace = CreateWorkspace();
using var client = await InProcRemoteHostClient.GetTestClientAsync(workspace).ConfigureAwait(false);
var remoteWorkspace = client.GetRemoteWorkspace();
var solution = workspace.CurrentSolution;
solution = AddProject(solution, LanguageNames.CSharp, documents: [], additionalDocuments: [], p2pReferences: []);
var projectId1 = solution.ProjectIds.Single();
solution = AddProject(solution, LanguageNames.CSharp, documents: [], additionalDocuments: [], p2pReferences: []);
var projectId2 = solution.ProjectIds.Where(id => id != projectId1).Single();
var project1ToProject2 = new ProjectReference(projectId2);
var project2ToProject1 = new ProjectReference(projectId1);
// Start with projectId1 -> projectId2
solution = solution.AddProjectReference(projectId1, project1ToProject2);
// verify initial setup
await UpdatePrimaryWorkspace(client, solution);
await VerifyAssetStorageAsync(client, solution);
Assert.Equal(
await solution.CompilationState.GetChecksumAsync(CancellationToken.None),
await remoteWorkspace.CurrentSolution.CompilationState.GetChecksumAsync(CancellationToken.None));
// reverse project references and incrementally update
solution = solution.RemoveProjectReference(projectId1, project1ToProject2);
solution = solution.AddProjectReference(projectId2, project2ToProject1);
await workspace.ChangeSolutionAsync(solution);
solution = workspace.CurrentSolution;
await UpdatePrimaryWorkspace(client, solution);
Assert.Equal(
await solution.CompilationState.GetChecksumAsync(CancellationToken.None),
await remoteWorkspace.CurrentSolution.CompilationState.GetChecksumAsync(CancellationToken.None));
// reverse project references again and incrementally update
solution = solution.RemoveProjectReference(projectId2, project2ToProject1);
solution = solution.AddProjectReference(projectId1, project1ToProject2);
await workspace.ChangeSolutionAsync(solution);
solution = workspace.CurrentSolution;
await UpdatePrimaryWorkspace(client, solution);
Assert.Equal(
await solution.CompilationState.GetChecksumAsync(CancellationToken.None),
await remoteWorkspace.CurrentSolution.CompilationState.GetChecksumAsync(CancellationToken.None));
}
[Fact]
public async Task TestRemoteWorkspaceCircularReferences()
{
using var tempRoot = new TempRoot();
var file = tempRoot.CreateDirectory().CreateFile("p1.dll");
file.CopyContentFrom(typeof(object).Assembly.Location);
var p1 = ProjectId.CreateNewId();
var p2 = ProjectId.CreateNewId();
var solutionInfo = SolutionInfo.Create(
SolutionId.CreateNewId(), VersionStamp.Create(), "",
new[]
{
ProjectInfo.Create(
p1, VersionStamp.Create(), "p1", "p1", LanguageNames.CSharp, outputFilePath: file.Path,
projectReferences: new [] { new ProjectReference(p2) }),
ProjectInfo.Create(
p2, VersionStamp.Create(), "p2", "p2", LanguageNames.CSharp,
metadataReferences: new [] { MetadataReference.CreateFromFile(file.Path) })
});
using var remoteWorkspace = new RemoteWorkspace(FeaturesTestCompositions.RemoteHost.GetHostServices());
// this shouldn't throw exception
var (solution, updated) = await remoteWorkspace.GetTestAccessor().TryUpdateWorkspaceCurrentSolutionAsync(
remoteWorkspace.GetTestAccessor().CreateSolutionFromInfo(solutionInfo), workspaceVersion: 1);
Assert.True(updated);
Assert.NotNull(solution);
}
private static ImmutableArray<ImmutableArray<T>> Permute<T>(T[] values)
{
using var _ = ArrayBuilder<ImmutableArray<T>>.GetInstance(out var result);
DoPermute(0, values.Length - 1);
return result.ToImmutable();
void DoPermute(int start, int end)
{
if (start == end)
{
// We have one of our possible n! solutions,
// add it to the list.
result.Add(values.ToImmutableArray());
}
else
{
for (var i = start; i <= end; i++)
{
(values[start], values[i]) = (values[i], values[start]);
DoPermute(start + 1, end);
(values[start], values[i]) = (values[i], values[start]);
}
}
}
}
private static async Task TestInProcAndRemoteWorkspace(
params ImmutableArray<(string hintName, SourceText text)>[] values)
{
// Try every permutation of these values.
foreach (var permutation in Permute(values))
await TestInProcAndRemoteWorkspaceWorker(permutation);
}
private static async Task TestInProcAndRemoteWorkspaceWorker(
ImmutableArray<ImmutableArray<(string hintName, SourceText text)>> values)
{
var throwIfCalled = false;
ImmutableArray<(string hintName, SourceText text)> sourceTexts = default;
var generator = new CallbackGenerator(
onInit: _ => { },
onExecute: _ => { },
computeSourceTexts: () =>
{
Contract.ThrowIfTrue(throwIfCalled);
return sourceTexts;
});
using var localWorkspace = CreateWorkspace();
DocumentId tempDocId;
// Keep this all in a nested scope so we don't accidentally access this data inside the loop below. We only
// want to access the true workspace solution (which will be a fork of the solution we're producing here).
{
var projectId = ProjectId.CreateNewId();
var analyzerReference = new TestGeneratorReference(generator);
var project = localWorkspace.CurrentSolution
.AddProject(ProjectInfo.Create(projectId, VersionStamp.Default, name: "Test", assemblyName: "Test", language: LanguageNames.CSharp))
.GetRequiredProject(projectId)
.AddAnalyzerReference(analyzerReference);
var tempDoc = project.AddDocument("X.cs", SourceText.From("// "));
tempDocId = tempDoc.Id;
Assert.True(localWorkspace.SetCurrentSolution(_ => tempDoc.Project.Solution, WorkspaceChangeKind.SolutionChanged));
}
using var client = await InProcRemoteHostClient.GetTestClientAsync(localWorkspace);
var remoteWorkspace = client.GetRemoteWorkspace();
for (var i = 0; i < values.Length; i++)
{
sourceTexts = values[i];
// make a change to the project to force a change between the local and oop solutions.
Assert.True(localWorkspace.SetCurrentSolution(s => s.WithDocumentText(tempDocId, SourceText.From("// " + i)), WorkspaceChangeKind.SolutionChanged));
await UpdatePrimaryWorkspace(client, localWorkspace.CurrentSolution);
var localProject = localWorkspace.CurrentSolution.Projects.Single();
var remoteProject = remoteWorkspace.CurrentSolution.Projects.Single();
// Run generators locally
throwIfCalled = false;
var localCompilation = await localProject.GetCompilationAsync();
// Now run them remotely. This must not actually call into the generator since nothing has changed.
throwIfCalled = true;
var remoteCompilation = await remoteProject.GetCompilationAsync();
await AssertSourceGeneratedDocumentsAreSame(localProject, remoteProject, expectedCount: sourceTexts.Length);
}
static async Task AssertSourceGeneratedDocumentsAreSame(Project localProject, Project remoteProject, int expectedCount)
{
// The docs on both sides must be in the exact same order, and with identical contents (including
// source-text encoding/hash-algorithm).
var localGeneratedDocs = (await localProject.GetSourceGeneratedDocumentsAsync()).ToImmutableArray();
var remoteGeneratedDocs = (await remoteProject.GetSourceGeneratedDocumentsAsync()).ToImmutableArray();
Assert.Equal(localGeneratedDocs.Length, remoteGeneratedDocs.Length);
Assert.Equal(expectedCount, localGeneratedDocs.Length);
for (var i = 0; i < expectedCount; i++)
{
var localDoc = localGeneratedDocs[i];
var remoteDoc = remoteGeneratedDocs[i];
Assert.Equal(localDoc.HintName, remoteDoc.HintName);
Assert.Equal(localDoc.DocumentState.Id, remoteDoc.DocumentState.Id);
var localText = await localDoc.GetTextAsync();
var remoteText = await localDoc.GetTextAsync();
Assert.Equal(localText.ToString(), remoteText.ToString());
Assert.Equal(localText.Encoding, remoteText.Encoding);
Assert.Equal(localText.ChecksumAlgorithm, remoteText.ChecksumAlgorithm);
}
}
}
private static SourceText CreateText(string content, Encoding encoding = null, SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1)
=> SourceText.From(content, encoding ?? Encoding.UTF8, checksumAlgorithm);
private static SourceText CreateStreamText(string content, bool useBOM, bool useMemoryStream)
{
var encoding = new UTF8Encoding(useBOM);
var bytes = encoding.GetBytes(content);
if (useMemoryStream)
{
using var stream = new MemoryStream(bytes);
return SourceText.From(stream, encoding, SourceHashAlgorithm.Sha1, throwIfBinaryDetected: true);
}
else
{
return SourceText.From(bytes, bytes.Length, encoding, SourceHashAlgorithm.Sha1, throwIfBinaryDetected: true);
}
}
[Fact]
public async Task InProcAndRemoteWorkspaceAgree1()
{
await TestInProcAndRemoteWorkspace(
ImmutableArray.Create(("SG.cs", CreateText(Guid.NewGuid().ToString()))));
}
[Fact]
public async Task InProcAndRemoteWorkspaceAgree2()
{
var sourceText = CreateText(Guid.NewGuid().ToString());
await TestInProcAndRemoteWorkspace(
ImmutableArray.Create(("SG.cs", sourceText)),
ImmutableArray.Create(("SG.cs", sourceText)));
}
[Fact]
public async Task InProcAndRemoteWorkspaceAgree3()
{
var sourceText = Guid.NewGuid().ToString();
await TestInProcAndRemoteWorkspace(
ImmutableArray.Create(("SG.cs", CreateText(sourceText))),
ImmutableArray.Create(("SG.cs", CreateText(sourceText))));
}
[Fact]
public async Task InProcAndRemoteWorkspaceAgree4()
{
await TestInProcAndRemoteWorkspace(
ImmutableArray.Create(("SG.cs", CreateText(Guid.NewGuid().ToString()))),
ImmutableArray.Create(("SG.cs", CreateText(Guid.NewGuid().ToString()))));
}
[Fact]
public async Task InProcAndRemoteWorkspaceAgree5()
{
await TestInProcAndRemoteWorkspace(
ImmutableArray.Create(("SG.cs", CreateText(Guid.NewGuid().ToString()))),
ImmutableArray.Create(("NewName.cs", CreateText(Guid.NewGuid().ToString()))));
}
[Fact]
public async Task InProcAndRemoteWorkspaceAgree6()
{
var sourceText = CreateText(Guid.NewGuid().ToString());
await TestInProcAndRemoteWorkspace(
ImmutableArray.Create(("SG.cs", sourceText)),
ImmutableArray.Create(("NewName.cs", sourceText)));
}
[Fact]
public async Task InProcAndRemoteWorkspaceAgree7()
{
var sourceText = Guid.NewGuid().ToString();
await TestInProcAndRemoteWorkspace(
ImmutableArray.Create(("SG.cs", CreateText(sourceText))),
ImmutableArray.Create(("NewName.cs", CreateText(sourceText))));
}
[Fact]
public async Task InProcAndRemoteWorkspaceAgree8()
{
await TestInProcAndRemoteWorkspace(
ImmutableArray.Create(("SG.cs", CreateText(Guid.NewGuid().ToString()))),
ImmutableArray.Create(("NewName.cs", CreateText(Guid.NewGuid().ToString()))));
}
[Fact]
public async Task InProcAndRemoteWorkspaceAgree9()
{
await TestInProcAndRemoteWorkspace(
ImmutableArray.Create(("SG.cs", CreateText("X", Encoding.ASCII))),
ImmutableArray.Create(("SG.cs", CreateText("X", Encoding.UTF8))));
}
[Fact]
public async Task InProcAndRemoteWorkspaceAgree10()
{
await TestInProcAndRemoteWorkspace(
ImmutableArray.Create(("SG.cs", CreateText("X", Encoding.UTF8, checksumAlgorithm: SourceHashAlgorithm.Sha1))),
ImmutableArray.Create(("SG.cs", CreateText("X", Encoding.UTF8, checksumAlgorithm: SourceHashAlgorithm.Sha256))));
}
[Fact]
public async Task InProcAndRemoteWorkspaceAgree11()
{
await TestInProcAndRemoteWorkspace(
ImmutableArray.Create(("SG.cs", CreateText(Guid.NewGuid().ToString()))),
ImmutableArray<(string, SourceText)>.Empty);
}
[Fact]
public async Task InProcAndRemoteWorkspaceAgree12()
{
await TestInProcAndRemoteWorkspace(
ImmutableArray<(string, SourceText)>.Empty,
ImmutableArray.Create(("SG.cs", CreateText(Guid.NewGuid().ToString()))));
}
[Fact]
public async Task InProcAndRemoteWorkspaceAgree13()
{
var contents = Guid.NewGuid().ToString();
await TestInProcAndRemoteWorkspace(
ImmutableArray.Create(("SG.cs", CreateText(contents))),
ImmutableArray.Create(("SG.cs", CreateText(contents)), ("SG1.cs", CreateText(contents))));
}
[Fact]
public async Task InProcAndRemoteWorkspaceAgree14()
{
var contents = Guid.NewGuid().ToString();
await TestInProcAndRemoteWorkspace(
ImmutableArray.Create(("SG.cs", CreateText(contents))),
ImmutableArray.Create(("SG.cs", CreateText(contents)), ("SG1.cs", CreateText("Other"))));
}
[Fact]
public async Task InProcAndRemoteWorkspaceAgree15()
{
var contents = Guid.NewGuid().ToString();
await TestInProcAndRemoteWorkspace(
ImmutableArray.Create(("SG.cs", CreateText(contents))),
ImmutableArray.Create(("SG1.cs", CreateText(contents)), ("SG.cs", CreateText("Other"))));
}
[Fact]
public async Task InProcAndRemoteWorkspaceAgree16()
{
var contents = Guid.NewGuid().ToString();
await TestInProcAndRemoteWorkspace(
ImmutableArray.Create(("SG.cs", CreateText(contents))),
ImmutableArray.Create(("SG1.cs", CreateText("Other")), ("SG.cs", CreateText(contents))));
}
[Fact]
public async Task InProcAndRemoteWorkspaceAgree17()
{
var contents = Guid.NewGuid().ToString();
await TestInProcAndRemoteWorkspace(
ImmutableArray.Create(("SG.cs", CreateText(contents))),
ImmutableArray.Create(("SG1.cs", CreateText("Other")), ("SG.cs", CreateText(contents))),
ImmutableArray<(string, SourceText)>.Empty);
}
[Fact]
public async Task InProcAndRemoteWorkspaceAgree18()
{
var contents = CreateText(Guid.NewGuid().ToString());
await TestInProcAndRemoteWorkspace(
ImmutableArray.Create(("SG1.cs", contents), ("SG2.cs", contents)));
}
[Fact]
public async Task InProcAndRemoteWorkspaceAgree19()
{
var contents = CreateText(Guid.NewGuid().ToString());
await TestInProcAndRemoteWorkspace(
ImmutableArray.Create(("SG1.cs", contents), ("SG2.cs", contents)),
ImmutableArray.Create(("SG2.cs", contents), ("SG1.cs", contents)));
}
[Fact]
public async Task InProcAndRemoteWorkspaceAgree20()
{
var contents = Guid.NewGuid().ToString();
await TestInProcAndRemoteWorkspace(
ImmutableArray.Create(("SG1.cs", CreateText(contents)), ("SG2.cs", CreateText(contents))),
ImmutableArray.Create(("SG2.cs", CreateText(contents)), ("SG1.cs", CreateText(contents))));
}
[Theory, CombinatorialData]
public async Task InProcAndRemoteWorkspaceAgree21(
bool useBOM1, bool useMemoryStream1, bool useBOM2, bool useMemoryStream2)
{
var contents = Guid.NewGuid().ToString();
await TestInProcAndRemoteWorkspace(
ImmutableArray.Create(("SG.cs", CreateStreamText(contents, useBOM: useBOM1, useMemoryStream: useMemoryStream1))),
ImmutableArray.Create(("SG.cs", CreateStreamText(contents, useBOM: useBOM2, useMemoryStream: useMemoryStream2))));
}
private static async Task<Solution> VerifyIncrementalUpdatesAsync(
TestWorkspace localWorkspace,
Workspace remoteWorkspace,
RemoteHostClient client,
Solution solution,
bool applyInBatch,
string csAddition,
string vbAddition)
{
var remoteSolution = remoteWorkspace.CurrentSolution;
var projectIds = solution.ProjectIds;
for (var i = 0; i < projectIds.Count; i++)
{
var projectName = $"Project{i}";
var project = solution.GetProject(projectIds[i]);
var changedDocuments = new List<string>();
var documentIds = project.DocumentIds;
for (var j = 0; j < documentIds.Count; j++)
{
var documentName = $"Document{j}";
var currentSolution = UpdateSolution(solution, projectName, documentName, csAddition, vbAddition);
changedDocuments.Add(documentName);
solution = currentSolution;
if (!applyInBatch)
{
await UpdateAndVerifyAsync();
}
}
if (applyInBatch)
{
await UpdateAndVerifyAsync();
}
async Task UpdateAndVerifyAsync()
{
var documentNames = changedDocuments.ToImmutableArray();
changedDocuments.Clear();
await localWorkspace.ChangeSolutionAsync(solution);
solution = localWorkspace.CurrentSolution;
await UpdatePrimaryWorkspace(client, solution);
var currentRemoteSolution = remoteWorkspace.CurrentSolution;
VerifyStates(remoteSolution, currentRemoteSolution, projectName, documentNames);
remoteSolution = currentRemoteSolution;
Assert.Equal(
await solution.CompilationState.GetChecksumAsync(CancellationToken.None),
await remoteSolution.CompilationState.GetChecksumAsync(CancellationToken.None));
}
}
return solution;
}
private static void VerifyStates(Solution solution1, Solution solution2, string projectName, ImmutableArray<string> documentNames)
{
Assert.Equal(WorkspaceKind.RemoteWorkspace, solution1.WorkspaceKind);
Assert.Equal(WorkspaceKind.RemoteWorkspace, solution2.WorkspaceKind);
SetEqual(solution1.ProjectIds, solution2.ProjectIds);
var (project, documents) = GetProjectAndDocuments(solution1, projectName, documentNames);
var projectId = project.Id;
var documentIds = documents.SelectAsArray(document => document.Id);
var projectIds = solution1.ProjectIds;
for (var i = 0; i < projectIds.Count; i++)
{
var currentProjectId = projectIds[i];
var projectStateShouldSame = projectId != currentProjectId;
Assert.Equal(projectStateShouldSame, object.ReferenceEquals(solution1.GetProject(currentProjectId).State, solution2.GetProject(currentProjectId).State));
if (!projectStateShouldSame)
{
SetEqual(solution1.GetProject(currentProjectId).DocumentIds, solution2.GetProject(currentProjectId).DocumentIds);
var documentIdsInProject = solution1.GetProject(currentProjectId).DocumentIds;
for (var j = 0; j < documentIdsInProject.Count; j++)
{
var currentDocumentId = documentIdsInProject[j];
var documentStateShouldSame = !documentIds.Contains(currentDocumentId);
Assert.Equal(documentStateShouldSame, object.ReferenceEquals(solution1.GetDocument(currentDocumentId).State, solution2.GetDocument(currentDocumentId).State));
}
}
}
}
private static async Task VerifyAssetStorageAsync(InProcRemoteHostClient client, Solution solution)
{
var map = await solution.GetAssetMapAsync(CancellationToken.None);
var storage = client.TestData.WorkspaceManager.SolutionAssetCache;
TestUtils.VerifyAssetStorage(map, storage);
}
private static Solution UpdateSolution(Solution solution, string projectName, string documentName, string csAddition, string vbAddition)
{
var (_, document) = GetProjectAndDocument(solution, projectName, documentName);
return document.WithText(GetNewText(document, csAddition, vbAddition)).Project.Solution;
}
private static SourceText GetNewText(Document document, string csAddition, string vbAddition)
{
if (document.Project.Language == LanguageNames.CSharp)
{
return SourceText.From(document.State.GetTextSynchronously(CancellationToken.None).ToString() + csAddition);
}
return SourceText.From(document.State.GetTextSynchronously(CancellationToken.None).ToString() + vbAddition);
}
private static (Project project, Document document) GetProjectAndDocument(Solution solution, string projectName, string documentName)
{
var project = solution.Projects.First(p => string.Equals(p.Name, projectName, StringComparison.OrdinalIgnoreCase));
var document = project.Documents.First(d => string.Equals(d.Name, documentName, StringComparison.OrdinalIgnoreCase));
return (project, document);
}
private static (Project project, ImmutableArray<Document> documents) GetProjectAndDocuments(Solution solution, string projectName, ImmutableArray<string> documentNames)
{
var project = solution.Projects.First(p => string.Equals(p.Name, projectName, StringComparison.OrdinalIgnoreCase));
var documents = documentNames.SelectAsArray(
documentName => project.Documents.First(d => string.Equals(d.Name, documentName, StringComparison.OrdinalIgnoreCase)));
return (project, documents);
}
private static async Task UpdatePrimaryWorkspace(RemoteHostClient client, Solution solution)
{
var workspaceVersion = solution.WorkspaceVersion;
await client.TryInvokeAsync<IRemoteAssetSynchronizationService>(
solution,
async (service, solutionInfo, cancellationToken) => await service.SynchronizePrimaryWorkspaceAsync(solutionInfo, workspaceVersion, cancellationToken),
CancellationToken.None);
}
private static Solution Populate(Solution solution)
{
solution = AddProject(solution, LanguageNames.CSharp,
[
"class CS { }",
"class CS2 { }"
],
[
"cs additional file content"
], []);
solution = AddProject(solution, LanguageNames.VisualBasic,
[
"Class VB\r\nEnd Class",
"Class VB2\r\nEnd Class"
],
[
"vb additional file content"
], [solution.ProjectIds.First()]);
solution = AddProject(solution, LanguageNames.CSharp,
[
"class Top { }"
],
[
"cs additional file content"
], solution.ProjectIds.ToArray());
solution = AddProject(solution, LanguageNames.CSharp,
[
"class OrphanCS { }",
"class OrphanCS2 { }"
],
[
"cs additional file content",
"cs additional file content2"
], []);
solution = AddProject(solution, LanguageNames.CSharp,
[
"class CS { }",
"class CS2 { }",
"class CS3 { }",
"class CS4 { }",
"class CS5 { }",
],
[
"cs additional file content"
], []);
solution = AddProject(solution, LanguageNames.VisualBasic,
[
"Class VB\r\nEnd Class",
"Class VB2\r\nEnd Class",
"Class VB3\r\nEnd Class",
"Class VB4\r\nEnd Class",
"Class VB5\r\nEnd Class",
],
[
"vb additional file content"
], []);
return solution;
}
private static Solution AddProject(Solution solution, string language, string[] documents, string[] additionalDocuments, ProjectId[] p2pReferences)
{
var projectName = $"Project{solution.ProjectIds.Count}";
var project = solution.AddProject(projectName, $"{projectName}.dll", language)
.AddMetadataReference(MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
.AddAnalyzerReference(new AnalyzerFileReference(typeof(object).Assembly.Location, new TestAnalyzerAssemblyLoader()));
var projectId = project.Id;
solution = project.Solution;
for (var i = 0; i < documents.Length; i++)
{
var current = solution.GetProject(projectId);
solution = current.AddDocument($"Document{i}", SourceText.From(documents[i])).Project.Solution;
}
for (var i = 0; i < additionalDocuments.Length; i++)
{
var current = solution.GetProject(projectId);
solution = current.AddAdditionalDocument($"AdditionalDocument{i}", SourceText.From(additionalDocuments[i])).Project.Solution;
}
for (var i = 0; i < p2pReferences.Length; i++)
{
var current = solution.GetProject(projectId);
solution = current.AddProjectReference(new ProjectReference(p2pReferences[i])).Solution;
}
return solution;
}
private static void SetEqual<T>(IEnumerable<T> expected, IEnumerable<T> actual)
{
var expectedSet = new HashSet<T>(expected);
var result = expected.Count() == actual.Count() && expectedSet.SetEquals(actual);
if (!result)
{
Assert.True(result);
}
}
}
}