Fix up tests that mocked IDocumentMappingService.GetLanguageKind(...)

This commit is contained in:
Dustin Campbell 2024-09-04 18:00:51 -07:00
Родитель f575ad02ca
Коммит ae81c663bd
7 изменённых файлов: 885 добавлений и 1138 удалений

Просмотреть файл

@ -12,8 +12,8 @@ using System.Threading.Tasks;
using Microsoft.AspNetCore.Razor.Language;
using Microsoft.AspNetCore.Razor.LanguageServer.CodeActions.Models;
using Microsoft.AspNetCore.Razor.LanguageServer.Hosting;
using Microsoft.AspNetCore.Razor.Test.Common;
using Microsoft.AspNetCore.Razor.Test.Common.LanguageServer;
using Microsoft.AspNetCore.Razor.Threading;
using Microsoft.CodeAnalysis.Razor.DocumentMapping;
using Microsoft.CodeAnalysis.Razor.Protocol;
using Microsoft.CodeAnalysis.Razor.Protocol.CodeActions;
@ -26,49 +26,17 @@ using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions;
public class CodeActionEndpointTest : LanguageServerTestBase
public class CodeActionEndpointTest(ITestOutputHelper testOutput) : LanguageServerTestBase(testOutput)
{
private readonly IDocumentMappingService _documentMappingService;
private readonly LanguageServerFeatureOptions _languageServerFeatureOptions;
private readonly IClientConnection _clientConnection;
public CodeActionEndpointTest(ITestOutputHelper testOutput)
: base(testOutput)
{
_documentMappingService = Mock.Of<IDocumentMappingService>(
s => s.TryMapToGeneratedDocumentRange(
It.IsAny<IRazorGeneratedDocument>(),
It.IsAny<LinePositionSpan>(),
out It.Ref<LinePositionSpan>.IsAny) == false &&
s.GetLanguageKind(It.IsAny<RazorCodeDocument>(), It.IsAny<int>(), It.IsAny<bool>()) == RazorLanguageKind.CSharp,
MockBehavior.Strict);
_languageServerFeatureOptions = Mock.Of<LanguageServerFeatureOptions>(
l => l.SupportsFileManipulation == true,
MockBehavior.Strict);
_clientConnection = Mock.Of<IClientConnection>(MockBehavior.Strict);
}
private static readonly LinePositionSpan s_defaultRange = new(new(5, 2), new(5, 2));
[Fact]
public async Task Handle_NoDocument()
{
// Arrange
var documentPath = new Uri("C:/path/to/Page.razor");
var codeActionEndpoint = new CodeActionEndpoint(
_documentMappingService,
Array.Empty<IRazorCodeActionProvider>(),
Array.Empty<ICSharpCodeActionProvider>(),
Array.Empty<IHtmlCodeActionProvider>(),
_clientConnection,
_languageServerFeatureOptions,
LoggerFactory,
telemetryReporter: null)
{
_supportsCodeActionResolve = false
};
var codeActionEndpoint = CreateEndpoint();
var request = new VSCodeActionParams()
{
TextDocument = new VSTextDocumentIdentifier { Uri = documentPath },
@ -79,7 +47,7 @@ public class CodeActionEndpointTest : LanguageServerTestBase
var requestContext = CreateRazorRequestContext(documentContext: null);
// Act
var commandOrCodeActionContainer = await codeActionEndpoint.HandleRequestAsync(request, requestContext, default);
var commandOrCodeActionContainer = await codeActionEndpoint.HandleRequestAsync(request, requestContext, DisposalToken);
// Assert
Assert.Null(commandOrCodeActionContainer);
@ -93,28 +61,19 @@ public class CodeActionEndpointTest : LanguageServerTestBase
var codeDocument = CreateCodeDocument("@code {}");
var documentContext = CreateDocumentContext(documentPath, codeDocument);
codeDocument.SetUnsupported();
var codeActionEndpoint = new CodeActionEndpoint(
_documentMappingService,
Array.Empty<IRazorCodeActionProvider>(),
Array.Empty<ICSharpCodeActionProvider>(),
Array.Empty<IHtmlCodeActionProvider>(),
_clientConnection,
_languageServerFeatureOptions,
LoggerFactory,
telemetryReporter: null)
{
_supportsCodeActionResolve = false
};
var codeActionEndpoint = CreateEndpoint();
var request = new VSCodeActionParams()
{
TextDocument = new VSTextDocumentIdentifier { Uri = documentPath },
Range = VsLspFactory.CreateZeroWidthRange(0, 1),
Context = new VSInternalCodeActionContext()
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
var commandOrCodeActionContainer = await codeActionEndpoint.HandleRequestAsync(request, requestContext, default);
var commandOrCodeActionContainer = await codeActionEndpoint.HandleRequestAsync(request, requestContext, DisposalToken);
// Assert
Assert.Null(commandOrCodeActionContainer);
@ -127,31 +86,23 @@ public class CodeActionEndpointTest : LanguageServerTestBase
var documentPath = new Uri("C:/path/to/Page.razor");
var codeDocument = CreateCodeDocument("@code {}");
var documentContext = CreateDocumentContext(documentPath, codeDocument);
var codeActionEndpoint = new CodeActionEndpoint(
_documentMappingService,
Array.Empty<IRazorCodeActionProvider>(),
Array.Empty<ICSharpCodeActionProvider>(),
Array.Empty<IHtmlCodeActionProvider>(),
_clientConnection,
_languageServerFeatureOptions,
LoggerFactory,
telemetryReporter: null)
{
_supportsCodeActionResolve = false
};
var codeActionEndpoint = CreateEndpoint();
var request = new VSCodeActionParams()
{
TextDocument = new VSTextDocumentIdentifier { Uri = documentPath },
Range = VsLspFactory.CreateZeroWidthRange(0, 1),
Context = new VSInternalCodeActionContext()
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
var commandOrCodeActionContainer = await codeActionEndpoint.HandleRequestAsync(request, requestContext, default);
var commandOrCodeActionContainer = await codeActionEndpoint.HandleRequestAsync(request, requestContext, DisposalToken);
// Assert
Assert.Empty(commandOrCodeActionContainer!);
Assert.NotNull(commandOrCodeActionContainer);
Assert.Empty(commandOrCodeActionContainer);
}
[Fact]
@ -161,20 +112,7 @@ public class CodeActionEndpointTest : LanguageServerTestBase
var documentPath = new Uri("C:/path/to/Page.razor");
var codeDocument = CreateCodeDocument("@code {}");
var documentContext = CreateDocumentContext(documentPath, codeDocument);
var codeActionEndpoint = new CodeActionEndpoint(
_documentMappingService,
new IRazorCodeActionProvider[] {
new MockRazorCodeActionProvider()
},
Array.Empty<ICSharpCodeActionProvider>(),
Array.Empty<IHtmlCodeActionProvider>(),
_clientConnection,
_languageServerFeatureOptions,
LoggerFactory,
telemetryReporter: null)
{
_supportsCodeActionResolve = false
};
var codeActionEndpoint = CreateEndpoint(razorCodeActionProviders: [CreateRazorCodeActionProvider()]);
var request = new VSCodeActionParams()
{
@ -182,10 +120,11 @@ public class CodeActionEndpointTest : LanguageServerTestBase
Range = VsLspFactory.CreateZeroWidthRange(0, 1),
Context = new VSInternalCodeActionContext()
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
var commandOrCodeActionContainer = await codeActionEndpoint.HandleRequestAsync(request, requestContext, default);
var commandOrCodeActionContainer = await codeActionEndpoint.HandleRequestAsync(request, requestContext, DisposalToken);
// Assert
Assert.NotNull(commandOrCodeActionContainer);
@ -199,22 +138,11 @@ public class CodeActionEndpointTest : LanguageServerTestBase
var documentPath = new Uri("C:/path/to/Page.razor");
var codeDocument = CreateCodeDocument("@code {}");
var documentContext = CreateDocumentContext(documentPath, codeDocument);
var documentMappingService = CreateDocumentMappingService();
var languageServer = CreateLanguageServer();
var codeActionEndpoint = new CodeActionEndpoint(
documentMappingService,
Array.Empty<IRazorCodeActionProvider>(),
new ICSharpCodeActionProvider[] {
new MockCSharpCodeActionProvider()
},
Array.Empty<IHtmlCodeActionProvider>(),
languageServer,
_languageServerFeatureOptions,
LoggerFactory,
telemetryReporter: null)
{
_supportsCodeActionResolve = false
};
var codeActionEndpoint = CreateEndpoint(
documentMappingService: CreateDocumentMappingService(s_defaultRange),
csharpCodeActionProviders: [CreateCSharpCodeActionProvider()],
clientConnection: TestClientConnection.Instance);
var request = new VSCodeActionParams()
{
@ -222,10 +150,11 @@ public class CodeActionEndpointTest : LanguageServerTestBase
Range = VsLspFactory.CreateZeroWidthRange(0, 1),
Context = new VSInternalCodeActionContext()
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
var commandOrCodeActionContainer = await codeActionEndpoint.HandleRequestAsync(request, requestContext, default);
var commandOrCodeActionContainer = await codeActionEndpoint.HandleRequestAsync(request, requestContext, DisposalToken);
// Assert
Assert.NotNull(commandOrCodeActionContainer);
@ -239,20 +168,7 @@ public class CodeActionEndpointTest : LanguageServerTestBase
var documentPath = new Uri("C:/path/to/Page.razor");
var codeDocument = CreateCodeDocument("@code {}");
var documentContext = CreateDocumentContext(documentPath, codeDocument);
var codeActionEndpoint = new CodeActionEndpoint(
_documentMappingService,
new IRazorCodeActionProvider[] {
new MockMultipleRazorCodeActionProvider(),
},
Array.Empty<ICSharpCodeActionProvider>(),
Array.Empty<IHtmlCodeActionProvider>(),
_clientConnection,
_languageServerFeatureOptions,
LoggerFactory,
telemetryReporter: null)
{
_supportsCodeActionResolve = false
};
var codeActionEndpoint = CreateEndpoint(razorCodeActionProviders: [CreateMultipleRazorCodeActionProvider()]);
var request = new VSCodeActionParams()
{
@ -260,10 +176,11 @@ public class CodeActionEndpointTest : LanguageServerTestBase
Range = VsLspFactory.CreateZeroWidthRange(0, 1),
Context = new VSInternalCodeActionContext()
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
var commandOrCodeActionContainer = await codeActionEndpoint.HandleRequestAsync(request, requestContext, default);
var commandOrCodeActionContainer = await codeActionEndpoint.HandleRequestAsync(request, requestContext, DisposalToken);
// Assert
Assert.NotNull(commandOrCodeActionContainer);
@ -277,27 +194,17 @@ public class CodeActionEndpointTest : LanguageServerTestBase
var documentPath = new Uri("C:/path/to/Page.razor");
var codeDocument = CreateCodeDocument("@code {}");
var documentContext = CreateDocumentContext(documentPath, codeDocument);
var documentMappingService = CreateDocumentMappingService();
var languageServer = CreateLanguageServer();
var codeActionEndpoint = new CodeActionEndpoint(
documentMappingService,
new IRazorCodeActionProvider[] {
new MockMultipleRazorCodeActionProvider(),
new MockMultipleRazorCodeActionProvider(),
new MockRazorCodeActionProvider(),
},
new ICSharpCodeActionProvider[] {
new MockCSharpCodeActionProvider(),
new MockCSharpCodeActionProvider()
},
Array.Empty<IHtmlCodeActionProvider>(),
languageServer,
_languageServerFeatureOptions,
LoggerFactory,
telemetryReporter: null)
{
_supportsCodeActionResolve = false
};
var codeActionEndpoint = CreateEndpoint(
documentMappingService: CreateDocumentMappingService(s_defaultRange),
razorCodeActionProviders: [
CreateMultipleRazorCodeActionProvider(),
CreateMultipleRazorCodeActionProvider(),
CreateRazorCodeActionProvider()],
csharpCodeActionProviders: [
CreateCSharpCodeActionProvider(),
CreateCSharpCodeActionProvider()],
clientConnection: TestClientConnection.Instance);
var request = new VSCodeActionParams()
{
@ -322,27 +229,17 @@ public class CodeActionEndpointTest : LanguageServerTestBase
var documentPath = new Uri("C:/path/to/Page.razor");
var codeDocument = CreateCodeDocument("@code {}");
var documentContext = CreateDocumentContext(documentPath, codeDocument);
var documentMappingService = CreateDocumentMappingService();
var languageServer = CreateLanguageServer();
var codeActionEndpoint = new CodeActionEndpoint(
documentMappingService,
new IRazorCodeActionProvider[] {
new MockRazorCodeActionProvider(),
new MockRazorCodeActionProvider(),
new MockRazorCodeActionProvider(),
},
new ICSharpCodeActionProvider[] {
new MockCSharpCodeActionProvider(),
new MockCSharpCodeActionProvider()
},
Array.Empty<IHtmlCodeActionProvider>(),
languageServer,
_languageServerFeatureOptions,
LoggerFactory,
telemetryReporter: null)
{
_supportsCodeActionResolve = false
};
var codeActionEndpoint = CreateEndpoint(
documentMappingService: CreateDocumentMappingService(s_defaultRange),
razorCodeActionProviders: [
CreateRazorCodeActionProvider(),
CreateRazorCodeActionProvider(),
CreateRazorCodeActionProvider()],
csharpCodeActionProviders: [
CreateCSharpCodeActionProvider(),
CreateCSharpCodeActionProvider()],
clientConnection: TestClientConnection.Instance);
var request = new VSCodeActionParams()
{
@ -350,6 +247,7 @@ public class CodeActionEndpointTest : LanguageServerTestBase
Range = VsLspFactory.CreateZeroWidthRange(0, 1),
Context = new VSInternalCodeActionContext()
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
@ -367,20 +265,7 @@ public class CodeActionEndpointTest : LanguageServerTestBase
var documentPath = new Uri("C:/path/to/Page.razor");
var codeDocument = CreateCodeDocument("@code {}");
var documentContext = CreateDocumentContext(documentPath, codeDocument);
var codeActionEndpoint = new CodeActionEndpoint(
_documentMappingService,
new IRazorCodeActionProvider[] {
new MockEmptyRazorCodeActionProvider()
},
Array.Empty<ICSharpCodeActionProvider>(),
Array.Empty<IHtmlCodeActionProvider>(),
_clientConnection,
_languageServerFeatureOptions,
LoggerFactory,
telemetryReporter: null)
{
_supportsCodeActionResolve = false
};
var codeActionEndpoint = CreateEndpoint(razorCodeActionProviders: [CreateEmptyRazorCodeActionProvider()]);
var request = new VSCodeActionParams()
{
@ -388,13 +273,15 @@ public class CodeActionEndpointTest : LanguageServerTestBase
Range = VsLspFactory.CreateZeroWidthRange(0, 1),
Context = new VSInternalCodeActionContext()
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
var commandOrCodeActionContainer = await codeActionEndpoint.HandleRequestAsync(request, requestContext, default);
// Assert
Assert.Empty(commandOrCodeActionContainer!);
Assert.NotNull(commandOrCodeActionContainer);
Assert.Empty(commandOrCodeActionContainer);
}
[Fact]
@ -404,28 +291,18 @@ public class CodeActionEndpointTest : LanguageServerTestBase
var documentPath = new Uri("C:/path/to/Page.razor");
var codeDocument = CreateCodeDocument("@code {}");
var documentContext = CreateDocumentContext(documentPath, codeDocument);
var documentMappingService = CreateDocumentMappingService();
var languageServer = CreateLanguageServer();
var codeActionEndpoint = new CodeActionEndpoint(
documentMappingService,
new IRazorCodeActionProvider[] {
new MockRazorCodeActionProvider(),
new MockEmptyRazorCodeActionProvider(),
new MockRazorCodeActionProvider(),
new MockEmptyRazorCodeActionProvider(),
},
new ICSharpCodeActionProvider[] {
new MockCSharpCodeActionProvider(),
new MockCSharpCodeActionProvider()
},
Array.Empty<IHtmlCodeActionProvider>(),
languageServer,
_languageServerFeatureOptions,
LoggerFactory,
telemetryReporter: null)
{
_supportsCodeActionResolve = false
};
var codeActionEndpoint = CreateEndpoint(
documentMappingService: CreateDocumentMappingService(s_defaultRange),
razorCodeActionProviders: [
CreateRazorCodeActionProvider(),
CreateEmptyRazorCodeActionProvider(),
CreateRazorCodeActionProvider(),
CreateEmptyRazorCodeActionProvider()],
csharpCodeActionProviders: [
CreateCSharpCodeActionProvider(),
CreateCSharpCodeActionProvider()],
clientConnection: TestClientConnection.Instance);
var request = new VSCodeActionParams()
{
@ -433,6 +310,7 @@ public class CodeActionEndpointTest : LanguageServerTestBase
Range = VsLspFactory.CreateZeroWidthRange(0, 1),
Context = new VSInternalCodeActionContext()
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
@ -450,22 +328,13 @@ public class CodeActionEndpointTest : LanguageServerTestBase
var documentPath = new Uri("C:/path/to/Page.razor");
var codeDocument = CreateCodeDocument("@code {}");
var documentContext = CreateDocumentContext(documentPath, codeDocument);
var codeActionEndpoint = new CodeActionEndpoint(
_documentMappingService,
new IRazorCodeActionProvider[] {
new MockRazorCodeActionProvider(),
new MockRazorCommandProvider(),
new MockEmptyRazorCodeActionProvider()
},
Array.Empty<ICSharpCodeActionProvider>(),
Array.Empty<IHtmlCodeActionProvider>(),
_clientConnection,
_languageServerFeatureOptions,
LoggerFactory,
telemetryReporter: null)
{
_supportsCodeActionResolve = true
};
var codeActionEndpoint = CreateEndpoint(
razorCodeActionProviders: [
CreateRazorCodeActionProvider(),
CreateRazorCommandProvider(),
CreateEmptyRazorCodeActionProvider()],
supportsCodeActionResolve: true);
var request = new VSCodeActionParams()
{
@ -473,6 +342,7 @@ public class CodeActionEndpointTest : LanguageServerTestBase
Range = VsLspFactory.CreateZeroWidthRange(0, 1),
Context = new VSInternalCodeActionContext()
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
@ -500,24 +370,13 @@ public class CodeActionEndpointTest : LanguageServerTestBase
var documentPath = new Uri("C:/path/to/Page.razor");
var codeDocument = CreateCodeDocument("@code {}");
var documentContext = CreateDocumentContext(documentPath, codeDocument);
var documentMappingService = CreateDocumentMappingService();
var languageServer = CreateLanguageServer();
var codeActionEndpoint = new CodeActionEndpoint(
documentMappingService,
new IRazorCodeActionProvider[] {
new MockRazorCodeActionProvider(),
},
new ICSharpCodeActionProvider[] {
new MockCSharpCodeActionProvider()
},
Array.Empty<IHtmlCodeActionProvider>(),
languageServer,
_languageServerFeatureOptions,
LoggerFactory,
telemetryReporter: null)
{
_supportsCodeActionResolve = true
};
var codeActionEndpoint = CreateEndpoint(
documentMappingService: CreateDocumentMappingService(s_defaultRange),
razorCodeActionProviders: [CreateRazorCodeActionProvider()],
csharpCodeActionProviders: [CreateCSharpCodeActionProvider()],
clientConnection: TestClientConnection.Instance,
supportsCodeActionResolve: true);
var request = new VSCodeActionParams()
{
@ -525,6 +384,7 @@ public class CodeActionEndpointTest : LanguageServerTestBase
Range = VsLspFactory.CreateZeroWidthRange(0, 1),
Context = new VSInternalCodeActionContext()
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
@ -554,22 +414,12 @@ public class CodeActionEndpointTest : LanguageServerTestBase
var documentPath = new Uri("C:/path/to/Page.razor");
var codeDocument = CreateCodeDocument("@code {}");
var documentContext = CreateDocumentContext(documentPath, codeDocument);
var codeActionEndpoint = new CodeActionEndpoint(
_documentMappingService,
new IRazorCodeActionProvider[] {
new MockRazorCodeActionProvider(),
new MockRazorCommandProvider(),
new MockEmptyRazorCodeActionProvider()
},
Array.Empty<ICSharpCodeActionProvider>(),
Array.Empty<IHtmlCodeActionProvider>(),
_clientConnection,
_languageServerFeatureOptions,
LoggerFactory,
telemetryReporter: null)
{
_supportsCodeActionResolve = false
};
var codeActionEndpoint = CreateEndpoint(
razorCodeActionProviders: [
CreateRazorCodeActionProvider(),
CreateRazorCommandProvider(),
CreateEmptyRazorCodeActionProvider()]);
var request = new VSCodeActionParams()
{
@ -577,6 +427,7 @@ public class CodeActionEndpointTest : LanguageServerTestBase
Range = VsLspFactory.CreateZeroWidthRange(0, 1),
Context = new VSInternalCodeActionContext()
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
@ -587,14 +438,15 @@ public class CodeActionEndpointTest : LanguageServerTestBase
Assert.Collection(commandOrCodeActionContainer,
c =>
{
Assert.True(c.TryGetFirst(out var command1));
var command = Assert.IsType<Command>(command1);
var codeActionParamsToken = (JsonObject)command.Arguments!.First();
Assert.True(c.TryGetFirst(out var first));
var command = Assert.IsType<Command>(first);
Assert.NotNull(command.Arguments);
var codeActionParamsToken = (JsonObject)command.Arguments.First();
var codeActionParams = codeActionParamsToken.Deserialize<RazorCodeActionResolutionParams>();
Assert.NotNull(codeActionParams);
Assert.Equal(LanguageServerConstants.CodeActions.EditBasedCodeActionCommand, codeActionParams.Action);
},
c => Assert.True(c.TryGetFirst(out var _)));
c => Assert.True(c.TryGetFirst(out _)));
}
[Fact]
@ -604,20 +456,7 @@ public class CodeActionEndpointTest : LanguageServerTestBase
var documentPath = new Uri("C:/path/to/Page.razor");
var codeDocument = CreateCodeDocument("@code {}");
var documentContext = CreateDocumentContext(documentPath, codeDocument);
var codeActionEndpoint = new CodeActionEndpoint(
_documentMappingService,
new IRazorCodeActionProvider[] {
new MockRazorCodeActionProvider()
},
Array.Empty<ICSharpCodeActionProvider>(),
Array.Empty<IHtmlCodeActionProvider>(),
_clientConnection,
_languageServerFeatureOptions,
LoggerFactory,
telemetryReporter: null)
{
_supportsCodeActionResolve = false
};
var codeActionEndpoint = CreateEndpoint(razorCodeActionProviders: [CreateRazorCodeActionProvider()]);
var initialRange = VsLspFactory.CreateZeroWidthRange(0, 1);
var selectionRange = VsLspFactory.CreateZeroWidthRange(0, 5);
@ -646,20 +485,7 @@ public class CodeActionEndpointTest : LanguageServerTestBase
var documentPath = new Uri("C:/path/to/Page.razor");
var codeDocument = CreateCodeDocument("@code {}");
var documentContext = CreateDocumentContext(documentPath, codeDocument);
var codeActionEndpoint = new CodeActionEndpoint(
_documentMappingService,
new IRazorCodeActionProvider[] {
new MockRazorCodeActionProvider()
},
Array.Empty<ICSharpCodeActionProvider>(),
Array.Empty<IHtmlCodeActionProvider>(),
_clientConnection,
_languageServerFeatureOptions,
LoggerFactory,
telemetryReporter: null)
{
_supportsCodeActionResolve = false
};
var codeActionEndpoint = CreateEndpoint(razorCodeActionProviders: [CreateRazorCodeActionProvider()]);
var initialRange = VsLspFactory.CreateZeroWidthRange(0, 1);
var request = new VSCodeActionParams()
@ -687,24 +513,8 @@ public class CodeActionEndpointTest : LanguageServerTestBase
var documentPath = new Uri("C:/path/to/Page.razor");
var codeDocument = CreateCodeDocument("@code {}");
var documentContext = CreateDocumentContext(documentPath, codeDocument);
LinePositionSpan projectedRange = default;
var documentMappingService = Mock.Of<IDocumentMappingService>(
d => d.TryMapToGeneratedDocumentRange(It.IsAny<IRazorGeneratedDocument>(), It.IsAny<LinePositionSpan>(), out projectedRange) == false
, MockBehavior.Strict);
var codeActionEndpoint = new CodeActionEndpoint(
documentMappingService,
Array.Empty<IRazorCodeActionProvider>(),
new ICSharpCodeActionProvider[] {
new MockCSharpCodeActionProvider()
},
Array.Empty<IHtmlCodeActionProvider>(),
_clientConnection,
_languageServerFeatureOptions,
LoggerFactory,
telemetryReporter: null)
{
_supportsCodeActionResolve = false
};
var codeActionEndpoint = CreateEndpoint(csharpCodeActionProviders: [CreateCSharpCodeActionProvider()]);
var initialRange = VsLspFactory.CreateZeroWidthRange(0, 1);
var request = new VSCodeActionParams()
@ -733,22 +543,11 @@ public class CodeActionEndpointTest : LanguageServerTestBase
var codeDocument = CreateCodeDocument("@code {}");
var documentContext = CreateDocumentContext(documentPath, codeDocument);
var projectedRange = VsLspFactory.CreateZeroWidthRange(15, 2);
var documentMappingService = CreateDocumentMappingService(projectedRange.ToLinePositionSpan());
var languageServer = CreateLanguageServer();
var codeActionEndpoint = new CodeActionEndpoint(
documentMappingService,
Array.Empty<IRazorCodeActionProvider>(),
new ICSharpCodeActionProvider[] {
new MockCSharpCodeActionProvider()
},
Array.Empty<IHtmlCodeActionProvider>(),
languageServer,
_languageServerFeatureOptions,
LoggerFactory,
telemetryReporter: null)
{
_supportsCodeActionResolve = false
};
var codeActionEndpoint = CreateEndpoint(
documentMappingService: CreateDocumentMappingService(projectedRange.ToLinePositionSpan()),
csharpCodeActionProviders: [CreateCSharpCodeActionProvider()],
clientConnection: TestClientConnection.Instance);
var initialRange = VsLspFactory.CreateZeroWidthRange(0, 1);
var request = new VSCodeActionParams()
@ -765,11 +564,12 @@ public class CodeActionEndpointTest : LanguageServerTestBase
Assert.NotNull(context);
// Act
var results = await codeActionEndpoint.GetCodeActionsFromLanguageServerAsync(RazorLanguageKind.CSharp, documentContext, context, Guid.Empty, cancellationToken: default);
var results = await codeActionEndpoint.GetCodeActionsFromLanguageServerAsync(RazorLanguageKind.CSharp, documentContext, context, Guid.Empty, cancellationToken: DisposalToken);
// Assert
var result = Assert.Single(results);
var diagnostics = result.Diagnostics!.ToArray();
Assert.NotNull(result.Diagnostics);
var diagnostics = result.Diagnostics.ToArray();
Assert.Equal(2, diagnostics.Length);
// Diagnostic ranges contain the projected range for
@ -782,136 +582,142 @@ public class CodeActionEndpointTest : LanguageServerTestBase
Assert.Equal(projectedRange, diagnostics[1].Range);
}
private static IDocumentMappingService CreateDocumentMappingService(LinePositionSpan projectedRange = default)
private CodeActionEndpoint CreateEndpoint(
IDocumentMappingService? documentMappingService = null,
ImmutableArray<IRazorCodeActionProvider> razorCodeActionProviders = default,
ImmutableArray<ICSharpCodeActionProvider> csharpCodeActionProviders = default,
ImmutableArray<IHtmlCodeActionProvider> htmlCodeActionProviders = default,
IClientConnection? clientConnection = null,
LanguageServerFeatureOptions? languageServerFeatureOptions = null,
bool supportsCodeActionResolve = false)
{
if (projectedRange == default)
return new CodeActionEndpoint(
documentMappingService ?? CreateDocumentMappingService(),
razorCodeActionProviders.NullToEmpty(),
csharpCodeActionProviders.NullToEmpty(),
htmlCodeActionProviders.NullToEmpty(),
clientConnection ?? StrictMock.Of<IClientConnection>(),
languageServerFeatureOptions ?? StrictMock.Of<LanguageServerFeatureOptions>(x => x.SupportsFileManipulation == true),
LoggerFactory,
telemetryReporter: null)
{
projectedRange = new LinePositionSpan(new(5, 2), new(5, 2));
}
var documentMappingService = Mock.Of<IDocumentMappingService>(
d => d.TryMapToGeneratedDocumentRange(It.IsAny<IRazorGeneratedDocument>(), It.IsAny<LinePositionSpan>(), out projectedRange) == true &&
d.GetLanguageKind(It.IsAny<RazorCodeDocument>(), It.IsAny<int>(), It.IsAny<bool>()) == RazorLanguageKind.CSharp
, MockBehavior.Strict);
return documentMappingService;
_supportsCodeActionResolve = supportsCodeActionResolve
};
}
private static IClientConnection CreateLanguageServer()
private static IDocumentMappingService CreateDocumentMappingService(LinePositionSpan? projectedRange = null)
{
return new TestLanguageServer();
var mock = new StrictMock<IDocumentMappingService>();
// If a range was provided, use that and return true; otherwise, return false.
var (outRange, result) = projectedRange is LinePositionSpan
? (projectedRange.GetValueOrDefault(), true)
: (It.Ref<LinePositionSpan>.IsAny, false);
mock.Setup(x => x.TryMapToGeneratedDocumentRange(It.IsAny<IRazorGeneratedDocument>(), It.IsAny<LinePositionSpan>(), out outRange))
.Returns(result);
return mock.Object;
}
private static RazorCodeDocument CreateCodeDocument(string text)
{
var codeDocument = TestRazorCodeDocument.Create(text);
var sourceDocument = TestRazorSourceDocument.Create(text);
var syntaxTree = RazorSyntaxTree.Parse(sourceDocument);
codeDocument.SetSyntaxTree(syntaxTree);
return codeDocument;
var projectEngine = RazorProjectEngine.Create(builder => { });
return projectEngine.ProcessDesignTime(sourceDocument, "mvc", importSources: [], tagHelpers: []);
}
private class MockRazorCodeActionProvider : IRazorCodeActionProvider
private static IRazorCodeActionProvider CreateEmptyRazorCodeActionProvider()
=> CreateRazorCodeActionProvider([]);
private static IRazorCodeActionProvider CreateRazorCodeActionProvider()
=> CreateRazorCodeActionProvider(new RazorVSInternalCodeAction());
private static IRazorCodeActionProvider CreateMultipleRazorCodeActionProvider()
=> CreateRazorCodeActionProvider(
new RazorVSInternalCodeAction(),
new RazorVSInternalCodeAction());
private static IRazorCodeActionProvider CreateRazorCommandProvider()
=> CreateRazorCodeActionProvider(
new RazorVSInternalCodeAction()
{
Title = "SomeTitle",
Data = JsonSerializer.SerializeToElement(new AddUsingsCodeActionParams()
{
Namespace = "Test",
Uri = new Uri("C:/path/to/Page.razor")
})
});
private static IRazorCodeActionProvider CreateRazorCodeActionProvider(params ImmutableArray<RazorVSInternalCodeAction> codeActions)
{
public Task<ImmutableArray<RazorVSInternalCodeAction>> ProvideAsync(RazorCodeActionContext context, CancellationToken cancellationToken)
var mock = new StrictMock<IRazorCodeActionProvider>();
mock.Setup(x => x.ProvideAsync(It.IsAny<RazorCodeActionContext>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(() => codeActions);
return mock.Object;
}
private static ICSharpCodeActionProvider CreateCSharpCodeActionProvider()
=> CreateCSharpCodeActionProvider([new RazorVSInternalCodeAction()]);
private static ICSharpCodeActionProvider CreateCSharpCodeActionProvider(params ImmutableArray<RazorVSInternalCodeAction> codeActions)
{
var mock = new StrictMock<ICSharpCodeActionProvider>();
mock.Setup(x => x.ProvideAsync(It.IsAny<RazorCodeActionContext>(), It.IsAny<ImmutableArray<RazorVSInternalCodeAction>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(() => codeActions);
return mock.Object;
}
private sealed class TestClientConnection : IClientConnection
{
public static readonly IClientConnection Instance = new TestClientConnection();
private static readonly string[] s_customTags = ["CodeActionName"];
private TestClientConnection()
{
return Task.FromResult<ImmutableArray<RazorVSInternalCodeAction>>([new RazorVSInternalCodeAction()]);
}
}
private class MockMultipleRazorCodeActionProvider : IRazorCodeActionProvider
{
public Task<ImmutableArray<RazorVSInternalCodeAction>> ProvideAsync(RazorCodeActionContext context, CancellationToken cancellationToken)
{
return Task.FromResult<ImmutableArray<RazorVSInternalCodeAction>>(
[
new RazorVSInternalCodeAction(),
new RazorVSInternalCodeAction()
]);
}
}
private class MockCSharpCodeActionProvider : ICSharpCodeActionProvider
{
public Task<ImmutableArray<RazorVSInternalCodeAction>> ProvideAsync(RazorCodeActionContext _1, ImmutableArray<RazorVSInternalCodeAction> _2, CancellationToken _3)
{
return Task.FromResult<ImmutableArray<RazorVSInternalCodeAction>>(
[
new RazorVSInternalCodeAction()
]);
}
}
private class MockRazorCommandProvider : IRazorCodeActionProvider
{
public Task<ImmutableArray<RazorVSInternalCodeAction>> ProvideAsync(RazorCodeActionContext _1, CancellationToken _2)
{
// O# Code Actions don't have `Data`, but `Commands` do
return Task.FromResult<ImmutableArray<RazorVSInternalCodeAction>>(
[
new RazorVSInternalCodeAction() {
Title = "SomeTitle",
Data = JsonSerializer.SerializeToElement(new AddUsingsCodeActionParams()
{
Namespace="Test",
Uri = new Uri("C:/path/to/Page.razor")
})
}
]);
}
}
private class MockEmptyRazorCodeActionProvider : IRazorCodeActionProvider
{
public Task<ImmutableArray<RazorVSInternalCodeAction>> ProvideAsync(RazorCodeActionContext _1, CancellationToken _2)
{
return SpecializedTasks.EmptyImmutableArray<RazorVSInternalCodeAction>();
}
}
private class TestLanguageServer : IClientConnection
{
public Task SendNotificationAsync<TParams>(string method, TParams @params, CancellationToken cancellationToken)
{
if (method != CustomMessageNames.RazorProvideCodeActionsEndpoint)
{
throw new InvalidOperationException($"Unexpected method {method}");
}
Assert.Equal(CustomMessageNames.RazorProvideCodeActionsEndpoint, method);
return Task.CompletedTask;
}
public Task SendNotificationAsync(string method, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
=> throw new NotImplementedException();
public Task<TResponse> SendRequestAsync<TParams, TResponse>(string method, TParams @params, CancellationToken cancellationToken)
{
if (method != CustomMessageNames.RazorProvideCodeActionsEndpoint)
{
throw new InvalidOperationException($"Unexpected method {method}");
}
Assert.Equal(CustomMessageNames.RazorProvideCodeActionsEndpoint, method);
if (@params is not DelegatedCodeActionParams delegatedCodeActionParams ||
delegatedCodeActionParams.CodeActionParams is not VSCodeActionParams codeActionParams ||
codeActionParams.Context is not VSInternalCodeActionContext codeActionContext)
{
throw new InvalidOperationException(@params!.GetType().FullName);
}
Assert.NotNull(@params);
var delegatedCodeActionParams = Assert.IsType<DelegatedCodeActionParams>(@params);
Assert.NotNull(delegatedCodeActionParams.CodeActionParams);
Assert.NotNull(delegatedCodeActionParams.CodeActionParams.Context);
var diagnostics = new List<Diagnostic>
{
new Diagnostic()
new()
{
Range = codeActionParams.Range,
Range = delegatedCodeActionParams.CodeActionParams.Range,
Message = "Range"
}
};
if (codeActionContext.SelectionRange is not null)
if (delegatedCodeActionParams.CodeActionParams.Context.SelectionRange is { } selectionRange)
{
diagnostics.Add(new Diagnostic()
diagnostics.Add(new()
{
Range = codeActionContext.SelectionRange,
Range = selectionRange,
Message = "Selection Range"
});
}
@ -922,12 +728,12 @@ public class CodeActionEndpointTest : LanguageServerTestBase
// is correct rather than providing specific test hooks in the CodeActionEndpoint
var result = new[]
{
new RazorVSInternalCodeAction()
{
Data = JsonSerializer.SerializeToElement(new { CustomTags = new object[] { "CodeActionName" } }),
Diagnostics = diagnostics.ToArray()
}
};
new RazorVSInternalCodeAction()
{
Data = JsonSerializer.SerializeToElement(new { CustomTags = s_customTags }),
Diagnostics = [.. diagnostics]
}
};
return Task.FromResult((TResponse)(object)result);
}

Просмотреть файл

@ -2,15 +2,14 @@
// Licensed under the MIT license. See License.txt in the project root for license information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Razor.Language;
using Microsoft.AspNetCore.Razor.LanguageServer.Hosting;
using Microsoft.AspNetCore.Razor.Test.Common;
using Microsoft.AspNetCore.Razor.Test.Common.LanguageServer;
using Microsoft.CodeAnalysis.Razor.DocumentMapping;
using Microsoft.CodeAnalysis.Razor.Protocol;
using Microsoft.CodeAnalysis.Razor.Protocol.DocumentPresentation;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Moq;
using Xunit;
@ -24,116 +23,83 @@ public class TextDocumentTextPresentationEndpointTests(ITestOutputHelper testOut
public async Task Handle_Html_MakesRequest()
{
// Arrange
var codeDocument = TestRazorCodeDocument.Create("<div></div>");
var documentMappingService = Mock.Of<IDocumentMappingService>(
s => s.GetLanguageKind(codeDocument, It.IsAny<int>(), It.IsAny<bool>()) == RazorLanguageKind.Html, MockBehavior.Strict);
TestCode code = "<[|d|]iv></div>";
var codeDocument = CreateCodeDocument(code.Text);
var uri = new Uri("file://path/test.razor");
var documentContext = CreateDocumentContext(uri, codeDocument);
var response = (WorkspaceEdit?)null;
var clientConnection = new Mock<IClientConnection>(MockBehavior.Strict);
clientConnection
.Setup(l => l.SendRequestAsync<IRazorPresentationParams, WorkspaceEdit?>(CustomMessageNames.RazorTextPresentationEndpoint, It.IsAny<IRazorPresentationParams>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(response)
.Verifiable();
var endpoint = new TextDocumentTextPresentationEndpoint(
documentMappingService,
clientConnection.Object,
FilePathService,
LoggerFactory);
var clientConnection = CreateClientConnection(response: null, verifiable: true);
var endpoint = CreateEndpoint(clientConnection);
var parameters = new TextPresentationParams()
{
TextDocument = new TextDocumentIdentifier
{
Uri = uri
},
Range = VsLspFactory.CreateSingleLineRange(line: 0, character: 1, length: 1),
TextDocument = new() { Uri = uri },
Range = codeDocument.Source.Text.GetRange(code.Span),
Text = "Hi there"
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
var result = await endpoint.HandleRequestAsync(parameters, requestContext, DisposalToken);
_ = await endpoint.HandleRequestAsync(parameters, requestContext, DisposalToken);
// Assert
clientConnection.Verify();
Mock.Get(clientConnection).Verify();
}
[Fact]
public async Task Handle_CSharp_DoesNotMakeRequest()
{
// Arrange
var codeDocument = TestRazorCodeDocument.Create("@counter");
var csharpDocument = codeDocument.GetCSharpDocument();
TestCode code = "@[|c|]ounter";
var codeDocument = CreateCodeDocument(code.Text);
var uri = new Uri("file://path/test.razor");
var documentContext = CreateDocumentContext(uri, codeDocument);
var projectedRange = It.IsAny<LinePositionSpan>();
var documentMappingService = Mock.Of<IDocumentMappingService>(
s => s.GetLanguageKind(codeDocument, It.IsAny<int>(), It.IsAny<bool>()) == RazorLanguageKind.CSharp &&
s.TryMapToGeneratedDocumentRange(csharpDocument, It.IsAny<LinePositionSpan>(), out projectedRange) == true, MockBehavior.Strict);
var clientConnection = new Mock<IClientConnection>(MockBehavior.Strict);
var endpoint = new TextDocumentTextPresentationEndpoint(
documentMappingService,
clientConnection.Object,
FilePathService,
LoggerFactory);
var clientConnection = StrictMock.Of<IClientConnection>();
var endpoint = CreateEndpoint(clientConnection);
var parameters = new TextPresentationParams()
{
TextDocument = new TextDocumentIdentifier
{
Uri = uri
},
Range = VsLspFactory.CreateSingleLineRange(line: 0, character: 1, length: 1),
TextDocument = new() { Uri = uri },
Range = codeDocument.Source.Text.GetRange(code.Span),
Text = "Hi there"
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
var result = await endpoint.HandleRequestAsync(parameters, requestContext, DisposalToken);
_ = await endpoint.HandleRequestAsync(parameters, requestContext, DisposalToken);
// Assert
clientConnection.Verify();
Mock.Get(clientConnection)
.VerifySendRequest<IRazorPresentationParams, WorkspaceEdit?>(CustomMessageNames.RazorTextPresentationEndpoint, Times.Never);
}
[Fact]
public async Task Handle_DocumentNotFound_ReturnsNull()
{
// Arrange
var codeDocument = TestRazorCodeDocument.Create("<div></div>");
TestCode code = "<[|d|]iv></div>";
var codeDocument = CreateCodeDocument(code.Text);
var uri = new Uri("file://path/test.razor");
var documentContext = CreateDocumentContext(uri, codeDocument);
var documentMappingService = Mock.Of<IDocumentMappingService>(
s => s.GetLanguageKind(codeDocument, It.IsAny<int>(), It.IsAny<bool>()) == RazorLanguageKind.Html, MockBehavior.Strict);
var response = (WorkspaceEdit?)null;
var clientConnection = new Mock<IClientConnection>(MockBehavior.Strict);
clientConnection
.Setup(l => l.SendRequestAsync<IRazorPresentationParams, WorkspaceEdit?>(CustomMessageNames.RazorTextPresentationEndpoint, It.IsAny<IRazorPresentationParams>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(response);
var endpoint = new TextDocumentTextPresentationEndpoint(
documentMappingService,
clientConnection.Object,
FilePathService,
LoggerFactory);
var clientConnection = CreateClientConnection(response: null);
var endpoint = CreateEndpoint(clientConnection);
var parameters = new TextPresentationParams()
{
TextDocument = new TextDocumentIdentifier
{
Uri = uri
},
Range = VsLspFactory.CreateSingleLineRange(line: 0, character: 1, length: 1),
TextDocument = new() { Uri = uri },
Range = codeDocument.Source.Text.GetRange(code.Span),
Text = "Hi there"
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
@ -147,35 +113,24 @@ public class TextDocumentTextPresentationEndpointTests(ITestOutputHelper testOut
public async Task Handle_UnsupportedCodeDocument_ReturnsNull()
{
// Arrange
var codeDocument = TestRazorCodeDocument.Create("<div></div>");
TestCode code = "<[|d|]iv></div>";
var codeDocument = CreateCodeDocument(code.Text);
codeDocument.SetUnsupported();
var uri = new Uri("file://path/test.razor");
var documentContext = CreateDocumentContext(uri, codeDocument);
var documentMappingService = Mock.Of<IDocumentMappingService>(
s => s.GetLanguageKind(codeDocument, It.IsAny<int>(), It.IsAny<bool>()) == RazorLanguageKind.Html, MockBehavior.Strict);
var response = new WorkspaceEdit();
var clientConnection = new Mock<IClientConnection>(MockBehavior.Strict);
clientConnection
.Setup(l => l.SendRequestAsync<IRazorPresentationParams, WorkspaceEdit?>(CustomMessageNames.RazorTextPresentationEndpoint, It.IsAny<IRazorPresentationParams>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(response);
var endpoint = new TextDocumentTextPresentationEndpoint(
documentMappingService,
clientConnection.Object,
FilePathService,
LoggerFactory);
var clientConnection = CreateClientConnection(response: new WorkspaceEdit());
var endpoint = CreateEndpoint(clientConnection);
var parameters = new TextPresentationParams()
{
TextDocument = new TextDocumentIdentifier
{
Uri = uri
},
Range = VsLspFactory.CreateSingleLineRange(line: 0, character: 1, length: 1),
TextDocument = new() { Uri = uri },
Range = codeDocument.Source.Text.GetRange(code.Span),
Text = "Hi there"
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
@ -184,4 +139,13 @@ public class TextDocumentTextPresentationEndpointTests(ITestOutputHelper testOut
// Assert
Assert.Null(result);
}
private TextDocumentTextPresentationEndpoint CreateEndpoint(IClientConnection clientConnection)
=> new(StrictMock.Of<IDocumentMappingService>(), clientConnection, FilePathService, LoggerFactory);
private static IClientConnection CreateClientConnection(WorkspaceEdit? response, bool verifiable = false)
=> TestMocks.CreateClientConnection(builder =>
{
builder.SetupSendRequest<IRazorPresentationParams, WorkspaceEdit?>(CustomMessageNames.RazorTextPresentationEndpoint, response, verifiable);
});
}

Просмотреть файл

@ -2,11 +2,11 @@
// Licensed under the MIT license. See License.txt in the project root for license information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Razor.Language;
using Microsoft.AspNetCore.Razor.LanguageServer.Hosting;
using Microsoft.AspNetCore.Razor.ProjectSystem;
using Microsoft.AspNetCore.Razor.Test.Common;
using Microsoft.AspNetCore.Razor.Test.Common.LanguageServer;
using Microsoft.AspNetCore.Razor.Test.Common.ProjectSystem;
using Microsoft.CodeAnalysis.Razor.DocumentMapping;
@ -15,7 +15,6 @@ using Microsoft.CodeAnalysis.Razor.Protocol;
using Microsoft.CodeAnalysis.Razor.Protocol.DocumentPresentation;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Moq;
using Xunit;
using Xunit.Abstractions;
using static Microsoft.AspNetCore.Razor.Language.CommonMetadata;
@ -30,46 +29,43 @@ public class TextDocumentUriPresentationEndpointTests(ITestOutputHelper testOutp
// Arrange
var projectManager = CreateProjectSnapshotManager();
var project = await projectManager.UpdateAsync(updater => updater.CreateAndAddProject("c:/path/project.csproj"));
var project = await projectManager.UpdateAsync(updater =>
{
return updater.CreateAndAddProject("c:/path/project.csproj");
});
await projectManager.CreateAndAddDocumentAsync(project, "c:/path/index.razor");
await projectManager.CreateAndAddDocumentAsync(project, "c:/path/MyTagHelper.razor");
var documentMappingService = Mock.Of<IDocumentMappingService>(
s => s.GetLanguageKind(It.IsAny<RazorCodeDocument>(), It.IsAny<int>(), It.IsAny<bool>()) == RazorLanguageKind.Html, MockBehavior.Strict);
var droppedUri = new Uri("file:///c:/path/MyTagHelper.razor");
var builder = TagHelperDescriptorBuilder.Create("MyTagHelper", "MyAssembly");
builder.SetMetadata(TypeNameIdentifier("MyTagHelper"), TypeNamespace("TestRootNamespace"));
var tagHelperDescriptor = builder.Build();
await projectManager.UpdateAsync(updater => updater.ProjectWorkspaceStateChanged(project.Key, ProjectWorkspaceState.Create([tagHelperDescriptor])));
await projectManager.UpdateAsync(updater =>
{
updater.ProjectWorkspaceStateChanged(project.Key, ProjectWorkspaceState.Create([builder.Build()]));
});
var razorFilePath = "c:/path/index.razor";
var uri = new Uri(razorFilePath);
await projectManager.UpdateAsync(updater => updater.DocumentOpened(project.Key, razorFilePath, SourceText.From("<div></div>")));
var documentSnapshot = projectManager.GetLoadedProject(project.Key).GetDocument(razorFilePath).AssumeNotNull();
await projectManager.UpdateAsync(updater =>
{
updater.DocumentOpened(project.Key, razorFilePath, SourceText.From("<div></div>"));
});
var documentContextFactory = new DocumentContextFactory(projectManager, LoggerFactory);
Assert.True(documentContextFactory.TryCreate(uri, null, out var documentContext));
Assert.True(documentContextFactory.TryCreate(uri, projectContext: null, out var documentContext));
var clientConnection = new Mock<IClientConnection>(MockBehavior.Strict);
var endpoint = new TextDocumentUriPresentationEndpoint(
documentMappingService,
clientConnection.Object,
FilePathService,
documentContextFactory,
LoggerFactory);
var endpoint = CreateEndpoint(documentContextFactory);
var parameters = new UriPresentationParams()
{
TextDocument = new TextDocumentIdentifier
{
Uri = uri
},
TextDocument = new() { Uri = uri },
Range = VsLspFactory.CreateSingleLineRange(line: 0, character: 1, length: 1),
Uris = [droppedUri]
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
@ -77,7 +73,12 @@ public class TextDocumentUriPresentationEndpointTests(ITestOutputHelper testOutp
// Assert
Assert.NotNull(result);
Assert.Equal("<MyTagHelper />", result.DocumentChanges!.Value.First[0].Edits[0].NewText);
Assert.NotNull(result.DocumentChanges);
var documentChanges = result.DocumentChanges.GetValueOrDefault();
Assert.True(documentChanges.TryGetFirst(out var documentEdits));
Assert.Equal("<MyTagHelper />", documentEdits[0].Edits[0].NewText);
}
[OSSkipConditionFact(["OSX", "Linux"])]
@ -86,43 +87,39 @@ public class TextDocumentUriPresentationEndpointTests(ITestOutputHelper testOutp
// Arrange
var projectManager = CreateProjectSnapshotManager();
var project = await projectManager.UpdateAsync(updater => updater.CreateAndAddProject("c:/path/project.csproj"));
var project = await projectManager.UpdateAsync(updater =>
{
return updater.CreateAndAddProject("c:/path/project.csproj");
});
await projectManager.CreateAndAddDocumentAsync(project, "c:/path/index.razor");
await projectManager.CreateAndAddDocumentAsync(project, "c:/path/MyTagHelper.razor");
var documentMappingService = Mock.Of<IDocumentMappingService>(
s => s.GetLanguageKind(It.IsAny<RazorCodeDocument>(), It.IsAny<int>(), It.IsAny<bool>()) == RazorLanguageKind.Html, MockBehavior.Strict);
var droppedUri = new Uri("file:///c:/path/MyTagHelper.razor");
var builder = TagHelperDescriptorBuilder.Create("MyTagHelper", "MyAssembly");
builder.SetMetadata(TypeNameIdentifier("MyTagHelper"), TypeNamespace("TestRootNamespace"));
var tagHelperDescriptor = builder.Build();
await projectManager.UpdateAsync(updater => updater.ProjectWorkspaceStateChanged(project.Key, ProjectWorkspaceState.Create([tagHelperDescriptor])));
await projectManager.UpdateAsync(updater =>
{
updater.ProjectWorkspaceStateChanged(project.Key, ProjectWorkspaceState.Create([builder.Build()]));
});
var razorFilePath = "c:/path/index.razor";
var uri = new Uri(razorFilePath);
await projectManager.UpdateAsync(updater => updater.DocumentOpened(project.Key, razorFilePath, SourceText.From("<div></div>")));
var documentSnapshot = projectManager.GetLoadedProject(project.Key).GetDocument(razorFilePath).AssumeNotNull();
await projectManager.UpdateAsync(updater =>
{
updater.DocumentOpened(project.Key, razorFilePath, SourceText.From("<div></div>"));
});
var documentContextFactory = new DocumentContextFactory(projectManager, LoggerFactory);
Assert.True(documentContextFactory.TryCreate(uri, null, out var documentContext));
var clientConnection = new Mock<IClientConnection>(MockBehavior.Strict);
var endpoint = new TextDocumentUriPresentationEndpoint(
documentMappingService,
clientConnection.Object,
FilePathService,
documentContextFactory,
LoggerFactory);
var endpoint = CreateEndpoint(documentContextFactory);
var parameters = new UriPresentationParams()
{
TextDocument = new TextDocumentIdentifier
{
Uri = uri
},
TextDocument = new() { Uri = uri },
Range = VsLspFactory.CreateSingleLineRange(line: 0, character: 1, length: 1),
Uris =
[
@ -131,6 +128,7 @@ public class TextDocumentUriPresentationEndpointTests(ITestOutputHelper testOutp
droppedUri,
]
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
@ -138,7 +136,12 @@ public class TextDocumentUriPresentationEndpointTests(ITestOutputHelper testOutp
// Assert
Assert.NotNull(result);
Assert.Equal("<MyTagHelper />", result!.DocumentChanges!.Value.First[0].Edits[0].NewText);
Assert.NotNull(result.DocumentChanges);
var documentChanges = result.DocumentChanges.GetValueOrDefault();
Assert.True(documentChanges.TryGetFirst(out var documentEdits));
Assert.Equal("<MyTagHelper />", documentEdits[0].Edits[0].NewText);
}
[OSSkipConditionFact(["OSX", "Linux"])]
@ -147,13 +150,14 @@ public class TextDocumentUriPresentationEndpointTests(ITestOutputHelper testOutp
// Arrange
var projectManager = CreateProjectSnapshotManager();
var project = await projectManager.UpdateAsync(updater => updater.CreateAndAddProject("c:/path/project.csproj"));
var project = await projectManager.UpdateAsync(updater =>
{
return updater.CreateAndAddProject("c:/path/project.csproj");
});
await projectManager.CreateAndAddDocumentAsync(project, "c:/path/index.razor");
await projectManager.CreateAndAddDocumentAsync(project, "c:/path/fetchdata.razor");
var documentMappingService = Mock.Of<IDocumentMappingService>(
s => s.GetLanguageKind(It.IsAny<RazorCodeDocument>(), It.IsAny<int>(), It.IsAny<bool>()) == RazorLanguageKind.Html, MockBehavior.Strict);
var droppedUri = new Uri("file:///c:/path/fetchdata.razor");
var builder = TagHelperDescriptorBuilder.Create("FetchData", "MyAssembly");
builder.SetMetadata(TypeNameIdentifier("FetchData"), TypeNamespace("TestRootNamespace"));
@ -163,36 +167,32 @@ public class TextDocumentUriPresentationEndpointTests(ITestOutputHelper testOutp
b.Name = "MyAttribute";
});
builder.BindAttribute(b => b.Name = "MyNonRequiredAttribute");
var tagHelperDescriptor = builder.Build();
await projectManager.UpdateAsync(updater => updater.ProjectWorkspaceStateChanged(project.Key, ProjectWorkspaceState.Create([tagHelperDescriptor])));
await projectManager.UpdateAsync(updater =>
{
updater.ProjectWorkspaceStateChanged(project.Key, ProjectWorkspaceState.Create([builder.Build()]));
});
var razorFilePath = "c:/path/index.razor";
var uri = new Uri(razorFilePath);
await projectManager.UpdateAsync(updater => updater.DocumentOpened(project.Key, razorFilePath, SourceText.From("<div></div>")));
var documentSnapshot = projectManager.GetLoadedProject(project.Key).GetDocument(razorFilePath).AssumeNotNull();
await projectManager.UpdateAsync(updater =>
{
updater.DocumentOpened(project.Key, razorFilePath, SourceText.From("<div></div>"));
});
var documentContextFactory = new DocumentContextFactory(projectManager, LoggerFactory);
Assert.True(documentContextFactory.TryCreate(uri, null, out var documentContext));
var clientConnection = new Mock<IClientConnection>(MockBehavior.Strict);
var endpoint = new TextDocumentUriPresentationEndpoint(
documentMappingService,
clientConnection.Object,
FilePathService,
documentContextFactory,
LoggerFactory);
var endpoint = CreateEndpoint(documentContextFactory);
var parameters = new UriPresentationParams()
{
TextDocument = new TextDocumentIdentifier
{
Uri = uri
},
TextDocument = new() { Uri = uri },
Range = VsLspFactory.CreateSingleLineRange(line: 0, character: 1, length: 1),
Uris = [droppedUri]
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
@ -200,51 +200,35 @@ public class TextDocumentUriPresentationEndpointTests(ITestOutputHelper testOutp
// Assert
Assert.NotNull(result);
Assert.Equal("<FetchData MyAttribute=\"\" />", result.DocumentChanges!.Value.First[0].Edits[0].NewText);
Assert.NotNull(result.DocumentChanges);
var documentChanges = result.DocumentChanges.GetValueOrDefault();
Assert.True(documentChanges.TryGetFirst(out var documentEdits));
Assert.Equal("<FetchData MyAttribute=\"\" />", documentEdits[0].Edits[0].NewText);
}
[Fact]
public async Task Handle_NoTypeNameIdentifier_ReturnsNull()
{
// Arrange
var codeDocument = TestRazorCodeDocument.Create("<div></div>");
var documentMappingService = Mock.Of<IDocumentMappingService>(
s => s.GetLanguageKind(codeDocument, It.IsAny<int>(), It.IsAny<bool>()) == RazorLanguageKind.Html, MockBehavior.Strict);
var componentCodeDocument = TestRazorCodeDocument.Create("<div></div>");
var droppedUri = new Uri("file:///c:/path/MyTagHelper.razor");
var builder = TagHelperDescriptorBuilder.Create("MyTagHelper", "MyAssembly");
var tagHelperDescriptor = builder.Build();
var documentSnapshot = Mock.Of<IDocumentSnapshot>(s => s.GetGeneratedOutputAsync(It.IsAny<bool>()) == Task.FromResult(componentCodeDocument), MockBehavior.Strict);
var codeDocument = CreateCodeDocument("<div></div>");
var uri = new Uri("file://path/test.razor");
var droppedUri = new Uri("file:///c:/path/MyTagHelper.razor");
var documentContextFactory = CreateDocumentContextFactory(uri, codeDocument);
var documentContext = CreateDocumentContext(uri, codeDocument);
var response = (WorkspaceEdit?)null;
var clientConnection = new Mock<IClientConnection>(MockBehavior.Strict);
clientConnection
.Setup(l => l.SendRequestAsync<IRazorPresentationParams, WorkspaceEdit?>(CustomMessageNames.RazorUriPresentationEndpoint, It.IsAny<IRazorPresentationParams>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(response);
var endpoint = new TextDocumentUriPresentationEndpoint(
documentMappingService,
clientConnection.Object,
FilePathService,
documentContextFactory,
LoggerFactory);
var clientConnection = CreateClientConnection(response: null);
var endpoint = CreateEndpoint(documentContextFactory, clientConnection);
var parameters = new UriPresentationParams()
{
TextDocument = new TextDocumentIdentifier
{
Uri = uri
},
TextDocument = new() { Uri = uri },
Range = VsLspFactory.CreateSingleLineRange(line: 0, character: 1, length: 1),
Uris = [droppedUri]
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
@ -258,36 +242,18 @@ public class TextDocumentUriPresentationEndpointTests(ITestOutputHelper testOutp
public async Task Handle_MultipleUris_ReturnsNull()
{
// Arrange
var codeDocument = TestRazorCodeDocument.Create("<div></div>");
var documentMappingService = Mock.Of<IDocumentMappingService>(
s => s.GetLanguageKind(codeDocument, It.IsAny<int>(), It.IsAny<bool>()) == RazorLanguageKind.Html, MockBehavior.Strict);
var documentSnapshot = Mock.Of<IDocumentSnapshot>(s => s.GetGeneratedOutputAsync(false) == Task.FromResult(codeDocument), MockBehavior.Strict);
var codeDocument = CreateCodeDocument("<div></div>");
var uri = new Uri("file://path/test.razor");
var documentContextFactory = CreateDocumentContextFactory(uri, codeDocument);
var documentContext = CreateDocumentContext(uri, codeDocument);
var response = (WorkspaceEdit?)null;
var clientConnection = new Mock<IClientConnection>(MockBehavior.Strict);
clientConnection
.Setup(l => l.SendRequestAsync<IRazorPresentationParams, WorkspaceEdit?>(CustomMessageNames.RazorUriPresentationEndpoint, It.IsAny<IRazorPresentationParams>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(response);
var endpoint = new TextDocumentUriPresentationEndpoint(
documentMappingService,
clientConnection.Object,
FilePathService,
documentContextFactory,
LoggerFactory);
var clientConnection = CreateClientConnection(response: null);
var endpoint = CreateEndpoint(documentContextFactory, clientConnection);
var parameters = new UriPresentationParams()
{
TextDocument = new TextDocumentIdentifier
{
Uri = uri
},
TextDocument = new() { Uri = uri },
Range = VsLspFactory.CreateSingleLineRange(line: 0, character: 1, length: 1),
Uris =
[
@ -296,6 +262,7 @@ public class TextDocumentUriPresentationEndpointTests(ITestOutputHelper testOutp
new Uri("file:///c:/path/MyTagHelper.razor"),
]
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
@ -309,40 +276,23 @@ public class TextDocumentUriPresentationEndpointTests(ITestOutputHelper testOutp
public async Task Handle_NotComponent_ReturnsNull()
{
// Arrange
var codeDocument = TestRazorCodeDocument.Create("<div></div>");
var documentMappingService = Mock.Of<IDocumentMappingService>(
s => s.GetLanguageKind(codeDocument, It.IsAny<int>(), It.IsAny<bool>()) == RazorLanguageKind.Html, MockBehavior.Strict);
var documentSnapshot = Mock.Of<IDocumentSnapshot>(s => s.GetGeneratedOutputAsync(false) == Task.FromResult(codeDocument), MockBehavior.Strict);
var codeDocument = CreateCodeDocument("<div></div>");
var droppedUri = new Uri("file:///c:/path/MyTagHelper.cshtml");
var uri = new Uri("file://path/test.razor");
var documentContextFactory = CreateDocumentContextFactory(uri, codeDocument);
var documentContext = CreateDocumentContext(uri, codeDocument);
var response = (WorkspaceEdit?)null;
var clientConnection = new Mock<IClientConnection>(MockBehavior.Strict);
clientConnection
.Setup(l => l.SendRequestAsync<IRazorPresentationParams, WorkspaceEdit?>(CustomMessageNames.RazorUriPresentationEndpoint, It.IsAny<IRazorPresentationParams>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(response);
var endpoint = new TextDocumentUriPresentationEndpoint(
documentMappingService,
clientConnection.Object,
FilePathService,
documentContextFactory,
LoggerFactory);
var clientConnection = CreateClientConnection(response: null);
var endpoint = CreateEndpoint(documentContextFactory, clientConnection);
var parameters = new UriPresentationParams()
{
TextDocument = new TextDocumentIdentifier
{
Uri = uri
},
TextDocument = new() { Uri = uri },
Range = VsLspFactory.CreateSingleLineRange(line: 0, character: 1, length: 1),
Uris = [droppedUri]
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
@ -358,47 +308,49 @@ public class TextDocumentUriPresentationEndpointTests(ITestOutputHelper testOutp
// Arrange
var projectManager = CreateProjectSnapshotManager();
var project = await projectManager.UpdateAsync(updater => updater.CreateAndAddProject("c:/path/project.csproj"));
var project = await projectManager.UpdateAsync(updater =>
{
return updater.CreateAndAddProject("c:/path/project.csproj");
});
await projectManager.CreateAndAddDocumentAsync(project, "c:/path/index.razor");
await projectManager.CreateAndAddDocumentAsync(project, "c:/path/fetchdata.razor");
var documentMappingService = Mock.Of<IDocumentMappingService>(
s => s.GetLanguageKind(It.IsAny<RazorCodeDocument>(), It.IsAny<int>(), It.IsAny<bool>()) == RazorLanguageKind.Html, MockBehavior.Strict);
var droppedUri1 = new Uri("file:///c:/path/fetchdata.razor.cs");
var droppedUri2 = new Uri("file:///c:/path/fetchdata.razor");
var builder = TagHelperDescriptorBuilder.Create("FetchData", "MyAssembly");
builder.SetMetadata(TypeNameIdentifier("FetchData"), TypeNamespace("TestRootNamespace"));
var tagHelperDescriptor = builder.Build();
await projectManager.UpdateAsync(updater => updater.ProjectWorkspaceStateChanged(project.Key, ProjectWorkspaceState.Create([tagHelperDescriptor])));
await projectManager.UpdateAsync(updater =>
{
updater.ProjectWorkspaceStateChanged(project.Key, ProjectWorkspaceState.Create([builder.Build()]));
});
var razorFilePath = "c:/path/index.razor";
var uri = new Uri(razorFilePath);
await projectManager.UpdateAsync(updater => updater.DocumentOpened(project.Key, razorFilePath, SourceText.From("<div></div>")));
var documentSnapshot = projectManager.GetLoadedProject(project.Key).GetDocument(razorFilePath).AssumeNotNull();
await projectManager.UpdateAsync(updater =>
{
updater.DocumentOpened(project.Key, razorFilePath, SourceText.From("<div></div>"));
});
var documentSnapshot = projectManager
.GetLoadedProject(project.Key)
.GetDocument(razorFilePath);
Assert.NotNull(documentSnapshot);
var documentContextFactory = new DocumentContextFactory(projectManager, LoggerFactory);
Assert.True(documentContextFactory.TryCreate(uri, null, out var documentContext));
Assert.True(documentContextFactory.TryCreate(uri, projectContext: null, out var documentContext));
var clientConnection = new Mock<IClientConnection>(MockBehavior.Strict);
var endpoint = new TextDocumentUriPresentationEndpoint(
documentMappingService,
clientConnection.Object,
FilePathService,
documentContextFactory,
LoggerFactory);
var endpoint = CreateEndpoint(documentContextFactory);
var parameters = new UriPresentationParams()
{
TextDocument = new TextDocumentIdentifier
{
Uri = uri
},
TextDocument = new() { Uri = uri },
Range = VsLspFactory.CreateSingleLineRange(line: 0, character: 1, length: 1),
Uris = [droppedUri1, droppedUri2]
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
@ -406,47 +358,32 @@ public class TextDocumentUriPresentationEndpointTests(ITestOutputHelper testOutp
// Assert
Assert.NotNull(result);
Assert.Equal("<FetchData />", result!.DocumentChanges!.Value.First[0].Edits[0].NewText);
Assert.NotNull(result.DocumentChanges);
var documentChanges = result.DocumentChanges.GetValueOrDefault();
Assert.True(documentChanges.TryGetFirst(out var documentEdits));
Assert.Equal("<FetchData />", documentEdits[0].Edits[0].NewText);
}
[Fact]
public async Task Handle_CSharp_ReturnsNull()
{
// Arrange
var codeDocument = TestRazorCodeDocument.Create("@counter");
var csharpDocument = codeDocument.GetCSharpDocument();
var codeDocument = CreateCodeDocument("@counter");
var uri = new Uri("file://path/test.razor");
var documentContext = CreateDocumentContext(uri, codeDocument);
var projectedRange = It.IsAny<LinePositionSpan>();
var documentMappingService = Mock.Of<IDocumentMappingService>(
s => s.GetLanguageKind(codeDocument, It.IsAny<int>(), It.IsAny<bool>()) == RazorLanguageKind.CSharp &&
s.TryMapToGeneratedDocumentRange(csharpDocument, It.IsAny<LinePositionSpan>(), out projectedRange) == true, MockBehavior.Strict);
var documentSnapshot = Mock.Of<IDocumentSnapshot>(s => s.GetGeneratedOutputAsync(false) == Task.FromResult(codeDocument), MockBehavior.Strict);
var documentContextFactory = CreateDocumentContextFactory(uri, codeDocument);
var response = (WorkspaceEdit?)null;
var clientConnection = new Mock<IClientConnection>(MockBehavior.Strict);
clientConnection
.Setup(l => l.SendRequestAsync<IRazorPresentationParams, WorkspaceEdit?>(CustomMessageNames.RazorUriPresentationEndpoint, It.IsAny<IRazorPresentationParams>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(response);
var endpoint = new TextDocumentUriPresentationEndpoint(
documentMappingService,
clientConnection.Object,
FilePathService,
documentContextFactory,
LoggerFactory);
var clientConnection = CreateClientConnection(response: null);
var endpoint = CreateEndpoint(documentContextFactory, clientConnection);
var parameters = new UriPresentationParams()
{
TextDocument = new TextDocumentIdentifier
{
Uri = uri
},
TextDocument = new() { Uri = uri },
Range = VsLspFactory.CreateSingleLineRange(line: 0, character: 1, length: 1)
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
@ -460,37 +397,21 @@ public class TextDocumentUriPresentationEndpointTests(ITestOutputHelper testOutp
public async Task Handle_DocumentNotFound_ReturnsNull()
{
// Arrange
var codeDocument = TestRazorCodeDocument.Create("<div></div>");
var codeDocument = CreateCodeDocument("<div></div>");
var uri = new Uri("file://path/test.razor");
var documentContext = CreateDocumentContext(uri, codeDocument);
var documentMappingService = Mock.Of<IDocumentMappingService>(
s => s.GetLanguageKind(codeDocument, It.IsAny<int>(), It.IsAny<bool>()) == RazorLanguageKind.Html, MockBehavior.Strict);
var documentSnapshot = Mock.Of<IDocumentSnapshot>(s => s.GetGeneratedOutputAsync(false) == Task.FromResult(codeDocument), MockBehavior.Strict);
var documentContextFactory = CreateDocumentContextFactory(uri, codeDocument);
var response = (WorkspaceEdit?)null;
var clientConnection = new Mock<IClientConnection>(MockBehavior.Strict);
clientConnection
.Setup(l => l.SendRequestAsync<IRazorPresentationParams, WorkspaceEdit?>(CustomMessageNames.RazorUriPresentationEndpoint, It.IsAny<IRazorPresentationParams>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(response);
var endpoint = new TextDocumentUriPresentationEndpoint(
documentMappingService,
clientConnection.Object,
FilePathService,
documentContextFactory,
LoggerFactory);
var clientConnection = CreateClientConnection(response: null);
var endpoint = CreateEndpoint(documentContextFactory, clientConnection);
var parameters = new UriPresentationParams()
{
TextDocument = new TextDocumentIdentifier
{
Uri = uri
},
TextDocument = new() { Uri = uri },
Range = VsLspFactory.CreateSingleLineRange(line: 0, character: 1, length: 1)
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
@ -504,38 +425,22 @@ public class TextDocumentUriPresentationEndpointTests(ITestOutputHelper testOutp
public async Task Handle_UnsupportedCodeDocument_ReturnsNull()
{
// Arrange
var codeDocument = TestRazorCodeDocument.Create("<div></div>");
var codeDocument = CreateCodeDocument("<div></div>");
codeDocument.SetUnsupported();
var uri = new Uri("file://path/test.razor");
var documentContext = CreateDocumentContext(uri, codeDocument);
var documentMappingService = Mock.Of<IDocumentMappingService>(
s => s.GetLanguageKind(codeDocument, It.IsAny<int>(), It.IsAny<bool>()) == RazorLanguageKind.Html, MockBehavior.Strict);
var documentSnapshot = Mock.Of<IDocumentSnapshot>(s => s.GetGeneratedOutputAsync(false) == Task.FromResult(codeDocument), MockBehavior.Strict);
var documentContextFactory = CreateDocumentContextFactory(uri, codeDocument);
var response = new WorkspaceEdit();
var clientConnection = new Mock<IClientConnection>(MockBehavior.Strict);
clientConnection
.Setup(l => l.SendRequestAsync<IRazorPresentationParams, WorkspaceEdit?>(CustomMessageNames.RazorUriPresentationEndpoint, It.IsAny<IRazorPresentationParams>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(response);
var endpoint = new TextDocumentUriPresentationEndpoint(
documentMappingService,
clientConnection.Object,
FilePathService,
documentContextFactory,
LoggerFactory);
var clientConnection = CreateClientConnection(response: new WorkspaceEdit());
var endpoint = CreateEndpoint(documentContextFactory, clientConnection);
var parameters = new UriPresentationParams()
{
TextDocument = new TextDocumentIdentifier
{
Uri = uri
},
TextDocument = new() { Uri = uri },
Range = VsLspFactory.CreateSingleLineRange(line: 0, character: 1, length: 1)
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
@ -549,37 +454,21 @@ public class TextDocumentUriPresentationEndpointTests(ITestOutputHelper testOutp
public async Task Handle_NoUris_ReturnsNull()
{
// Arrange
var codeDocument = TestRazorCodeDocument.Create("<div></div>");
var codeDocument = CreateCodeDocument("<div></div>");
var uri = new Uri("file://path/test.razor");
var documentContext = CreateDocumentContext(uri, codeDocument);
var documentMappingService = Mock.Of<IDocumentMappingService>(
s => s.GetLanguageKind(codeDocument, It.IsAny<int>(), It.IsAny<bool>()) == RazorLanguageKind.Html, MockBehavior.Strict);
var documentSnapshot = Mock.Of<IDocumentSnapshot>(s => s.GetGeneratedOutputAsync(false) == Task.FromResult(codeDocument), MockBehavior.Strict);
var documentContextFactory = CreateDocumentContextFactory(uri, codeDocument);
var response = (WorkspaceEdit?)null;
var clientConnection = new Mock<IClientConnection>(MockBehavior.Strict);
clientConnection
.Setup(l => l.SendRequestAsync<IRazorPresentationParams, WorkspaceEdit?>(CustomMessageNames.RazorUriPresentationEndpoint, It.IsAny<IRazorPresentationParams>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(response);
var endpoint = new TextDocumentUriPresentationEndpoint(
documentMappingService,
clientConnection.Object,
FilePathService,
documentContextFactory,
LoggerFactory);
var clientConnection = CreateClientConnection(response: null);
var endpoint = CreateEndpoint(documentContextFactory, clientConnection);
var parameters = new UriPresentationParams()
{
TextDocument = new TextDocumentIdentifier
{
Uri = uri
},
TextDocument = new() { Uri = uri },
Range = VsLspFactory.CreateSingleLineRange(line: 0, character: 1, length: 1)
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
@ -588,4 +477,22 @@ public class TextDocumentUriPresentationEndpointTests(ITestOutputHelper testOutp
// Assert
Assert.Null(result);
}
private TextDocumentUriPresentationEndpoint CreateEndpoint(
IDocumentContextFactory documentContextFactory,
IClientConnection? clientConnection = null)
{
return new TextDocumentUriPresentationEndpoint(
StrictMock.Of<IDocumentMappingService>(),
clientConnection ?? StrictMock.Of<IClientConnection>(),
FilePathService,
documentContextFactory,
LoggerFactory);
}
private static IClientConnection CreateClientConnection(WorkspaceEdit? response)
=> TestMocks.CreateClientConnection(builder =>
{
builder.SetupSendRequest<IRazorPresentationParams, WorkspaceEdit?>(CustomMessageNames.RazorUriPresentationEndpoint, response);
});
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -110,7 +110,7 @@ public class RenameEndpointTest(ITestOutputHelper testOutput) : LanguageServerTe
public async Task Handle_Rename_FileManipulationNotSupported_ReturnsNull()
{
// Arrange
var options = StrictMock.Of<LanguageServerFeatureOptions>(o =>
var options = StrictMock.Of<LanguageServerFeatureOptions>(static o =>
o.SupportsFileManipulation == false &&
o.ReturnCodeActionAndRenamePathsWithPrefixedSlash == false);
var (endpoint, documentContextFactory) = await CreateEndpointAndDocumentContextFactoryAsync(options);
@ -538,39 +538,36 @@ public class RenameEndpointTest(ITestOutputHelper testOutput) : LanguageServerTe
public async Task Handle_Rename_SingleServer_CallsDelegatedLanguageServer()
{
// Arrange
var options = StrictMock.Of<LanguageServerFeatureOptions>(o =>
var options = StrictMock.Of<LanguageServerFeatureOptions>(static o =>
o.SupportsFileManipulation == true &&
o.SingleServerSupport == true &&
o.ReturnCodeActionAndRenamePathsWithPrefixedSlash == false);
var delegatedEdit = new WorkspaceEdit();
var clientConnectionMock = new StrictMock<IClientConnection>();
clientConnectionMock
.Setup(c => c.SendRequestAsync<IDelegatedParams, WorkspaceEdit>(CustomMessageNames.RazorRenameEndpointName, It.IsAny<DelegatedRenameParams>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(delegatedEdit);
var clientConnection = TestMocks.CreateClientConnection(builder =>
{
builder.SetupSendRequest<IDelegatedParams, WorkspaceEdit>(CustomMessageNames.RazorRenameEndpointName, response: delegatedEdit);
});
var documentMappingServiceMock = new StrictMock<IDocumentMappingService>();
documentMappingServiceMock
.Setup(c => c.GetLanguageKind(It.IsAny<RazorCodeDocument>(), It.IsAny<int>(), It.IsAny<bool>()))
.Returns(RazorLanguageKind.CSharp);
var projectedPosition = new LinePosition(1, 1);
var projectedIndex = 1;
documentMappingServiceMock
.Setup(c => c.TryMapToGeneratedDocumentPosition(It.IsAny<IRazorGeneratedDocument>(), It.IsAny<int>(), out projectedPosition, out projectedIndex))
.Setup(x => x.TryMapToGeneratedDocumentPosition(It.IsAny<IRazorGeneratedDocument>(), It.IsAny<int>(), out projectedPosition, out projectedIndex))
.Returns(true);
var editMappingServiceMock = new StrictMock<IEditMappingService>();
editMappingServiceMock
.Setup(c => c.RemapWorkspaceEditAsync(It.IsAny<IDocumentSnapshot>(), It.IsAny<WorkspaceEdit>(), It.IsAny<CancellationToken>()))
.Setup(x => x.RemapWorkspaceEditAsync(It.IsAny<IDocumentSnapshot>(), It.IsAny<WorkspaceEdit>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(delegatedEdit);
var (endpoint, documentContextFactory) = await CreateEndpointAndDocumentContextFactoryAsync(
options,
documentMappingServiceMock.Object,
editMappingServiceMock.Object,
clientConnectionMock.Object);
clientConnection);
var uri = PathUtilities.GetUri(s_componentWithParamFilePath);
var request = new RenameParams
@ -594,29 +591,19 @@ public class RenameEndpointTest(ITestOutputHelper testOutput) : LanguageServerTe
public async Task Handle_Rename_SingleServer_DoesNotDelegateForRazor()
{
// Arrange
var options = StrictMock.Of<LanguageServerFeatureOptions>(o =>
var options = StrictMock.Of<LanguageServerFeatureOptions>(static o =>
o.SupportsFileManipulation == true &&
o.SingleServerSupport == true &&
o.ReturnCodeActionAndRenamePathsWithPrefixedSlash == false);
var clientConnection = StrictMock.Of<IClientConnection>();
var documentMappingServiceMock = new StrictMock<IDocumentMappingService>();
documentMappingServiceMock
.Setup(c => c.GetLanguageKind(It.IsAny<RazorCodeDocument>(), It.IsAny<int>(), It.IsAny<bool>()))
.Returns(RazorLanguageKind.Razor);
var documentMappingService = StrictMock.Of<IDocumentMappingService>();
var editMappingService = StrictMock.Of<IEditMappingService>();
var (endpoint, documentContextFactory) = await CreateEndpointAndDocumentContextFactoryAsync(
options,
documentMappingServiceMock.Object,
editMappingService,
clientConnection);
var (endpoint, documentContextFactory) = await CreateEndpointAndDocumentContextFactoryAsync(options, documentMappingService);
var request = new RenameParams
{
TextDocument = new() { Uri = PathUtilities.GetUri(s_componentWithParamFilePath) },
Position = VsLspFactory.CreatePosition(1, 0),
Position = VsLspFactory.CreatePosition(0, 1), // This is right after the '@' in '@namespace'
NewName = "Test2"
};
@ -663,10 +650,11 @@ public class RenameEndpointTest(ITestOutputHelper testOutput) : LanguageServerTe
return textLoaderMock.Object;
});
var projectService = new TestRazorProjectService(
remoteTextLoaderFactoryMock.Object,
projectManager,
LoggerFactory);
var projectService = AddDisposable(
new TestRazorProjectService(
remoteTextLoaderFactoryMock.Object,
projectManager,
LoggerFactory));
var projectKey1 = await projectService.AddProjectAsync(
s_projectFilePath1, s_intermediateOutputPath1, RazorConfiguration.Default, RootNamespace1, displayName: null, DisposalToken);
@ -707,7 +695,7 @@ public class RenameEndpointTest(ITestOutputHelper testOutput) : LanguageServerTe
await projectService.UpdateDocumentAsync(s_componentWithParamFilePath, SourceText.From(ComponentWithParamText), DisposalToken);
var searchEngine = new RazorComponentSearchEngine(projectManager, LoggerFactory);
options ??= StrictMock.Of<LanguageServerFeatureOptions>(o =>
options ??= StrictMock.Of<LanguageServerFeatureOptions>(static o =>
o.SupportsFileManipulation == true &&
o.SingleServerSupport == false &&
o.ReturnCodeActionAndRenamePathsWithPrefixedSlash == false);
@ -715,9 +703,7 @@ public class RenameEndpointTest(ITestOutputHelper testOutput) : LanguageServerTe
if (documentMappingService == null)
{
var documentMappingServiceMock = new StrictMock<IDocumentMappingService>();
documentMappingServiceMock
.Setup(c => c.GetLanguageKind(It.IsAny<RazorCodeDocument>(), It.IsAny<int>(), It.IsAny<bool>()))
.Returns(RazorLanguageKind.Html);
var projectedPosition = new LinePosition(1, 1);
var projectedIndex = 1;
documentMappingServiceMock

Просмотреть файл

@ -8,6 +8,7 @@ using System.Threading.Tasks;
using Microsoft.AspNetCore.Razor.Language;
using Microsoft.AspNetCore.Razor.LanguageServer.Formatting;
using Microsoft.AspNetCore.Razor.LanguageServer.Hosting;
using Microsoft.AspNetCore.Razor.Test.Common;
using Microsoft.AspNetCore.Razor.Test.Common.LanguageServer;
using Microsoft.CodeAnalysis.Razor.ProjectSystem;
using Microsoft.CodeAnalysis.Razor.Protocol;
@ -27,21 +28,19 @@ public class WrapWithTagEndpointTest(ITestOutputHelper testOutput) : LanguageSer
var codeDocument = CreateCodeDocument("<div></div>");
var uri = new Uri("file://path/test.razor");
var documentContext = CreateDocumentContext(uri, codeDocument);
var response = new WrapWithTagResponse();
var clientConnection = new Mock<IClientConnection>(MockBehavior.Strict);
clientConnection
.Setup(l => l.SendRequestAsync<WrapWithTagParams, WrapWithTagResponse>(LanguageServerConstants.RazorWrapWithTagEndpoint, It.IsAny<WrapWithTagParams>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(response);
var clientConnection = TestMocks.CreateClientConnection(builder =>
{
builder.SetupSendRequest<WrapWithTagParams, WrapWithTagResponse>(LanguageServerConstants.RazorWrapWithTagEndpoint, response: new(), verifiable: true);
});
var endpoint = new WrapWithTagEndpoint(
clientConnection.Object,
LoggerFactory);
var endpoint = new WrapWithTagEndpoint(clientConnection, LoggerFactory);
var wrapWithDivParams = new WrapWithTagParams(new TextDocumentIdentifier { Uri = uri })
var wrapWithDivParams = new WrapWithTagParams(new() { Uri = uri })
{
Range = VsLspFactory.CreateSingleLineRange(start: (0, 0), length: 2),
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
@ -49,7 +48,7 @@ public class WrapWithTagEndpointTest(ITestOutputHelper testOutput) : LanguageSer
// Assert
Assert.NotNull(result);
clientConnection.Verify();
Mock.Get(clientConnection).Verify();
}
[Fact]
@ -59,21 +58,19 @@ public class WrapWithTagEndpointTest(ITestOutputHelper testOutput) : LanguageSer
var codeDocument = CreateCodeDocument("@(counter)");
var uri = new Uri("file://path/test.razor");
var documentContext = CreateDocumentContext(uri, codeDocument);
var response = new WrapWithTagResponse();
var clientConnection = new Mock<IClientConnection>(MockBehavior.Strict);
clientConnection
.Setup(l => l.SendRequestAsync<WrapWithTagParams, WrapWithTagResponse>(LanguageServerConstants.RazorWrapWithTagEndpoint, It.IsAny<WrapWithTagParams>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(response);
var clientConnection = TestMocks.CreateClientConnection(builder =>
{
builder.SetupSendRequest<WrapWithTagParams, WrapWithTagResponse>(LanguageServerConstants.RazorWrapWithTagEndpoint, response: new(), verifiable: true);
});
var endpoint = new WrapWithTagEndpoint(
clientConnection.Object,
LoggerFactory);
var endpoint = new WrapWithTagEndpoint(clientConnection, LoggerFactory);
var wrapWithDivParams = new WrapWithTagParams(new TextDocumentIdentifier { Uri = uri })
var wrapWithDivParams = new WrapWithTagParams(new() { Uri = uri })
{
Range = VsLspFactory.CreateSingleLineRange(start: (0, 0), length: 2),
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
@ -81,7 +78,8 @@ public class WrapWithTagEndpointTest(ITestOutputHelper testOutput) : LanguageSer
// Assert
Assert.Null(result);
clientConnection.Verify();
Mock.Get(clientConnection)
.VerifySendRequest<WrapWithTagParams, WrapWithTagResponse>(LanguageServerConstants.RazorWrapWithTagEndpoint, Times.Never);
}
[Fact]
@ -91,21 +89,19 @@ public class WrapWithTagEndpointTest(ITestOutputHelper testOutput) : LanguageSer
var codeDocument = CreateCodeDocument("@counter");
var uri = new Uri("file://path/test.razor");
var documentContext = CreateDocumentContext(uri, codeDocument);
var response = new WrapWithTagResponse();
var clientConnection = new Mock<IClientConnection>(MockBehavior.Strict);
clientConnection
.Setup(l => l.SendRequestAsync<WrapWithTagParams, WrapWithTagResponse>(LanguageServerConstants.RazorWrapWithTagEndpoint, It.IsAny<WrapWithTagParams>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(response);
var clientConnection = TestMocks.CreateClientConnection(builder =>
{
builder.SetupSendRequest<WrapWithTagParams, WrapWithTagResponse>(LanguageServerConstants.RazorWrapWithTagEndpoint, response: new(), verifiable: true);
});
var endpoint = new WrapWithTagEndpoint(
clientConnection.Object,
LoggerFactory);
var endpoint = new WrapWithTagEndpoint(clientConnection, LoggerFactory);
var wrapWithDivParams = new WrapWithTagParams(new TextDocumentIdentifier { Uri = uri })
var wrapWithDivParams = new WrapWithTagParams(new() { Uri = uri })
{
Range = VsLspFactory.CreateSingleLineRange(start: (0, 0), length: 8),
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
@ -113,7 +109,7 @@ public class WrapWithTagEndpointTest(ITestOutputHelper testOutput) : LanguageSer
// Assert
Assert.NotNull(result);
clientConnection.Verify();
Mock.Get(clientConnection).Verify();
}
[Fact]
@ -123,21 +119,19 @@ public class WrapWithTagEndpointTest(ITestOutputHelper testOutput) : LanguageSer
var codeDocument = CreateCodeDocument("@counter");
var uri = new Uri("file://path/test.razor");
var documentContext = CreateDocumentContext(uri, codeDocument);
var response = new WrapWithTagResponse();
var clientConnection = new Mock<IClientConnection>(MockBehavior.Strict);
clientConnection
.Setup(l => l.SendRequestAsync<WrapWithTagParams, WrapWithTagResponse>(LanguageServerConstants.RazorWrapWithTagEndpoint, It.IsAny<WrapWithTagParams>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(response);
var clientConnection = TestMocks.CreateClientConnection(builder =>
{
builder.SetupSendRequest<WrapWithTagParams, WrapWithTagResponse>(LanguageServerConstants.RazorWrapWithTagEndpoint, response: new(), verifiable: true);
});
var endpoint = new WrapWithTagEndpoint(
clientConnection.Object,
LoggerFactory);
var endpoint = new WrapWithTagEndpoint(clientConnection, LoggerFactory);
var wrapWithDivParams = new WrapWithTagParams(new TextDocumentIdentifier { Uri = uri })
var wrapWithDivParams = new WrapWithTagParams(new() { Uri = uri })
{
Range = VsLspFactory.CreateSingleLineRange(line: 0, character: 2, length: 2),
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
@ -145,7 +139,8 @@ public class WrapWithTagEndpointTest(ITestOutputHelper testOutput) : LanguageSer
// Assert
Assert.Null(result);
clientConnection.Verify();
Mock.Get(clientConnection)
.VerifySendRequest<WrapWithTagParams, WrapWithTagResponse>(LanguageServerConstants.RazorWrapWithTagEndpoint, Times.Never);
}
[Fact]
@ -155,21 +150,19 @@ public class WrapWithTagEndpointTest(ITestOutputHelper testOutput) : LanguageSer
var codeDocument = CreateCodeDocument("@counter");
var uri = new Uri("file://path/test.razor");
var documentContext = CreateDocumentContext(uri, codeDocument);
var response = new WrapWithTagResponse();
var clientConnection = new Mock<IClientConnection>(MockBehavior.Strict);
clientConnection
.Setup(l => l.SendRequestAsync<WrapWithTagParams, WrapWithTagResponse>(LanguageServerConstants.RazorWrapWithTagEndpoint, It.IsAny<WrapWithTagParams>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(response);
var clientConnection = TestMocks.CreateClientConnection(builder =>
{
builder.SetupSendRequest<WrapWithTagParams, WrapWithTagResponse>(LanguageServerConstants.RazorWrapWithTagEndpoint, response: new(), verifiable: true);
});
var endpoint = new WrapWithTagEndpoint(
clientConnection.Object,
LoggerFactory);
var endpoint = new WrapWithTagEndpoint(clientConnection, LoggerFactory);
var wrapWithDivParams = new WrapWithTagParams(new TextDocumentIdentifier { Uri = uri })
var wrapWithDivParams = new WrapWithTagParams(new() { Uri = uri })
{
Range = VsLspFactory.CreateZeroWidthRange(0, 4),
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
@ -177,7 +170,7 @@ public class WrapWithTagEndpointTest(ITestOutputHelper testOutput) : LanguageSer
// Assert
Assert.NotNull(result);
clientConnection.Verify();
Mock.Get(clientConnection).Verify();
}
[Fact]
@ -186,14 +179,18 @@ public class WrapWithTagEndpointTest(ITestOutputHelper testOutput) : LanguageSer
// Arrange
var missingUri = new Uri("file://path/nottest.razor");
var clientConnection = new Mock<IClientConnection>(MockBehavior.Strict);
var clientConnection = TestMocks.CreateClientConnection(builder =>
{
builder.SetupSendRequest<WrapWithTagParams, WrapWithTagResponse>(LanguageServerConstants.RazorWrapWithTagEndpoint, response: new(), verifiable: true);
});
var endpoint = new WrapWithTagEndpoint(clientConnection.Object, LoggerFactory);
var endpoint = new WrapWithTagEndpoint(clientConnection, LoggerFactory);
var wrapWithDivParams = new WrapWithTagParams(new TextDocumentIdentifier { Uri = missingUri })
var wrapWithDivParams = new WrapWithTagParams(new() { Uri = missingUri })
{
Range = VsLspFactory.CreateSingleLineRange(start: (0, 0), length: 2),
};
var requestContext = CreateRazorRequestContext(documentContext: null);
// Act
@ -201,6 +198,8 @@ public class WrapWithTagEndpointTest(ITestOutputHelper testOutput) : LanguageSer
// Assert
Assert.Null(result);
Mock.Get(clientConnection)
.VerifySendRequest<WrapWithTagParams, WrapWithTagResponse>(LanguageServerConstants.RazorWrapWithTagEndpoint, Times.Never);
}
[Fact]
@ -212,14 +211,18 @@ public class WrapWithTagEndpointTest(ITestOutputHelper testOutput) : LanguageSer
var uri = new Uri("file://path/test.razor");
var documentContext = CreateDocumentContext(uri, codeDocument);
var clientConnection = new Mock<IClientConnection>(MockBehavior.Strict);
var clientConnection = TestMocks.CreateClientConnection(builder =>
{
builder.SetupSendRequest<WrapWithTagParams, WrapWithTagResponse>(LanguageServerConstants.RazorWrapWithTagEndpoint, response: new(), verifiable: true);
});
var endpoint = new WrapWithTagEndpoint(clientConnection.Object, LoggerFactory);
var endpoint = new WrapWithTagEndpoint(clientConnection, LoggerFactory);
var wrapWithDivParams = new WrapWithTagParams(new TextDocumentIdentifier { Uri = uri })
var wrapWithDivParams = new WrapWithTagParams(new() { Uri = uri })
{
Range = VsLspFactory.CreateSingleLineRange(start: (0, 0), length: 2),
};
var requestContext = CreateRazorRequestContext(documentContext);
// Act
@ -227,28 +230,31 @@ public class WrapWithTagEndpointTest(ITestOutputHelper testOutput) : LanguageSer
// Assert
Assert.Null(result);
Mock.Get(clientConnection)
.VerifySendRequest<WrapWithTagParams, WrapWithTagResponse>(LanguageServerConstants.RazorWrapWithTagEndpoint, Times.Never);
}
[Fact]
public async Task CleanUpTextEdits_NoTilde()
{
var input = """
@if (true)
{
}
""";
var expected = """
<div>
@if (true)
{
}
""";
var expected = """
<div>
@if (true)
{
}
</div>
""";
</div>
""";
var uri = new Uri("file://path.razor");
var factory = CreateDocumentContextFactory(uri, input);
Assert.True(factory.TryCreate(uri, out var context));
var inputSourceText = await context!.GetSourceTextAsync(DisposalToken);
var inputSourceText = await context.GetSourceTextAsync(DisposalToken);
var computedEdits = new TextEdit[]
{
@ -259,7 +265,7 @@ public class WrapWithTagEndpointTest(ITestOutputHelper testOutput) : LanguageSer
newText: " }" + Environment.NewLine + "</div>"),
};
var htmlSourceText = await context!.GetHtmlSourceTextAsync(DisposalToken);
var htmlSourceText = await context.GetHtmlSourceTextAsync(DisposalToken);
var edits = HtmlFormatter.FixHtmlTextEdits(htmlSourceText, computedEdits);
Assert.Same(computedEdits, edits);
@ -271,23 +277,23 @@ public class WrapWithTagEndpointTest(ITestOutputHelper testOutput) : LanguageSer
public async Task CleanUpTextEdits_BadEditWithTilde()
{
var input = """
@if (true)
{
}
""";
var expected = """
<div>
@if (true)
{
}
""";
var expected = """
<div>
@if (true)
{
}
</div>
""";
</div>
""";
var uri = new Uri("file://path.razor");
var factory = CreateDocumentContextFactory(uri, input);
Assert.True(factory.TryCreate(uri, out var context));
var inputSourceText = await context!.GetSourceTextAsync(DisposalToken);
var inputSourceText = await context.GetSourceTextAsync(DisposalToken);
var computedEdits = new TextEdit[]
{
@ -299,7 +305,7 @@ public class WrapWithTagEndpointTest(ITestOutputHelper testOutput) : LanguageSer
newText: " ~" + Environment.NewLine + "</div>")
};
var htmlSourceText = await context!.GetHtmlSourceTextAsync(DisposalToken);
var htmlSourceText = await context.GetHtmlSourceTextAsync(DisposalToken);
var edits = HtmlFormatter.FixHtmlTextEdits(htmlSourceText, computedEdits);
Assert.NotSame(computedEdits, edits);
@ -311,18 +317,18 @@ public class WrapWithTagEndpointTest(ITestOutputHelper testOutput) : LanguageSer
public async Task CleanUpTextEdits_GoodEditWithTilde()
{
var input = """
@if (true)
{
~
""";
var expected = """
<div>
@if (true)
{
~
""";
var expected = """
<div>
@if (true)
{
~
</div>
""";
</div>
""";
var uri = new Uri("file://path.razor");
var factory = CreateDocumentContextFactory(uri, input);

Просмотреть файл

@ -1,10 +1,14 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See License.txt in the project root for license information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Razor.LanguageServer.Hosting;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Moq;
using Moq.Language.Flow;
namespace Microsoft.AspNetCore.Razor.Test.Common;
@ -26,4 +30,58 @@ internal static class TestMocks
return mock.Object;
}
public interface IClientConnectionBuilder
{
void SetupSendRequest<TParams, TResponse>(string method, TResponse response, bool verifiable = false);
void SetupSendRequest<TParams, TResponse>(string method, TParams @params, TResponse response, bool verifiable = false);
}
private sealed class ClientConnectionBuilder : IClientConnectionBuilder
{
public StrictMock<IClientConnection> Mock { get; } = new();
public void SetupSendRequest<TParams, TResponse>(string method, TResponse response, bool verifiable = false)
{
var returnsResult = Mock
.Setup(x => x.SendRequestAsync<TParams, TResponse>(method, It.IsAny<TParams>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(response);
if (verifiable)
{
returnsResult.Verifiable();
}
}
public void SetupSendRequest<TParams, TResponse>(string method, TParams @params, TResponse response, bool verifiable = false)
{
var returnsResult = Mock
.Setup(x => x.SendRequestAsync<TParams, TResponse>(method, @params, It.IsAny<CancellationToken>()))
.ReturnsAsync(response);
if (verifiable)
{
returnsResult.Verifiable();
}
}
}
public static IClientConnection CreateClientConnection(Action<IClientConnectionBuilder> configure)
{
var builder = new ClientConnectionBuilder();
configure?.Invoke(builder);
return builder.Mock.Object;
}
public static void VerifySendRequest<TParams, TResponse>(this Mock<IClientConnection> mock, string method, Times times)
=> mock.Verify(x => x.SendRequestAsync<TParams, TResponse>(method, It.IsAny<TParams>(), It.IsAny<CancellationToken>()), times);
public static void VerifySendRequest<TParams, TResponse>(this Mock<IClientConnection> mock, string method, Func<Times> times)
=> mock.Verify(x => x.SendRequestAsync<TParams, TResponse>(method, It.IsAny<TParams>(), It.IsAny<CancellationToken>()), times);
public static void VerifySendRequest<TParams, TResponse>(this Mock<IClientConnection> mock, string method, TParams @params, Times times)
=> mock.Verify(x => x.SendRequestAsync<TParams, TResponse>(method, @params, It.IsAny<CancellationToken>()), times);
public static void VerifySendRequest<TParams, TResponse>(this Mock<IClientConnection> mock, string method, TParams @params, Func<Times> times)
=> mock.Verify(x => x.SendRequestAsync<TParams, TResponse>(method, @params, It.IsAny<CancellationToken>()), times);
}