public void Test_WorkspaceChanges()
        {
            var workspace = new TestWorkspace();
            var solution = workspace.CurrentSolution;
            var project1 = workspace.AddProject("P1");
            var graph = ProjectDependencyService.GetDependencyGraphAsync(workspace.CurrentSolution, CancellationToken.None).Result;
            var project2 = workspace.AddProject("P2");
            graph = ProjectDependencyService.GetDependencyGraphAsync(workspace.CurrentSolution, CancellationToken.None).Result;
            var sortedProjects = graph.GetTopologicallySortedProjects();
            AssertEx.SetEqual(sortedProjects, project1, project2);
            
            Project ps = workspace.CurrentSolution.GetProject(project1);
            int startCount = ps.MetadataReferences.Count;

            var source2 = @"
using System;
public class X
{
}
";
            MetadataReference comp1 = CreateCSharpCompilation(source2).ToMetadataReference();            
            workspace.OnMetadataReferenceAdded(project1, comp1);
            workspace.OnAssemblyNameChanged(project1, "ChangedP1");
            
            Assert.False(ps.CompilationOptions.CheckOverflow);
            CompilationOptions co = new CSharp.CSharpCompilationOptions(outputKind: OutputKind.DynamicallyLinkedLibrary, checkOverflow: true);            
            workspace.OnCompilationOptionsChanged(project1, co);
            
            ps = workspace.CurrentSolution.GetProject(project1);
            Assert.Equal(startCount + 1, ps.MetadataReferences.Count);
            Assert.Equal(ps.AssemblyName, "ChangedP1");
            Assert.True(ps.CompilationOptions.CheckOverflow);            
        }
Exemple #2
0
        private async Task AssertFormatAsync(string expected, SyntaxTree tree)
        {
            using (var workspace = new TestWorkspace())
            {
                var formattedRoot = await Formatter.FormatAsync(tree.GetRoot(), workspace);
                var actualFormattedText = formattedRoot.ToFullString();

                Assert.Equal(expected, actualFormattedText);
            }
        }
 public void Test_WorkspaceOutputFilePathChanges()
 {
     var workspace = new TestWorkspace();
     var solution = workspace.CurrentSolution;
     var project = workspace.AddProject("P1");
     Project ps = workspace.CurrentSolution.GetProject(project);
     Assert.Equal(null, ps.OutputFilePath);
     workspace.OnOutputFilePathChanged(project, "NewPath");            
     ps = workspace.CurrentSolution.GetProject(project);
     Assert.Equal("NewPath", ps.OutputFilePath);
 }
 public void TestMoveToLatestSolution()
 {
     var workspace = new TestWorkspace();
     var solution = workspace.CurrentSolution;
     var project1 = workspace.AddProject("P1");
     var graph = ProjectDependencyService.GetDependencyGraphAsync(workspace.CurrentSolution, CancellationToken.None).Result;
     var project2 = workspace.AddProject("P2");
     graph = ProjectDependencyService.GetDependencyGraphAsync(workspace.CurrentSolution, CancellationToken.None).Result;
     var sortedProjects = graph.GetTopologicallySortedProjects();
     AssertEx.SetEqual(sortedProjects, project1, project2);
     workspace.OnAssemblyNameChanged(project1, "ChangedP1");                     
 }
Exemple #5
0
            private static TestWorkspace CreateWorkspace(
                string projectLanguage,
                IEnumerable <string>?metadataSources,
                bool includeXmlDocComments,
                string?sourceWithSymbolReference,
                string?languageVersion,
                string?metadataLanguageVersion
                )
            {
                var languageVersionAttribute = languageVersion is null
                    ? ""
                    : $@" LanguageVersion=""{languageVersion}""";

                var xmlString = string.Concat(
                    @"
<Workspace>
    <Project Language=""",
                    projectLanguage,
                    @""" CommonReferences=""true""",
                    languageVersionAttribute
                    );

                xmlString += ">";

                metadataSources ??= new[] { AbstractMetadataAsSourceTests.DefaultMetadataSource };

                foreach (var source in metadataSources)
                {
                    var metadataLanguage = DeduceLanguageString(source);
                    var metadataLanguageVersionAttribute = metadataLanguageVersion is null
                        ? ""
                        : $@" LanguageVersion=""{metadataLanguageVersion}""";
                    xmlString = string.Concat(
                        xmlString,
                        $@"
        <MetadataReferenceFromSource Language=""{metadataLanguage}"" CommonReferences=""true"" {metadataLanguageVersionAttribute} IncludeXmlDocComments=""{includeXmlDocComments}"">
            <Document FilePath=""MetadataDocument"">
{SecurityElement.Escape(source)}
            </Document>
        </MetadataReferenceFromSource>"
                        );
                }

                if (sourceWithSymbolReference != null)
                {
                    xmlString = string.Concat(
                        xmlString,
                        string.Format(
                            @"
        <Document FilePath=""SourceDocument"">
{0}
        </Document>",
                            sourceWithSymbolReference
                            )
                        );
                }

                xmlString = string.Concat(
                    xmlString,
                    @"
    </Project>
</Workspace>"
                    );

                return(TestWorkspace.Create(xmlString));
            }
 public void Initialize()
 {
     _workspace = new TestWorkspace();
 }
 protected Task <TestLspServer> CreateMultiProjectLspServerAsync(string xmlMarkup, LSP.ClientCapabilities?clientCapabilities = null)
 => CreateTestLspServerAsync(TestWorkspace.Create(xmlMarkup, composition: Composition), clientCapabilities, WellKnownLspServerKinds.AlwaysActiveVSLspServer);
Exemple #8
0
 public static T GetService <T>(TestWorkspace workspace)
 => workspace.GetService <T>();
Exemple #9
0
 protected abstract Action CreateNextHandler(TestWorkspace workspace);
 protected override TestWorkspace CreateWorkspaceFromFile(string definition, ParseOptions parseOptions)
 => TestWorkspace.CreateCSharp(definition, (CSharpParseOptions)parseOptions);
 public TestContext(TestWorkspace workspace)
 {
     _workspace = workspace;
     _metadataAsSourceService  = _workspace.GetService <IMetadataAsSourceFileService>();
     _textBufferFactoryService = _workspace.GetService <ITextBufferFactoryService>();
 }
 internal void InitializeWorkspace(TestWorkspace workspace)
 {
     _provider   = new NavigateToItemProvider(workspace, AsynchronousOperationListenerProvider.NullListener);
     _aggregator = new NavigateToTestAggregator(_provider);
 }
Exemple #13
0
 internal static Holder CreateSession(string code, Dictionary <OptionKey2, object> optionSet = null)
 {
     return(CreateSession(
                TestWorkspace.CreateCSharp(code),
                CurlyBrace.OpenCharacter, CurlyBrace.CloseCharacter, optionSet));
 }
 internal async Task <Tuple <Diagnostic, CodeFixCollection> > GetDiagnosticAndFixAsync(
     TestWorkspace workspace, string fixAllActionEquivalenceKey = null, object fixProviderData = null)
 {
     return((await GetDiagnosticAndFixesAsync(workspace, fixAllActionEquivalenceKey, fixProviderData)).FirstOrDefault());
 }
        private async Task <Tuple <Solution, Solution> > TestAddDocument(
            TestWorkspace workspace,
            string expected,
            IEnumerable <CodeActionOperation> operations,
            bool hasProjectChange,
            ProjectId modifiedProjectId,
            IList <string> expectedFolders,
            string expectedDocumentName,
            bool compareTokens)
        {
            var appliedChanges = ApplyOperationsAndGetSolution(workspace, operations);
            var oldSolution    = appliedChanges.Item1;
            var newSolution    = appliedChanges.Item2;

            Document addedDocument = null;

            if (!hasProjectChange)
            {
                addedDocument = SolutionUtilities.GetSingleAddedDocument(oldSolution, newSolution);
            }
            else
            {
                Assert.NotNull(modifiedProjectId);
                addedDocument = newSolution.GetProject(modifiedProjectId).Documents.SingleOrDefault(doc => doc.Name == expectedDocumentName);
            }

            Assert.NotNull(addedDocument);

            AssertEx.Equal(expectedFolders, addedDocument.Folders);
            Assert.Equal(expectedDocumentName, addedDocument.Name);
            if (compareTokens)
            {
                TokenUtilities.AssertTokensEqual(
                    expected, (await addedDocument.GetTextAsync()).ToString(), GetLanguage());
            }
            else
            {
                Assert.Equal(expected, (await addedDocument.GetTextAsync()).ToString());
            }

            var editHandler = workspace.ExportProvider.GetExportedValue <ICodeActionEditHandlerService>();

            if (!hasProjectChange)
            {
                // If there is just one document change then we expect the preview to be a WpfTextView
                var content  = (await editHandler.GetPreviews(workspace, operations, CancellationToken.None).GetPreviewsAsync())[0];
                var diffView = content as IWpfDifferenceViewer;
                Assert.NotNull(diffView);
                diffView.Close();
            }
            else
            {
                // If there are more changes than just the document we need to browse all the changes and get the document change
                var  contents   = editHandler.GetPreviews(workspace, operations, CancellationToken.None);
                bool hasPreview = false;
                var  previews   = await contents.GetPreviewsAsync();

                if (previews != null)
                {
                    foreach (var preview in previews)
                    {
                        if (preview != null)
                        {
                            var diffView = preview as IWpfDifferenceViewer;
                            if (diffView != null)
                            {
                                hasPreview = true;
                                diffView.Close();
                                break;
                            }
                        }
                    }
                }

                Assert.True(hasPreview);
            }

            return(Tuple.Create(oldSolution, newSolution));
        }
 internal abstract Task <IEnumerable <Diagnostic> > GetDiagnosticsAsync(TestWorkspace workspace, object fixProviderData);
 internal abstract Task <IEnumerable <Tuple <Diagnostic, CodeFixCollection> > > GetDiagnosticAndFixesAsync(
     TestWorkspace workspace, string fixAllActionEquivalenceKey, object fixProviderData);
Exemple #18
0
 private static bool IsWorkspaceElement(string text)
 {
     return(TestWorkspace.IsWorkspaceElement(text));
 }
Exemple #19
0
 protected abstract Task <IList <CodeAction> > GetCodeActionsWorkerAsync(
     TestWorkspace workspace, string fixAllActionEquivalenceKey, object fixProviderData = null);
Exemple #20
0
        private static async Task <List <IOutliningRegionTag> > GetTagsFromWorkspaceAsync(TestWorkspace workspace)
        {
            var hostdoc           = workspace.Documents.First();
            var view              = hostdoc.GetTextView();
            var textService       = workspace.GetService <ITextEditorFactoryService>();
            var editorService     = workspace.GetService <IEditorOptionsFactoryService>();
            var projectionService = workspace.GetService <IProjectionBufferFactoryService>();

            var provider = new VisualStudio14StructureTaggerProvider(
                workspace.ExportProvider.GetExportedValue <IForegroundNotificationService>(),
                textService, editorService, projectionService,
                AggregateAsynchronousOperationListener.EmptyListeners);

            var document = workspace.CurrentSolution.GetDocument(hostdoc.Id);
            var context  = new TaggerContext <IOutliningRegionTag>(document, view.TextSnapshot);
            await provider.ProduceTagsAsync_ForTestingPurposesOnly(context);

            return(context.tagSpans.Select(x => x.Tag).ToList());
        }
        public static ChangeSignatureTestState Create(XElement workspaceXml)
        {
            var workspace = TestWorkspace.Create(workspaceXml);

            return(new ChangeSignatureTestState(workspace));
        }
Exemple #22
0
 protected override Task <TestWorkspace> CreateWorkspaceFromFileAsync(string initialMarkup, TestParameters parameters)
 => TestWorkspace.CreateCSharpAsync(initialMarkup, parameters.parseOptions, parameters.compilationOptions);
 protected override Task <TestWorkspace> CreateWorkspaceFromFileAsync(string definition, ParseOptions parseOptions, CompilationOptions compilationOptions)
 {
     return(TestWorkspace.CreateCSharpAsync(definition, parseOptions, compilationOptions));
 }
Exemple #24
0
 public StaticChecksRun(TestWorkspace testWorkSpace)
 {
     this.testWorkspace = testWorkSpace;
 }
 protected override TestWorkspace CreateTestWorkspace(string initialMarkup)
 => TestWorkspace.CreateCSharp(initialMarkup);
Exemple #26
0
 internal abstract IChainedCommandHandler <AutomaticLineEnderCommandArgs> GetCommandHandler(TestWorkspace workspace);
 internal override AbstractCommentSelectionBase <ValueTuple> GetToggleCommentCommandHandler(TestWorkspace workspace)
 {
     return((AbstractCommentSelectionBase <ValueTuple>)workspace.ExportProvider.GetExportedValues <ICommandHandler>()
            .First(export => typeof(ToggleLineCommentCommandHandler).Equals(export.GetType())));
 }
Exemple #28
0
 public static T GetExportedValue <T>(TestWorkspace workspace)
 => workspace.ExportProvider.GetExportedValue <T>();
 internal override TestWorkspace GetWorkspace(string markup, ExportProvider exportProvider)
 => TestWorkspace.CreateCSharp(markup, exportProvider: exportProvider);
 /// <summary>
 /// Waits for the async operations on the workspace to complete.
 /// This ensures that events like workspace registration / workspace changes are processed by the time we exit this method.
 /// </summary>
 protected static async Task WaitForWorkspaceOperationsAsync(TestWorkspace workspace)
 {
     var workspaceWaiter = GetWorkspaceWaiter(workspace);
     await workspaceWaiter.ExpeditedWaitAsync();
 }
        public async Task TestTagsChangedForPortionThatChanged()
        {
            var code =
                @"class Program2
{
    string x = @""/// <summary>$$
/// </summary>"";
}";

            using var workspace = TestWorkspace.CreateCSharp(code);
            var document      = workspace.Documents.First();
            var subjectBuffer = document.GetTextBuffer();

            var checkpoint = new Checkpoint();

            var notificationService = workspace.GetService <IForegroundNotificationService>();
            var tagComputer         = new SyntacticClassificationTaggerProvider.TagComputer(
                new SyntacticClassificationTaggerProvider(
                    workspace.ExportProvider.GetExportedValue <IThreadingContext>(),
                    notificationService,
                    typeMap: null,
                    AsynchronousOperationListenerProvider.NullProvider),
                subjectBuffer,
                notificationService,
                AsynchronousOperationListenerProvider.NullListener,
                typeMap: null,
                diffTimeout: TimeSpan.MaxValue);

            // Capture the expected value before the await, in case it changes.
            var expectedLength      = subjectBuffer.CurrentSnapshot.Length;
            int?actualVersionNumber = null;
            int?actualLength        = null;
            var callstacks          = new List <string>();

            tagComputer.TagsChanged += (s, e) =>
            {
                actualVersionNumber = e.Span.Snapshot.Version.VersionNumber;
                actualLength        = e.Span.Length;
                callstacks.Add(new StackTrace().ToString());
                checkpoint.Release();
            };

            await checkpoint.Task;

            Assert.Equal(0, actualVersionNumber);
            Assert.Equal(expectedLength, actualLength);
            Assert.Equal(1, callstacks.Count);

            checkpoint = new Checkpoint();

            // Now apply an edit that require us to reclassify more that just the current line
            var snapshot = subjectBuffer.Insert(document.CursorPosition.Value, "\"");

            expectedLength = snapshot.Length;

            // NOTE: TagsChanged is raised on the UI thread, so there is no race between
            // assigning expected here and verifying in the event handler, because the
            // event handler can't run until we await.
            await checkpoint.Task;

            Assert.Equal(1, actualVersionNumber);
            Assert.Equal(37, actualLength);
            Assert.Equal(2, callstacks.Count);
        }
 private static async Task <TestWorkspace> CreateWorkspaceFromFileAsync(string file, bool isVisualBasic, ParseOptions parseOptions, CompilationOptions compilationOptions)
 {
     return(isVisualBasic ?
            await TestWorkspace.CreateVisualBasicAsync(file, (VB.VisualBasicParseOptions) parseOptions, (VB.VisualBasicCompilationOptions) compilationOptions) :
            await TestWorkspace.CreateCSharpAsync(file, (CS.CSharpParseOptions) parseOptions, (CS.CSharpCompilationOptions) compilationOptions));
 }
        public async Task AnalyzeDocumentAsync_InsignificantChangesInMethodBody()
        {
            var source1 = @"
class C
{
    public static void Main()
    {
        // comment
        System.Console.WriteLine(1);
    }
}
";
            var source2 = @"
class C
{
    public static void Main()
    {
        System.Console.WriteLine(1);
    }
}
";

            using var workspace = TestWorkspace.CreateCSharp(source1, exportProvider: s_exportProviderFactoryWithTestActiveStatementSpanTracker.CreateExportProvider());
            var oldSolution = workspace.CurrentSolution;
            var oldProject  = oldSolution.Projects.Single();
            var oldDocument = oldProject.Documents.Single();
            var oldText     = await oldDocument.GetTextAsync();

            var oldSyntaxRoot = await oldDocument.GetSyntaxRootAsync();

            var documentId  = oldDocument.Id;
            var newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2));
            var newDocument = newSolution.GetDocument(documentId);
            var newText     = await newDocument.GetTextAsync();

            var newSyntaxRoot = await newDocument.GetSyntaxRootAsync();

            const string oldStatementSource   = "System.Console.WriteLine(1);";
            var          oldStatementPosition = source1.IndexOf(oldStatementSource, StringComparison.Ordinal);
            var          oldStatementTextSpan = new TextSpan(oldStatementPosition, oldStatementSource.Length);
            var          oldStatementSpan     = oldText.Lines.GetLinePositionSpan(oldStatementTextSpan);
            var          oldStatementSyntax   = oldSyntaxRoot.FindNode(oldStatementTextSpan);

            var baseActiveStatements = ImmutableArray.Create(ActiveStatementsDescription.CreateActiveStatement(ActiveStatementFlags.IsLeafFrame, oldStatementSpan, DocumentId.CreateNewId(ProjectId.CreateNewId())));
            var spanTracker          = Assert.IsType <TestActiveStatementSpanTracker>(workspace.Services.GetRequiredService <IActiveStatementSpanTrackerFactory>().GetOrCreateActiveStatementSpanTracker());
            var analyzer             = new CSharpEditAndContinueAnalyzer(spanTracker);

            var result = await analyzer.AnalyzeDocumentAsync(oldDocument, baseActiveStatements, newDocument, CancellationToken.None);

            Assert.True(result.HasChanges);
            Assert.True(result.SemanticEdits[0].PreserveLocalVariables);
            var syntaxMap = result.SemanticEdits[0].SyntaxMap;

            var newStatementSpan     = result.ActiveStatements[0].Span;
            var newStatementTextSpan = newText.Lines.GetTextSpan(newStatementSpan);
            var newStatementSyntax   = newSyntaxRoot.FindNode(newStatementTextSpan);

            var oldStatementSyntaxMapped = syntaxMap(newStatementSyntax);

            Assert.Same(oldStatementSyntax, oldStatementSyntaxMapped);
        }
 public Holder(TestWorkspace workspace, IBraceCompletionSession session)
 {
     this.Workspace = workspace;
     this.Session   = session;
 }
Exemple #35
0
 protected async Task <IList <CodeAction> > GetCodeActionsAsync(
     TestWorkspace workspace, string fixAllActionEquivalenceKey, object fixProviderData = null)
 {
     return(MassageActions(await GetCodeActionsWorkerAsync(workspace, fixAllActionEquivalenceKey, fixProviderData)));
 }