From 364907d7a18ced4f0e65ebbc7ff0f5bce25a18d1 Mon Sep 17 00:00:00 2001 From: tmat Date: Mon, 12 May 2025 14:31:53 -0700 Subject: [PATCH 1/7] Fix MoveType to create debuggable documents --- eng/config/BannedSymbols.txt | 1 + ...ionOrUserDiagnosticTest_TestAddDocument.cs | 12 +++++------ ...ctUserDiagnosticTest_GenerateTypeDialog.cs | 11 ++++------ .../MoveType/AbstractMoveTypeTest.cs | 21 +++++++++++++------ .../AbstractMoveTypeService.Editor.cs | 6 ++++++ .../AbstractMoveTypeService.MoveTypeEditor.cs | 6 ++---- .../Portable/Workspace/Solution/Solution.cs | 3 +++ .../CoreTest/SolutionTests/SolutionTests.cs | 5 ++++- .../CoreTestUtilities/SolutionUtilities.cs | 2 +- .../Workspaces/TestHostDocument.cs | 3 ++- .../TestWorkspace_XmlConsumption.cs | 9 +++++++- 11 files changed, 51 insertions(+), 28 deletions(-) diff --git a/eng/config/BannedSymbols.txt b/eng/config/BannedSymbols.txt index d8c18b513fdbf..8558e121b5dc2 100644 --- a/eng/config/BannedSymbols.txt +++ b/eng/config/BannedSymbols.txt @@ -59,6 +59,7 @@ M:Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.Create(Microsoft.Code M:Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.Create(Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxNode,Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions,System.String,System.Text.Encoding); Use VisualBasicSyntaxTree sublass that takes checksum algorithm M:Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.ParseText(System.String,Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions,System.String,System.Text.Encoding,System.Collections.Immutable.ImmutableDictionary{System.String,Microsoft.CodeAnalysis.ReportDiagnostic},System.Threading.CancellationToken); Use overload with SourceText M:Microsoft.CodeAnalysis.Workspaces.Workspace.SetCurrentSolution(Microsoft.CodeAnalysis.Solution); Use SetCurrentSolutionEx instead. +M:Microsoft.CodeAnalysis.Project.AddDocument(System.String,System.String,System.Collections.Generic.IEnumerable{System.String},System.String); Use overload that takes SourceText. Make sure SourceText is created with encoding and checksum algorithm. M:System.Enum.GetHashCode(); Cast to integral type to avoid boxing on .NET Framework M:Microsoft.CodeAnalysis.CodeActions.CodeAction.PostProcessAsync(System.Collections.Generic.IEnumerable{Microsoft.CodeAnalysis.CodeActions.CodeActionOperation},System.Threading.CancellationToken); Use overload that takes a solution M:Microsoft.CodeAnalysis.CodeActions.CodeAction.PostProcessChangesAsync(Microsoft.CodeAnalysis.Solution,System.Threading.CancellationToken); Use overload that takes a solution diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest_TestAddDocument.cs b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest_TestAddDocument.cs index 80348a22e8dfa..e2c6489f88bbc 100644 --- a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest_TestAddDocument.cs +++ b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest_TestAddDocument.cs @@ -43,7 +43,7 @@ await TestAddDocument( } } - protected async Task> TestAddDocumentAsync( + protected async Task<(Solution oldSolution, Solution newSolution)> TestAddDocumentAsync( TestParameters parameters, EditorTestWorkspace workspace, string expectedMarkup, @@ -71,7 +71,7 @@ await TestAddDocument( expectedDocumentName, action); } - private async Task> TestAddDocument( + private async Task<(Solution oldSolution, Solution newSolution)> TestAddDocument( EditorTestWorkspace workspace, string expectedMarkup, ImmutableArray expectedFolders, @@ -89,7 +89,7 @@ private async Task> TestAddDocument( expectedDocumentName: expectedDocumentName); } - protected static async Task> TestAddDocument( + protected static async Task<(Solution oldSolution, Solution newSolution)> TestAddDocument( EditorTestWorkspace workspace, string expected, ImmutableArray operations, @@ -98,9 +98,7 @@ protected static async Task> TestAddDocument( ImmutableArray expectedFolders, string expectedDocumentName) { - var appliedChanges = await ApplyOperationsAndGetSolutionAsync(workspace, operations); - var oldSolution = appliedChanges.Item1; - var newSolution = appliedChanges.Item2; + var (oldSolution, newSolution) = await ApplyOperationsAndGetSolutionAsync(workspace, operations); Document addedDocument = null; if (!hasProjectChange) @@ -155,6 +153,6 @@ protected static async Task> TestAddDocument( Assert.True(hasPreview); } - return Tuple.Create(oldSolution, newSolution); + return (oldSolution, newSolution); } } diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractUserDiagnosticTest_GenerateTypeDialog.cs b/src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractUserDiagnosticTest_GenerateTypeDialog.cs index 09ab9950482e3..4233fdfac332f 100644 --- a/src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractUserDiagnosticTest_GenerateTypeDialog.cs +++ b/src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractUserDiagnosticTest_GenerateTypeDialog.cs @@ -99,11 +99,11 @@ internal async Task TestWithMockedGenerateTypeDialog( Assert.Equal(action.Title, FeaturesResources.Generate_new_type); var operations = await action.GetOperationsAsync( workspace.CurrentSolution, CodeAnalysisProgress.None, CancellationToken.None); - Tuple oldSolutionAndNewSolution = null; + Solution oldSolution, newSolution; if (!isNewFile) { - oldSolutionAndNewSolution = await TestOperationsAsync( + (oldSolution, newSolution) = await TestOperationsAsync( testState.Workspace, expected, operations, conflictSpans: [], renameSpans: [], @@ -113,11 +113,11 @@ internal async Task TestWithMockedGenerateTypeDialog( } else { - oldSolutionAndNewSolution = await TestAddDocument( + (oldSolution, newSolution) = await TestAddDocument( testState.Workspace, expected, operations, - projectName != null, + hasProjectChange: projectName != null, testState.ProjectToBeModified.Id, newFileFolderContainers, newFileName); @@ -136,8 +136,6 @@ await TestOperationsAsync(testState.Workspace, expectedTextWithUsings, operation if (checkIfUsingsNotIncluded) { - var oldSolution = oldSolutionAndNewSolution.Item1; - var newSolution = oldSolutionAndNewSolution.Item2; var changedDocumentIds = SolutionUtilities.GetChangedDocuments(oldSolution, newSolution); Assert.False(changedDocumentIds.Contains(testState.InvocationDocument.Id)); @@ -147,7 +145,6 @@ await TestOperationsAsync(testState.Workspace, expectedTextWithUsings, operation if (projectName != null) { var appliedChanges = await ApplyOperationsAndGetSolutionAsync(testState.Workspace, operations); - var newSolution = appliedChanges.Item2; var triggeredProject = newSolution.GetProject(testState.TriggeredProject.Id); // Make sure the Project reference is present diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/MoveType/AbstractMoveTypeTest.cs b/src/EditorFeatures/DiagnosticsTestUtilities/MoveType/AbstractMoveTypeTest.cs index 4ef6536f45d98..2a338dbee381e 100644 --- a/src/EditorFeatures/DiagnosticsTestUtilities/MoveType/AbstractMoveTypeTest.cs +++ b/src/EditorFeatures/DiagnosticsTestUtilities/MoveType/AbstractMoveTypeTest.cs @@ -7,6 +7,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -14,6 +15,7 @@ using Microsoft.CodeAnalysis.CodeRefactorings.MoveType; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; +using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.UnitTests; using Roslyn.Test.Utilities; @@ -159,19 +161,26 @@ private protected async Task TestMoveTypeToNewFileAsync( var sourceDocumentId = workspace.Documents[0].Id; // Verify the newly added document and its text - var oldSolutionAndNewSolution = await TestAddDocumentAsync( + var (oldSolution, newSolution) = await TestAddDocumentAsync( testOptions, workspace, destinationDocumentText, expectedDocumentName, destinationDocumentContainers); // Verify source document's text after moving type. - var oldSolution = oldSolutionAndNewSolution.Item1; - var newSolution = oldSolutionAndNewSolution.Item2; var changedDocumentIds = SolutionUtilities.GetChangedDocuments(oldSolution, newSolution); Assert.True(changedDocumentIds.Contains(sourceDocumentId), "source document was not changed."); - var modifiedSourceDocument = newSolution.GetDocument(sourceDocumentId); - var actualSourceTextAfterRefactoring = (await modifiedSourceDocument.GetTextAsync()).ToString(); - AssertEx.Equal(expectedSourceTextAfterRefactoring, actualSourceTextAfterRefactoring); + var addedDocument = SolutionUtilities.GetSingleAddedDocument(oldSolution, newSolution); + var addedSourceText = await addedDocument.GetTextAsync(); + var oldSourceDocument = oldSolution.GetRequiredDocument(sourceDocumentId); + var oldSourceText = await oldSourceDocument.GetTextAsync(); + var newSourceDocument = newSolution.GetRequiredDocument(sourceDocumentId); + var newSourceText = await newSourceDocument.GetTextAsync(); + + Assert.Equal(Path.Combine(Path.GetDirectoryName(addedDocument.FilePath), expectedDocumentName), addedDocument.FilePath); + Assert.Equal(oldSourceText.Encoding, addedSourceText.Encoding); + Assert.Equal(oldSourceText.ChecksumAlgorithm, addedSourceText.ChecksumAlgorithm); + + AssertEx.Equal(expectedSourceTextAfterRefactoring, newSourceText.ToString()); } else { diff --git a/src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.Editor.cs b/src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.Editor.cs index 35aede8ef24c6..7e70c10d45391 100644 --- a/src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.Editor.cs +++ b/src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.Editor.cs @@ -6,6 +6,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeRefactorings.MoveType; @@ -50,5 +51,10 @@ public static Editor GetEditor(MoveTypeOperationKind operationKind, TService ser MoveTypeOperationKind.MoveTypeNamespaceScope => new MoveTypeNamespaceScopeEditor(service, document, typeDeclaration, fileName, cancellationToken), _ => throw ExceptionUtilities.UnexpectedValue(operationKind), }; + + protected string? GetTargetDocumentFilePath() + => PathUtilities.GetDirectoryName(SemanticDocument.Document.FilePath) is { } dir + ? PathUtilities.CombinePaths(dir, FileName) + : null; } } diff --git a/src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.MoveTypeEditor.cs b/src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.MoveTypeEditor.cs index e4fc8389b3993..2bd31a250ab03 100644 --- a/src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.MoveTypeEditor.cs +++ b/src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.MoveTypeEditor.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -157,10 +158,7 @@ private async Task AddNewDocumentWithSingleTypeDeclarationAsync(Docume // add an empty document to solution, so that we'll have options from the right context. var solutionWithNewDocument = projectToBeUpdated.Solution.AddDocument( - newDocumentId, FileName, text: string.Empty, folders: document.Folders); - - // update the text for the new document - solutionWithNewDocument = solutionWithNewDocument.WithDocumentSyntaxRoot(newDocumentId, modifiedRoot, PreservationMode.PreserveIdentity); + newDocumentId, FileName, modifiedRoot, document.Folders, filePath: GetTargetDocumentFilePath()); // get the updated document, give it the minimal set of imports that the type // inside it needs. diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs b/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs index f208799139398..9a7b2fad65d87 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs @@ -985,7 +985,10 @@ public Solution AddDocument(DocumentId documentId, string name, SyntaxNode synta if (syntaxRoot == null) throw new ArgumentNullException(nameof(syntaxRoot)); + var project = GetRequiredProjectState(documentId.ProjectId); + + // The empty text is replaced in WithDocumentSyntaxRoot with the actual text that matches the syntax tree. var sourceText = SourceText.From(string.Empty, encoding: null, project.ChecksumAlgorithm); return AddDocumentImpl(project, documentId, name, sourceText, PublicContract.ToBoxedImmutableArrayWithNonNullItems(folders, nameof(folders)), filePath, isGenerated). diff --git a/src/Workspaces/CoreTest/SolutionTests/SolutionTests.cs b/src/Workspaces/CoreTest/SolutionTests/SolutionTests.cs index 08255f93bca97..f57480561bcad 100644 --- a/src/Workspaces/CoreTest/SolutionTests/SolutionTests.cs +++ b/src/Workspaces/CoreTest/SolutionTests/SolutionTests.cs @@ -2478,7 +2478,7 @@ public void AddDocument_SyntaxRoot_ExplicitTree() var filePath = Path.Combine(TempRoot.Root, "x.cs"); var folders = new[] { "folder1", "folder2" }; - var root = CSharp.SyntaxFactory.ParseSyntaxTree(SourceText.From("class C {}", encoding: null, SourceHashAlgorithm.Sha1)).GetRoot(); + var root = CSharp.SyntaxFactory.ParseSyntaxTree(SourceText.From("class C {}", encoding: Encoding.ASCII, SourceHashAlgorithm.Sha1)).GetRoot(); Assert.Equal(SourceHashAlgorithm.Sha1, root.SyntaxTree.GetText().ChecksumAlgorithm); var solution2 = solution.AddDocument(documentId, "name", root, folders, filePath); @@ -2489,6 +2489,9 @@ public void AddDocument_SyntaxRoot_ExplicitTree() // the checksum algorithm of the tree is ignored, instead the one set on the project is used: Assert.Equal(SourceHashAlgorithms.Default, sourceText.ChecksumAlgorithm); + // the encoding is preserved: + Assert.Equal(Encoding.ASCII, sourceText.Encoding); + AssertEx.Equal(folders, document2.Folders); Assert.Equal(filePath, document2.FilePath); Assert.False(document2.State.Attributes.IsGenerated); diff --git a/src/Workspaces/CoreTestUtilities/SolutionUtilities.cs b/src/Workspaces/CoreTestUtilities/SolutionUtilities.cs index 228cb2057c98d..5457e905eb83d 100644 --- a/src/Workspaces/CoreTestUtilities/SolutionUtilities.cs +++ b/src/Workspaces/CoreTestUtilities/SolutionUtilities.cs @@ -69,7 +69,7 @@ public static Document GetSingleAddedDocument(Solution oldSolution, Solution new var projectDifferences = GetSingleChangedProjectChanges(oldSolution, newSolution); var documentId = projectDifferences.GetAddedDocuments().Single(); - return newSolution.GetDocument(documentId)!; + return newSolution.GetRequiredDocument(documentId); } public static IEnumerable GetTextChangedDocuments(Solution oldSolution, Solution newSolution) diff --git a/src/Workspaces/CoreTestUtilities/Workspaces/TestHostDocument.cs b/src/Workspaces/CoreTestUtilities/Workspaces/TestHostDocument.cs index 11b3e983608cf..4eee565e43341 100644 --- a/src/Workspaces/CoreTestUtilities/Workspaces/TestHostDocument.cs +++ b/src/Workspaces/CoreTestUtilities/Workspaces/TestHostDocument.cs @@ -6,6 +6,7 @@ using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; +using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; @@ -186,7 +187,7 @@ internal override string? FilePath => _hostDocument.FilePath; public override Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) - => Task.FromResult(TextAndVersion.Create(SourceText.From(_text, encoding: null, options.ChecksumAlgorithm), VersionStamp.Create(), _hostDocument.FilePath)); + => Task.FromResult(TextAndVersion.Create(SourceText.From(_text, encoding: Encoding.UTF8, options.ChecksumAlgorithm), VersionStamp.Create(), _hostDocument.FilePath)); } public TextLoader Loader => _loader; diff --git a/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace_XmlConsumption.cs b/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace_XmlConsumption.cs index 276c64ce2636e..2b8004f4234a7 100644 --- a/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace_XmlConsumption.cs +++ b/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace_XmlConsumption.cs @@ -146,6 +146,11 @@ private TProject CreateProject( language == LanguageNames.VisualBasic ? ".vbproj" : ("." + language)); } + if (projectFilePath != null) + { + projectFilePath = PathUtilities.CombinePaths(TempRoot.Root, projectFilePath); + } + var projectOutputDir = AbstractTestHostProject.GetTestOutputDirectory(projectFilePath); var languageServices = Services.GetLanguageServices(language); @@ -667,8 +672,10 @@ private TDocument CreateDocument( AssertEx.Fail($"The document attributes on file {fileName} conflicted"); } + var filePath = Path.Combine(TempRoot.Root, fileName); + return CreateDocument( - exportProvider, languageServiceProvider, code, fileName, fileName, cursorPosition, spans, codeKind, folders, isLinkFile, documentServiceProvider); + exportProvider, languageServiceProvider, code, fileName, filePath, cursorPosition, spans, codeKind, folders, isLinkFile, documentServiceProvider); } #nullable enable From 3fc25c8e8812fda2bbf5bdfda158bd235bc51685 Mon Sep 17 00:00:00 2001 From: tmat Date: Mon, 12 May 2025 14:53:13 -0700 Subject: [PATCH 2/7] Fixes --- ...der.AbstractGlobalSuppressMessageCodeAction.cs | 5 ++++- .../Snippets/AbstractSnippetProviderTests.cs | 15 ++++++++++++--- .../Core/Portable/Workspace/Solution/Solution.cs | 1 - 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.AbstractGlobalSuppressMessageCodeAction.cs b/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.AbstractGlobalSuppressMessageCodeAction.cs index dce4b49dc2284..37a1d650a4e9e 100644 --- a/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.AbstractGlobalSuppressMessageCodeAction.cs +++ b/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.AbstractGlobalSuppressMessageCodeAction.cs @@ -8,10 +8,12 @@ using System.Collections.Immutable; using System.IO; using System.Linq; +using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.LanguageService; +using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes.Suppression; @@ -104,7 +106,8 @@ protected async Task GetOrCreateSuppressionsDocumentAsync(Cancellation else { // Create an empty global suppressions file. - suppressionsDoc = _project.AddDocument(suppressionsFileName, string.Empty); + var emptyText = SourceText.From("", Encoding.UTF8, SourceHashAlgorithms.Default); + suppressionsDoc = _project.AddDocument(suppressionsFileName, emptyText, filePath: suppressionsFilePath); } } } diff --git a/src/Features/TestUtilities/Snippets/AbstractSnippetProviderTests.cs b/src/Features/TestUtilities/Snippets/AbstractSnippetProviderTests.cs index 838958b955dd1..53086d840f911 100644 --- a/src/Features/TestUtilities/Snippets/AbstractSnippetProviderTests.cs +++ b/src/Features/TestUtilities/Snippets/AbstractSnippetProviderTests.cs @@ -4,6 +4,8 @@ using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Extensions; @@ -37,11 +39,18 @@ protected async Task VerifySnippetAsync( .WithMetadataReferences(metadataReferences); TestFileMarkupParser.GetPosition(markupBeforeCommit, out markupBeforeCommit, out var snippetRequestPosition); - var document = project.AddDocument("TestDocument", markupBeforeCommit, filePath: "/TestDocument"); + var document = project.AddDocument( + "TestDocument", + SourceText.From(markupBeforeCommit, Encoding.UTF8, SourceHashAlgorithms.Default), + filePath: Path.Combine(TempRoot.Root, "TestDocument")); if (editorconfig is not null) { - var editorConfigDoc = document.Project.AddAnalyzerConfigDocument(".editorconfig", SourceText.From(editorconfig), filePath: "/.editorconfig"); + var editorConfigDoc = document.Project.AddAnalyzerConfigDocument( + ".editorconfig", + SourceText.From(editorconfig, Encoding.UTF8, SourceHashAlgorithms.Default), + filePath: Path.Combine(TempRoot.Root, ".editorconfig")); + document = editorConfigDoc.Project.GetDocument(document.Id)!; } @@ -120,7 +129,7 @@ protected async Task VerifySnippetIsAbsentAsync( .WithMetadataReferences(metadataReferences); TestFileMarkupParser.GetPosition(markup, out markup, out var snippetRequestPosition); - var document = project.AddDocument("TestDocument", markup); + var document = project.AddDocument("TestDocument", SourceText.From(markup, Encoding.UTF8, SourceHashAlgorithms.Default)); var snippetServiceInterface = document.GetRequiredLanguageService(); var snippetService = Assert.IsAssignableFrom(snippetServiceInterface); diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs b/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs index 9a7b2fad65d87..e219806aa4dc4 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs @@ -985,7 +985,6 @@ public Solution AddDocument(DocumentId documentId, string name, SyntaxNode synta if (syntaxRoot == null) throw new ArgumentNullException(nameof(syntaxRoot)); - var project = GetRequiredProjectState(documentId.ProjectId); // The empty text is replaced in WithDocumentSyntaxRoot with the actual text that matches the syntax tree. From 8d8616b306922c3730bf9d6ce4d289968d4ef17d Mon Sep 17 00:00:00 2001 From: tmat Date: Mon, 12 May 2025 18:40:22 -0700 Subject: [PATCH 3/7] Fixes --- .../MakeFieldReadonlyTests.cs | 4 +- .../UseAutoProperty/UseAutoPropertyTests.cs | 16 +++--- .../UseAutoProperty/UseAutoPropertyTests.vb | 16 +++--- .../AddParameterTests.Formatting.cs | 4 +- .../ExtractInterface/ExtractInterfaceTests.cs | 2 +- ...stractMetadataAsSourceTests.TestContext.cs | 2 +- .../Test2/NavigationBar/TestHelpers.vb | 4 +- .../VisualBasicNavigationBarTests.vb | 18 +++---- .../Test2/Rename/RenameEngineTests.vb | 4 +- .../Test2/Rename/RenameTagProducerTests.vb | 2 +- .../SyncNamespacesServiceTests.vb | 21 ++++---- .../ExtractLocalFunctionTests.cs | 8 +-- .../AbstractLanguageServerProtocolTests.cs | 7 +-- .../Diagnostics/PullDiagnosticTests.cs | 51 +++++++++---------- .../CodeModel/CSharp/RootCodeModelTests.vb | 9 ++-- .../Workspaces/TestWorkspace.cs | 2 + .../TestWorkspace_XmlConsumption.cs | 4 +- 17 files changed, 87 insertions(+), 87 deletions(-) diff --git a/src/Analyzers/CSharp/Tests/MakeFieldReadonly/MakeFieldReadonlyTests.cs b/src/Analyzers/CSharp/Tests/MakeFieldReadonly/MakeFieldReadonlyTests.cs index 64900d236f191..19047d5507cd6 100644 --- a/src/Analyzers/CSharp/Tests/MakeFieldReadonly/MakeFieldReadonlyTests.cs +++ b/src/Analyzers/CSharp/Tests/MakeFieldReadonly/MakeFieldReadonlyTests.cs @@ -2012,7 +2012,7 @@ await TestMissingInRegularAndScriptAsync( """ - + public sealed partial class Test { private int [|_value|]; @@ -2021,7 +2021,7 @@ public static void M() => _ = new Test { Value = 1 }; } - + using System.CodeDom.Compiler; [GeneratedCode(null, null)] diff --git a/src/Analyzers/CSharp/Tests/UseAutoProperty/UseAutoPropertyTests.cs b/src/Analyzers/CSharp/Tests/UseAutoProperty/UseAutoPropertyTests.cs index dee40acd9b076..600dd05a4ac29 100644 --- a/src/Analyzers/CSharp/Tests/UseAutoProperty/UseAutoPropertyTests.cs +++ b/src/Analyzers/CSharp/Tests/UseAutoProperty/UseAutoPropertyTests.cs @@ -2751,7 +2751,7 @@ await TestInRegularAndScript1Async( """ - + public class Foo { private readonly object o; @@ -2759,7 +2759,7 @@ public class Foo [||]public object O => o; } - + [*] indent_style = tab @@ -2769,13 +2769,13 @@ public class Foo """ - + public class Foo { public object O { get; } } - + [*] indent_style = tab @@ -2791,7 +2791,7 @@ await TestInRegularAndScript1Async( """ - + public class Foo { private readonly object o; @@ -2799,7 +2799,7 @@ public class Foo [||]public object O => o; } - + [*] indent_style = space @@ -2809,13 +2809,13 @@ public class Foo """ - + public class Foo { public object O { get; } } - + [*] indent_style = space diff --git a/src/Analyzers/VisualBasic/Tests/UseAutoProperty/UseAutoPropertyTests.vb b/src/Analyzers/VisualBasic/Tests/UseAutoProperty/UseAutoPropertyTests.vb index b43157676639d..6b45bb99245ed 100644 --- a/src/Analyzers/VisualBasic/Tests/UseAutoProperty/UseAutoPropertyTests.vb +++ b/src/Analyzers/VisualBasic/Tests/UseAutoProperty/UseAutoPropertyTests.vb @@ -1126,7 +1126,7 @@ End Class", options:=[Option](FormattingOptions2.UseTabs, False)) Await TestInRegularAndScriptAsync( " - + Public Class Foo [||]Private ReadOnly o2 As Object @@ -1137,7 +1137,7 @@ Public Class Foo End Property End Class - + [*] indent_style = tab @@ -1145,12 +1145,12 @@ indent_style = tab ", " - + Public Class Foo Public ReadOnly Property O As Object End Class - + [*] indent_style = tab @@ -1163,7 +1163,7 @@ indent_style = tab Await TestInRegularAndScriptAsync( " - + Public Class Foo [||]Private ReadOnly o2 As Object @@ -1174,7 +1174,7 @@ Public Class Foo End Property End Class - + [*] indent_style = space @@ -1182,12 +1182,12 @@ indent_style = space ", " - + Public Class Foo Public ReadOnly Property O As Object End Class - + [*] indent_style = space diff --git a/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.Formatting.cs b/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.Formatting.cs index 7dfdd9d677337..7cbe3440a5533 100644 --- a/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.Formatting.cs +++ b/src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.Formatting.cs @@ -516,7 +516,7 @@ public async Task AddParameter_Formatting_PreserveIndentBraces_Editorconfig() var markup = @" - + public class C { public void M$$() @@ -524,7 +524,7 @@ public class C } } - [*.cs] + [*.cs] csharp_indent_braces = true diff --git a/src/EditorFeatures/CSharpTest/ExtractInterface/ExtractInterfaceTests.cs b/src/EditorFeatures/CSharpTest/ExtractInterface/ExtractInterfaceTests.cs index 13eb5390aa1f5..64ccb42a46c8b 100644 --- a/src/EditorFeatures/CSharpTest/ExtractInterface/ExtractInterfaceTests.cs +++ b/src/EditorFeatures/CSharpTest/ExtractInterface/ExtractInterfaceTests.cs @@ -2007,7 +2007,7 @@ public async Task RemoveEnumeratorCancellationAttribute() var markup = """ - GetNavigationSymbolAsync() { - var testDocument = Workspace.Documents.Single(d => d.FilePath == "SourceDocument"); + var testDocument = Workspace.Documents.Single(d => d.Name == "SourceDocument"); var document = Workspace.CurrentSolution.GetRequiredDocument(testDocument.Id); var syntaxRoot = await document.GetRequiredSyntaxRootAsync(CancellationToken.None); diff --git a/src/EditorFeatures/Test2/NavigationBar/TestHelpers.vb b/src/EditorFeatures/Test2/NavigationBar/TestHelpers.vb index 968c05751cb0c..e59a7ceebee6b 100644 --- a/src/EditorFeatures/Test2/NavigationBar/TestHelpers.vb +++ b/src/EditorFeatures/Test2/NavigationBar/TestHelpers.vb @@ -109,13 +109,13 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.NavigationBar Public Async Function AssertNavigationPointAsync( workspaceElement As XElement, host As TestHost, - startingDocumentFilePath As String, + startingDocumentName As String, leftItemToSelectText As String, rightItemToSelectText As String, Optional expectedVirtualSpace As Integer = 0) As Tasks.Task Using workspace = EditorTestWorkspace.Create(workspaceElement, composition:=If(host = TestHost.OutOfProcess, s_oopComposition, s_composition)) - Dim sourceDocument = workspace.CurrentSolution.Projects.First().Documents.First(Function(doc) doc.FilePath = startingDocumentFilePath) + Dim sourceDocument = workspace.CurrentSolution.Projects.First().Documents.First(Function(doc) doc.Name = startingDocumentName) Dim snapshot = (Await sourceDocument.GetTextAsync()).FindCorrespondingEditorTextSnapshot() Dim service = DirectCast(sourceDocument.GetLanguageService(Of INavigationBarItemService)(), AbstractEditorNavigationBarItemService) diff --git a/src/EditorFeatures/Test2/NavigationBar/VisualBasicNavigationBarTests.vb b/src/EditorFeatures/Test2/NavigationBar/VisualBasicNavigationBarTests.vb index d50444ee7e6ed..cea7a0b15518f 100644 --- a/src/EditorFeatures/Test2/NavigationBar/VisualBasicNavigationBarTests.vb +++ b/src/EditorFeatures/Test2/NavigationBar/VisualBasicNavigationBarTests.vb @@ -956,7 +956,7 @@ End Class , host, - startingDocumentFilePath:="Source.vb", + startingDocumentName:="Source.vb", leftItemToSelectText:="Program", rightItemToSelectText:="TargetMethod") End Function @@ -979,7 +979,7 @@ End Class , host, - startingDocumentFilePath:="Code.vb", + startingDocumentName:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="SomeNumbers") End Function @@ -997,7 +997,7 @@ End Class , host, - startingDocumentFilePath:="Code.vb", + startingDocumentName:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function @@ -1016,7 +1016,7 @@ End Class , host, - startingDocumentFilePath:="Code.vb", + startingDocumentName:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function @@ -1038,7 +1038,7 @@ End Class , host, - startingDocumentFilePath:="Code.vb", + startingDocumentName:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function @@ -1058,7 +1058,7 @@ End Class , host, - startingDocumentFilePath:="Code.vb", + startingDocumentName:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function @@ -1078,7 +1078,7 @@ End Class , host, - startingDocumentFilePath:="Code.vb", + startingDocumentName:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function @@ -1098,7 +1098,7 @@ End Class , host, - startingDocumentFilePath:="Code.vb", + startingDocumentName:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S", expectedVirtualSpace:=8) @@ -1119,7 +1119,7 @@ End Class , host, - startingDocumentFilePath:="Code.vb", + startingDocumentName:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S", expectedVirtualSpace:=4) diff --git a/src/EditorFeatures/Test2/Rename/RenameEngineTests.vb b/src/EditorFeatures/Test2/Rename/RenameEngineTests.vb index cad46c181540c..88df9f53b3fdf 100644 --- a/src/EditorFeatures/Test2/Rename/RenameEngineTests.vb +++ b/src/EditorFeatures/Test2/Rename/RenameEngineTests.vb @@ -345,8 +345,8 @@ class C2 , host:=host, renameTo:="def") - Dim originalDocument = result.ConflictResolution.OldSolution.Projects.First().Documents.Where(Function(d) d.FilePath = "Test2.cs").Single() - Dim newDocument = result.ConflictResolution.NewSolution.Projects.First().Documents.Where(Function(d) d.FilePath = "Test2.cs").Single() + Dim originalDocument = result.ConflictResolution.OldSolution.Projects.First().Documents.Where(Function(d) d.Name = "Test2.cs").Single() + Dim newDocument = result.ConflictResolution.NewSolution.Projects.First().Documents.Where(Function(d) d.Name = "Test2.cs").Single() Assert.Same(originalDocument.State, newDocument.State) Assert.Equal(1, result.ConflictResolution.NewSolution.GetChangedDocuments(result.ConflictResolution.OldSolution).Count) End Using diff --git a/src/EditorFeatures/Test2/Rename/RenameTagProducerTests.vb b/src/EditorFeatures/Test2/Rename/RenameTagProducerTests.vb index 043732945a107..cc44376e7e730 100644 --- a/src/EditorFeatures/Test2/Rename/RenameTagProducerTests.vb +++ b/src/EditorFeatures/Test2/Rename/RenameTagProducerTests.vb @@ -406,7 +406,7 @@ public class Class1 textBuffer.Replace(New Span(location, 1), "B") Await WaitForRename(workspace) - Dim conflictDocument = workspace.Documents.Single(Function(d) d.FilePath = "B.cs") + Dim conflictDocument = workspace.Documents.Single(Function(d) d.Name = "B.cs") Dim expectedSpans = GetAnnotatedSpans("conflict", conflictDocument) Dim taggedSpans = GetTagsOfType(RenameConflictTag.Instance, renameService, conflictDocument.GetTextBuffer()) Assert.Equal(expectedSpans, taggedSpans) diff --git a/src/EditorFeatures/Test2/SyncNamespaces/SyncNamespacesServiceTests.vb b/src/EditorFeatures/Test2/SyncNamespaces/SyncNamespacesServiceTests.vb index a2c2d4b2e7ac0..5464e3644f2ea 100644 --- a/src/EditorFeatures/Test2/SyncNamespaces/SyncNamespacesServiceTests.vb +++ b/src/EditorFeatures/Test2/SyncNamespaces/SyncNamespacesServiceTests.vb @@ -3,6 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable +Imports System.IO Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces @@ -207,13 +208,13 @@ namespace Test2.Namespace.App Public Async Function MultipleProjects_MultipleMismatchedNamespaces_HasChanges() As Task Dim test = - - + + is_global=true -build_property.ProjectDir = /Test/ +build_property.ProjectDir = <%= Path.Combine(TestWorkspace.RootDirectory, "Test") %> build_property.RootNamespace = Test.Namespace - + namespace Test.Namespace { class Goo @@ -222,13 +223,13 @@ namespace Test.Namespace } - - + + is_global=true -build_property.ProjectDir = /Test2/ +build_property.ProjectDir = <%= Path.Combine(TestWorkspace.RootDirectory, "Test2") %> build_property.RootNamespace = Test2.Namespace - + namespace Test2.Namespace { class Goo @@ -243,12 +244,12 @@ namespace Test2.Namespace Dim projects = workspace.CurrentSolution.Projects.ToImmutableArray() Dim project = projects.Single(Function(proj As Project) - Return proj.FilePath = "/Test/Test.csproj" + Return Path.GetFileName(proj.FilePath) = "Test.csproj" End Function) Dim document = project.Documents.Single() Dim project2 = projects.Single(Function(proj As Project) - Return proj.FilePath = "/Test2/Test2.csproj" + Return Path.GetFileName(proj.FilePath) = "Test2.csproj" End Function) Dim document2 = project2.Documents.Single() diff --git a/src/Features/CSharpTest/ExtractMethod/ExtractLocalFunctionTests.cs b/src/Features/CSharpTest/ExtractMethod/ExtractLocalFunctionTests.cs index 0ae7a1e3a0f34..c6586b0c3f0e1 100644 --- a/src/Features/CSharpTest/ExtractMethod/ExtractLocalFunctionTests.cs +++ b/src/Features/CSharpTest/ExtractMethod/ExtractLocalFunctionTests.cs @@ -4574,7 +4574,7 @@ public async Task TestNaming_CamelCase_DoesntApply() var input = """ - + class Program1 { static void Main() @@ -4584,7 +4584,7 @@ static void Main() } } - + """ + EditorConfigNaming_CamelCase + """ dotnet_naming_symbols.local_functions.required_modifiers = static @@ -4595,7 +4595,7 @@ static void Main() var expected = """ - + class Program1 { static void Main() @@ -4610,7 +4610,7 @@ bool NewMethod() } } - + """ + EditorConfigNaming_CamelCase + """ dotnet_naming_symbols.local_functions.required_modifiers = static diff --git a/src/LanguageServer/Protocol.TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs b/src/LanguageServer/Protocol.TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs index 9925ad95eab88..3f6b84fef0821 100644 --- a/src/LanguageServer/Protocol.TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs +++ b/src/LanguageServer/Protocol.TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs @@ -335,7 +335,7 @@ private async Task CreateTestLspServerAsync(LspTestWorkspace work if (document.IsSourceGenerated) continue; - solution = solution.WithDocumentFilePath(document.Id, GetDocumentFilePathFromName(document.Name)); + Assert.True(PathUtilities.IsAbsolute(document.FilePath)); var documentText = await solution.GetRequiredDocument(document.Id).GetTextAsync(CancellationToken.None); solution = solution.WithDocumentText(document.Id, SourceText.From(documentText.ToString(), System.Text.Encoding.UTF8, SourceHashAlgorithms.Default)); @@ -344,7 +344,7 @@ private async Task CreateTestLspServerAsync(LspTestWorkspace work foreach (var project in workspace.Projects) { // Ensure all the projects have a valid file path. - solution = solution.WithProjectFilePath(project.Id, GetDocumentFilePathFromName(project.FilePath)); + Assert.True(PathUtilities.IsAbsolute(project.FilePath)); } var analyzerReferencesByLanguage = CreateTestAnalyzersReference(); @@ -496,9 +496,6 @@ private protected static LSP.Location GetLocationPlusOne(LSP.Location originalLo }; } - private static string GetDocumentFilePathFromName(string documentName) - => "C:\\" + documentName; - private static LSP.DidChangeTextDocumentParams CreateDidChangeTextDocumentParams( DocumentUri documentUri, ImmutableArray<(LSP.Range Range, string Text)> changes) diff --git a/src/LanguageServer/ProtocolUnitTests/Diagnostics/PullDiagnosticTests.cs b/src/LanguageServer/ProtocolUnitTests/Diagnostics/PullDiagnosticTests.cs index aab9adbec58e5..0be41bed6132b 100644 --- a/src/LanguageServer/ProtocolUnitTests/Diagnostics/PullDiagnosticTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Diagnostics/PullDiagnosticTests.cs @@ -18,6 +18,7 @@ using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.TaskList; +using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Threading; using Roslyn.LanguageServer.Protocol; @@ -1263,18 +1264,20 @@ public async Task EditAndContinue(bool useVSDiagnostics, bool mutatingLspWorkspa var documentResults1 = await RunGetDocumentPullDiagnosticsAsync(testLspServer, openDocument.GetURI(), useVSDiagnostics, category: PullDiagnosticCategories.EditAndContinue); + var rootUri = ProtocolConversions.GetAbsoluteUriString(TestWorkspace.RootDirectory); + // both diagnostics located in the open document are reported: AssertEx.Equal( [ - "file:///C:/test1.cs -> [ENC_OPEN_DOC1,ENC_OPEN_DOC2]", + $"{rootUri}/test1.cs -> [ENC_OPEN_DOC1,ENC_OPEN_DOC2]", ], documentResults1.Select(Inspect)); var workspaceResults1 = await RunGetWorkspacePullDiagnosticsAsync(testLspServer, useVSDiagnostics, includeTaskListItems: false, category: PullDiagnosticCategories.EditAndContinue); AssertEx.Equal( [ - "file:///C:/test2.cs -> [ENC_CLOSED_DOC]", - "file:///C:/Test.csproj -> [ENC_PROJECT]", + $"{rootUri}/test2.cs -> [ENC_CLOSED_DOC]", + $"{rootUri}/Test.csproj -> [ENC_PROJECT]", ], workspaceResults1.Select(Inspect)); // clear workspace diagnostics: @@ -1287,15 +1290,15 @@ public async Task EditAndContinue(bool useVSDiagnostics, bool mutatingLspWorkspa AssertEx.Equal( [ - "file:///C:/test1.cs -> [ENC_OPEN_DOC2]", + $"{rootUri}/test1.cs -> [ENC_OPEN_DOC2]", ], documentResults2.Select(Inspect)); var workspaceResults2 = await RunGetWorkspacePullDiagnosticsAsync( testLspServer, useVSDiagnostics, previousResults: CreateDiagnosticParamsFromPreviousReports(workspaceResults1), includeTaskListItems: false, category: PullDiagnosticCategories.EditAndContinue); AssertEx.Equal( [ - "file:///C:/test2.cs -> []", - "file:///C:/Test.csproj -> []", + $"{rootUri}/test2.cs -> []", + $"{rootUri}/Test.csproj -> []", ], workspaceResults2.Select(Inspect)); // deactivate EnC session: @@ -1307,7 +1310,7 @@ public async Task EditAndContinue(bool useVSDiagnostics, bool mutatingLspWorkspa testLspServer, openDocument.GetURI(), previousResultId: documentResults2.Single().ResultId, useVSDiagnostics: useVSDiagnostics, category: PullDiagnosticCategories.EditAndContinue); AssertEx.Equal( [ - "file:///C:/test1.cs -> []", + $"{rootUri}/test1.cs -> []", ], documentResults3.Select(Inspect)); var workspaceResults3 = await RunGetWorkspacePullDiagnosticsAsync( @@ -1318,27 +1321,23 @@ static DiagnosticData CreateDocumentDiagnostic(string id, Document document) => CreateDiagnostic(id, document.Project, document); static DiagnosticData CreateDiagnostic(string id, Project project, Document? document = null) - { - return new( - id, - category: "EditAndContinue", - message: "test message", - severity: DiagnosticSeverity.Error, - defaultSeverity: DiagnosticSeverity.Error, - isEnabledByDefault: true, - warningLevel: 0, - projectId: project.Id, - customTags: [], - properties: ImmutableDictionary.Empty, - location: new DiagnosticDataLocation(new FileLinePositionSpan("file", span: default), document?.Id), - additionalLocations: [], - language: project.Language); - } + => new( + id, + category: "EditAndContinue", + message: "test message", + severity: DiagnosticSeverity.Error, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + warningLevel: 0, + projectId: project.Id, + customTags: [], + properties: ImmutableDictionary.Empty, + location: new DiagnosticDataLocation(new FileLinePositionSpan("file", span: default), document?.Id), + additionalLocations: [], + language: project.Language); static string Inspect(TestDiagnosticResult result) - { - return $"{result.TextDocument.DocumentUri} -> [{string.Join(",", result.Diagnostics?.Select(d => d.Code?.Value) ?? [])}]"; - } + => $"{result.TextDocument.DocumentUri} -> [{string.Join(",", result.Diagnostics?.Select(d => d.Code?.Value) ?? [])}]"; } [Theory, CombinatorialData] diff --git a/src/VisualStudio/Core/Test/CodeModel/CSharp/RootCodeModelTests.vb b/src/VisualStudio/Core/Test/CodeModel/CSharp/RootCodeModelTests.vb index 594df394db8b7..1dabe997b83e1 100644 --- a/src/VisualStudio/Core/Test/CodeModel/CSharp/RootCodeModelTests.vb +++ b/src/VisualStudio/Core/Test/CodeModel/CSharp/RootCodeModelTests.vb @@ -2,6 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports System.IO Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel @@ -176,7 +177,7 @@ namespace N Assert.NotNull(underlyingFileCodeModel) Dim filePath = underlyingFileCodeModel.Workspace.GetFilePath(underlyingFileCodeModel.GetDocumentId()) - Assert.Equal("C.cs", filePath) + Assert.Equal(Path.Combine(TestWorkspace.RootDirectory, "C.cs"), filePath) End Sub) End Sub @@ -213,7 +214,7 @@ namespace N Assert.NotNull(underlyingFileCodeModel) Dim filePath = underlyingFileCodeModel.Workspace.GetFilePath(underlyingFileCodeModel.GetDocumentId()) - Assert.Equal("C.g.cs", filePath) + Assert.Equal(Path.Combine(TestWorkspace.RootDirectory, "C.g.cs"), filePath) End Sub) End Sub @@ -258,7 +259,7 @@ namespace N Assert.NotNull(underlyingFileCodeModel) Dim filePath = underlyingFileCodeModel.Workspace.GetFilePath(underlyingFileCodeModel.GetDocumentId()) - Assert.Equal("C.cs", filePath) + Assert.Equal(Path.Combine(TestWorkspace.RootDirectory, "C.cs"), filePath) End Sub) End Sub @@ -303,7 +304,7 @@ namespace N Assert.NotNull(underlyingFileCodeModel) Dim filePath = underlyingFileCodeModel.Workspace.GetFilePath(underlyingFileCodeModel.GetDocumentId()) - Assert.Equal("C.cs", filePath) + Assert.Equal(Path.Combine(TestWorkspace.RootDirectory, "C.cs"), filePath) End Sub) End Sub diff --git a/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace.cs b/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace.cs index 3012bbc2a5680..001839622e629 100644 --- a/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace.cs +++ b/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace.cs @@ -14,6 +14,8 @@ namespace Microsoft.CodeAnalysis.Test.Utilities; public partial class TestWorkspace : TestWorkspace { + public static string RootDirectory => TempRoot.Root; + internal TestWorkspace( TestComposition? composition = null, string? workspaceKind = WorkspaceKind.Host, diff --git a/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace_XmlConsumption.cs b/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace_XmlConsumption.cs index 2b8004f4234a7..383d24c93fa07 100644 --- a/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace_XmlConsumption.cs +++ b/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace_XmlConsumption.cs @@ -148,7 +148,7 @@ private TProject CreateProject( if (projectFilePath != null) { - projectFilePath = PathUtilities.CombinePaths(TempRoot.Root, projectFilePath); + projectFilePath = PathUtilities.CombinePaths(TestWorkspace.RootDirectory, projectFilePath); } var projectOutputDir = AbstractTestHostProject.GetTestOutputDirectory(projectFilePath); @@ -672,7 +672,7 @@ private TDocument CreateDocument( AssertEx.Fail($"The document attributes on file {fileName} conflicted"); } - var filePath = Path.Combine(TempRoot.Root, fileName); + var filePath = Path.Combine(TestWorkspace.RootDirectory, fileName); return CreateDocument( exportProvider, languageServiceProvider, code, fileName, filePath, cursorPosition, spans, codeKind, folders, isLinkFile, documentServiceProvider); From 6c68488fabfde526346c6c7528364eb976a121d5 Mon Sep 17 00:00:00 2001 From: tmat Date: Tue, 13 May 2025 10:38:18 -0700 Subject: [PATCH 4/7] More fixes --- .../Diagnostics/DiagnosticProviderTests.vb | 3 +- .../Diagnostics/DiagnosticServiceTests.vb | 19 ++++--- src/EditorFeatures/Test2/Peek/PeekTests.vb | 6 +-- .../SyncNamespacesServiceTests.vb | 52 +++++++++---------- .../DocumentOutlineTestsBase.cs | 34 +++--------- 5 files changed, 47 insertions(+), 67 deletions(-) diff --git a/src/EditorFeatures/Test2/Diagnostics/DiagnosticProviderTests.vb b/src/EditorFeatures/Test2/Diagnostics/DiagnosticProviderTests.vb index 10b648744e280..4553ffe542eb1 100644 --- a/src/EditorFeatures/Test2/Diagnostics/DiagnosticProviderTests.vb +++ b/src/EditorFeatures/Test2/Diagnostics/DiagnosticProviderTests.vb @@ -3,6 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable +Imports System.IO Imports System.Threading Imports Microsoft.CodeAnalysis.CSharp Imports Microsoft.CodeAnalysis.Diagnostics @@ -331,7 +332,7 @@ Namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics.UnitTests Private Shared Function GetDocumentId(workspace As EditorTestWorkspace, document As String) As DocumentId Return (From doc In workspace.Documents - Where doc.FilePath.Equals(document) + Where Path.GetFileName(doc.FilePath).Equals(document) Select doc.Id).Single() End Function diff --git a/src/EditorFeatures/Test2/Diagnostics/DiagnosticServiceTests.vb b/src/EditorFeatures/Test2/Diagnostics/DiagnosticServiceTests.vb index 416331a733318..7137b683e809c 100644 --- a/src/EditorFeatures/Test2/Diagnostics/DiagnosticServiceTests.vb +++ b/src/EditorFeatures/Test2/Diagnostics/DiagnosticServiceTests.vb @@ -554,11 +554,12 @@ Namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics.UnitTests Using workspace = TestWorkspace.CreateWorkspace(test, composition:=s_compositionWithMockDiagnosticUpdateSourceRegistrationService) Dim solution = workspace.CurrentSolution Dim documentId = solution.Projects.Single().DocumentIds.Single() - solution = solution.WithDocumentTextLoader(documentId, New FailingTextLoader("Test.cs"), PreservationMode.PreserveIdentity) + Dim document = solution.GetDocument(documentId) + solution = solution.WithDocumentTextLoader(documentId, New FailingTextLoader(document.FilePath), PreservationMode.PreserveIdentity) Await workspace.ChangeSolutionAsync(solution) - Dim project = solution.Projects.Single() - Dim document = project.Documents.Single() + document = solution.GetDocument(documentId) + Dim project = document.Project ' analyzer throws an exception Dim analyzer = New CodeBlockStartedAnalyzer(Of Microsoft.CodeAnalysis.CSharp.SyntaxKind) @@ -572,7 +573,7 @@ Namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics.UnitTests Dim diagnostics = Await GetDiagnosticsForSpanAsync(diagnosticService, document, span).ConfigureAwait(False) Assert.Equal(1, diagnostics.Length) Assert.True(diagnostics(0).Id = "IDE1100") - Assert.Equal(String.Format(WorkspacesResources.Error_reading_content_of_source_file_0_1, "Test.cs", "Bad data!"), diagnostics(0).Message) + Assert.Equal(String.Format(WorkspacesResources.Error_reading_content_of_source_file_0_1, document.FilePath, "Bad data!"), diagnostics(0).Message) End Using End Function @@ -894,11 +895,13 @@ class AnonymousFunctions Using workspace = TestWorkspace.CreateWorkspace(test, composition:=s_compositionWithMockDiagnosticUpdateSourceRegistrationService) Dim solution = workspace.CurrentSolution Dim documentId = solution.Projects.Single().DocumentIds.Single() - solution = solution.WithDocumentTextLoader(documentId, New FailingTextLoader("Test.cs"), PreservationMode.PreserveIdentity) + Dim document = solution.GetDocument(documentId) + + solution = solution.WithDocumentTextLoader(documentId, New FailingTextLoader(document.FilePath), PreservationMode.PreserveIdentity) Await workspace.ChangeSolutionAsync(solution) - Dim project = solution.Projects.Single() - Dim document = project.Documents.Single() + document = solution.GetDocument(documentId) + Dim project = document.Project Dim analyzer = New StatefulCompilationAnalyzer Dim analyzerReference = New AnalyzerImageReference(ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer)) @@ -916,7 +919,7 @@ class AnonymousFunctions Dim documentDiagnostics = Await DiagnosticProviderTestUtilities.GetDocumentDiagnosticsAsync(workspace, document, TextSpan.FromBounds(0, 0)) AssertEx.Equal( { - "IDE1100: " & String.Format(WorkspacesResources.Error_reading_content_of_source_file_0_1, "Test.cs", "Bad data!") + "IDE1100: " & String.Format(WorkspacesResources.Error_reading_content_of_source_file_0_1, document.FilePath, "Bad data!") }, documentDiagnostics.Select(Function(d) d.Id & ": " & d.GetMessage())) End Using diff --git a/src/EditorFeatures/Test2/Peek/PeekTests.vb b/src/EditorFeatures/Test2/Peek/PeekTests.vb index 93223ec856638..4661fd9bb1566 100644 --- a/src/EditorFeatures/Test2/Peek/PeekTests.vb +++ b/src/EditorFeatures/Test2/Peek/PeekTests.vb @@ -204,15 +204,15 @@ public class D } } ]]> - public class Component { -#line 4 "Test.razor" +#line 4 "<%= Path.Combine(TestWorkspace.RootDirectory, "Test.razor") %>" public void M() { } } - ]]> + ) Dim result = GetPeekResultCollection(workspace) diff --git a/src/EditorFeatures/Test2/SyncNamespaces/SyncNamespacesServiceTests.vb b/src/EditorFeatures/Test2/SyncNamespaces/SyncNamespacesServiceTests.vb index 5464e3644f2ea..b715afd4b2475 100644 --- a/src/EditorFeatures/Test2/SyncNamespaces/SyncNamespacesServiceTests.vb +++ b/src/EditorFeatures/Test2/SyncNamespaces/SyncNamespacesServiceTests.vb @@ -5,8 +5,6 @@ Imports System.Collections.Immutable Imports System.IO Imports System.Threading -Imports Microsoft.CodeAnalysis.CodeActions -Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.SyncNamespaces @@ -19,13 +17,13 @@ Namespace Microsoft.CodeAnalysis.Editor.Implementation.CodeFixes.UnitTests Public Async Function SingleProject_MatchingNamespace_NoChanges() As Task Dim test = - - + + is_global=true -build_property.ProjectDir = /Test/ +build_property.ProjectDir = <%= Path.Combine(TestWorkspace.RootDirectory, "Test") %> build_property.RootNamespace = Test.Namespace - + namespace Test.Namespace.App { class Goo @@ -54,13 +52,13 @@ namespace Test.Namespace.App Public Async Function SingleProject_MismatchedNamespace_HasChanges() As Task Dim test = - - + + is_global=true -build_property.ProjectDir = /Test/ +build_property.ProjectDir = <%= Path.Combine(TestWorkspace.RootDirectory, "Test") %> build_property.RootNamespace = Test.Namespace - + namespace Test { class Goo @@ -97,13 +95,13 @@ namespace Test Public Async Function MultipleProjects_MatchingNamespaces_NoChanges() As Task Dim test = - - + + is_global=true -build_property.ProjectDir = /Test/ +build_property.ProjectDir = <%= Path.Combine(TestWorkspace.RootDirectory, "Test") %> build_property.RootNamespace = Test.Namespace - + namespace Test.Namespace.App { class Goo @@ -112,13 +110,13 @@ namespace Test.Namespace.App } - - + + is_global=true -build_property.ProjectDir = /Test2/ +build_property.ProjectDir = <%= Path.Combine(TestWorkspace.RootDirectory, "Test2") %> build_property.RootNamespace = Test2.Namespace - + namespace Test2.Namespace.App { class Goo @@ -147,13 +145,13 @@ namespace Test2.Namespace.App Public Async Function MultipleProjects_OneMismatchedNamespace_HasChanges() As Task Dim test = - - + + is_global=true -build_property.ProjectDir = /Test/ +build_property.ProjectDir = <%= Path.Combine(TestWorkspace.RootDirectory, "Test") %> build_property.RootNamespace = Test.Namespace - + namespace Test.Namespace { class Goo @@ -162,13 +160,13 @@ namespace Test.Namespace } - - + + is_global=true -build_property.ProjectDir = /Test2/ +build_property.ProjectDir = <%= Path.Combine(TestWorkspace.RootDirectory, "Test2") %> build_property.RootNamespace = Test2.Namespace - + namespace Test2.Namespace.App { class Goo @@ -183,7 +181,7 @@ namespace Test2.Namespace.App Dim projects = workspace.CurrentSolution.Projects.ToImmutableArray() Dim project = projects.Single(Function(proj As Project) - Return proj.FilePath = "/Test/Test.csproj" + Return Path.GetFileName(proj.FilePath) = "Test.csproj" End Function) Dim document = project.Documents.Single() diff --git a/src/VisualStudio/CSharp/Test/DocumentOutline/DocumentOutlineTestsBase.cs b/src/VisualStudio/CSharp/Test/DocumentOutline/DocumentOutlineTestsBase.cs index d0e17de34c5ef..87819c159de97 100644 --- a/src/VisualStudio/CSharp/Test/DocumentOutline/DocumentOutlineTestsBase.cs +++ b/src/VisualStudio/CSharp/Test/DocumentOutline/DocumentOutlineTestsBase.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; +using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; @@ -19,9 +20,8 @@ using Microsoft.VisualStudio.LanguageServer.Client; using Microsoft.VisualStudio.LanguageServices.DocumentOutline; using Microsoft.VisualStudio.Text; -using Roslyn.LanguageServer.Protocol; using Roslyn.Test.Utilities; -using StreamJsonRpc; +using Roslyn.Utilities; using Xunit.Abstractions; using static Roslyn.Test.Utilities.AbstractLanguageServerProtocolTests; using IAsyncDisposable = System.IAsyncDisposable; @@ -31,8 +31,6 @@ namespace Roslyn.VisualStudio.CSharp.UnitTests.DocumentOutline; [UseExportProvider] public abstract class DocumentOutlineTestsBase { - private const string PathRoot = "C:\\\ue25b\\"; - private readonly TestOutputLspLogger _logger; protected DocumentOutlineTestsBase(ITestOutputHelper testOutputHelper) { @@ -64,7 +62,7 @@ internal DocumentOutlineTestMocks( internal ITextBuffer TextBuffer { get; } internal string FilePath - => PathRoot + _workspace.Documents.Single().FilePath!; + => _workspace.Documents.Single().FilePath!; public ValueTask DisposeAsync() => _disposable.DisposeAsync(); @@ -97,30 +95,10 @@ protected async Task CreateMocksAsync(string code) private async Task CreateTestLspServerAsync(EditorTestWorkspace workspace) { - var solution = workspace.CurrentSolution; - - foreach (var document in workspace.Documents) - { - if (document.IsSourceGenerated) - continue; - - solution = solution.WithDocumentFilePath(document.Id, PathRoot + document.Name); - - var documentText = await solution.GetRequiredDocument(document.Id).GetTextAsync(CancellationToken.None); - solution = solution.WithDocumentText(document.Id, SourceText.From(documentText.ToString(), System.Text.Encoding.UTF8)); - } - - foreach (var project in workspace.Projects) - { - // Ensure all the projects have a valid file path. - solution = solution.WithProjectFilePath(project.Id, PathRoot + project.Name); - } - - solution = solution.WithAnalyzerReferences([new TestAnalyzerReferenceByLanguage(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap())]); - await workspace.ChangeSolutionAsync(solution); + await workspace.ChangeSolutionAsync( + workspace.CurrentSolution.WithAnalyzerReferences([new TestAnalyzerReferenceByLanguage(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap())])); - var server = await EditorTestLspServer.CreateAsync(workspace, new InitializationOptions(), _logger); - return server; + return await EditorTestLspServer.CreateAsync(workspace, new InitializationOptions(), _logger); } internal sealed class EditorTestLspServer : AbstractTestLspServer From c9b0f1f4a0c8f925cb0e9914d6873e79af7138b9 Mon Sep 17 00:00:00 2001 From: tmat Date: Tue, 13 May 2025 10:40:21 -0700 Subject: [PATCH 5/7] Remove unnecessary code --- .../AbstractLanguageServerProtocolTests.cs | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/src/LanguageServer/Protocol.TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs b/src/LanguageServer/Protocol.TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs index 3f6b84fef0821..a887ae34e8a51 100644 --- a/src/LanguageServer/Protocol.TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs +++ b/src/LanguageServer/Protocol.TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs @@ -330,23 +330,6 @@ private async Task CreateTestLspServerAsync(LspTestWorkspace work { var solution = workspace.CurrentSolution; - foreach (var document in workspace.Documents) - { - if (document.IsSourceGenerated) - continue; - - Assert.True(PathUtilities.IsAbsolute(document.FilePath)); - - var documentText = await solution.GetRequiredDocument(document.Id).GetTextAsync(CancellationToken.None); - solution = solution.WithDocumentText(document.Id, SourceText.From(documentText.ToString(), System.Text.Encoding.UTF8, SourceHashAlgorithms.Default)); - } - - foreach (var project in workspace.Projects) - { - // Ensure all the projects have a valid file path. - Assert.True(PathUtilities.IsAbsolute(project.FilePath)); - } - var analyzerReferencesByLanguage = CreateTestAnalyzersReference(); if (initializationOptions.AdditionalAnalyzers != null) analyzerReferencesByLanguage = analyzerReferencesByLanguage.WithAdditionalAnalyzers(languageName, initializationOptions.AdditionalAnalyzers); From 3c06b078672732734b6973dea50fa51e3c4bbf03 Mon Sep 17 00:00:00 2001 From: tmat Date: Tue, 13 May 2025 21:22:37 -0700 Subject: [PATCH 6/7] Fixes --- .../NavigateTo/InteractiveNavigateToTests.cs | 4 ++-- .../CSharpTest/NavigateTo/NavigateToTests.cs | 4 ++-- .../Rename/CSharpInlineRenameServiceTests.cs | 22 +++++++++++------- .../NavigateTo/NavigateToTests.vb | 2 +- .../MoveStaticMembersOptions.cs | 6 ++--- .../MoveStaticMembersWithDialogCodeAction.cs | 4 ++-- .../Diagnostics/PullDiagnosticTests.cs | 23 +++++++++++-------- .../VisualBasic/RootCodeModelTests.vb | 9 ++++---- .../MoveStaticMembersViewModelTest.vb | 9 ++++---- .../InheritsFromGraphQueryTests.vb | 14 +++++++---- .../CpsDiagnosticItemSourceTests.vb | 4 +++- .../Venus/DocumentService_IntegrationTests.vb | 17 ++++++++------ 12 files changed, 70 insertions(+), 48 deletions(-) diff --git a/src/EditorFeatures/CSharpTest/Interactive/NavigateTo/InteractiveNavigateToTests.cs b/src/EditorFeatures/CSharpTest/Interactive/NavigateTo/InteractiveNavigateToTests.cs index e2dd31b7fd2dc..fbdeae5eea4b0 100644 --- a/src/EditorFeatures/CSharpTest/Interactive/NavigateTo/InteractiveNavigateToTests.cs +++ b/src/EditorFeatures/CSharpTest/Interactive/NavigateTo/InteractiveNavigateToTests.cs @@ -615,13 +615,13 @@ await TestAsync(testHost, composition, code, async w => var descriptionItems = itemDisplay.DescriptionItems; - void assertDescription(string label, string value) + void assertDescription(string label, string? value) { var descriptionItem = descriptionItems.Single(i => i.Category.Single().Text == label); Assert.Equal(value, descriptionItem.Details.Single().Text); } - assertDescription("File:", w.Documents.Single().Name); + assertDescription("File:", w.Documents.Single().FilePath); assertDescription("Line:", "3"); // one based line number assertDescription("Project:", "Test"); }); diff --git a/src/EditorFeatures/CSharpTest/NavigateTo/NavigateToTests.cs b/src/EditorFeatures/CSharpTest/NavigateTo/NavigateToTests.cs index 795bf709725e7..2a757190cb0c6 100644 --- a/src/EditorFeatures/CSharpTest/NavigateTo/NavigateToTests.cs +++ b/src/EditorFeatures/CSharpTest/NavigateTo/NavigateToTests.cs @@ -1029,13 +1029,13 @@ await TestAsync(testHost, composition, """ var descriptionItems = itemDisplay.DescriptionItems; - void assertDescription(string label, string value) + void assertDescription(string label, string? value) { var descriptionItem = descriptionItems.Single(i => i.Category.Single().Text == label); Assert.Equal(value, descriptionItem.Details.Single().Text); } - assertDescription("File:", w.Documents.Single().Name); + assertDescription("File:", w.Documents.Single().FilePath); assertDescription("Line:", "3"); // one based line number assertDescription("Project:", "Test"); }); diff --git a/src/EditorFeatures/CSharpTest/Rename/CSharpInlineRenameServiceTests.cs b/src/EditorFeatures/CSharpTest/Rename/CSharpInlineRenameServiceTests.cs index 56e7cb6f5964b..23b76cd2288f8 100644 --- a/src/EditorFeatures/CSharpTest/Rename/CSharpInlineRenameServiceTests.cs +++ b/src/EditorFeatures/CSharpTest/Rename/CSharpInlineRenameServiceTests.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using System.IO; using System.Linq; using System.Text.Json; using System.Threading; @@ -77,16 +78,21 @@ private static async Task VerifyGetRenameContextAsync( [WorkItem("https://github.com/dotnet/roslyn/issues/74545")] public async Task VerifyContextReachEndOfFile() { - var markup = @" -public class Sampl$$eClass() -{ -}"; + var markup = """ + public class Sampl$$eClass() + { + } + """; + + var escapedPath = Path.Combine(TestWorkspace.RootDirectory, "test1.cs").Replace("\\", "\\\\"); + await VerifyGetRenameContextAsync( markup, - @" -{ - ""definition"" : [ {""Item1"":""test1.cs"", ""Item2"":""public class SampleClass()\r\n{\r\n}""} ] -}", + $$""" + { + "definition": [{"Item1":"{{escapedPath}}", "Item2":"public class SampleClass()\r\n{\r\n}"}] + } + """, new SymbolRenameOptions(), CancellationToken.None); } diff --git a/src/EditorFeatures/VisualBasicTest/NavigateTo/NavigateToTests.vb b/src/EditorFeatures/VisualBasicTest/NavigateTo/NavigateToTests.vb index e65db62bf19e0..56e6382b9af58 100644 --- a/src/EditorFeatures/VisualBasicTest/NavigateTo/NavigateToTests.vb +++ b/src/EditorFeatures/VisualBasicTest/NavigateTo/NavigateToTests.vb @@ -792,7 +792,7 @@ End Class", Async Function(w) Assert.Equal(value, descriptionItem.Details.Single().Text) End Sub - assertDescription("File:", w.Documents.Single().Name) + assertDescription("File:", w.Documents.Single().FilePath) assertDescription("Line:", "2") assertDescription("Project:", "Test") End Function) diff --git a/src/Features/Core/Portable/MoveStaticMembers/MoveStaticMembersOptions.cs b/src/Features/Core/Portable/MoveStaticMembers/MoveStaticMembersOptions.cs index 6d1c8b4528457..6fefee44ca621 100644 --- a/src/Features/Core/Portable/MoveStaticMembers/MoveStaticMembersOptions.cs +++ b/src/Features/Core/Portable/MoveStaticMembers/MoveStaticMembersOptions.cs @@ -12,7 +12,7 @@ internal readonly struct MoveStaticMembersOptions { public bool IsCancelled { get; } - public string FileName { get; } + public string FilePath { get; } public bool IsNewType { get; } @@ -42,7 +42,7 @@ public MoveStaticMembersOptions( RoslynDebug.AssertNotNull(sourceLocation.SyntaxTree); IsCancelled = isCancelled; - FileName = sourceLocation.SyntaxTree.FilePath; + FilePath = sourceLocation.SyntaxTree.FilePath; IsNewType = false; Destination = destination; TypeName = null; @@ -57,7 +57,7 @@ public MoveStaticMembersOptions( bool isCancelled = false) { IsCancelled = isCancelled; - FileName = fileName; + FilePath = fileName; IsNewType = true; Destination = null; var namespacesAndType = fullTypeName.Split(separator: '.'); diff --git a/src/Features/Core/Portable/MoveStaticMembers/MoveStaticMembersWithDialogCodeAction.cs b/src/Features/Core/Portable/MoveStaticMembers/MoveStaticMembersWithDialogCodeAction.cs index 941fe57932d2d..11fe4ab91a4c6 100644 --- a/src/Features/Core/Portable/MoveStaticMembers/MoveStaticMembersWithDialogCodeAction.cs +++ b/src/Features/Core/Portable/MoveStaticMembers/MoveStaticMembersWithDialogCodeAction.cs @@ -63,7 +63,7 @@ protected override async Task> ComputeOperation // we already have our destination type, but we need to find the document it is in // When it is an existing type, "FileName" points to a full path rather than just the name // There should be no two docs that have the same file path - var destinationDocId = _document.Project.Solution.GetDocumentIdsWithFilePath(moveOptions.FileName).Single(); + var destinationDocId = _document.Project.Solution.GetDocumentIdsWithFilePath(moveOptions.FilePath).Single(); var fixedSolution = await RefactorAndMoveAsync( moveOptions.SelectedMembers, @@ -102,7 +102,7 @@ protected override async Task> ComputeOperation var (newDoc, annotation) = await ExtractTypeHelpers.AddTypeToNewFileAsync( sourceDoc.Project.Solution, moveOptions.NamespaceDisplay, - moveOptions.FileName, + moveOptions.FilePath, sourceDoc.Project.Id, sourceDoc.Folders, newType, diff --git a/src/LanguageServer/ProtocolUnitTests/Diagnostics/PullDiagnosticTests.cs b/src/LanguageServer/ProtocolUnitTests/Diagnostics/PullDiagnosticTests.cs index 0be41bed6132b..cffdff4781ab0 100644 --- a/src/LanguageServer/ProtocolUnitTests/Diagnostics/PullDiagnosticTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Diagnostics/PullDiagnosticTests.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Immutable; +using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -1583,7 +1584,7 @@ class A { var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer, useVSDiagnostics); Assert.Equal(3, results.Length); - Assert.Equal(ProtocolConversions.CreateAbsoluteDocumentUri(@"C:\test1.cs"), results[0].TextDocument!.DocumentUri); + Assert.Equal(ProtocolConversions.CreateAbsoluteDocumentUri(Path.Combine(TestWorkspace.RootDirectory, "test1.cs")), results[0].TextDocument!.DocumentUri); Assert.Equal("CS1513", results[0].Diagnostics!.Single().Code); Assert.Equal(1, results[0].Diagnostics!.Single().Range.Start.Line); AssertEx.Empty(results[1].Diagnostics); @@ -1999,11 +2000,11 @@ public async Task TestWorkspaceDiagnosticsDoesNotThrowIfProjectWithoutFilePathEx var workspaceXml = $""" - - {csharpMarkup} + + {csharpMarkup} - - + + """; @@ -2012,10 +2013,14 @@ public async Task TestWorkspaceDiagnosticsDoesNotThrowIfProjectWithoutFilePathEx var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer, useVSDiagnostics); - Assert.Equal(3, results.Length); - Assert.Equal(@"C:/C.cs", results[0].TextDocument.DocumentUri.GetRequiredParsedUri().AbsolutePath); - Assert.Equal(@"C:/CSProj1.csproj", results[1].TextDocument.DocumentUri.GetRequiredParsedUri().AbsolutePath); - Assert.Equal(@"C:/C2.cs", results[2].TextDocument.DocumentUri.GetRequiredParsedUri().AbsolutePath); + var dir = TestWorkspace.RootDirectory.Replace("\\", "/"); + + AssertEx.SequenceEqual( + [ + $"{dir}/C.cs", + $"{dir}/CSProj1.csproj", + $"{dir}/C2.cs" + ], results.Select(r => r.TextDocument.DocumentUri.GetRequiredParsedUri().AbsolutePath)); } [Theory, CombinatorialData] diff --git a/src/VisualStudio/Core/Test/CodeModel/VisualBasic/RootCodeModelTests.vb b/src/VisualStudio/Core/Test/CodeModel/VisualBasic/RootCodeModelTests.vb index e1cad09cec895..6d59e00d61b6a 100644 --- a/src/VisualStudio/Core/Test/CodeModel/VisualBasic/RootCodeModelTests.vb +++ b/src/VisualStudio/Core/Test/CodeModel/VisualBasic/RootCodeModelTests.vb @@ -2,6 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports System.IO Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel @@ -111,7 +112,7 @@ End Namespace Assert.NotNull(underlyingFileCodeModel) Dim filePath = underlyingFileCodeModel.Workspace.GetFilePath(underlyingFileCodeModel.GetDocumentId()) - Assert.Equal("C.vb", filePath) + Assert.Equal(Path.Combine(TestWorkspace.RootDirectory, "C.vb"), filePath) End Sub) End Sub @@ -146,7 +147,7 @@ End Namespace Assert.NotNull(underlyingFileCodeModel) Dim filePath = underlyingFileCodeModel.Workspace.GetFilePath(underlyingFileCodeModel.GetDocumentId()) - Assert.Equal("C.g.vb", filePath) + Assert.Equal(Path.Combine(TestWorkspace.RootDirectory, "C.g.vb"), filePath) End Sub) End Sub @@ -187,7 +188,7 @@ End Namespace Assert.NotNull(underlyingFileCodeModel) Dim filePath = underlyingFileCodeModel.Workspace.GetFilePath(underlyingFileCodeModel.GetDocumentId()) - Assert.Equal("C.vb", filePath) + Assert.Equal(Path.Combine(TestWorkspace.RootDirectory, "C.vb"), filePath) End Sub) End Sub @@ -228,7 +229,7 @@ End Namespace Assert.NotNull(underlyingFileCodeModel) Dim filePath = underlyingFileCodeModel.Workspace.GetFilePath(underlyingFileCodeModel.GetDocumentId()) - Assert.Equal("C.vb", filePath) + Assert.Equal(Path.Combine(TestWorkspace.RootDirectory, "C.vb"), filePath) End Sub) End Sub diff --git a/src/VisualStudio/Core/Test/MoveStaticMembers/MoveStaticMembersViewModelTest.vb b/src/VisualStudio/Core/Test/MoveStaticMembers/MoveStaticMembersViewModelTest.vb index 65f171ebd2ba8..7c21c5d629c66 100644 --- a/src/VisualStudio/Core/Test/MoveStaticMembers/MoveStaticMembersViewModelTest.vb +++ b/src/VisualStudio/Core/Test/MoveStaticMembers/MoveStaticMembersViewModelTest.vb @@ -3,6 +3,7 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable +Imports System.IO Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces @@ -106,7 +107,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.MoveStaticMembers Dim options = VisualStudioMoveStaticMembersOptionsService.GenerateOptions(LanguageNames.CSharp, viewModel, True) Assert.False(options.IsCancelled) - Assert.Equal("TestClassHelpers.cs", options.FileName) + Assert.Equal("TestClassHelpers.cs", options.FilePath) Assert.Equal("TestClassHelpers", options.TypeName) Assert.Equal("TestNs.ExtraNs", options.NamespaceDisplay) End Function @@ -425,7 +426,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.MoveStaticMembers Assert.False(options.IsCancelled) Assert.NotNull(options.Destination) Assert.Equal("TestNs.ConflictingClassName", options.Destination.ToDisplayString()) - Assert.Equal("TestFile.cs", options.FileName) + Assert.Equal(Path.Combine(TestWorkspace.RootDirectory, "TestFile.cs"), options.FilePath) End Function @@ -550,7 +551,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.MoveStaticMembers Dim options = VisualStudioMoveStaticMembersOptionsService.GenerateOptions(LanguageNames.VisualBasic, viewModel, True) Assert.False(options.IsCancelled) - Assert.Equal("TestClassHelpers.vb", options.FileName) + Assert.Equal("TestClassHelpers.vb", options.FilePath) Assert.Equal("TestClassHelpers", options.TypeName) Assert.Equal("TestNs.ExtraNs", options.NamespaceDisplay) End Function @@ -865,7 +866,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.MoveStaticMembers Assert.False(options.IsCancelled) Assert.NotNull(options.Destination) Assert.Equal("TestNs.ConflictingClassName", options.Destination.ToDisplayString()) - Assert.Equal("TestFile.vb", options.FileName) + Assert.Equal(Path.Combine(TestWorkspace.RootDirectory, "TestFile.vb"), options.FilePath) End Function #End Region End Class diff --git a/src/VisualStudio/Core/Test/Progression/InheritsFromGraphQueryTests.vb b/src/VisualStudio/Core/Test/Progression/InheritsFromGraphQueryTests.vb index 8379a19d621f2..1faa562860c9e 100644 --- a/src/VisualStudio/Core/Test/Progression/InheritsFromGraphQueryTests.vb +++ b/src/VisualStudio/Core/Test/Progression/InheritsFromGraphQueryTests.vb @@ -2,7 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports System.IO Imports System.Threading.Tasks +Imports Microsoft.CodeAnalysis.LanguageServer Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.GraphModel Imports Microsoft.VisualStudio.LanguageServices.Implementation.Progression @@ -79,21 +81,23 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression Using testState = ProgressionTestState.Create( - public class A { } + public class A { } ProjectA - public class B : A { } + public class B : A { } ProjectB - public class C : B$$ { } + public class C : B$$ { } ) Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync() Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New InheritsGraphQuery(), GraphContextDirection.Target) + Dim dirUri = ProtocolConversions.GetAbsoluteUriString(Path.Combine(TestWorkspace.RootDirectory, "bin")) & "/" + AssertSimplifiedGraphIs( outputContext.Graph, @@ -105,8 +109,8 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression - - + /> + /> ) End Using diff --git a/src/VisualStudio/Core/Test/SolutionExplorer/CpsDiagnosticItemSourceTests.vb b/src/VisualStudio/Core/Test/SolutionExplorer/CpsDiagnosticItemSourceTests.vb index fd1a95b6ad9cb..95bb70cf9d4af 100644 --- a/src/VisualStudio/Core/Test/SolutionExplorer/CpsDiagnosticItemSourceTests.vb +++ b/src/VisualStudio/Core/Test/SolutionExplorer/CpsDiagnosticItemSourceTests.vb @@ -3,10 +3,12 @@ ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable +Imports System.IO Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces +Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.[Shared].TestHooks Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.Internal.VisualStudio.PlatformUI @@ -44,7 +46,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.SolutionExplorer workspace, project.FilePath, project.Id, - New MockHierarchyItem() With {.CanonicalName = "\net472\analyzerdependency\" + analyzerPath}, + New MockHierarchyItem() With {.CanonicalName = Path.Combine(TestWorkspace.RootDirectory, "net472", "analyzerdependency") + "\" + analyzerPath}, New FakeAnalyzersCommandHandler(), listenerProvider) diff --git a/src/VisualStudio/Core/Test/Venus/DocumentService_IntegrationTests.vb b/src/VisualStudio/Core/Test/Venus/DocumentService_IntegrationTests.vb index 2aec249ad56ae..aa8daa875eca0 100644 --- a/src/VisualStudio/Core/Test/Venus/DocumentService_IntegrationTests.vb +++ b/src/VisualStudio/Core/Test/Venus/DocumentService_IntegrationTests.vb @@ -41,7 +41,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Venus Private Shared ReadOnly s_compositionWithMockDiagnosticUpdateSourceRegistrationService As TestComposition = EditorTestCompositions.EditorFeatures - Public Async Function TestFindUsageIntegration() As System.Threading.Tasks.Task + Public Async Function TestFindUsageIntegration() As Task Dim input = @@ -87,8 +87,9 @@ class {|Definition:C1|} Dim definitionSpan = definitionDocument.AnnotatedSpans("Definition").Single() Dim referenceSpan = definitionDocument.SelectedSpans.First() Dim expected = { - (definitionDocument.Name, definitionText.Lines.GetLinePositionSpan(definitionSpan).Start, definitionText.Lines.GetLineFromPosition(definitionSpan.Start).ToString().Trim()), - (definitionDocument.Name, definitionText.Lines.GetLinePositionSpan(referenceSpan).Start, definitionText.Lines.GetLineFromPosition(referenceSpan.Start).ToString().Trim())} + (definitionDocument.FilePath, definitionText.Lines.GetLinePositionSpan(definitionSpan).Start, definitionText.Lines.GetLineFromPosition(definitionSpan.Start).ToString().Trim()), + (definitionDocument.FilePath, definitionText.Lines.GetLinePositionSpan(referenceSpan).Start, definitionText.Lines.GetLineFromPosition(referenceSpan.Start).ToString().Trim()) + } Dim factory = TestFindAllReferencesService.Instance.LastWindow.MyTableManager.LastSink.LastFactory Dim snapshot = factory.GetCurrentSnapshot() @@ -115,7 +116,7 @@ class {|Definition:C1|} End Function - Public Async Function TestCodeLensIntegration() As System.Threading.Tasks.Task + Public Async Function TestCodeLensIntegration() As Task Dim input = @@ -152,7 +153,9 @@ class {|Definition:C1|} Dim definitionText = Await workspace.CurrentSolution.GetDocument(definitionDocument.Id).GetTextAsync() Dim referenceSpan = definitionDocument.SelectedSpans.First() - Dim expected = {(definitionDocument.Name, definitionText.Lines.GetLinePositionSpan(referenceSpan).Start, definitionText.Lines.GetLineFromPosition(referenceSpan.Start).ToString())} + Dim expected = { + (definitionDocument.FilePath, definitionText.Lines.GetLinePositionSpan(referenceSpan).Start, definitionText.Lines.GetLineFromPosition(referenceSpan.Start).ToString()) + } Dim actual = New List(Of (String, LinePosition, String)) @@ -168,7 +171,7 @@ class {|Definition:C1|} - Public Async Function TestDocumentOperationCanApplyChange(ignoreUnchangeableDocuments As Boolean) As System.Threading.Tasks.Task + Public Async Function TestDocumentOperationCanApplyChange(ignoreUnchangeableDocuments As Boolean) As Task Dim input = @@ -208,7 +211,7 @@ class C { } End Function - Public Async Function TestDocumentOperationCanApplySupportDiagnostics() As System.Threading.Tasks.Task + Public Async Function TestDocumentOperationCanApplySupportDiagnostics() As Task Dim input = From 856c6b4d184c400ebb85e7ff6677147ea95705cc Mon Sep 17 00:00:00 2001 From: tmat Date: Wed, 14 May 2025 09:27:19 -0700 Subject: [PATCH 7/7] Fix --- .../Interactive/NavigateTo/InteractiveNavigateToTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/EditorFeatures/CSharpTest/Interactive/NavigateTo/InteractiveNavigateToTests.cs b/src/EditorFeatures/CSharpTest/Interactive/NavigateTo/InteractiveNavigateToTests.cs index fbdeae5eea4b0..435d94cb1d066 100644 --- a/src/EditorFeatures/CSharpTest/Interactive/NavigateTo/InteractiveNavigateToTests.cs +++ b/src/EditorFeatures/CSharpTest/Interactive/NavigateTo/InteractiveNavigateToTests.cs @@ -615,7 +615,7 @@ await TestAsync(testHost, composition, code, async w => var descriptionItems = itemDisplay.DescriptionItems; - void assertDescription(string label, string? value) + void assertDescription(string label, string value) { var descriptionItem = descriptionItems.Single(i => i.Category.Single().Text == label); Assert.Equal(value, descriptionItem.Details.Single().Text);