From e19d56255c799ccb41c3436e6a47894196871fe4 Mon Sep 17 00:00:00 2001 From: David Driscoll Date: Sun, 4 Oct 2020 21:38:47 -0400 Subject: [PATCH] additional nullable annotation cleanup --- .editorconfig | 1 + Directory.Build.props | 6 +- benchmarks/Pipeline/Class1.cs | 12 +- sample/SampleServer/TextDocumentHandler.cs | 6 +- src/Client/LangaugeClientRegistry.cs | 1 - ...nguageClientServiceCollectionExtensions.cs | 1 - src/Dap.Client/DebugAdapterClient.cs | 4 +- .../DefaultDebugAdapterClientFacade.cs | 1 - src/Dap.Shared/DapResponseRouter.cs | 2 + .../GenerateRequestMethodsGenerator.cs | 2 +- src/JsonRpc.Testing/JsonRpcServerTestBase.cs | 2 + src/JsonRpc/HandlerCollection.cs | 1 - .../JsonRpcHandlerCollectionExtensions.cs | 2 - src/JsonRpc/JsonRpcServer.cs | 2 +- src/JsonRpc/RequestRouterBase.cs | 3 +- src/JsonRpc/ResponseRouter.cs | 4 - src/JsonRpc/Server/ServerResponse.cs | 2 +- src/Protocol/AbstractHandlers.cs | 2 +- .../TextDocumentClientCapabilities.cs | 1 + src/Protocol/Client/ClientLanguageClient.cs | 1 - src/Protocol/Client/GeneralLanguageClient.cs | 1 - src/Protocol/Client/ILanguageClient.cs | 1 - .../Client/TextDocumentLanguageClient.cs | 1 - src/Protocol/Client/WindowLanguageClient.cs | 1 - .../Client/WorkspaceLanguageClient.cs | 1 - src/Protocol/Document/IDocumentLinkHandler.cs | 4 +- .../Document/Proposals/IMonikerHandler.cs | 3 +- .../Proposals/ISemanticTokensHandler.cs | 14 -- .../Proposals/SemanticTokensBuilder.cs | 4 +- .../Proposals/SemanticTokensDocument.cs | 48 +++---- .../Models/DocumentHighlightParams.cs | 2 +- .../Models/Proposals/MonikerParams.cs | 3 +- .../Proposals/MonikerRegistrationOptions.cs | 1 + .../SemanticTokensFullOrDeltaPartialResult.cs | 1 - src/Protocol/Models/TelemetryEventParams.cs | 2 +- src/Protocol/Models/TextDocumentIdentifier.cs | 2 + src/Protocol/Progress/IProgressManager.cs | 20 ++- .../Progress/IRequestProgressObservable.cs | 2 +- .../PartialItemsRequestProgressObservable.cs | 14 +- src/Protocol/Progress/ProgressManager.cs | 2 +- .../Progress/RequestProgressObservable.cs | 6 + .../Converters/BooleanOrConverter.cs | 4 +- .../Converters/ProgressTokenConverter.cs | 19 +-- .../RangeOrPlaceholderRangeConverter.cs | 2 +- src/Protocol/Serialization/Serializer.cs | 1 - src/Protocol/Server/ClientLanguageServer.cs | 1 - src/Protocol/Server/GeneralLanguageServer.cs | 1 - src/Protocol/Server/ILanguageServer.cs | 1 - .../Server/TextDocumentLanguageServer.cs | 1 - src/Protocol/Server/WindowLanguageServer.cs | 1 - .../Server/WorkspaceLanguageServer.cs | 1 - .../LspHandlerTypeDescriptorProvider.cs | 6 +- .../DidChangeConfigurationProvider.cs | 3 +- .../Configuration/ScopedConfiguration.cs | 1 + src/Server/DefaultLanguageServerFacade.cs | 1 - src/Server/LangaugeServerRegistry.cs | 3 +- src/Server/LanguageServer.Shutdown.cs | 7 +- src/Server/LanguageServerHelpers.cs | 3 +- ...nguageServerServiceCollectionExtensions.cs | 1 + .../LanguageServerWorkspaceFolderManager.cs | 1 - src/Server/Matchers/TextDocumentMatcher.cs | 3 + src/Shared/InterimLanguageProtocolRegistry.cs | 1 - test/.editorconfig | 9 ++ test/Client.Tests/ClientTests.cs | 126 +++++++++--------- .../Logging/TestOutputLogScope.cs | 13 +- test/Client.Tests/Logging/TestOutputLogger.cs | 4 +- .../Logging/TestOutputLoggingProvider.cs | 2 +- test/Client.Tests/PipeServerTestBase.cs | 14 +- test/Client.Tests/TestBase.cs | 13 +- test/Client.Tests/TestResponse.cs | 2 +- test/Dap.Tests/EventingTests.cs | 30 +++-- test/Dap.Tests/FoundationTests.cs | 34 ++--- .../ConnectionAndDisconnectionTests.cs | 9 +- .../Integration/CustomRequestsTests.cs | 32 ++--- .../Fixtures/DebugAdapterProtocolFixture.cs | 4 +- .../Integration/Fixtures/DefaultClient.cs | 6 +- .../Integration/Fixtures/DefaultServer.cs | 6 +- .../HandlersManagerIntegrationTests.cs | 8 +- test/Dap.Tests/Integration/ProgressTests.cs | 7 +- .../Integration/RecursiveResolutionTests.cs | 2 + .../Integration/RequestCancellationTests.cs | 4 +- ...uageClientServiceCollectionSupportTests.cs | 7 +- ...uageServerServiceCollectionSupportTests.cs | 7 +- test/Generation.Tests/GenerationHelpers.cs | 2 +- test/JsonRpc.Tests/AggregateSettlerTests.cs | 4 + test/JsonRpc.Tests/HandlerResolverTests.cs | 1 - test/JsonRpc.Tests/InputHandlerTests.cs | 100 ++++++++------ test/JsonRpc.Tests/IntegrationTests.cs | 62 ++++----- test/JsonRpc.Tests/JsonRpcServerTests.cs | 6 +- .../MediatorTestsNotificationHandler.cs | 1 - .../MediatorTestsNotificationHandlerOfT.cs | 4 +- .../MediatorTestsRequestHandlerOfTRequest.cs | 6 +- ...rTestsRequestHandlerOfTRequestTResponse.cs | 14 +- test/JsonRpc.Tests/OutputHandlerTests.cs | 2 +- .../JsonRpc.Tests/RecursiveResolutionTests.cs | 6 +- test/JsonRpc.Tests/RequestRouterTests.cs | 1 - test/JsonRpc.Tests/ResponseRouterTests.cs | 14 +- .../ServerShouldThrowCorrectExceptions.cs | 4 +- .../Server/SpecificatiosIdTests.cs | 6 +- .../ServiceCollectionSupportTests.cs | 17 ++- .../TestLanguageServerRegistry.cs | 3 +- .../Client/CompletionItemCapabilityTests.cs | 4 +- .../PublishDiagnosticsCapabilityTests.cs | 4 +- .../Server/CodeLensOptionsTests.cs | 1 - .../Server/CompletionOptionsTests.cs | 1 - .../Server/DocumentLinkOptionsTests.cs | 1 - .../DocumentOnTypeFormattingOptionsTests.cs | 1 - .../Server/ExecuteCommandOptionsTests.cs | 1 - .../Server/SignatureHelpOptionsTests.cs | 1 - .../ClientCapabilityProviderFixture.cs | 1 - .../ClientCapabilityProviderTests.cs | 20 ++- test/Lsp.Tests/CodeActionKindTests.cs | 2 +- test/Lsp.Tests/CompletionItemKindTests.cs | 4 +- test/Lsp.Tests/DiagnosticKindTests.cs | 2 +- test/Lsp.Tests/DocumentSymbolKindTests.cs | 4 +- test/Lsp.Tests/Fixture.cs | 6 +- test/Lsp.Tests/FluentAssertionsExtensions.cs | 2 +- test/Lsp.Tests/FoundationTests.cs | 72 +++++----- test/Lsp.Tests/HandlerResolverTests.cs | 3 +- .../ConnectionAndDisconnectionTests.cs | 9 +- .../Integration/DynamicRegistrationTests.cs | 18 +-- test/Lsp.Tests/Integration/EventingTests.cs | 55 ++++---- .../Integration/ExecuteCommandTests.cs | 92 ++++++------- test/Lsp.Tests/Integration/ExtensionTests.cs | 23 ++-- .../Integration/Fixtures/DefaultClient.cs | 6 +- .../Integration/Fixtures/DefaultServer.cs | 6 +- .../Integration/Fixtures/ExampleExtensions.cs | 10 +- .../Fixtures/LanguageProtocolFixture.cs | 8 +- .../HandlersManagerIntegrationTests.cs | 12 +- .../Integration/InitializationTests.cs | 4 +- .../LanguageServerConfigurationTests.cs | 15 +-- .../Integration/LanguageServerLoggingTests.cs | 2 - test/Lsp.Tests/Integration/LogMessageTests.cs | 4 +- test/Lsp.Tests/Integration/MonikerTests.cs | 6 +- .../Integration/OverrideHandlerTests.cs | 13 +- .../Lsp.Tests/Integration/PartialItemTests.cs | 13 +- .../Integration/PartialItemsTests.cs | 11 +- test/Lsp.Tests/Integration/ProgressTests.cs | 19 +-- .../Integration/RecursiveResolutionTests.cs | 4 + test/Lsp.Tests/Integration/RenameTests.cs | 44 +++--- .../Integration/RequestCancellationTests.cs | 11 +- .../Lsp.Tests/Integration/ShowMessageTests.cs | 4 +- .../Integration/TypedCodeActionTests.cs | 108 +++++++-------- .../Integration/TypedCodeLensTests.cs | 117 ++++++++-------- .../Integration/TypedCompletionTests.cs | 99 +++++++------- .../Integration/TypedDocumentLinkTests.cs | 59 ++++---- .../Integration/WorkspaceFolderTests.cs | 11 +- test/Lsp.Tests/JsonFixtureAttribute.cs | 8 +- test/Lsp.Tests/JsonRpcTestContainer.cs | 2 +- ...uageClientServiceCollectionSupportTests.cs | 5 +- ...uageServerServiceCollectionSupportTests.cs | 5 +- test/Lsp.Tests/LspRequestRouterTests.cs | 27 ---- .../ExecuteCommandHandlerMatcherTests.cs | 5 +- .../Matchers/ResolveCommandMatcherTests.cs | 40 +++--- .../Matchers/TextDocumentMatcherTests.cs | 42 +++--- ...rTestsRequestHandlerOfTRequestTResponse.cs | 5 +- test/Lsp.Tests/Minimatch/BasicTests.cs | 15 ++- .../Lsp.Tests/Models/FoldingRangeKindTests.cs | 2 +- .../Lsp.Tests/Models/InitializeParamsTests.cs | 2 +- .../RequestProcessIdentifierTests.cs | 2 - test/Lsp.Tests/SemanticTokensDocumentTests.cs | 48 +++---- .../Lsp.Tests/SupportedCapabilitiesFixture.cs | 4 + .../TextDocumentSyncHandlerExtensions.cs | 11 -- test/Lsp.Tests/VsCodeDocumentUriTests.cs | 5 - test/Lsp.Tests/WorkspaceSymbolKindTests.cs | 4 +- .../AutoNSubstitute/AutoSubstitute.cs | 4 +- .../AutoNSubstitute/AutoTestBase.cs | 2 +- .../AutoNSubstitute/TestLoggerFactory.cs | 13 +- test/TestingUtils/FactWithSkipOnAttribute.cs | 5 +- .../TestingUtils/TheoryWithSkipOnAttribute.cs | 4 +- test/TestingUtils/UnitTestDetector.cs | 2 +- 171 files changed, 967 insertions(+), 1051 deletions(-) create mode 100644 test/.editorconfig diff --git a/.editorconfig b/.editorconfig index a3d8b54ab..4cbf46047 100644 --- a/.editorconfig +++ b/.editorconfig @@ -128,6 +128,7 @@ resharper_web_config_module_not_resolved_highlighting=warning resharper_web_config_type_not_resolved_highlighting=warning resharper_web_config_wrong_module_highlighting=warning +dotnet_diagnostic.VSTHRD200.severity = none [*.{cs,cshtml}] charset=utf-8 diff --git a/Directory.Build.props b/Directory.Build.props index 42bad2d6e..b55d07820 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -5,7 +5,7 @@ David Driscoll preview strict - + enable true false images/packageicon.png @@ -24,7 +24,7 @@ - + Visible="false"/> + diff --git a/benchmarks/Pipeline/Class1.cs b/benchmarks/Pipeline/Class1.cs index 641e34f4b..ccd5286d7 100644 --- a/benchmarks/Pipeline/Class1.cs +++ b/benchmarks/Pipeline/Class1.cs @@ -17,19 +17,19 @@ namespace Pipeline [SimpleJob(RuntimeMoniker.NetCoreApp21)] public class ClassicVsPipelines { - private const string sampleCommand = + private const string SampleCommand = "Content-Length: 88\r\n\r\n{\"seq\":1,\"type\":\"response\",\"request_seq\":1,\"success\":true,\"command\":\"command\",\"body\":{}}"; - private const string anotherPayload = + private const string AnotherPayload = "Content-Length: 894\r\n\r\n{\"edit\":{\"documentChanges\":[{\"textDocument\":{\"version\":1,\"uri\":\"file:///abc/123/d.cs\"},\"edits\":[{\"range\":{\"start\":{\"line\":1,\"character\":1},\"end\":{\"line\":2,\"character\":2}},\"newText\":\"new text\"},{\"range\":{\"start\":{\"line\":3,\"character\":3},\"end\":{\"line\":4,\"character\":4}},\"newText\":\"new text2\"}]},{\"textDocument\":{\"version\":1,\"uri\":\"file:///abc/123/b.cs\"},\"edits\":[{\"range\":{\"start\":{\"line\":1,\"character\":1},\"end\":{\"line\":2,\"character\":2}},\"newText\":\"new text2\"},{\"range\":{\"start\":{\"line\":3,\"character\":3},\"end\":{\"line\":4,\"character\":4}},\"newText\":\"new text3\"}]},{\"kind\":\"create\",\"uri\":\"file:///abc/123/b.cs\",\"options\":{\"overwrite\":true,\"ignoreIfExists\":true}},{\"kind\":\"rename\",\"oldUri\":\"file:///abc/123/b.cs\",\"newUri\":\"file:///abc/123/c.cs\",\"options\":{\"overwrite\":true,\"ignoreIfExists\":true}},{\"kind\":\"delete\",\"uri\":\"file:///abc/123/c.cs\",\"options\":{\"recursive\":false,\"ignoreIfNotExists\":true}}]}}"; - private ClassicHandler _classic; - private PipelinesBased _pipelines; + private ClassicHandler? _classic; + private PipelinesBased? _pipelines; [Params( - sampleCommand, - anotherPayload + SampleCommand, + AnotherPayload )] public string Payload { get; set; } diff --git a/sample/SampleServer/TextDocumentHandler.cs b/sample/SampleServer/TextDocumentHandler.cs index e36edd029..a65bf4655 100644 --- a/sample/SampleServer/TextDocumentHandler.cs +++ b/sample/SampleServer/TextDocumentHandler.cs @@ -13,6 +13,7 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Server.WorkDone; using OmniSharp.Extensions.LanguageServer.Protocol.Workspace; +#pragma warning disable CS0618 namespace SampleServer { @@ -154,17 +155,16 @@ CancellationToken cancellationToken internal class MyWorkspaceSymbolsHandler : WorkspaceSymbolsHandler { - private readonly IServerWorkDoneManager _manager; private readonly IServerWorkDoneManager _serverWorkDoneManager; private readonly IProgressManager _progressManager; - private readonly ILogger logger; + private readonly ILogger _logger; public MyWorkspaceSymbolsHandler(IServerWorkDoneManager serverWorkDoneManager, IProgressManager progressManager, ILogger logger) : base(new WorkspaceSymbolRegistrationOptions()) { _serverWorkDoneManager = serverWorkDoneManager; _progressManager = progressManager; - this.logger = logger; + this._logger = logger; } public override async Task> Handle( diff --git a/src/Client/LangaugeClientRegistry.cs b/src/Client/LangaugeClientRegistry.cs index c798c415d..f77d32db4 100644 --- a/src/Client/LangaugeClientRegistry.cs +++ b/src/Client/LangaugeClientRegistry.cs @@ -1,4 +1,3 @@ -using System; using DryIoc; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Client; diff --git a/src/Client/LanguageClientServiceCollectionExtensions.cs b/src/Client/LanguageClientServiceCollectionExtensions.cs index 893852922..7fec5fc1d 100644 --- a/src/Client/LanguageClientServiceCollectionExtensions.cs +++ b/src/Client/LanguageClientServiceCollectionExtensions.cs @@ -7,7 +7,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; -using Microsoft.Extensions.Primitives; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Client.Configuration; using OmniSharp.Extensions.LanguageServer.Protocol.Client; diff --git a/src/Dap.Client/DebugAdapterClient.cs b/src/Dap.Client/DebugAdapterClient.cs index c7d5b4a2c..cb79819a0 100644 --- a/src/Dap.Client/DebugAdapterClient.cs +++ b/src/Dap.Client/DebugAdapterClient.cs @@ -161,11 +161,11 @@ await DebugAdapterEventingHelper.Run( _instanceHasStarted.Started = true; } - async Task IRequestHandler.Handle(InitializedEvent request, CancellationToken cancellationToken) + Task IRequestHandler.Handle(InitializedEvent request, CancellationToken cancellationToken) { _initializedComplete.OnNext(request); _initializedComplete.OnCompleted(); - return Unit.Value; + return Unit.Task; } private void RegisterCapabilities(InitializeRequestArguments capabilities) diff --git a/src/Dap.Client/DefaultDebugAdapterClientFacade.cs b/src/Dap.Client/DefaultDebugAdapterClientFacade.cs index 2c4860161..6d9fc4f58 100644 --- a/src/Dap.Client/DefaultDebugAdapterClientFacade.cs +++ b/src/Dap.Client/DefaultDebugAdapterClientFacade.cs @@ -1,7 +1,6 @@ using DryIoc; using OmniSharp.Extensions.DebugAdapter.Protocol; using OmniSharp.Extensions.DebugAdapter.Protocol.Client; -using OmniSharp.Extensions.DebugAdapter.Protocol.Server; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Client diff --git a/src/Dap.Shared/DapResponseRouter.cs b/src/Dap.Shared/DapResponseRouter.cs index 1ff379023..0133caaeb 100644 --- a/src/Dap.Shared/DapResponseRouter.cs +++ b/src/Dap.Shared/DapResponseRouter.cs @@ -110,7 +110,9 @@ public async Task Returning(CancellationToken cancellation cancellationToken.Register( () => { if (tcs.Task.IsCompleted) return; +#pragma warning disable VSTHRD110 _router.SendRequest(RequestNames.Cancel, new { requestId = nextId }).Returning(CancellationToken.None); +#pragma warning restore VSTHRD110 } ); } diff --git a/src/JsonRpc.Generators/GenerateRequestMethodsGenerator.cs b/src/JsonRpc.Generators/GenerateRequestMethodsGenerator.cs index b5780fb9e..44d90907d 100644 --- a/src/JsonRpc.Generators/GenerateRequestMethodsGenerator.cs +++ b/src/JsonRpc.Generators/GenerateRequestMethodsGenerator.cs @@ -65,7 +65,7 @@ public Task GenerateRichAsync(TransformationContext contex { var requestType = GetRequestType(handlerInterface); var responseType = GetResponseType(handlerInterface); - methods.AddRange(HandleRequests(handlerInterface, symbol, requestType, responseType, registry, additionalUsings)); + methods.AddRange(HandleRequests(handlerInterface, symbol, requestType, responseType!, registry, additionalUsings)); } } diff --git a/src/JsonRpc.Testing/JsonRpcServerTestBase.cs b/src/JsonRpc.Testing/JsonRpcServerTestBase.cs index b926e76a8..540aeca4f 100644 --- a/src/JsonRpc.Testing/JsonRpcServerTestBase.cs +++ b/src/JsonRpc.Testing/JsonRpcServerTestBase.cs @@ -72,8 +72,10 @@ Action serverOptionsAction ); await Task.WhenAll(clientTask, serverTask).ConfigureAwait(false); +#pragma warning disable VSTHRD103 _client = clientTask.Result; _server = serverTask.Result; +#pragma warning restore VSTHRD103 Disposable.Add(_client); Disposable.Add(_server); diff --git a/src/JsonRpc/HandlerCollection.cs b/src/JsonRpc/HandlerCollection.cs index e1a913f38..e8f1d5ac6 100644 --- a/src/JsonRpc/HandlerCollection.cs +++ b/src/JsonRpc/HandlerCollection.cs @@ -7,7 +7,6 @@ using System.Reflection; using DryIoc; using MediatR; -using Microsoft.Extensions.DependencyInjection; namespace OmniSharp.Extensions.JsonRpc { diff --git a/src/JsonRpc/JsonRpcHandlerCollectionExtensions.cs b/src/JsonRpc/JsonRpcHandlerCollectionExtensions.cs index 8db4804fd..65695712e 100644 --- a/src/JsonRpc/JsonRpcHandlerCollectionExtensions.cs +++ b/src/JsonRpc/JsonRpcHandlerCollectionExtensions.cs @@ -1,7 +1,5 @@ -using System; using System.Collections.Generic; using DryIoc; -using Microsoft.Extensions.DependencyInjection; namespace OmniSharp.Extensions.JsonRpc { diff --git a/src/JsonRpc/JsonRpcServer.cs b/src/JsonRpc/JsonRpcServer.cs index 759b657c8..e6b749620 100644 --- a/src/JsonRpc/JsonRpcServer.cs +++ b/src/JsonRpc/JsonRpcServer.cs @@ -7,7 +7,7 @@ namespace OmniSharp.Extensions.JsonRpc { - public class JsonRpcServer : JsonRpcServerBase, IJsonRpcServer, IServiceProvider + public class JsonRpcServer : JsonRpcServerBase, IJsonRpcServer { private readonly Connection _connection; private readonly IServiceProvider _serviceProvider; diff --git a/src/JsonRpc/RequestRouterBase.cs b/src/JsonRpc/RequestRouterBase.cs index 8ef8b8b92..0470fc30b 100644 --- a/src/JsonRpc/RequestRouterBase.cs +++ b/src/JsonRpc/RequestRouterBase.cs @@ -150,7 +150,8 @@ ILogger logger { var property = typeof(Task<>) .MakeGenericType(result.GetType().GetTypeInfo().GetGenericArguments()[0]).GetTypeInfo() - .GetProperty(nameof(Task.Result), BindingFlags.Public | BindingFlags.Instance)!; + .GetProperty("Result" + , BindingFlags.Public | BindingFlags.Instance)!; responseValue = property.GetValue(result); if (responseValue?.GetType() == typeof(Unit)) diff --git a/src/JsonRpc/ResponseRouter.cs b/src/JsonRpc/ResponseRouter.cs index ee7f9326d..4ef205245 100644 --- a/src/JsonRpc/ResponseRouter.cs +++ b/src/JsonRpc/ResponseRouter.cs @@ -105,10 +105,6 @@ public async Task Returning(CancellationToken cancellation return result.ToObject(_router.Serializer.JsonSerializer); } - catch (ObjectDisposedException) - { - throw; - } finally { _router.Requests.TryRemove(nextId, out _); diff --git a/src/JsonRpc/Server/ServerResponse.cs b/src/JsonRpc/Server/ServerResponse.cs index 5fc395832..9c9df875b 100644 --- a/src/JsonRpc/Server/ServerResponse.cs +++ b/src/JsonRpc/Server/ServerResponse.cs @@ -4,7 +4,7 @@ namespace OmniSharp.Extensions.JsonRpc.Server { public class ServerResponse : ResponseBase { - public ServerResponse(object id, JToken result) : base(id) => Result = result; + public ServerResponse(object id, JToken? result) : base(id) => Result = result ?? JValue.CreateNull(); public JToken Result { get; set; } } diff --git a/src/Protocol/AbstractHandlers.cs b/src/Protocol/AbstractHandlers.cs index db525bd43..1b47f19f5 100644 --- a/src/Protocol/AbstractHandlers.cs +++ b/src/Protocol/AbstractHandlers.cs @@ -90,7 +90,7 @@ public abstract class PartialResults, IRegistration, ICapability where TParams : IPartialItemsRequest - where TResponse : IEnumerable, new() + where TResponse : IEnumerable?, new() where TRegistrationOptions : class, new() where TCapability : ICapability { diff --git a/src/Protocol/Client/Capabilities/TextDocumentClientCapabilities.cs b/src/Protocol/Client/Capabilities/TextDocumentClientCapabilities.cs index a4ad2a83b..50fee0a79 100644 --- a/src/Protocol/Client/Capabilities/TextDocumentClientCapabilities.cs +++ b/src/Protocol/Client/Capabilities/TextDocumentClientCapabilities.cs @@ -142,6 +142,7 @@ public class TextDocumentClientCapabilities : CapabilitiesBase /// /// @since 3.16.0 /// + [Obsolete(Constants.Proposal)] public Supports Moniker { get; set; } } } diff --git a/src/Protocol/Client/ClientLanguageClient.cs b/src/Protocol/Client/ClientLanguageClient.cs index dd6974cec..3575a6438 100644 --- a/src/Protocol/Client/ClientLanguageClient.cs +++ b/src/Protocol/Client/ClientLanguageClient.cs @@ -1,4 +1,3 @@ -using System; using DryIoc; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Progress; diff --git a/src/Protocol/Client/GeneralLanguageClient.cs b/src/Protocol/Client/GeneralLanguageClient.cs index 39940525e..48c65c38e 100644 --- a/src/Protocol/Client/GeneralLanguageClient.cs +++ b/src/Protocol/Client/GeneralLanguageClient.cs @@ -1,4 +1,3 @@ -using System; using DryIoc; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Progress; diff --git a/src/Protocol/Client/ILanguageClient.cs b/src/Protocol/Client/ILanguageClient.cs index 0a5a49059..ac98d8cd9 100644 --- a/src/Protocol/Client/ILanguageClient.cs +++ b/src/Protocol/Client/ILanguageClient.cs @@ -1,7 +1,6 @@ using System; using System.Threading; using System.Threading.Tasks; -using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Client.WorkDone; namespace OmniSharp.Extensions.LanguageServer.Protocol.Client diff --git a/src/Protocol/Client/TextDocumentLanguageClient.cs b/src/Protocol/Client/TextDocumentLanguageClient.cs index c9215c4cc..3187aaa83 100644 --- a/src/Protocol/Client/TextDocumentLanguageClient.cs +++ b/src/Protocol/Client/TextDocumentLanguageClient.cs @@ -1,4 +1,3 @@ -using System; using DryIoc; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Progress; diff --git a/src/Protocol/Client/WindowLanguageClient.cs b/src/Protocol/Client/WindowLanguageClient.cs index cdaf39901..9d69d8d5d 100644 --- a/src/Protocol/Client/WindowLanguageClient.cs +++ b/src/Protocol/Client/WindowLanguageClient.cs @@ -1,4 +1,3 @@ -using System; using DryIoc; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Progress; diff --git a/src/Protocol/Client/WorkspaceLanguageClient.cs b/src/Protocol/Client/WorkspaceLanguageClient.cs index a82bb5910..bb89b96e7 100644 --- a/src/Protocol/Client/WorkspaceLanguageClient.cs +++ b/src/Protocol/Client/WorkspaceLanguageClient.cs @@ -1,4 +1,3 @@ -using System; using DryIoc; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Progress; diff --git a/src/Protocol/Document/IDocumentLinkHandler.cs b/src/Protocol/Document/IDocumentLinkHandler.cs index 75cb2efa7..b2c58e422 100644 --- a/src/Protocol/Document/IDocumentLinkHandler.cs +++ b/src/Protocol/Document/IDocumentLinkHandler.cs @@ -480,7 +480,7 @@ public static ILanguageServerRegistry OnDocumentLink( ); } - private class DelegatingDocumentLinkHandler : DocumentLinkHandlerBase, ICanBeIdentifiedHandler where T : HandlerIdentity?, new() + private class DelegatingDocumentLinkHandler : DocumentLinkHandlerBase where T : HandlerIdentity?, new() { private readonly Func>> _handleParams; private readonly Func, DocumentLinkCapability, CancellationToken, Task>> _handleResolve; @@ -502,7 +502,7 @@ protected override Task> HandleResolve(DocumentLink request, _handleResolve(request, Capability, cancellationToken); } - private class DelegatingPartialDocumentLinkHandler : PartialDocumentLinkHandlerBase, ICanBeIdentifiedHandler where T : HandlerIdentity?, new() + private class DelegatingPartialDocumentLinkHandler : PartialDocumentLinkHandlerBase where T : HandlerIdentity?, new() { private readonly Action>>, DocumentLinkCapability, CancellationToken> _handleParams; private readonly Func, DocumentLinkCapability, CancellationToken, Task>> _handleResolve; diff --git a/src/Protocol/Document/Proposals/IMonikerHandler.cs b/src/Protocol/Document/Proposals/IMonikerHandler.cs index e07ea37ff..e1fda460d 100644 --- a/src/Protocol/Document/Proposals/IMonikerHandler.cs +++ b/src/Protocol/Document/Proposals/IMonikerHandler.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using OmniSharp.Extensions.JsonRpc; @@ -42,7 +41,7 @@ protected MonikerHandlerBase(MonikerRegistrationOptions registrationOptions) [Obsolete(Constants.Proposal)] public abstract class PartialMonikerHandlerBase : - AbstractHandlers.PartialResults, Moniker, MonikerCapability, MonikerRegistrationOptions>, IMonikerHandler + AbstractHandlers.PartialResults?, Moniker, MonikerCapability, MonikerRegistrationOptions>, IMonikerHandler { protected PartialMonikerHandlerBase(MonikerRegistrationOptions registrationOptions, IProgressManager progressManager) : base( registrationOptions, progressManager, diff --git a/src/Protocol/Document/Proposals/ISemanticTokensHandler.cs b/src/Protocol/Document/Proposals/ISemanticTokensHandler.cs index d04d68fbd..cc686d9ef 100644 --- a/src/Protocol/Document/Proposals/ISemanticTokensHandler.cs +++ b/src/Protocol/Document/Proposals/ISemanticTokensHandler.cs @@ -1,8 +1,6 @@ using System; -using System.Reactive.Subjects; using System.Threading; using System.Threading.Tasks; -using MediatR; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Generation; using OmniSharp.Extensions.LanguageServer.Protocol.Client; @@ -172,18 +170,6 @@ SemanticTokensRegistrationOptions registrationOptions _getSemanticTokensDocument = getSemanticTokensDocument; } - public DelegatingHandlerBase( - Func tokenize, - Func> getSemanticTokensDocument, - SemanticTokensRegistrationOptions registrationOptions - ) : this( - (s, t, c, ct) => tokenize(s, t, c), - (t, c, ct) => getSemanticTokensDocument(t, c), - registrationOptions - ) - { - } - protected override Task Tokenize(SemanticTokensBuilder builder, ITextDocumentIdentifierParams identifier, CancellationToken cancellationToken) => _tokenize(builder, identifier, _capability, cancellationToken); diff --git a/src/Protocol/Document/Proposals/SemanticTokensBuilder.cs b/src/Protocol/Document/Proposals/SemanticTokensBuilder.cs index c825e358d..d99270dc8 100644 --- a/src/Protocol/Document/Proposals/SemanticTokensBuilder.cs +++ b/src/Protocol/Document/Proposals/SemanticTokensBuilder.cs @@ -171,8 +171,8 @@ public void Push(Range range, int tokenType, int tokenModifiers) /// public SemanticTokensDocument Commit() { - _document._dataLen = _dataLen; - _document._data = _data.ToImmutable(); + _document.DataLen = _dataLen; + _document.Data = _data.ToImmutable(); return _document; } } diff --git a/src/Protocol/Document/Proposals/SemanticTokensDocument.cs b/src/Protocol/Document/Proposals/SemanticTokensDocument.cs index 935007610..b1044be90 100644 --- a/src/Protocol/Document/Proposals/SemanticTokensDocument.cs +++ b/src/Protocol/Document/Proposals/SemanticTokensDocument.cs @@ -12,8 +12,8 @@ public class SemanticTokensDocument private Guid _id; - internal ImmutableArray _data; - internal int _dataLen; + internal ImmutableArray Data; + internal int DataLen; private ImmutableArray? _prevData; @@ -31,8 +31,8 @@ public SemanticTokensDocument(SemanticTokensLegend legend) private void Initialize() { _id = Guid.NewGuid(); - _data = new ImmutableArray(); - _dataLen = 0; + Data = new ImmutableArray(); + DataLen = 0; } public string Id => _id.ToString(); @@ -47,7 +47,7 @@ public SemanticTokensBuilder Edit(SemanticTokensDeltaParams @params) { if (@params.PreviousResultId == Id) { - _prevData = _data; + _prevData = Data; } return new SemanticTokensBuilder(this, _legend); @@ -58,7 +58,7 @@ public SemanticTokens GetSemanticTokens() _prevData = null; return new SemanticTokens { ResultId = Id, - Data = _data + Data = Data }; } @@ -71,17 +71,17 @@ public SemanticTokens GetSemanticTokens(Range range) var currentCharOffset = 0; var capturing = false; var innerOffset = 0; - for (var i = 0; i < _data.Length; i += 5) + for (var i = 0; i < Data.Length; i += 5) { - var lineOffset = _data[i]; + var lineOffset = Data[i]; currentLine += lineOffset; if (lineOffset > 0) currentCharOffset = 0; if (!capturing) { if (range.Start.Line == currentLine) { - var charOffset = _data[i + 1]; - var length = _data[i + 2]; + var charOffset = Data[i + 1]; + var length = Data[i + 2]; // TODO: Do we want to capture partial tokens? // using Sys|tem.Collections.Generic| // ^^^ do we want a token for 'tem`? @@ -89,7 +89,7 @@ public SemanticTokens GetSemanticTokens(Range range) { capturing = true; // var overlap = ((currentCharOffset + charOffset) - range.Start.Character); - data.AddRange(0, charOffset, length, _data[i + 3], _data[i + 4]); + data.AddRange(0, charOffset, length, Data[i + 3], Data[i + 4]); continue; } @@ -97,7 +97,7 @@ public SemanticTokens GetSemanticTokens(Range range) { capturing = true; var overlap = currentCharOffset + charOffset + length - range.Start.Character; - data.AddRange(0, 0, overlap, _data[i + 3], _data[i + 4]); + data.AddRange(0, 0, overlap, Data[i + 3], Data[i + 4]); innerOffset = charOffset - overlap; continue; } @@ -109,8 +109,8 @@ public SemanticTokens GetSemanticTokens(Range range) { if (range.End.Line == currentLine) { - var charOffset = _data[i + 1]; - var length = _data[i + 2]; + var charOffset = Data[i + 1]; + var length = Data[i + 2]; if (currentCharOffset + charOffset >= range.End.Character) { break; @@ -119,27 +119,27 @@ public SemanticTokens GetSemanticTokens(Range range) if (currentCharOffset + charOffset + length >= range.End.Character) { var overlap = currentCharOffset + charOffset + length - range.End.Character; - data.AddRange(lineOffset, charOffset, length - overlap, _data[i + 3], _data[i + 4]); + data.AddRange(lineOffset, charOffset, length - overlap, Data[i + 3], Data[i + 4]); break; } currentCharOffset += charOffset; - data.AddRange(_data[i], _data[i + 1], _data[i + 2], _data[i + 3], _data[i + 4]); + data.AddRange(Data[i], Data[i + 1], Data[i + 2], Data[i + 3], Data[i + 4]); } else { if (innerOffset > 0) { data.AddRange( - _data[i], _data[i + 1] - innerOffset, _data[i + 2], _data[i + 3], - _data[i + 4] + Data[i], Data[i + 1] - innerOffset, Data[i + 2], Data[i + 3], + Data[i + 4] ); innerOffset = 0; } else { - data.AddRange(_data[i], _data[i + 1], _data[i + 2], _data[i + 3], _data[i + 4]); + data.AddRange(Data[i], Data[i + 1], Data[i + 2], Data[i + 3], Data[i + 4]); } } } @@ -157,10 +157,10 @@ public SemanticTokensFullOrDelta GetSemanticTokensEdits() var prevData = _prevData.Value; var prevDataLength = prevData.Length; - var dataLength = _data.Length; + var dataLength = Data.Length; var startIndex = 0; while (startIndex < dataLength && startIndex < prevDataLength && prevData[startIndex] == - _data[startIndex]) + Data[startIndex]) { startIndex++; } @@ -170,12 +170,12 @@ public SemanticTokensFullOrDelta GetSemanticTokensEdits() // Find end index var endIndex = 0; while (endIndex < dataLength && endIndex < prevDataLength && - prevData[prevDataLength - 1 - endIndex] == _data[dataLength - 1 - endIndex]) + prevData[prevDataLength - 1 - endIndex] == Data[dataLength - 1 - endIndex]) { endIndex++; } - var newData = ImmutableArray.Create(_data, startIndex, dataLength - endIndex - startIndex); + var newData = ImmutableArray.Create(Data, startIndex, dataLength - endIndex - startIndex); var result = new SemanticTokensDelta { ResultId = Id, Edits = new[] { @@ -196,7 +196,7 @@ public SemanticTokensFullOrDelta GetSemanticTokensEdits() new SemanticTokensEdit { Start = startIndex, DeleteCount = 0, - Data = ImmutableArray.Create(_data, startIndex, _dataLen - startIndex) + Data = ImmutableArray.Create(Data, startIndex, DataLen - startIndex) } } }; diff --git a/src/Protocol/Models/DocumentHighlightParams.cs b/src/Protocol/Models/DocumentHighlightParams.cs index 5312d6e88..78bfe8b4e 100644 --- a/src/Protocol/Models/DocumentHighlightParams.cs +++ b/src/Protocol/Models/DocumentHighlightParams.cs @@ -4,7 +4,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { [Method(TextDocumentNames.DocumentHighlight, Direction.ClientToServer)] - public class DocumentHighlightParams : WorkDoneTextDocumentPositionParams, IPartialItemsRequest + public class DocumentHighlightParams : WorkDoneTextDocumentPositionParams, IPartialItemsRequest { /// [Optional] diff --git a/src/Protocol/Models/Proposals/MonikerParams.cs b/src/Protocol/Models/Proposals/MonikerParams.cs index 2f17c512c..31dbccead 100644 --- a/src/Protocol/Models/Proposals/MonikerParams.cs +++ b/src/Protocol/Models/Proposals/MonikerParams.cs @@ -1,5 +1,4 @@ using System; -using MediatR; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; @@ -17,7 +16,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models.Proposals /// [Obsolete(Constants.Proposal)] [Method(TextDocumentNames.Moniker, Direction.ClientToServer)] - public class MonikerParams : WorkDoneTextDocumentPositionParams, IPartialItemsRequest, Moniker> + public class MonikerParams : WorkDoneTextDocumentPositionParams, IPartialItemsRequest?, Moniker> { /// [Optional] diff --git a/src/Protocol/Models/Proposals/MonikerRegistrationOptions.cs b/src/Protocol/Models/Proposals/MonikerRegistrationOptions.cs index 795876d3d..bb6e61cad 100644 --- a/src/Protocol/Models/Proposals/MonikerRegistrationOptions.cs +++ b/src/Protocol/Models/Proposals/MonikerRegistrationOptions.cs @@ -25,6 +25,7 @@ public MonikerRegistrationOptionsOptionsConverter(IHandlersManager handlersManag public override StaticOptions Convert(MonikerRegistrationOptions source) { return new StaticOptions { + WorkDoneProgress = source.WorkDoneProgress, }; } } diff --git a/src/Protocol/Models/Proposals/SemanticTokensFullOrDeltaPartialResult.cs b/src/Protocol/Models/Proposals/SemanticTokensFullOrDeltaPartialResult.cs index 400f3c7be..b4313ca02 100644 --- a/src/Protocol/Models/Proposals/SemanticTokensFullOrDeltaPartialResult.cs +++ b/src/Protocol/Models/Proposals/SemanticTokensFullOrDeltaPartialResult.cs @@ -1,5 +1,4 @@ using System; -using System.Diagnostics.CodeAnalysis; using Newtonsoft.Json; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters; diff --git a/src/Protocol/Models/TelemetryEventParams.cs b/src/Protocol/Models/TelemetryEventParams.cs index 0ff3d5eca..cee1c2c89 100644 --- a/src/Protocol/Models/TelemetryEventParams.cs +++ b/src/Protocol/Models/TelemetryEventParams.cs @@ -9,6 +9,6 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Models [Method(WindowNames.TelemetryEvent, Direction.ServerToClient)] public class TelemetryEventParams : IRequest { - [JsonExtensionData] private IDictionary Data { get; set; } = new Dictionary(); + [JsonExtensionData] public IDictionary Data { get; set; } = new Dictionary(); } } diff --git a/src/Protocol/Models/TextDocumentIdentifier.cs b/src/Protocol/Models/TextDocumentIdentifier.cs index b4b7d50b9..7ead135c3 100644 --- a/src/Protocol/Models/TextDocumentIdentifier.cs +++ b/src/Protocol/Models/TextDocumentIdentifier.cs @@ -32,6 +32,7 @@ public override bool Equals(object? obj) return Equals((TextDocumentIdentifier) obj); } + // ReSharper disable once ConstantConditionalAccessQualifier public override int GetHashCode() => Uri?.GetHashCode() ?? 0; public static bool operator ==(TextDocumentIdentifier left, TextDocumentIdentifier right) => Equals(left, right); @@ -42,6 +43,7 @@ public override bool Equals(object? obj) public static implicit operator TextDocumentIdentifier(string uri) => new TextDocumentIdentifier { Uri = uri }; + // ReSharper disable once ConstantConditionalAccessQualifier private string DebuggerDisplay => Uri?.ToString() ?? string.Empty; /// diff --git a/src/Protocol/Progress/IProgressManager.cs b/src/Protocol/Progress/IProgressManager.cs index c445cd95b..df6a0df52 100644 --- a/src/Protocol/Progress/IProgressManager.cs +++ b/src/Protocol/Progress/IProgressManager.cs @@ -12,19 +12,27 @@ public interface IProgressManager : IProgressHandler IProgressObservable Monitor(ProgressToken token, Func factory); IRequestProgressObservable MonitorUntil( - IPartialItemRequest request, Func factory, CancellationToken cancellationToken + IPartialItemRequest request, + Func factory, + CancellationToken cancellationToken ); IRequestProgressObservable MonitorUntil( - IPartialItemRequest request, Func factory, CancellationToken cancellationToken + IPartialItemRequest request, + Func factory, + CancellationToken cancellationToken ); IRequestProgressObservable, TResponse> MonitorUntil( - IPartialItemsRequest request, Func, TResponse> factory, CancellationToken cancellationToken - ) - where TResponse : IEnumerable?; + IPartialItemsRequest request, + Func, TResponse> factory, + CancellationToken cancellationToken + ) where TResponse : IEnumerable?; - IRequestProgressObservable MonitorUntil(IPartialItemsRequest, TItem> request, CancellationToken cancellationToken); + IRequestProgressObservable MonitorUntil( + IPartialItemsRequest, TItem> request, + CancellationToken cancellationToken + ); IProgressObserver For(ProgressToken token, CancellationToken cancellationToken); IProgressObserver For(IPartialItemRequest request, CancellationToken cancellationToken); diff --git a/src/Protocol/Progress/IRequestProgressObservable.cs b/src/Protocol/Progress/IRequestProgressObservable.cs index fef0a0fdb..c96d29658 100644 --- a/src/Protocol/Progress/IRequestProgressObservable.cs +++ b/src/Protocol/Progress/IRequestProgressObservable.cs @@ -12,7 +12,7 @@ public interface IRequestProgressObservable : IProgressObser TaskAwaiter GetAwaiter(); } - public interface IRequestProgressObservable : IRequestProgressObservable, Container> + public interface IRequestProgressObservable : IRequestProgressObservable?, Container?> { } } diff --git a/src/Protocol/Progress/PartialItemsRequestProgressObservable.cs b/src/Protocol/Progress/PartialItemsRequestProgressObservable.cs index e3cc16cd1..0a8ea56c9 100644 --- a/src/Protocol/Progress/PartialItemsRequestProgressObservable.cs +++ b/src/Protocol/Progress/PartialItemsRequestProgressObservable.cs @@ -14,7 +14,7 @@ namespace OmniSharp.Extensions.LanguageServer.Protocol.Progress { internal class PartialItemsRequestProgressObservable : IRequestProgressObservable, TResult>, IObserver, IDisposable - where TResult : IEnumerable + where TResult : IEnumerable? { private readonly ISerializer _serializer; private readonly ReplaySubject> _dataSubject; @@ -43,7 +43,11 @@ Action disposal } ).Select(factory) ).ToTask(cancellationToken); +#pragma warning disable VSTHRD105 +#pragma warning disable VSTHRD110 _task.ContinueWith(x => Dispose()); +#pragma warning restore VSTHRD110 +#pragma warning restore VSTHRD105 ProgressToken = token; if (_dataSubject is IDisposable disposable) @@ -81,15 +85,17 @@ public void Dispose() public IDisposable Subscribe(IObserver> observer) => _disposable.IsDisposed ? Disposable.Empty : _dataSubject.Subscribe(observer); +#pragma warning disable VSTHRD003 public Task AsTask() => _task; +#pragma warning restore VSTHRD003 public TaskAwaiter GetAwaiter() => _task.GetAwaiter(); } - internal class PartialItemsRequestProgressObservable : PartialItemsRequestProgressObservable>, IRequestProgressObservable + internal class PartialItemsRequestProgressObservable : PartialItemsRequestProgressObservable?>, IRequestProgressObservable { public PartialItemsRequestProgressObservable( - ISerializer serializer, ProgressToken token, IObservable> requestResult, - Func, Container> factory, CancellationToken cancellationToken, Action disposal + ISerializer serializer, ProgressToken token, IObservable?> requestResult, + Func, Container?> factory, CancellationToken cancellationToken, Action disposal ) : base( serializer, token, requestResult, factory, cancellationToken, disposal diff --git a/src/Protocol/Progress/ProgressManager.cs b/src/Protocol/Progress/ProgressManager.cs index a85887706..3377e19a8 100644 --- a/src/Protocol/Progress/ProgressManager.cs +++ b/src/Protocol/Progress/ProgressManager.cs @@ -119,7 +119,7 @@ public IRequestProgressObservable, TResponse> MonitorUntil request, Func, TResponse> factory, CancellationToken cancellationToken ) - where TResponse : IEnumerable + where TResponse : IEnumerable? { request.PartialResultToken ??= new ProgressToken(Guid.NewGuid().ToString()); if (_activeObservables.TryGetValue(request.PartialResultToken, out var o) && o is IRequestProgressObservable, TResponse> observable) diff --git a/src/Protocol/Progress/RequestProgressObservable.cs b/src/Protocol/Progress/RequestProgressObservable.cs index c87335af3..3b7df4e10 100644 --- a/src/Protocol/Progress/RequestProgressObservable.cs +++ b/src/Protocol/Progress/RequestProgressObservable.cs @@ -34,7 +34,11 @@ Action disposal _disposable = new CompositeDisposable { request.Connect(), Disposable.Create(disposal) }; _task = _dataSubject.ForkJoin(requestResult, factory).ToTask(cancellationToken); +#pragma warning disable VSTHRD105 +#pragma warning disable VSTHRD110 _task.ContinueWith(x => Dispose()); +#pragma warning restore VSTHRD110 +#pragma warning restore VSTHRD105 ProgressToken = token; if (_dataSubject is IDisposable disposable) @@ -72,7 +76,9 @@ public void Dispose() public IDisposable Subscribe(IObserver observer) => _disposable.IsDisposed ? Disposable.Empty : _dataSubject.Subscribe(observer); +#pragma warning disable VSTHRD003 public Task AsTask() => _task; +#pragma warning restore VSTHRD003 public TaskAwaiter GetAwaiter() => _task.GetAwaiter(); } } diff --git a/src/Protocol/Serialization/Converters/BooleanOrConverter.cs b/src/Protocol/Serialization/Converters/BooleanOrConverter.cs index 75c86dce2..cc8c05cbe 100644 --- a/src/Protocol/Serialization/Converters/BooleanOrConverter.cs +++ b/src/Protocol/Serialization/Converters/BooleanOrConverter.cs @@ -44,10 +44,10 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist { var parentType = objectType.GetTypeInfo().GenericTypeArguments[0]; return ReadJsonGenericMethod.MakeGenericMethod(parentType) - .Invoke(null, new[] { reader, existingValue, serializer }); + .Invoke(null, new object[] { reader, serializer }); } - private static BooleanOr ReadJsonGeneric(JsonReader reader, object existingValue, JsonSerializer serializer) + private static BooleanOr ReadJsonGeneric(JsonReader reader, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Boolean) { diff --git a/src/Protocol/Serialization/Converters/ProgressTokenConverter.cs b/src/Protocol/Serialization/Converters/ProgressTokenConverter.cs index 60bafc9a1..eaa4c8630 100644 --- a/src/Protocol/Serialization/Converters/ProgressTokenConverter.cs +++ b/src/Protocol/Serialization/Converters/ProgressTokenConverter.cs @@ -8,24 +8,19 @@ internal class ProgressTokenConverter : JsonConverter { public override void WriteJson(JsonWriter writer, ProgressToken? value, JsonSerializer serializer) { - if (value.IsLong) serializer.Serialize(writer, value.Long); + if (value == null) writer.WriteNull(); + else if (value.IsLong) serializer.Serialize(writer, value.Long); else if (value.IsString) serializer.Serialize(writer, value.String); else writer.WriteNull(); } public override ProgressToken? ReadJson(JsonReader reader, Type objectType, ProgressToken? existingValue, bool hasExistingValue, JsonSerializer serializer) { - if (reader.TokenType == JsonToken.Integer) - { - return new ProgressToken((long) reader.Value); - } - - if (reader.TokenType == JsonToken.String && reader.Value is string str && !string.IsNullOrWhiteSpace(str)) - { - return new ProgressToken(str); - } - - return null; + return reader.TokenType switch { + JsonToken.Integer => new ProgressToken((long) reader.Value), + JsonToken.String when reader.Value is string str && !string.IsNullOrWhiteSpace(str) => new ProgressToken(str), + _ => null + }; } public override bool CanRead => true; diff --git a/src/Protocol/Serialization/Converters/RangeOrPlaceholderRangeConverter.cs b/src/Protocol/Serialization/Converters/RangeOrPlaceholderRangeConverter.cs index 2590292e7..38887e41d 100644 --- a/src/Protocol/Serialization/Converters/RangeOrPlaceholderRangeConverter.cs +++ b/src/Protocol/Serialization/Converters/RangeOrPlaceholderRangeConverter.cs @@ -18,7 +18,7 @@ public override void WriteJson(JsonWriter writer, RangeOrPlaceholderRange? value { serializer.Serialize(writer, value.PlaceholderRange); } - else if (value.IsDefaultBehavior) + else if (value?.IsDefaultBehavior == true) { serializer.Serialize(writer, value.DefaultBehavior); } diff --git a/src/Protocol/Serialization/Serializer.cs b/src/Protocol/Serialization/Serializer.cs index 911bb73f3..aed2e556c 100644 --- a/src/Protocol/Serialization/Serializer.cs +++ b/src/Protocol/Serialization/Serializer.cs @@ -4,7 +4,6 @@ using System.Reflection; using Newtonsoft.Json; using OmniSharp.Extensions.JsonRpc.Serialization; -using OmniSharp.Extensions.JsonRpc.Serialization.Converters; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters; diff --git a/src/Protocol/Server/ClientLanguageServer.cs b/src/Protocol/Server/ClientLanguageServer.cs index 5ab0d7c1e..cf36d7ff9 100644 --- a/src/Protocol/Server/ClientLanguageServer.cs +++ b/src/Protocol/Server/ClientLanguageServer.cs @@ -1,4 +1,3 @@ -using System; using DryIoc; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Progress; diff --git a/src/Protocol/Server/GeneralLanguageServer.cs b/src/Protocol/Server/GeneralLanguageServer.cs index 06e47c3fe..2ccd81a62 100644 --- a/src/Protocol/Server/GeneralLanguageServer.cs +++ b/src/Protocol/Server/GeneralLanguageServer.cs @@ -1,4 +1,3 @@ -using System; using DryIoc; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Progress; diff --git a/src/Protocol/Server/ILanguageServer.cs b/src/Protocol/Server/ILanguageServer.cs index bad098fb1..ad0470f6b 100644 --- a/src/Protocol/Server/ILanguageServer.cs +++ b/src/Protocol/Server/ILanguageServer.cs @@ -1,7 +1,6 @@ using System; using System.Threading; using System.Threading.Tasks; -using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Server.WorkDone; diff --git a/src/Protocol/Server/TextDocumentLanguageServer.cs b/src/Protocol/Server/TextDocumentLanguageServer.cs index 111926afe..2c04ce3fd 100644 --- a/src/Protocol/Server/TextDocumentLanguageServer.cs +++ b/src/Protocol/Server/TextDocumentLanguageServer.cs @@ -1,4 +1,3 @@ -using System; using DryIoc; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Progress; diff --git a/src/Protocol/Server/WindowLanguageServer.cs b/src/Protocol/Server/WindowLanguageServer.cs index ded775d37..e0cc867fa 100644 --- a/src/Protocol/Server/WindowLanguageServer.cs +++ b/src/Protocol/Server/WindowLanguageServer.cs @@ -1,4 +1,3 @@ -using System; using DryIoc; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Progress; diff --git a/src/Protocol/Server/WorkspaceLanguageServer.cs b/src/Protocol/Server/WorkspaceLanguageServer.cs index 054b4d636..7ed30e69c 100644 --- a/src/Protocol/Server/WorkspaceLanguageServer.cs +++ b/src/Protocol/Server/WorkspaceLanguageServer.cs @@ -1,4 +1,3 @@ -using System; using DryIoc; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Progress; diff --git a/src/Protocol/Shared/LspHandlerTypeDescriptorProvider.cs b/src/Protocol/Shared/LspHandlerTypeDescriptorProvider.cs index a13bebd68..8f620107f 100644 --- a/src/Protocol/Shared/LspHandlerTypeDescriptorProvider.cs +++ b/src/Protocol/Shared/LspHandlerTypeDescriptorProvider.cs @@ -15,7 +15,7 @@ public interface ILspHandlerTypeDescriptorProvider : IHandlerTypeDescriptorProvi public class LspHandlerTypeDescriptorProvider : ILspHandlerTypeDescriptorProvider, IHandlerTypeDescriptorProvider { - private readonly ConcurrentDictionary MethodNames = new ConcurrentDictionary(); + private readonly ConcurrentDictionary _methodNames = new ConcurrentDictionary(); internal readonly ILookup KnownHandlers; @@ -76,7 +76,7 @@ internal LspHandlerTypeDescriptorProvider(IEnumerable assemblies) public string? GetMethodName(Type type) { - if (MethodNames.TryGetValue(type, out var method)) return method; + if (_methodNames.TryGetValue(type, out var method)) return method; // Custom method var attribute = MethodAttribute.From(type); @@ -94,7 +94,7 @@ internal LspHandlerTypeDescriptorProvider(IEnumerable assemblies) return null; } - MethodNames.TryAdd(type, attribute.Method); + _methodNames.TryAdd(type, attribute.Method); return attribute.Method; } } diff --git a/src/Server/Configuration/DidChangeConfigurationProvider.cs b/src/Server/Configuration/DidChangeConfigurationProvider.cs index 273ad0888..aeedb2dfd 100644 --- a/src/Server/Configuration/DidChangeConfigurationProvider.cs +++ b/src/Server/Configuration/DidChangeConfigurationProvider.cs @@ -53,6 +53,7 @@ ConfigurationConverter configurationConverter var triggerChange = new Subject(); _compositeDisposable.Add(triggerChange); _triggerChange = triggerChange; + // ReSharper disable once SuspiciousTypeConversion.Global if (_configuration is IDisposable disposableConfiguration) _compositeDisposable.Add(disposableConfiguration); _compositeDisposable.Add(triggerChange.Throttle(TimeSpan.FromMilliseconds(50)).Select(_ => GetWorkspaceConfiguration()).Switch().Subscribe()); } @@ -224,7 +225,7 @@ public async Task GetScopedConfiguration(DocumentUri scope var config = new ScopedConfiguration( _configuration, _configurationConverter, - data, + data!, Disposable.Create( () => _openScopes.TryRemove(scopeUri, out _) ) diff --git a/src/Server/Configuration/ScopedConfiguration.cs b/src/Server/Configuration/ScopedConfiguration.cs index 4e9541990..da51a9f93 100644 --- a/src/Server/Configuration/ScopedConfiguration.cs +++ b/src/Server/Configuration/ScopedConfiguration.cs @@ -47,6 +47,7 @@ public string this[string key] public void Dispose() { + // ReSharper disable once SuspiciousTypeConversion.Global if (_configuration is IDisposable disposable) disposable.Dispose(); _disposable.Dispose(); } diff --git a/src/Server/DefaultLanguageServerFacade.cs b/src/Server/DefaultLanguageServerFacade.cs index b30433968..e2ba1ad5d 100644 --- a/src/Server/DefaultLanguageServerFacade.cs +++ b/src/Server/DefaultLanguageServerFacade.cs @@ -3,7 +3,6 @@ using System.Threading; using System.Threading.Tasks; using DryIoc; -using MediatR; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Document; diff --git a/src/Server/LangaugeServerRegistry.cs b/src/Server/LangaugeServerRegistry.cs index 2b99f620a..870fc71df 100644 --- a/src/Server/LangaugeServerRegistry.cs +++ b/src/Server/LangaugeServerRegistry.cs @@ -1,5 +1,4 @@ -using System; -using DryIoc; +using DryIoc; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Server; diff --git a/src/Server/LanguageServer.Shutdown.cs b/src/Server/LanguageServer.Shutdown.cs index 463178799..2c8aab3fd 100644 --- a/src/Server/LanguageServer.Shutdown.cs +++ b/src/Server/LanguageServer.Shutdown.cs @@ -21,10 +21,11 @@ public partial class LanguageServer : IExitHandler, IShutdownHandler public Task WasShutDown => _shutdownSubject.ToTask(); public Task WaitForExit => _exitSubject.ToTask(); - public void ForcefulShutdown() + #pragma warning disable VSTHRD100 + public async void ForcefulShutdown() { - ( (IShutdownHandler) this ).Handle(ShutdownParams.Instance, CancellationToken.None); - ( (IExitHandler) this ).Handle(ExitParams.Instance, CancellationToken.None); + await ( (IShutdownHandler) this ).Handle(ShutdownParams.Instance, CancellationToken.None); + await ( (IExitHandler) this ).Handle(ExitParams.Instance, CancellationToken.None); } async Task IRequestHandler.Handle(ExitParams request, CancellationToken token) diff --git a/src/Server/LanguageServerHelpers.cs b/src/Server/LanguageServerHelpers.cs index c959d0dd5..5c480c096 100644 --- a/src/Server/LanguageServerHelpers.cs +++ b/src/Server/LanguageServerHelpers.cs @@ -5,7 +5,6 @@ using System.Reactive.Disposables; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; -using System.Threading.Tasks; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Models; @@ -95,7 +94,7 @@ IReadOnlyList descriptors var registrations = new List(); foreach (var descriptor in descriptors) { - if (descriptor.HasCapability && supportedCapabilities.AllowsDynamicRegistration(descriptor.CapabilityType)) + if (descriptor.HasCapability && supportedCapabilities.AllowsDynamicRegistration(descriptor.CapabilityType!)) { if (descriptor.RegistrationOptions is IWorkDoneProgressOptions wdpo) { diff --git a/src/Server/LanguageServerServiceCollectionExtensions.cs b/src/Server/LanguageServerServiceCollectionExtensions.cs index 07fde55cb..03061a356 100644 --- a/src/Server/LanguageServerServiceCollectionExtensions.cs +++ b/src/Server/LanguageServerServiceCollectionExtensions.cs @@ -15,6 +15,7 @@ using OmniSharp.Extensions.LanguageServer.Server.Matchers; using OmniSharp.Extensions.LanguageServer.Server.Pipelines; using OmniSharp.Extensions.LanguageServer.Shared; +#pragma warning disable CS0618 namespace OmniSharp.Extensions.LanguageServer.Server { diff --git a/src/Server/LanguageServerWorkspaceFolderManager.cs b/src/Server/LanguageServerWorkspaceFolderManager.cs index 5d66ee4d8..4ec207494 100644 --- a/src/Server/LanguageServerWorkspaceFolderManager.cs +++ b/src/Server/LanguageServerWorkspaceFolderManager.cs @@ -4,7 +4,6 @@ using System.Linq; using System.Reactive.Linq; using System.Reactive.Subjects; -using System.Reactive.Threading.Tasks; using System.Threading; using System.Threading.Tasks; using MediatR; diff --git a/src/Server/Matchers/TextDocumentMatcher.cs b/src/Server/Matchers/TextDocumentMatcher.cs index 3039969ab..758d716e4 100644 --- a/src/Server/Matchers/TextDocumentMatcher.cs +++ b/src/Server/Matchers/TextDocumentMatcher.cs @@ -26,6 +26,7 @@ public IEnumerable FindHandler(object parameters, IEnumer { case ITextDocumentIdentifierParams textDocumentIdentifierParams: { + // ReSharper disable once ConstantConditionalAccessQualifier if (textDocumentIdentifierParams.TextDocument?.Uri is null) break; var attributes = GetTextDocumentAttributes(textDocumentIdentifierParams.TextDocument.Uri); @@ -35,6 +36,7 @@ public IEnumerable FindHandler(object parameters, IEnumer } case DidOpenTextDocumentParams openTextDocumentParams: { + // ReSharper disable once ConstantConditionalAccessQualifier if (openTextDocumentParams.TextDocument?.Uri is null) break; var attributes = new TextDocumentAttributes(openTextDocumentParams.TextDocument.Uri, openTextDocumentParams.TextDocument.LanguageId); @@ -44,6 +46,7 @@ public IEnumerable FindHandler(object parameters, IEnumer } case DidChangeTextDocumentParams didChangeDocumentParams: { + // ReSharper disable once ConstantConditionalAccessQualifier if (didChangeDocumentParams.TextDocument?.Uri is null) break; // TODO: Do something with document version here? var attributes = GetTextDocumentAttributes(didChangeDocumentParams.TextDocument.Uri); diff --git a/src/Shared/InterimLanguageProtocolRegistry.cs b/src/Shared/InterimLanguageProtocolRegistry.cs index e99a4f739..239c0696e 100644 --- a/src/Shared/InterimLanguageProtocolRegistry.cs +++ b/src/Shared/InterimLanguageProtocolRegistry.cs @@ -1,6 +1,5 @@ using System; using DryIoc; -using Microsoft.Extensions.DependencyInjection; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Document; diff --git a/test/.editorconfig b/test/.editorconfig new file mode 100644 index 000000000..e076c5fc2 --- /dev/null +++ b/test/.editorconfig @@ -0,0 +1,9 @@ +[*] +dotnet_diagnostic.CS0618.severity = none +dotnet_diagnostic.CS4014.severity = none +dotnet_diagnostic.CS1998.severity = none +dotnet_diagnostic.VSTHRD003.severity = none +dotnet_diagnostic.VSTHRD103.severity = none +dotnet_diagnostic.VSTHRD105.severity = none +dotnet_diagnostic.VSTHRD110.severity = none +dotnet_diagnostic.VSTHRD200.severity = none diff --git a/test/Client.Tests/ClientTests.cs b/test/Client.Tests/ClientTests.cs index 71dc851dd..0875ae437 100644 --- a/test/Client.Tests/ClientTests.cs +++ b/test/Client.Tests/ClientTests.cs @@ -45,16 +45,16 @@ public async Task Hover_Success() const int column = 5; var expectedHoverContent = new MarkedStringsOrMarkupContent("123", "456", "789"); - var (client, server) = await Initialize( - client => { - client.WithCapability( + var (client, _) = await Initialize( + clientOptions => { + clientOptions.WithCapability( new HoverCapability { ContentFormat = new Container(MarkupKind.Markdown, MarkupKind.PlainText), } ); }, - server => { - server.OnHover( + serverOptions => { + serverOptions.OnHover( (request, token) => { Assert.NotNull(request.TextDocument); @@ -74,7 +74,7 @@ public async Task Hover_Success() End = request.Position } } - ); + )!; }, new HoverRegistrationOptions() ); } @@ -87,8 +87,8 @@ public async Task Hover_Success() } ); - Assert.NotNull(hover.Range); - Assert.NotNull(hover.Range.Start); + Assert.NotNull(hover!.Range); + Assert.NotNull(hover.Range!.Start); Assert.NotNull(hover.Range.End); Assert.Equal(line, hover.Range.Start.Line); @@ -100,9 +100,9 @@ public async Task Hover_Success() Assert.NotNull(hover.Contents); Assert.True(expectedHoverContent.HasMarkedStrings); Assert.Equal( - expectedHoverContent.MarkedStrings + expectedHoverContent.MarkedStrings! .Select(markedString => markedString.Value), - hover.Contents.MarkedStrings.Select( + hover.Contents.MarkedStrings!.Select( markedString => markedString.Value ) ); @@ -129,9 +129,9 @@ public async Task Completions_Success() } }; - var (client, server) = await Initialize( - client => { - client.WithCapability( + var (client, _) = await Initialize( + clientOptions => { + clientOptions.WithCapability( new CompletionCapability { CompletionItem = new CompletionItemCapabilityOptions { DeprecatedSupport = true, @@ -146,8 +146,8 @@ public async Task Completions_Success() } ); }, - server => { - server.OnCompletion( + serverOptions => { + serverOptions.OnCompletion( (request, cancellationToken) => { Assert.NotNull(request.TextDocument); @@ -186,7 +186,7 @@ public async Task Completions_Success() Assert.Equal(expectedCompletionItem.Label, actualCompletionItem.Label); Assert.NotNull(actualCompletionItem.TextEdit); - Assert.Equal(expectedCompletionItem.TextEdit.NewText, actualCompletionItem.TextEdit.NewText); + Assert.Equal(expectedCompletionItem.TextEdit!.NewText, actualCompletionItem.TextEdit!.NewText); Assert.NotNull(actualCompletionItem.TextEdit.Range); Assert.NotNull(actualCompletionItem.TextEdit.Range.Start); @@ -239,9 +239,9 @@ public async Task SignatureHelp_Success() } }; - var (client, server) = await Initialize( - client => { - client.WithCapability( + var (client, _) = await Initialize( + clientOptions => { + clientOptions.WithCapability( new SignatureHelpCapability { ContextSupport = true, SignatureInformation = new SignatureInformationCapabilityOptions { @@ -253,8 +253,8 @@ public async Task SignatureHelp_Success() } ); }, - server => { - server.OnSignatureHelp( + serverOptions => { + serverOptions.OnSignatureHelp( (request, cancellationToken) => { Assert.NotNull(request.TextDocument); @@ -263,7 +263,7 @@ public async Task SignatureHelp_Success() Assert.Equal(line, request.Position.Line); Assert.Equal(column, request.Position.Character); - return Task.FromResult(expectedSignatureHelp); + return Task.FromResult(expectedSignatureHelp)!; }, new SignatureHelpRegistrationOptions() ); } @@ -276,7 +276,7 @@ public async Task SignatureHelp_Success() }, CancellationToken ); - Assert.Equal(expectedSignatureHelp.ActiveParameter, actualSignatureHelp.ActiveParameter); + Assert.Equal(expectedSignatureHelp.ActiveParameter, actualSignatureHelp!.ActiveParameter); Assert.Equal(expectedSignatureHelp.ActiveSignature, actualSignatureHelp.ActiveSignature); var actualSignatures = actualSignatureHelp.Signatures.ToArray(); @@ -284,19 +284,19 @@ public async Task SignatureHelp_Success() actualSignatures, actualSignature => { var expectedSignature = expectedSignatureHelp.Signatures.ToArray()[0]; - Assert.True(actualSignature.Documentation.HasString); - Assert.Equal(expectedSignature.Documentation.String, actualSignature.Documentation.String); + Assert.True(actualSignature.Documentation!.HasString); + Assert.Equal(expectedSignature.Documentation!.String, actualSignature.Documentation.String); Assert.Equal(expectedSignature.Label, actualSignature.Label); - var expectedParameters = expectedSignature.Parameters.ToArray(); - var actualParameters = actualSignature.Parameters.ToArray(); + var expectedParameters = expectedSignature.Parameters!.ToArray(); + var actualParameters = actualSignature.Parameters!.ToArray(); Assert.Collection( actualParameters, actualParameter => { var expectedParameter = expectedParameters[0]; - Assert.True(actualParameter.Documentation.HasString); - Assert.Equal(expectedParameter.Documentation.String, actualParameter.Documentation.String); + Assert.True(actualParameter.Documentation!.HasString); + Assert.Equal(expectedParameter.Documentation!.String, actualParameter.Documentation.String); Assert.Equal(expectedParameter.Label.Label, actualParameter.Label.Label); } ); @@ -324,16 +324,16 @@ public async Task Definition_Success() ) ); - var (client, server) = await Initialize( - client => { - client.WithCapability( + var (client, _) = await Initialize( + clientOptions => { + clientOptions.WithCapability( new DefinitionCapability { LinkSupport = true } ); }, - server => { - server.OnDefinition( + serverOptions => { + serverOptions.OnDefinition( (request, cancellationToken) => { Assert.NotNull(request.TextDocument); @@ -361,7 +361,7 @@ public async Task Definition_Success() var expectedDefinition = expectedDefinitions.Single(); Assert.NotNull(actualDefinition.Location); - Assert.Equal(expectedDefinition.Location.Uri, actualDefinition.Location.Uri); + Assert.Equal(expectedDefinition.Location!.Uri, actualDefinition.Location!.Uri); Assert.NotNull(actualDefinition.Location.Range); Assert.NotNull(actualDefinition.Location.Range.Start); @@ -398,14 +398,14 @@ public async Task DocumentHighlights_Success() } ); - var (client, server) = await Initialize( - client => { - client.WithCapability( + var (client, _) = await Initialize( + clientOptions => { + clientOptions.WithCapability( new DocumentHighlightCapability() ); }, - server => { - server.OnDocumentHighlight( + serverOptions => { + serverOptions.OnDocumentHighlight( (request, cancellationToken) => { Assert.NotNull(request.TextDocument); @@ -414,7 +414,7 @@ public async Task DocumentHighlights_Success() Assert.Equal(line, request.Position.Line); Assert.Equal(column, request.Position.Character); - return Task.FromResult(expectedHighlights); + return Task.FromResult(expectedHighlights)!; }, new DocumentHighlightRegistrationOptions() ); } @@ -427,7 +427,7 @@ public async Task DocumentHighlights_Success() }, CancellationToken ); - var actualDefinitions = definitions.ToArray(); + var actualDefinitions = definitions!.ToArray(); Assert.Collection( actualDefinitions, actualHighlight => { var expectedHighlight = expectedHighlights.Single(); @@ -466,9 +466,9 @@ public async Task DocumentSymbols_DocumentSymbol_Success() new SymbolInformationOrDocumentSymbol(documentSymbol) ); - var (client, server) = await Initialize( - client => { - client.WithCapability( + var (client, _) = await Initialize( + clientOptions => { + clientOptions.WithCapability( new DocumentSymbolCapability { DynamicRegistration = true, SymbolKind = new SymbolKindCapabilityOptions { @@ -484,8 +484,8 @@ public async Task DocumentSymbols_DocumentSymbol_Success() } ); }, - server => { - server.OnDocumentSymbol( + serverOptions => { + serverOptions.OnDocumentSymbol( (request, cancellationToken) => { Assert.NotNull(request.TextDocument); @@ -511,7 +511,7 @@ public async Task DocumentSymbols_DocumentSymbol_Success() Assert.True(expectedSymbol.IsDocumentSymbol); Assert.NotNull(actualSymbol.DocumentSymbol); - Assert.Equal(expectedSymbol.DocumentSymbol.Detail, actualSymbol.DocumentSymbol.Detail); + Assert.Equal(expectedSymbol.DocumentSymbol!.Detail, actualSymbol.DocumentSymbol!.Detail); Assert.Equal(expectedSymbol.DocumentSymbol.Kind, actualSymbol.DocumentSymbol.Kind); Assert.Equal( expectedSymbol.DocumentSymbol.Range.Start.Line, @@ -549,21 +549,21 @@ public async Task FoldingRanges_Success() } ); - var (client, server) = await Initialize( - client => { - client.WithCapability( + var (client, _) = await Initialize( + clientOptions => { + clientOptions.WithCapability( new FoldingRangeCapability { RangeLimit = 100, LineFoldingOnly = true } ); }, - server => { - server.OnFoldingRange( + serverOptions => { + serverOptions.OnFoldingRange( (request, cancellationToken) => { Assert.NotNull(request.TextDocument); Assert.Equal(expectedDocumentUri, request.TextDocument.Uri); - return Task.FromResult(expectedFoldingRanges); + return Task.FromResult(expectedFoldingRanges)!; }, new FoldingRangeRegistrationOptions() ); } @@ -575,7 +575,7 @@ public async Task FoldingRanges_Success() }, CancellationToken ); - var actualFoldingRanges = foldingRanges.ToArray(); + var actualFoldingRanges = foldingRanges!.ToArray(); Assert.Collection( actualFoldingRanges, actualFoldingRange => { var expectedFoldingRange = expectedFoldingRanges.Single(); @@ -619,22 +619,22 @@ public async Task Diagnostics_Success() var receivedDiagnosticsNotification = new TaskCompletionSource(); - DocumentUri actualDocumentUri = null; - List actualDiagnostics = null; + DocumentUri? actualDocumentUri = null; + List? actualDiagnostics = null; - var (client, server) = await Initialize( - client => { - client.OnPublishDiagnostics( + var (_, server) = await Initialize( + clientOptions => { + clientOptions.OnPublishDiagnostics( request => { actualDocumentUri = request.Uri; actualDiagnostics = request.Diagnostics.ToList(); - receivedDiagnosticsNotification.TrySetResult(null); + receivedDiagnosticsNotification.TrySetResult(null!); return Unit.Task; } ); }, - server => { } + serverOptions => { } ); server.TextDocument.PublishDiagnostics( @@ -660,7 +660,7 @@ public async Task Diagnostics_Success() Assert.Equal(expectedDocumentUri, actualDocumentUri); Assert.NotNull(actualDiagnostics); - Assert.Equal(1, actualDiagnostics.Count); + Assert.Equal(1, actualDiagnostics!.Count); var expectedDiagnostic = expectedDiagnostics[0]; var actualDiagnostic = actualDiagnostics[0]; diff --git a/test/Client.Tests/Logging/TestOutputLogScope.cs b/test/Client.Tests/Logging/TestOutputLogScope.cs index e3150359a..afcd34e28 100644 --- a/test/Client.Tests/Logging/TestOutputLogScope.cs +++ b/test/Client.Tests/Logging/TestOutputLogScope.cs @@ -18,13 +18,14 @@ internal class TestOutputLogScope /// public static TestOutputLogScope Current { - get => _currentScope.Value; + get => _currentScope.Value!; set => _currentScope.Value = value; } /// /// The scope name. /// + // ReSharper disable once NotAccessedField.Local private readonly string _name; /// @@ -50,7 +51,7 @@ public TestOutputLogScope(string name, object state) /// /// The scope's parent scope (if any). /// - public TestOutputLogScope Parent { get; private set; } + public TestOutputLogScope? Parent { get; private set; } /// /// Create a new and make it the current . @@ -67,9 +68,7 @@ public TestOutputLogScope(string name, object state) public static IDisposable Push(string name, object state) { var parent = Current; - Current = new TestOutputLogScope(name, state) { - Parent = parent - }; + Current = new TestOutputLogScope(name, state) { Parent = parent }; return new ScopeDisposal(); } @@ -80,7 +79,7 @@ public static IDisposable Push(string name, object state) /// /// The scope's string representation. /// - public override string ToString() => _state?.ToString(); + public override string ToString() => _state.ToString()!; /// /// Wrapper for disposal of log scope. @@ -101,7 +100,7 @@ public void Dispose() if (_disposed) return; - Current = Current?.Parent; + Current = Current.Parent!; _disposed = true; } } diff --git a/test/Client.Tests/Logging/TestOutputLogger.cs b/test/Client.Tests/Logging/TestOutputLogger.cs index d3e2a727e..95275aa31 100644 --- a/test/Client.Tests/Logging/TestOutputLogger.cs +++ b/test/Client.Tests/Logging/TestOutputLogger.cs @@ -67,7 +67,7 @@ public TestOutputLogger(ITestOutputHelper testOutput, string name, LogLevel mini /// /// An representing the scope. /// - public IDisposable BeginScope(TState state) => TestOutputLogScope.Push(_name, state); + public IDisposable BeginScope(TState state) => TestOutputLogScope.Push(_name, state!); /// /// Determine whether logging is enabled at the specified level. @@ -101,7 +101,7 @@ public TestOutputLogger(ITestOutputHelper testOutput, string name, LogLevel mini /// /// A delegate that formats the log message. /// - public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) { if (logLevel < _minimumLevel) return; diff --git a/test/Client.Tests/Logging/TestOutputLoggingProvider.cs b/test/Client.Tests/Logging/TestOutputLoggingProvider.cs index 8b1368703..b96674a5a 100644 --- a/test/Client.Tests/Logging/TestOutputLoggingProvider.cs +++ b/test/Client.Tests/Logging/TestOutputLoggingProvider.cs @@ -53,7 +53,7 @@ public TestOutputLoggingProvider(ITestOutputHelper testOutput, LogLevel minimumL /// /// The logger. /// - public ILogger CreateLogger(string name) + public ILogger CreateLogger(string? name) { if (name == null) name = string.Empty; diff --git a/test/Client.Tests/PipeServerTestBase.cs b/test/Client.Tests/PipeServerTestBase.cs index 5c0094407..13e0c7fa8 100644 --- a/test/Client.Tests/PipeServerTestBase.cs +++ b/test/Client.Tests/PipeServerTestBase.cs @@ -14,19 +14,19 @@ namespace OmniSharp.Extensions.LanguageServer.Client.Tests { /// - /// The base class for test suites that use a . + /// The base class for test suites that use a . /// public abstract class PipeServerTestBase : TestBase, IAsyncLifetime { /// - /// The used to connect client and server streams. + /// The used to connect client and server streams. /// private readonly CancellationTokenSource _cancellationTokenSource; protected CancellationToken CancellationToken => _cancellationTokenSource.Token; - private ILanguageClient _client; - private ILanguageServer _server; + private ILanguageClient? _client; + private ILanguageServer? _server; /// /// Create a new . @@ -47,10 +47,10 @@ protected PipeServerTestBase(ITestOutputHelper testOutput) /// /// The workspace root path. /// - protected string WorkspaceRoot => Path.GetDirectoryName(GetType().Assembly.Location); + protected string WorkspaceRoot => Path.GetDirectoryName(GetType().Assembly.Location)!; /// - /// Create a connected to the test's . + /// Create a connected to the test's . /// /// /// The . @@ -90,6 +90,6 @@ await Task.WhenAll( } public virtual Task InitializeAsync() => Task.CompletedTask; - public Task DisposeAsync() => _client?.Shutdown(); + public Task DisposeAsync() => _client?.Shutdown()!; } } diff --git a/test/Client.Tests/TestBase.cs b/test/Client.Tests/TestBase.cs index fc0170dad..2f43fce2c 100644 --- a/test/Client.Tests/TestBase.cs +++ b/test/Client.Tests/TestBase.cs @@ -13,8 +13,7 @@ namespace OmniSharp.Extensions.LanguageServer.Client.Tests /// /// The base class for test suites. /// - public abstract class TestBase - : IDisposable + public abstract class TestBase : IDisposable { /// /// Create a new test-suite. @@ -39,21 +38,20 @@ protected TestBase(ITestOutputHelper testOutput) Disposal.Add(LoggerFactory); // LoggerFactory.AddDebug(LogLevel); + // ReSharper disable once VirtualMemberCallInConstructor LoggerFactory.AddTestOutput(TestOutput, LogLevel); // Ugly hack to get access to the current test. CurrentTest = (ITest) TestOutput.GetType() - .GetField("test", BindingFlags.NonPublic | BindingFlags.Instance) - .GetValue(TestOutput); + .GetField("test", BindingFlags.NonPublic | BindingFlags.Instance)! + .GetValue(TestOutput)!; Assert.True(CurrentTest != null, "Cannot retrieve current test from ITestOutputHelper."); Log = LoggerFactory.CreateLogger("CurrentTest"); - Disposal.Add( - Log.BeginScope("TestDisplayName='{TestName}'", CurrentTest.DisplayName) - ); + Disposal.Add(Log.BeginScope("TestDisplayName='{TestName}'", CurrentTest!.DisplayName)); } /// @@ -86,6 +84,7 @@ protected virtual void Dispose(bool disposing) } finally { + // ReSharper disable once SuspiciousTypeConversion.Global if (Log is IDisposable logDisposal) logDisposal.Dispose(); } diff --git a/test/Client.Tests/TestResponse.cs b/test/Client.Tests/TestResponse.cs index a419de6ae..94c712198 100644 --- a/test/Client.Tests/TestResponse.cs +++ b/test/Client.Tests/TestResponse.cs @@ -8,6 +8,6 @@ internal class TestResponse /// /// A test value for the response. /// - public string Value { get; set; } + public string? Value { get; set; } } } diff --git a/test/Dap.Tests/EventingTests.cs b/test/Dap.Tests/EventingTests.cs index ca80fc2fc..27a32e7c0 100644 --- a/test/Dap.Tests/EventingTests.cs +++ b/test/Dap.Tests/EventingTests.cs @@ -60,12 +60,14 @@ public async Task Initialize_Interface_Is_Supported_On_Handlers() Substitute.For(new[] { typeof(IOnDebugAdapterServerInitialize), typeof(CompletionsHandler) }, Array.Empty()) as IOnDebugAdapterServerInitialize; var (client, server) = await Initialize( - options => options.AddHandler(onDebugAdapterClientInitialize as IJsonRpcHandler), - options => options.AddHandler(onDebugAdapterServerInitialize as IJsonRpcHandler) + // ReSharper disable once SuspiciousTypeConversion.Global + options => options.AddHandler((IJsonRpcHandler) onDebugAdapterClientInitialize!), + // ReSharper disable once SuspiciousTypeConversion.Global + options => options.AddHandler((IJsonRpcHandler) onDebugAdapterServerInitialize!) ); - await onDebugAdapterClientInitialize.Received(1).OnInitialize(client, client.ClientSettings, Arg.Any()); - await onDebugAdapterServerInitialize.Received(1).OnInitialize(server, server.ClientSettings, Arg.Any()); + await onDebugAdapterClientInitialize.Received(1)!.OnInitialize(client, client.ClientSettings, Arg.Any()); + await onDebugAdapterServerInitialize.Received(1)!.OnInitialize(server, server.ClientSettings, Arg.Any()); } [Fact] @@ -105,12 +107,14 @@ public async Task Initialized_Interface_Is_Supported_On_Handlers() Substitute.For(new[] { typeof(IOnDebugAdapterServerInitialized), typeof(CompletionsHandler) }, Array.Empty()) as IOnDebugAdapterServerInitialized; var (client, server) = await Initialize( - options => options.AddHandler(onDebugAdapterClientInitialized as IJsonRpcHandler), - options => options.AddHandler(onDebugAdapterServerInitialized as IJsonRpcHandler) + // ReSharper disable once SuspiciousTypeConversion.Global + options => options.AddHandler((IJsonRpcHandler) onDebugAdapterClientInitialized!), + // ReSharper disable once SuspiciousTypeConversion.Global + options => options.AddHandler((IJsonRpcHandler) onDebugAdapterServerInitialized!) ); - await onDebugAdapterClientInitialized.Received(1).OnInitialized(client, client.ClientSettings, client.ServerSettings, Arg.Any()); - await onDebugAdapterServerInitialized.Received(1).OnInitialized(server, server.ClientSettings, server.ServerSettings, Arg.Any()); + await onDebugAdapterClientInitialized.Received(1)!.OnInitialized(client, client.ClientSettings, client.ServerSettings, Arg.Any()); + await onDebugAdapterServerInitialized.Received(1)!.OnInitialized(server, server.ClientSettings, server.ServerSettings, Arg.Any()); } [Fact] @@ -150,12 +154,14 @@ public async Task Started_Interface_Is_Supported_On_Handlers() Substitute.For(new[] { typeof(IOnDebugAdapterServerStarted), typeof(CompletionsHandler) }, Array.Empty()) as IOnDebugAdapterServerStarted; var (client, server) = await Initialize( - options => options.AddHandler(onDebugAdapterClientStarted as IJsonRpcHandler), - options => options.AddHandler(onDebugAdapterServerStarted as IJsonRpcHandler) + // ReSharper disable once SuspiciousTypeConversion.Global + options => options.AddHandler((IJsonRpcHandler) onDebugAdapterClientStarted!), + // ReSharper disable once SuspiciousTypeConversion.Global + options => options.AddHandler((IJsonRpcHandler) onDebugAdapterServerStarted!) ); - await onDebugAdapterClientStarted.Received(1).OnStarted(client, Arg.Any()); - await onDebugAdapterServerStarted.Received(1).OnStarted(server, Arg.Any()); + await onDebugAdapterClientStarted.Received(1)!.OnStarted(client, Arg.Any()); + await onDebugAdapterServerStarted.Received(1)!.OnStarted(server, Arg.Any()); } } } diff --git a/test/Dap.Tests/FoundationTests.cs b/test/Dap.Tests/FoundationTests.cs index 4867c0444..df26df821 100644 --- a/test/Dap.Tests/FoundationTests.cs +++ b/test/Dap.Tests/FoundationTests.cs @@ -134,8 +134,8 @@ public void HandlersShouldMatchParamsMethodAttribute(Type type) { var paramsType = HandlerTypeDescriptorHelper.GetHandlerInterface(type).GetGenericArguments()[0]; - var lhs = MethodAttribute.From(type); - var rhs = MethodAttribute.From(paramsType); + var lhs = MethodAttribute.From(type)!; + var rhs = MethodAttribute.From(paramsType)!; lhs.Method.Should().Be(rhs.Method, $"{type.FullName} method does not match {paramsType.FullName}"); lhs.Direction.Should().Be(rhs.Direction, $"{type.FullName} direction does not match {paramsType.FullName}"); } @@ -161,7 +161,7 @@ public void HandlersShouldAbstractClass(IHandlerTypeDescriptor descriptor) { _logger.LogInformation("Delegating Handler: {Type}", delegatingHandler); delegatingHandler.DeclaringType.Should().NotBeNull(); - delegatingHandler.DeclaringType.GetMethods(BindingFlags.Public | BindingFlags.Static).Any(z => z.Name.StartsWith("On")).Should() + delegatingHandler.DeclaringType!.GetMethods(BindingFlags.Public | BindingFlags.Static).Any(z => z.Name.StartsWith("On")).Should() .BeTrue($"{descriptor.HandlerType.FullName} is missing delegating extension method"); } } @@ -267,7 +267,7 @@ Func ForParameter(int index, Func m) } var containsCancellationToken = ForParameter(1, info => info.ParameterType.GetGenericArguments().Reverse().Take(2).Any(x => x == typeof(CancellationToken))); - var returnType = descriptor.HasResponseType ? typeof(Task<>).MakeGenericType(descriptor.ResponseType) : typeof(Task); + var returnType = descriptor.HasResponseType ? typeof(Task<>).MakeGenericType(descriptor.ResponseType!) : typeof(Task); var returns = ForParameter(1, info => info.ParameterType.GetGenericArguments().LastOrDefault() == returnType); var isAction = ForParameter(1, info => info.ParameterType.Name.StartsWith(nameof(Action))); var isFunc = ForParameter(1, info => info.ParameterType.Name.StartsWith("Func")); @@ -275,13 +275,13 @@ Func ForParameter(int index, Func m) if (descriptor.IsRequest) { - matcher.Match($"Func<{descriptor.ParamsType.Name}, {returnType.Name}>", isFunc, takesParameter, returns); + matcher.Match($"Func<{descriptor.ParamsType!.Name}, {returnType.Name}>", isFunc, takesParameter, returns); matcher.Match($"Func<{descriptor.ParamsType.Name}, CancellationToken, {returnType.Name}>", isFunc, takesParameter, containsCancellationToken, returns); } if (descriptor.IsNotification) { - matcher.Match($"Func<{descriptor.ParamsType.Name}, {returnType.Name}>", isFunc, takesParameter, returns); + matcher.Match($"Func<{descriptor.ParamsType!.Name}, {returnType.Name}>", isFunc, takesParameter, returns); matcher.Match($"Func<{descriptor.ParamsType.Name}, CancellationToken, {returnType.Name}>", isFunc, takesParameter, containsCancellationToken, returns); matcher.Match($"Action<{descriptor.ParamsType.Name}>", isAction, takesParameter); matcher.Match($"Action<{descriptor.ParamsType.Name}, CancellationToken>", isAction, takesParameter, containsCancellationToken); @@ -290,7 +290,7 @@ Func ForParameter(int index, Func m) { var matcher = new MethodMatcher(sendMethodRegistries, descriptor, extensionClass, sendMethodName); Func containsCancellationToken = info => info.GetParameters().Reverse().Take(2).Any(x => x.ParameterType == typeof(CancellationToken)); - var returnType = descriptor.HasResponseType ? typeof(Task<>).MakeGenericType(descriptor.ResponseType) : typeof(Task); + var returnType = descriptor.HasResponseType ? typeof(Task<>).MakeGenericType(descriptor.ResponseType!) : typeof(Task); Func returns = info => info.ReturnType == returnType; Func isAction = info => info.ReturnType.Name == "Void"; var isFunc = returns; @@ -298,12 +298,12 @@ Func ForParameter(int index, Func m) if (descriptor.IsRequest) { - matcher.Match($"Func<{descriptor.ParamsType.Name}, CancellationToken, {returnType.Name}>", isFunc, takesParameter, containsCancellationToken, returns); + matcher.Match($"Func<{descriptor.ParamsType!.Name}, CancellationToken, {returnType.Name}>", isFunc, takesParameter, containsCancellationToken, returns); } if (descriptor.IsNotification) { - matcher.Match($"Action<{descriptor.ParamsType.Name}>", isAction, takesParameter); + matcher.Match($"Action<{descriptor.ParamsType!.Name}>", isAction, takesParameter); } } } @@ -393,9 +393,9 @@ public ParamsShouldHaveMethodAttributeData() foreach (var type in typeof(IDataBreakpointInfoHandler).Assembly.ExportedTypes .Where( z => z.IsClass && !z.IsAbstract && z.GetInterfaces().Any( - z => - z.IsGenericType && - typeof(IRequest<>).IsAssignableFrom(z.GetGenericTypeDefinition()) + x => + x.IsGenericType && + typeof(IRequest<>).IsAssignableFrom(x.GetGenericTypeDefinition()) ) )) { @@ -449,9 +449,9 @@ private static bool IsValidInterface(Type type) public static Type GetHandlerInterface(Type type) { if (IsValidInterface(type)) return type; - return type?.GetTypeInfo() + return type.GetTypeInfo() .ImplementedInterfaces - .First(IsValidInterface); + .First(IsValidInterface)!; } @@ -476,7 +476,7 @@ public TypeHandlerData() if (type.IsGenericTypeDefinition && !MethodAttribute.AllFrom(type).Any()) continue; if (type == typeof(IProgressStartHandler) || type == typeof(IProgressUpdateHandler) || type == typeof(IProgressEndHandler)) continue; - Add(handlerTypeDescriptorProvider.GetHandlerTypeDescriptor(type)); + Add(handlerTypeDescriptorProvider.GetHandlerTypeDescriptor(type)!); } } } @@ -500,7 +500,7 @@ public TypeHandlerExtensionData() { if (type.IsGenericTypeDefinition && !MethodAttribute.AllFrom(type).Any()) continue; if (type == typeof(IProgressStartHandler) || type == typeof(IProgressUpdateHandler) || type == typeof(IProgressEndHandler)) continue; - var descriptor = handlerTypeDescriptorProvider.GetHandlerTypeDescriptor(type); + var descriptor = handlerTypeDescriptorProvider.GetHandlerTypeDescriptor(type)!; Add( descriptor, @@ -518,7 +518,7 @@ public TypeHandlerExtensionData() private static string SpecialCasedHandlerName(IHandlerTypeDescriptor descriptor) => new Regex(@"(\w+(?:\`\d)?)$") .Replace( - descriptor.HandlerType.Name ?? string.Empty, + descriptor.HandlerType.Name, descriptor.HandlerType.Name.Substring(1, descriptor.HandlerType.Name.IndexOf("Handler", StringComparison.Ordinal) - 1) ); diff --git a/test/Dap.Tests/Integration/ConnectionAndDisconnectionTests.cs b/test/Dap.Tests/Integration/ConnectionAndDisconnectionTests.cs index 77786b7cb..702389e8c 100644 --- a/test/Dap.Tests/Integration/ConnectionAndDisconnectionTests.cs +++ b/test/Dap.Tests/Integration/ConnectionAndDisconnectionTests.cs @@ -9,6 +9,7 @@ using OmniSharp.Extensions.JsonRpc.Testing; using Xunit; using Xunit.Abstractions; +#pragma warning disable CS0162 namespace Dap.Tests.Integration { @@ -23,7 +24,7 @@ public ConnectionAndDisconnectionTests(ITestOutputHelper outputHelper) : base( [Fact] public async Task Server_Should_Stay_Alive_When_Requests_Throw_An_Exception() { - var (client, server) = await Initialize(ConfigureClient, ConfigureServer); + var (client, _) = await Initialize(ConfigureClient, ConfigureServer); var result = await client.SendRequest("keepalive").Returning(CancellationToken); result.Should().BeTrue(); @@ -38,7 +39,7 @@ public async Task Server_Should_Stay_Alive_When_Requests_Throw_An_Exception() [Fact] public async Task Client_Should_Stay_Alive_When_Requests_Throw_An_Exception() { - var (client, server) = await Initialize(ConfigureClient, ConfigureServer); + var (_, server) = await Initialize(ConfigureClient, ConfigureServer); var result = await server.SendRequest("keepalive").Returning(CancellationToken); result.Should().BeTrue(); @@ -53,7 +54,7 @@ public async Task Client_Should_Stay_Alive_When_Requests_Throw_An_Exception() [Fact] public async Task Server_Should_Support_Links() { - var (client, server) = await Initialize(ConfigureClient, ConfigureServer); + var (client, _) = await Initialize(ConfigureClient, ConfigureServer); var result = await client.SendRequest("ka").Returning(CancellationToken); result.Should().BeTrue(); @@ -68,7 +69,7 @@ public async Task Server_Should_Support_Links() [Fact] public async Task Client_Should_Support_Links() { - var (client, server) = await Initialize(ConfigureClient, ConfigureServer); + var (_, server) = await Initialize(ConfigureClient, ConfigureServer); var result = await server.SendRequest("ka").Returning(CancellationToken); result.Should().BeTrue(); diff --git a/test/Dap.Tests/Integration/CustomRequestsTests.cs b/test/Dap.Tests/Integration/CustomRequestsTests.cs index 77ffafade..dac194d35 100644 --- a/test/Dap.Tests/Integration/CustomRequestsTests.cs +++ b/test/Dap.Tests/Integration/CustomRequestsTests.cs @@ -23,7 +23,7 @@ public CustomRequestsTests(ITestOutputHelper outputHelper) : base(new JsonRpcTes public async Task Should_Support_Custom_Attach_Request_Using_Base_Class() { var fake = Substitute.For>(); - var (client, server) = await Initialize(options => { }, options => { options.AddHandler(fake); }); + var (client, _) = await Initialize(options => { }, options => { options.AddHandler(fake); }); await client.RequestAttach( new CustomAttachRequestArguments { @@ -45,7 +45,7 @@ await client.RequestAttach( public async Task Should_Support_Custom_Attach_Request_Receiving_Regular_Request_Using_Base_Class() { var fake = Substitute.For(); - var (client, server) = await Initialize(options => { }, options => { options.AddHandler(fake); }); + var (client, _) = await Initialize(options => { }, options => { options.AddHandler(fake); }); await client.RequestAttach( new CustomAttachRequestArguments { @@ -67,7 +67,7 @@ await client.RequestAttach( public async Task Should_Support_Custom_Attach_Request_Using_Extension_Data_Using_Base_Class() { var fake = Substitute.For>(); - var (client, server) = await Initialize(options => { }, options => { options.AddHandler(fake); }); + var (client, _) = await Initialize(options => { }, options => { options.AddHandler(fake); }); await client.RequestAttach( new AttachRequestArguments { @@ -91,7 +91,7 @@ await client.RequestAttach( public async Task Should_Support_Custom_Launch_Request_Using_Base_Class() { var fake = Substitute.For>(); - var (client, server) = await Initialize(options => { }, options => { options.AddHandler(fake); }); + var (client, _) = await Initialize(options => { }, options => { options.AddHandler(fake); }); await client.RequestLaunch( new CustomLaunchRequestArguments { @@ -109,7 +109,7 @@ await client.RequestLaunch( public async Task Should_Support_Custom_Launch_Request_Receiving_Regular_Request_Using_Base_Class() { var fake = Substitute.For(); - var (client, server) = await Initialize(options => { }, options => { options.AddHandler(fake); }); + var (client, _) = await Initialize(options => { }, options => { options.AddHandler(fake); }); await client.RequestLaunch( new CustomLaunchRequestArguments { @@ -127,7 +127,7 @@ await client.RequestLaunch( public async Task Should_Support_Custom_Launch_Request_Using_Extension_Data_Base_Class() { var fake = Substitute.For>(); - var (client, server) = await Initialize(options => { }, options => { options.AddHandler(fake); }); + var (client, _) = await Initialize(options => { }, options => { options.AddHandler(fake); }); await client.RequestLaunch( new CustomLaunchRequestArguments { @@ -147,7 +147,7 @@ await client.RequestLaunch( public async Task Should_Support_Custom_Attach_Request_Using_Delegate() { var fake = Substitute.For>>(); - var (client, server) = await Initialize(options => { }, options => { options.OnAttach(fake); }); + var (client, _) = await Initialize(options => { }, options => { options.OnAttach(fake); }); await client.RequestAttach( new CustomAttachRequestArguments { @@ -169,7 +169,7 @@ await client.RequestAttach( public async Task Should_Support_Custom_Attach_Request_Receiving_Regular_Request_Using_Delegate() { var fake = Substitute.For>>(); - var (client, server) = await Initialize(options => { }, options => { options.OnAttach(fake); }); + var (client, _) = await Initialize(options => { }, options => { options.OnAttach(fake); }); await client.RequestAttach( new CustomAttachRequestArguments { @@ -191,7 +191,7 @@ await client.RequestAttach( public async Task Should_Support_Custom_Attach_Request_Using_Extension_Data_Using_Delegate() { var fake = Substitute.For>>(); - var (client, server) = await Initialize(options => { }, options => { options.OnAttach(fake); }); + var (client, _) = await Initialize(options => { }, options => { options.OnAttach(fake); }); await client.RequestAttach( new AttachRequestArguments { @@ -215,7 +215,7 @@ await client.RequestAttach( public async Task Should_Support_Custom_Launch_Request_Using_Delegate() { var fake = Substitute.For>>(); - var (client, server) = await Initialize(options => { }, options => { options.OnLaunch(fake); }); + var (client, _) = await Initialize(options => { }, options => { options.OnLaunch(fake); }); await client.RequestLaunch( new CustomLaunchRequestArguments { @@ -233,7 +233,7 @@ await client.RequestLaunch( public async Task Should_Support_Custom_Launch_Request_Receiving_Regular_Request_Using_Delegate() { var fake = Substitute.For>>(); - var (client, server) = await Initialize(options => { }, options => { options.OnLaunch(fake); }); + var (client, _) = await Initialize(options => { }, options => { options.OnLaunch(fake); }); await client.RequestLaunch( new CustomLaunchRequestArguments { @@ -251,7 +251,7 @@ await client.RequestLaunch( public async Task Should_Support_Custom_Launch_Request_Using_Extension_Data_Using_Delegate() { var fake = Substitute.For>>(); - var (client, server) = await Initialize(options => { }, options => { options.OnLaunch(fake); }); + var (client, _) = await Initialize(options => { }, options => { options.OnLaunch(fake); }); await client.RequestLaunch( new CustomLaunchRequestArguments { @@ -269,11 +269,11 @@ await client.RequestLaunch( public class CustomAttachRequestArguments : AttachRequestArguments { - public string ComputerName { get; set; } + public string ComputerName { get; set; } = null!; - public string ProcessId { get; set; } + public string ProcessId { get; set; } = null!; - public string RunspaceId { get; set; } + public string RunspaceId { get; set; } = null!; } public class CustomLaunchRequestArguments : LaunchRequestArguments @@ -281,7 +281,7 @@ public class CustomLaunchRequestArguments : LaunchRequestArguments /// /// Gets or sets the absolute path to the script to debug. /// - public string Script { get; set; } + public string Script { get; set; } = null!; } } } diff --git a/test/Dap.Tests/Integration/Fixtures/DebugAdapterProtocolFixture.cs b/test/Dap.Tests/Integration/Fixtures/DebugAdapterProtocolFixture.cs index 3f16c0d48..2bd203431 100644 --- a/test/Dap.Tests/Integration/Fixtures/DebugAdapterProtocolFixture.cs +++ b/test/Dap.Tests/Integration/Fixtures/DebugAdapterProtocolFixture.cs @@ -22,7 +22,7 @@ public class DebugAdapterProtocolFixture Task.CompletedTask; } -} \ No newline at end of file +} diff --git a/test/Dap.Tests/Integration/Fixtures/DefaultClient.cs b/test/Dap.Tests/Integration/Fixtures/DefaultClient.cs index 0f68a5fef..1a7c6304e 100644 --- a/test/Dap.Tests/Integration/Fixtures/DefaultClient.cs +++ b/test/Dap.Tests/Integration/Fixtures/DefaultClient.cs @@ -4,12 +4,8 @@ namespace Dap.Tests.Integration.Fixtures { public sealed class DefaultClient : IConfigureDebugAdapterClientOptions { - public DefaultClient() - { - } - public void Configure(DebugAdapterClientOptions options) { } } -} \ No newline at end of file +} diff --git a/test/Dap.Tests/Integration/Fixtures/DefaultServer.cs b/test/Dap.Tests/Integration/Fixtures/DefaultServer.cs index c8d7ea28d..35b0c404c 100644 --- a/test/Dap.Tests/Integration/Fixtures/DefaultServer.cs +++ b/test/Dap.Tests/Integration/Fixtures/DefaultServer.cs @@ -4,12 +4,8 @@ namespace Dap.Tests.Integration.Fixtures { public sealed class DefaultServer : IConfigureDebugAdapterServerOptions { - public DefaultServer() - { - } - public void Configure(DebugAdapterServerOptions options) { } } -} \ No newline at end of file +} diff --git a/test/Dap.Tests/Integration/HandlersManagerIntegrationTests.cs b/test/Dap.Tests/Integration/HandlersManagerIntegrationTests.cs index 11b5b73b5..2c72996e8 100644 --- a/test/Dap.Tests/Integration/HandlersManagerIntegrationTests.cs +++ b/test/Dap.Tests/Integration/HandlersManagerIntegrationTests.cs @@ -21,7 +21,7 @@ public HandlersManagerIntegrationTests(ITestOutputHelper testOutputHelper) : bas [Fact] public async Task Should_Return_Default_Handlers() { - var (client, server) = await Initialize(options => {}, options => {}); + var (_, server) = await Initialize(options => {}, options => {}); var handlersManager = server.GetRequiredService(); handlersManager.Descriptors.Should().HaveCount(2); @@ -31,7 +31,7 @@ public async Task Should_Return_Default_Handlers() [Fact] public async Task Link_Should_Fail_If_No_Handler_Is_Defined() { - var (client, server) = await Initialize(options => {}, options => {}); + var (_, server) = await Initialize(options => {}, options => {}); var handlersManager = server.GetRequiredService(); @@ -42,10 +42,10 @@ public async Task Link_Should_Fail_If_No_Handler_Is_Defined() [Fact] public async Task Link_Should_Fail_If_Link_Is_On_The_Wrong_Side() { - var (client, server) = await Initialize(options => {}, options => {}); + var (_, server) = await Initialize(options => {}, options => {}); var handlersManager = server.GetRequiredService(); - handlersManager.Add(Substitute.For(new Type[] { typeof(ICompletionsHandler) }, Array.Empty()) as IJsonRpcHandler, new JsonRpcHandlerOptions()); + handlersManager.Add((Substitute.For(new[] { typeof(ICompletionsHandler) }, Array.Empty()) as IJsonRpcHandler)!, new JsonRpcHandlerOptions()); Action a = () => handlersManager.AddLink("my/completions", RequestNames.Completions); a.Should().Throw().Which.Message.Should().Contain($"Did you mean to link '{RequestNames.Completions}' to 'my/completions' instead"); diff --git a/test/Dap.Tests/Integration/ProgressTests.cs b/test/Dap.Tests/Integration/ProgressTests.cs index 6c58ccb61..6e99fbc08 100644 --- a/test/Dap.Tests/Integration/ProgressTests.cs +++ b/test/Dap.Tests/Integration/ProgressTests.cs @@ -24,11 +24,6 @@ public ProgressTests(ITestOutputHelper outputHelper) : base( { } - private class Data - { - public string Value { get; set; } = "Value"; - } - [Fact(Skip = "Tests work locally - fail sometimes on ci :(")] public async Task Should_Support_Progress_From_Sever_To_Client() { @@ -83,6 +78,7 @@ public async Task Should_Support_Progress_From_Sever_To_Client() ProgressStartEvent begin => begin.Message, ProgressUpdateEvent begin => begin.Message, ProgressEndEvent begin => begin.Message, + _ => throw new NotSupportedException() } ); @@ -149,6 +145,7 @@ public async Task Should_Support_Cancelling_Progress_From_Server_To_Client_Reque ProgressStartEvent begin => begin.Message, ProgressUpdateEvent begin => begin.Message, ProgressEndEvent begin => begin.Message, + _ => throw new NotSupportedException() } ); diff --git a/test/Dap.Tests/Integration/RecursiveResolutionTests.cs b/test/Dap.Tests/Integration/RecursiveResolutionTests.cs index 7c8e9d64d..3972207d0 100644 --- a/test/Dap.Tests/Integration/RecursiveResolutionTests.cs +++ b/test/Dap.Tests/Integration/RecursiveResolutionTests.cs @@ -192,6 +192,7 @@ public class ClassRequest : IRequest [Method(nameof(ClassRequest))] class ClassHandler : IJsonRpcRequestHandler where T : class { + // ReSharper disable once NotAccessedField.Local private readonly T _jsonRpcServer; public ClassHandler(T jsonRpcServer) @@ -210,6 +211,7 @@ public class InterfaceRequest : IRequest [Method(nameof(InterfaceRequest))] class InterfaceHandler : IJsonRpcRequestHandler { + // ReSharper disable once NotAccessedField.Local private readonly T _jsonRpcServer; public InterfaceHandler(T jsonRpcServer) diff --git a/test/Dap.Tests/Integration/RequestCancellationTests.cs b/test/Dap.Tests/Integration/RequestCancellationTests.cs index 50df095eb..4e9f4cfe5 100644 --- a/test/Dap.Tests/Integration/RequestCancellationTests.cs +++ b/test/Dap.Tests/Integration/RequestCancellationTests.cs @@ -23,7 +23,7 @@ public RequestCancellationTests(ITestOutputHelper outputHelper) : base(new JsonR [Fact] public async Task Should_Cancel_Pending_Requests() { - var (client, server) = await Initialize(ConfigureClient, ConfigureServer); + var (client, _) = await Initialize(ConfigureClient, ConfigureServer); Func> action = () => { var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100)); @@ -37,7 +37,7 @@ public async Task Should_Cancel_Pending_Requests() public void Should_Cancel_Requests_After_Timeout() { Func> action = async () => { - var (client, server) = await Initialize( + var (client, _) = await Initialize( ConfigureClient, x => { ConfigureServer(x); x.WithMaximumRequestTimeout(TimeSpan.FromMilliseconds(1000)); diff --git a/test/Dap.Tests/LanguageClientServiceCollectionSupportTests.cs b/test/Dap.Tests/LanguageClientServiceCollectionSupportTests.cs index b0251046b..4ea252ba4 100644 --- a/test/Dap.Tests/LanguageClientServiceCollectionSupportTests.cs +++ b/test/Dap.Tests/LanguageClientServiceCollectionSupportTests.cs @@ -57,8 +57,10 @@ public void Handlers_Can_Be_Added_From_The_Service_Collection() .WithInput(pipe.Reader) .WithOutput(pipe.Writer) .WithServices( - services => - services.AddJsonRpcHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }) + serviceCollection => + serviceCollection.AddJsonRpcHandler( + new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial } + ) ); } ) @@ -146,6 +148,7 @@ private class Request : IRequest private class Response { + // ReSharper disable once UnusedAutoPropertyAccessor.Local public string Value { get; } public Response(string value) => Value = value; diff --git a/test/Dap.Tests/LanguageServerServiceCollectionSupportTests.cs b/test/Dap.Tests/LanguageServerServiceCollectionSupportTests.cs index b660fb76d..08b7c06ab 100644 --- a/test/Dap.Tests/LanguageServerServiceCollectionSupportTests.cs +++ b/test/Dap.Tests/LanguageServerServiceCollectionSupportTests.cs @@ -57,8 +57,10 @@ public void Handlers_Can_Be_Added_From_The_Service_Collection() .WithInput(pipe.Reader) .WithOutput(pipe.Writer) .WithServices( - services => - services.AddJsonRpcHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }) + serviceCollection => + serviceCollection.AddJsonRpcHandler( + new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial } + ) ); } ) @@ -146,6 +148,7 @@ private class Request : IRequest private class Response { + // ReSharper disable once UnusedAutoPropertyAccessor.Local public string Value { get; } public Response(string value) => Value = value; diff --git a/test/Generation.Tests/GenerationHelpers.cs b/test/Generation.Tests/GenerationHelpers.cs index 43d8b671b..de4a19f8e 100644 --- a/test/Generation.Tests/GenerationHelpers.cs +++ b/test/Generation.Tests/GenerationHelpers.cs @@ -90,7 +90,7 @@ public static async Task GenerateAsync(string source) throw new InvalidOperationException("Could not get the syntax tree of the sources"); } - var compilation = (CSharpCompilation) await document.Project.GetCompilationAsync(); + var compilation = (CSharpCompilation) (await document.Project.GetCompilationAsync())!; if (compilation is null) { throw new InvalidOperationException("Could not compile the sources"); diff --git a/test/JsonRpc.Tests/AggregateSettlerTests.cs b/test/JsonRpc.Tests/AggregateSettlerTests.cs index 4fd39b172..f3b31ab4f 100644 --- a/test/JsonRpc.Tests/AggregateSettlerTests.cs +++ b/test/JsonRpc.Tests/AggregateSettlerTests.cs @@ -215,6 +215,7 @@ public AggregateRequestSettlerScheduler(TestScheduler testScheduler, IRequestSet _serverRequestSettler = serverRequestSettler; } + // ReSharper disable once UnusedMethodReturnValue.Local public IDisposable ScheduleAbsoluteStart(SettlerType settlerType, long dueTime) => settlerType switch { SettlerType.Client => _testScheduler.ScheduleAbsolute(dueTime, () => _clientRequestSettler.OnStartRequest()), @@ -222,6 +223,7 @@ public IDisposable ScheduleAbsoluteStart(SettlerType settlerType, long dueTime) _ => throw new NotImplementedException() }; + // ReSharper disable once UnusedMethodReturnValue.Local public IDisposable ScheduleAbsoluteEnd(SettlerType settlerType, long dueTime) => settlerType switch { SettlerType.Client => _testScheduler.ScheduleAbsolute(dueTime, () => _clientRequestSettler.OnEndRequest()), @@ -229,6 +231,7 @@ public IDisposable ScheduleAbsoluteEnd(SettlerType settlerType, long dueTime) => _ => throw new NotImplementedException() }; + // ReSharper disable once UnusedMethodReturnValue.Local public IDisposable ScheduleRelativeStart(SettlerType settlerType, long dueTime) => settlerType switch { SettlerType.Client => _testScheduler.ScheduleRelative(dueTime, () => _clientRequestSettler.OnStartRequest()), @@ -236,6 +239,7 @@ public IDisposable ScheduleRelativeStart(SettlerType settlerType, long dueTime) _ => throw new NotImplementedException() }; + // ReSharper disable once UnusedMethodReturnValue.Local public IDisposable ScheduleRelativeEnd(SettlerType settlerType, long dueTime) => settlerType switch { SettlerType.Client => _testScheduler.ScheduleRelative(dueTime, () => _clientRequestSettler.OnEndRequest()), diff --git a/test/JsonRpc.Tests/HandlerResolverTests.cs b/test/JsonRpc.Tests/HandlerResolverTests.cs index 3dda9ffea..381ae0b67 100644 --- a/test/JsonRpc.Tests/HandlerResolverTests.cs +++ b/test/JsonRpc.Tests/HandlerResolverTests.cs @@ -4,7 +4,6 @@ using FluentAssertions; using FluentAssertions.Common; using MediatR; -using Microsoft.Extensions.DependencyInjection; using NSubstitute; using OmniSharp.Extensions.JsonRpc; using Xunit; diff --git a/test/JsonRpc.Tests/InputHandlerTests.cs b/test/JsonRpc.Tests/InputHandlerTests.cs index 05aecba70..e44867d1a 100644 --- a/test/JsonRpc.Tests/InputHandlerTests.cs +++ b/test/JsonRpc.Tests/InputHandlerTests.cs @@ -33,7 +33,7 @@ private InputHandler NewHandler( IOutputHandler outputHandler, IReceiver receiver, IRequestProcessIdentifier requestProcessIdentifier, - IRequestRouter requestRouter, + IRequestRouter requestRouter, ILoggerFactory loggerFactory, IResponseRouter responseRouter ) => @@ -62,7 +62,8 @@ public async Task Should_Pass_In_Requests() using var handler = NewHandler( pipe.Reader, outputHandler, receiver, - Substitute.For(), Substitute.For>(), + Substitute.For(), + Substitute.For>(), _loggerFactory, Substitute.For() ); await pipe.Writer.WriteAsync(Encoding.UTF8.GetBytes("Content-Length: 2\r\n\r\n{}")); @@ -87,7 +88,8 @@ public async Task Should_Handle_Multiple_Requests_At_Once() using var handler = NewHandler( pipe.Reader, outputHandler, receiver, - Substitute.For(), Substitute.For>(), + Substitute.For(), + Substitute.For>(), _loggerFactory, Substitute.For() ); await pipe.Writer.WriteAsync( @@ -128,7 +130,8 @@ public async Task Should_Handle_Different_Additional_Headers_and_Whitespace(stri using var handler = NewHandler( pipe.Reader, outputHandler, receiver, - Substitute.For(), Substitute.For>(), + Substitute.For(), + Substitute.For>(), _loggerFactory, Substitute.For() ); await pipe.Writer.WriteAsync(Encoding.UTF8.GetBytes(data)); @@ -155,7 +158,8 @@ public async Task Should_Handle_Multiple_Requests_Back_To_Back() using var handler = NewHandler( pipe.Reader, outputHandler, receiver, - Substitute.For(), Substitute.For>(), + Substitute.For(), + Substitute.For>(), _loggerFactory, Substitute.For() ); @@ -187,7 +191,8 @@ public async Task Should_Handle_Multiple_Requests_In_Pieces() using var handler = NewHandler( pipe.Reader, outputHandler, receiver, - Substitute.For(), Substitute.For>(), + Substitute.For(), + Substitute.For>(), _loggerFactory, Substitute.For() ); @@ -229,7 +234,8 @@ public async Task Should_Handle_Multiple_Chunked_Requests(string content) using var handler = NewHandler( pipe.Reader, outputHandler, receiver, - Substitute.For(), Substitute.For>(), + Substitute.For(), + Substitute.For>(), _loggerFactory, Substitute.For() ); @@ -261,7 +267,8 @@ public async Task Should_Handle_Header_Terminiator_Being_Incomplete() using var handler = NewHandler( pipe.Reader, outputHandler, receiver, - Substitute.For(), Substitute.For>(), + Substitute.For(), + Substitute.For>(), _loggerFactory, Substitute.For() ); @@ -313,7 +320,8 @@ public async Task ShouldPassAdditionalUtf8EncodedRequests(string data) using var handler = NewHandler( pipe.Reader, outputHandler, receiver, - Substitute.For(), Substitute.For>(), + Substitute.For(), + Substitute.For>(), _loggerFactory, Substitute.For() ); @@ -335,7 +343,7 @@ await pipe.Writer.WriteAsync( call.GetMethodInfo().Name.Should().Be("IsValid"); call.GetArguments()[0].Should().BeAssignableTo(); var arg = call.GetArguments()[0] as JToken; - arg.ToString().Should().Be(JToken.Parse(data).ToString()); + arg!.ToString().Should().Be(JToken.Parse(data).ToString()); } [Theory] @@ -349,7 +357,7 @@ public async Task Should_Parse_Logs(string name, Func createPipeRead var reader = createPipeReader(); var receiver = new Receiver(); - var incomingRequestRouter = Substitute.For>(); + var incomingRequestRouter = Substitute.For>(); var outputHandler = Substitute.For(); var responseRouter = Substitute.For(); @@ -401,37 +409,38 @@ public JsonRpcLogs() { var data = GetData(assembly, streamName); - var msgTypes = data.Select( - z => { - if (z.MsgKind.EndsWith("response")) - { - return ( type: "response", kind: z.MsgType ); - } - - if (z.MsgKind.EndsWith("request")) - { - return ( type: "request", kind: z.MsgType ); - } - - if (z.MsgKind.EndsWith("notification") && z.MsgType != JsonRpcNames.CancelRequest) - { - return ( type: "notification", kind: z.MsgType ); - } - - return ( type: null, kind: null ); - } - ) - .Where(z => z.type != null) - .ToLookup(z => z.kind, z => z.type); - - Add(streamName, () => CreateReader(data), msgTypes); + var msgTypes = data + .Select( + z => { + if (z.MsgKind.EndsWith("response")) + { + return ( type: "response", kind: z.MsgType ); + } + + if (z.MsgKind.EndsWith("request")) + { + return ( type: "request", kind: z.MsgType ); + } + + if (z.MsgKind.EndsWith("notification") && z.MsgType != JsonRpcNames.CancelRequest) + { + return ( type: "notification", kind: z.MsgType ); + } + + return ( type: null, kind: null ); + } + ) + .Where(z => z.type != null) + .ToLookup(z => z.kind!, z => z.type!); + + Add(streamName, () => CreateReader(data), msgTypes!); } } private DataItem[] GetData(Assembly assembly, string name) { var stream = assembly.GetManifestResourceStream(name); - using var streamReader = new StreamReader(stream); + using var streamReader = new StreamReader(stream!); using var jsonReader = new JsonTextReader(streamReader); var serializer = new JsonSerializer(); return serializer.Deserialize(jsonReader); @@ -470,13 +479,13 @@ private PipeReader CreateReader(DataItem[] data) var pipeIn = new Pipe(); - var _serializer = new JsonRpcSerializer(); + var serializer = new JsonRpcSerializer(); Task.Run( async () => { foreach (var item in outputData) { - var content = _serializer.SerializeObject(item); + var content = serializer.SerializeObject(item); var contentBytes = Encoding.UTF8.GetBytes(content).AsMemory(); await pipeIn.Writer.WriteAsync( @@ -496,12 +505,15 @@ await pipeIn.Writer.WriteAsync( private class DataItem { - public string Time { get; set; } - public string Msg { get; set; } - public string MsgKind { get; set; } - public string MsgType { get; set; } - public string MsgId { get; set; } - public JToken Arg { get; set; } + // ReSharper disable once UnusedMember.Local + public string Time { get; set; } = null!; + + // ReSharper disable once UnusedMember.Local + public string Msg { get; set; } = null!; + public string MsgKind { get; set; } = null!; + public string MsgType { get; set; } = null!; + public string MsgId { get; set; } = null!; + public JToken Arg { get; set; } = null!; } } } diff --git a/test/JsonRpc.Tests/IntegrationTests.cs b/test/JsonRpc.Tests/IntegrationTests.cs index 6b6d487a0..6e6422015 100644 --- a/test/JsonRpc.Tests/IntegrationTests.cs +++ b/test/JsonRpc.Tests/IntegrationTests.cs @@ -26,15 +26,15 @@ private class Request : IRequest private class Data { - public string Value { get; set; } + public string Value { get; set; } = null!; } [Fact] public async Task Should_Send_and_receive_requests() { var (client, server) = await Initialize( - client => { client.OnRequest("myrequest", async () => new Data { Value = "myresponse" }); }, - server => { server.OnRequest("myrequest", async () => new Data { Value = string.Join("", "myresponse".Reverse()) }); } + clientOptions => { clientOptions.OnRequest("myrequest", async () => new Data { Value = "myresponse" }); }, + serverOptions => { serverOptions.OnRequest("myrequest", async () => new Data { Value = string.Join("", "myresponse".Reverse()) }); } ); var serverResponse = await client.SendRequest("myrequest").Returning(CancellationToken); @@ -48,14 +48,14 @@ public async Task Should_Send_and_receive_requests() public async Task Should_throw_when_sending_requests() { var (client, server) = await Initialize( - client => { client.OnRequest("myrequest", async (Request request) => new Data { Value = "myresponse" }); }, - server => { server.OnRequest("myrequest", async (Request request) => new Data { Value = string.Join("", "myresponse".Reverse()) }); } + clientOptions => { clientOptions.OnRequest("myrequest", async (Request request) => new Data { Value = "myresponse" }); }, + serverOptions => { serverOptions.OnRequest("myrequest", async (Request request) => new Data { Value = string.Join("", "myresponse".Reverse()) }); } ); - Func clientRequest = () => client.SendRequest("myrequest", (Request) null).Returning(CancellationToken); + Func clientRequest = () => client.SendRequest("myrequest", (Request) null!).Returning(CancellationToken); clientRequest.Should().Throw(); - Func serverRequest = () => server.SendRequest("myrequest", (Request) null).Returning(CancellationToken); + Func serverRequest = () => server.SendRequest("myrequest", (Request) null!).Returning(CancellationToken); serverRequest.Should().Throw(); } @@ -63,8 +63,8 @@ public async Task Should_throw_when_sending_requests() public async Task Should_throw_when_receiving_requests() { var (client, server) = await Initialize( - client => { client.OnRequest("myrequest", async (Request request) => (Data) null); }, - server => { server.OnRequest("myrequest", async (Request request) => (Data) null); } + clientOptions => { clientOptions.OnRequest("myrequest", async (Request request) => (Data) null!); }, + serverOptions => { serverOptions.OnRequest("myrequest", async (Request request) => (Data) null!); } ); Func clientRequest = () => client.SendRequest("myrequest", new Request()).Returning(CancellationToken); @@ -80,16 +80,16 @@ public async Task Should_Send_and_receive_notifications() var clientNotification = new AsyncSubject(); var serverNotification = new AsyncSubject(); var (client, server) = await Initialize( - client => { - client.OnNotification( + clientOptions => { + clientOptions.OnNotification( "mynotification", (Data data) => { clientNotification.OnNext(data); clientNotification.OnCompleted(); } ); }, - server => { - server.OnNotification( + serverOptions => { + serverOptions.OnNotification( "mynotification", (Data data) => { serverNotification.OnNext(data); serverNotification.OnCompleted(); @@ -111,16 +111,16 @@ public async Task Should_Send_and_receive_notifications() public async Task Should_Send_and_cancel_requests_immediate() { var (client, server) = await Initialize( - client => { - client.OnRequest( + clientOptions => { + clientOptions.OnRequest( "myrequest", async ct => { await Task.Delay(TimeSpan.FromMinutes(1), ct); return new Data { Value = "myresponse" }; } ); }, - server => { - server.OnRequest( + serverOptions => { + serverOptions.OnRequest( "myrequest", async ct => { await Task.Delay(TimeSpan.FromMinutes(1), ct); return new Data { Value = string.Join("", "myresponse".Reverse()) }; @@ -147,16 +147,16 @@ public async Task Should_Send_and_cancel_requests_immediate() public async Task Should_Send_and_cancel_requests_from_otherside() { var (client, server) = await Initialize( - client => { - client.OnRequest( + clientOptions => { + clientOptions.OnRequest( "myrequest", async ct => { await Task.Delay(TimeSpan.FromMinutes(1), ct); return new Data { Value = "myresponse" }; } ); }, - server => { - server.OnRequest( + serverOptions => { + serverOptions.OnRequest( "myrequest", async ct => { await Task.Delay(TimeSpan.FromMinutes(1), ct); return new Data { Value = string.Join("", "myresponse".Reverse()) }; @@ -184,8 +184,8 @@ public async Task Should_Send_and_cancel_requests_from_otherside() public async Task Should_Cancel_Parallel_Requests_When_Options_Are_Given() { var (client, server) = await Initialize( - client => { - client.OnRequest( + clientOptions => { + clientOptions.OnRequest( "parallelrequest", async ct => { await Task.Delay(TimeSpan.FromSeconds(10), ct); @@ -193,14 +193,14 @@ public async Task Should_Cancel_Parallel_Requests_When_Options_Are_Given() }, new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Parallel } ); - client.OnRequest( + clientOptions.OnRequest( "serialrequest", async ct => new Data { Value = "myresponse" }, new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial } ); }, - server => { - server.OnRequest( + serverOptions => { + serverOptions.OnRequest( "parallelrequest", async ct => { await Task.Delay(TimeSpan.FromSeconds(10), ct); @@ -208,7 +208,7 @@ public async Task Should_Cancel_Parallel_Requests_When_Options_Are_Given() }, new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Parallel } ); - server.OnRequest( + serverOptions.OnRequest( "serialrequest", async ct => new Data { Value = "myresponse" }, new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial } @@ -235,14 +235,14 @@ public async Task Should_Cancel_Parallel_Requests_When_Options_Are_Given() public async Task Should_Link_Request_A_to_Request_B() { var (client, server) = await Initialize( - client => { - client + clientOptions => { + clientOptions .OnRequest("myrequest", async () => new Data { Value = "myresponse" }) .WithLink("myrequest", "myrequest2") ; }, - server => { - server + serverOptions => { + serverOptions .OnRequest("myrequest", async () => new Data { Value = string.Join("", "myresponse".Reverse()) }) .WithLink("myrequest", "myrequest2") ; diff --git a/test/JsonRpc.Tests/JsonRpcServerTests.cs b/test/JsonRpc.Tests/JsonRpcServerTests.cs index aabae324a..b899bb12d 100644 --- a/test/JsonRpc.Tests/JsonRpcServerTests.cs +++ b/test/JsonRpc.Tests/JsonRpcServerTests.cs @@ -20,7 +20,7 @@ public JsonRpcServerTests(ITestOutputHelper testOutputHelper) : base(new JsonRpc [Fact] public async Task Can_Connect_To_Stdio() { - var (client, server) = await Initialize( + await Initialize( clientOptions => { clientOptions .WithInput(Console.OpenStandardInput().UsePipeReader()) @@ -50,7 +50,7 @@ public async Task Can_Connect_To_A_Named_Pipe() PipeOptions.CurrentUserOnly | PipeOptions.Asynchronous ); - var (client, server) = await Initialize( + await Initialize( clientOptions => { clientOptions .WithInput(clientPipe) @@ -119,7 +119,7 @@ public async Task Can_Reconnect_To_A_Named_Pipe() PipeOptions.CurrentUserOnly | PipeOptions.Asynchronous ); - var (client, server) = await Initialize( + await Initialize( clientOptions => { clientOptions .WithInput(clientPipe) diff --git a/test/JsonRpc.Tests/MediatorTestsNotificationHandler.cs b/test/JsonRpc.Tests/MediatorTestsNotificationHandler.cs index 308403239..5a713a22f 100644 --- a/test/JsonRpc.Tests/MediatorTestsNotificationHandler.cs +++ b/test/JsonRpc.Tests/MediatorTestsNotificationHandler.cs @@ -2,7 +2,6 @@ using System.Threading.Tasks; using DryIoc; using MediatR; -using Microsoft.Extensions.DependencyInjection; using NSubstitute; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Server; diff --git a/test/JsonRpc.Tests/MediatorTestsNotificationHandlerOfT.cs b/test/JsonRpc.Tests/MediatorTestsNotificationHandlerOfT.cs index 9c6335e87..d9a80e958 100644 --- a/test/JsonRpc.Tests/MediatorTestsNotificationHandlerOfT.cs +++ b/test/JsonRpc.Tests/MediatorTestsNotificationHandlerOfT.cs @@ -3,7 +3,6 @@ using System.Threading.Tasks; using DryIoc; using MediatR; -using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NSubstitute; @@ -24,7 +23,7 @@ public interface ICancelRequestHandler : IJsonRpcNotificationHandler Container = JsonRpcTestContainer.Create(testOutputHelper); @@ -33,7 +32,6 @@ public class CancelParams : IRequest public async Task ExecutesHandler() { var cancelRequestHandler = Substitute.For(); - var mediator = Substitute.For(); var collection = new HandlerCollection(Substitute.For(), new HandlerTypeDescriptorProvider(new [] { typeof(HandlerTypeDescriptorProvider).Assembly, typeof(HandlerResolverTests).Assembly })) { cancelRequestHandler }; AutoSubstitute.Provide(collection); diff --git a/test/JsonRpc.Tests/MediatorTestsRequestHandlerOfTRequest.cs b/test/JsonRpc.Tests/MediatorTestsRequestHandlerOfTRequest.cs index 94a863a0e..dd94b4c70 100644 --- a/test/JsonRpc.Tests/MediatorTestsRequestHandlerOfTRequest.cs +++ b/test/JsonRpc.Tests/MediatorTestsRequestHandlerOfTRequest.cs @@ -3,7 +3,6 @@ using System.Threading.Tasks; using DryIoc; using MediatR; -using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NSubstitute; @@ -24,7 +23,7 @@ public interface IExecuteCommandHandler : IJsonRpcRequestHandler Container = JsonRpcTestContainer.Create(testOutputHelper); @@ -33,7 +32,6 @@ public class ExecuteCommandParams : IRequest public async Task ExecutesHandler() { var executeCommandHandler = Substitute.For(); - var mediator = Substitute.For(); var collection = new HandlerCollection(Substitute.For(), new HandlerTypeDescriptorProvider(new [] { typeof(HandlerTypeDescriptorProvider).Assembly, typeof(HandlerResolverTests).Assembly })) { executeCommandHandler }; AutoSubstitute.Provide(collection); @@ -43,7 +41,7 @@ public async Task ExecutesHandler() var @params = new ExecuteCommandParams { Command = "123" }; var request = new Request(id, "workspace/executeCommand", JObject.Parse(JsonConvert.SerializeObject(@params))); - var response = await router.RouteRequest(router.GetDescriptors(request), request, CancellationToken.None); + await router.RouteRequest(router.GetDescriptors(request), request, CancellationToken.None); await executeCommandHandler.Received(1).Handle(Arg.Any(), Arg.Any()); } diff --git a/test/JsonRpc.Tests/MediatorTestsRequestHandlerOfTRequestTResponse.cs b/test/JsonRpc.Tests/MediatorTestsRequestHandlerOfTRequestTResponse.cs index 0989e71e6..215fbf14f 100644 --- a/test/JsonRpc.Tests/MediatorTestsRequestHandlerOfTRequestTResponse.cs +++ b/test/JsonRpc.Tests/MediatorTestsRequestHandlerOfTRequestTResponse.cs @@ -4,7 +4,6 @@ using System.Threading.Tasks; using DryIoc; using MediatR; -using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NSubstitute; @@ -25,15 +24,15 @@ public interface ICodeActionHandler : IJsonRpcRequestHandler> { - public string TextDocument { get; set; } - public string Range { get; set; } - public string Context { get; set; } + public string TextDocument { get; set; } = null!; + public string Range { get; set; } = null!; + public string Context { get; set; } = null!; } public class Command { - public string Title { get; set; } - [JsonProperty("command")] public string Name { get; set; } + public string Title { get; set; } = null!; + [JsonProperty("command")] public string Name { get; set; } = null!; } public MediatorTestsRequestHandlerOfTRequestTResponse(ITestOutputHelper testOutputHelper) : base(testOutputHelper) => @@ -43,7 +42,6 @@ public MediatorTestsRequestHandlerOfTRequestTResponse(ITestOutputHelper testOutp public async Task ExecutesHandler() { var codeActionHandler = Substitute.For(); - var mediator = Substitute.For(); var collection = new HandlerCollection(Substitute.For(), new HandlerTypeDescriptorProvider(new [] { typeof(HandlerTypeDescriptorProvider).Assembly, typeof(HandlerResolverTests).Assembly })) { codeActionHandler }; AutoSubstitute.Provide(collection); @@ -53,7 +51,7 @@ public async Task ExecutesHandler() var @params = new CodeActionParams { TextDocument = "TextDocument", Range = "Range", Context = "Context" }; var request = new Request(id, "textDocument/codeAction", JObject.Parse(JsonConvert.SerializeObject(@params))); - var response = await router.RouteRequest(router.GetDescriptors(request), request, CancellationToken.None); + await router.RouteRequest(router.GetDescriptors(request), request, CancellationToken.None); await codeActionHandler.Received(1).Handle(Arg.Any(), Arg.Any()); } diff --git a/test/JsonRpc.Tests/OutputHandlerTests.cs b/test/JsonRpc.Tests/OutputHandlerTests.cs index 45517d3e5..4fc63cddc 100644 --- a/test/JsonRpc.Tests/OutputHandlerTests.cs +++ b/test/JsonRpc.Tests/OutputHandlerTests.cs @@ -121,7 +121,7 @@ public async Task ShouldSerializeErrors() public async Task ShouldFilterMessages() { var pipe = new Pipe(new PipeOptions()); - using var handler = NewHandler(pipe.Writer, _ => _ is RpcError e && e.Id.Equals(2)); + using var handler = NewHandler(pipe.Writer, _ => _ is RpcError e && e.Id!.Equals(2)); var value = new RpcError(1, new ErrorMessage(1, "something", new object())); var value2 = new RpcError(2, new ErrorMessage(1, "something", new object())); diff --git a/test/JsonRpc.Tests/RecursiveResolutionTests.cs b/test/JsonRpc.Tests/RecursiveResolutionTests.cs index 9cc2667a5..8e922f089 100644 --- a/test/JsonRpc.Tests/RecursiveResolutionTests.cs +++ b/test/JsonRpc.Tests/RecursiveResolutionTests.cs @@ -1,5 +1,4 @@ using System; -using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using DryIoc; @@ -10,7 +9,6 @@ using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Testing; using TestingUtils; -using Xunit; using Xunit.Abstractions; namespace JsonRpc.Tests @@ -25,7 +23,7 @@ public RecursiveResolutionTests(ITestOutputHelper testOutputHelper) : base(new J public void Server_Can_Be_Injected_Into_Handler_After_Creation_Using_Registration() { Func a = async () => { - var (client, server) = await Initialize( + var (_, server) = await Initialize( options => { }, options => { } ); @@ -118,6 +116,7 @@ public class ClassRequest : IRequest [Method(nameof(ClassRequest))] class ClassHandler : IJsonRpcRequestHandler where T : IJsonRpcServerFacade { + // ReSharper disable once NotAccessedField.Local private readonly T _jsonRpcServer; public ClassHandler(T jsonRpcServer) @@ -136,6 +135,7 @@ public class InterfaceRequest : IRequest [Method(nameof(InterfaceRequest))] class InterfaceHandler : IJsonRpcRequestHandler where T : IJsonRpcServerFacade { + // ReSharper disable once NotAccessedField.Local private readonly T _jsonRpcServer; public InterfaceHandler(T jsonRpcServer) diff --git a/test/JsonRpc.Tests/RequestRouterTests.cs b/test/JsonRpc.Tests/RequestRouterTests.cs index ff784e57a..38e912a11 100644 --- a/test/JsonRpc.Tests/RequestRouterTests.cs +++ b/test/JsonRpc.Tests/RequestRouterTests.cs @@ -3,7 +3,6 @@ using System.Threading; using System.Threading.Tasks; using DryIoc; -using Microsoft.Extensions.DependencyInjection; using NSubstitute; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Server; diff --git a/test/JsonRpc.Tests/ResponseRouterTests.cs b/test/JsonRpc.Tests/ResponseRouterTests.cs index 1d357e3e1..347007a48 100644 --- a/test/JsonRpc.Tests/ResponseRouterTests.cs +++ b/test/JsonRpc.Tests/ResponseRouterTests.cs @@ -22,10 +22,10 @@ public async Task WorksWithResultType() var router = new ResponseRouter(new Lazy(() => outputHandler), new JsonRpcSerializer(), new HandlerTypeDescriptorProvider(new [] { typeof(HandlerTypeDescriptorProvider).Assembly, typeof(HandlerResolverTests).Assembly })); outputHandler - .When(x => x.Send(Arg.Is(x => x.GetType() == typeof(OutgoingRequest)))) + .When(x => x.Send(Arg.Is(z => z.GetType() == typeof(OutgoingRequest)))) .Do( call => { - router.TryGetRequest((long) call.Arg().Id, out var method, out var tcs); + router.TryGetRequest((long) call.Arg().Id!, out _, out var tcs); tcs.TrySetResult(new JObject()); } ); @@ -33,7 +33,7 @@ public async Task WorksWithResultType() var response = await router.SendRequest(new ItemParams(), CancellationToken.None); var request = outputHandler.ReceivedCalls().Single().GetArguments()[0] as OutgoingRequest; - request.Method.Should().Be("abcd"); + request!.Method.Should().Be("abcd"); response.Should().NotBeNull(); response.Should().BeOfType(); @@ -46,10 +46,10 @@ public async Task WorksWithUnitType() var router = new ResponseRouter(new Lazy(() => outputHandler), new JsonRpcSerializer(), new HandlerTypeDescriptorProvider(new [] { typeof(HandlerTypeDescriptorProvider).Assembly, typeof(HandlerResolverTests).Assembly })); outputHandler - .When(x => x.Send(Arg.Is(x => x.GetType() == typeof(OutgoingRequest)))) + .When(x => x.Send(Arg.Is(z => z.GetType() == typeof(OutgoingRequest)))) .Do( call => { - router.TryGetRequest((long) call.Arg().Id, out var method, out var tcs); + router.TryGetRequest((long) call.Arg().Id!, out _, out var tcs); tcs.SetResult(new JObject()); } ); @@ -57,7 +57,7 @@ public async Task WorksWithUnitType() await router.SendRequest(new UnitParams(), CancellationToken.None); var request = outputHandler.ReceivedCalls().Single().GetArguments()[0] as OutgoingRequest; - request.Method.Should().Be("unit"); + request!.Method.Should().Be("unit"); } [Fact] @@ -69,7 +69,7 @@ public async Task WorksWithNotification() router.SendNotification(new NotificationParams()); var request = outputHandler.ReceivedCalls().Single().GetArguments()[0] as OutgoingNotification; - request.Method.Should().Be("notification"); + request!.Method.Should().Be("notification"); } [Method("abcd")] diff --git a/test/JsonRpc.Tests/Server/ServerShouldThrowCorrectExceptions.cs b/test/JsonRpc.Tests/Server/ServerShouldThrowCorrectExceptions.cs index 39772f0b9..01f8378ab 100644 --- a/test/JsonRpc.Tests/Server/ServerShouldThrowCorrectExceptions.cs +++ b/test/JsonRpc.Tests/Server/ServerShouldThrowCorrectExceptions.cs @@ -17,13 +17,13 @@ public ServerShouldThrowCorrectExceptions(ITestOutputHelper outputHelper) : base private class Data { - public string Value { get; set; } + public string Value { get; set; } = null!; } [Fact] public async Task Should_Throw_Method_Not_Supported() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( clientOptions => { }, serverOptions => { serverOptions.OnRequest("method", async (Data data) => new Data { Value = data.Value }); } ); diff --git a/test/JsonRpc.Tests/Server/SpecificatiosIdTests.cs b/test/JsonRpc.Tests/Server/SpecificatiosIdTests.cs index 0b517d976..0570b48ea 100644 --- a/test/JsonRpc.Tests/Server/SpecificatiosIdTests.cs +++ b/test/JsonRpc.Tests/Server/SpecificatiosIdTests.cs @@ -11,11 +11,11 @@ public class SpecificatiosIdTests { [Theory] [ClassData(typeof(SimpleTestMessages))] - public void ShouldParse_SimpleMessages(string message, Type outputType, object expectedResult) + public void ShouldParse_SimpleMessages(string message, Type outputType, object? expectedResult) { var receiver = new Receiver(); var (requests, _) = receiver.GetRequests(JToken.Parse(message)); - var result = requests.Single().Request; + var result = requests.Single().Request!; result.Id.Should().Be(expectedResult); if (expectedResult != null) @@ -24,7 +24,7 @@ public void ShouldParse_SimpleMessages(string message, Type outputType, object e } } - private class SimpleTestMessages : TheoryData + private class SimpleTestMessages : TheoryData { public SimpleTestMessages() { diff --git a/test/JsonRpc.Tests/ServiceCollectionSupportTests.cs b/test/JsonRpc.Tests/ServiceCollectionSupportTests.cs index d2c5524f9..d05a48218 100644 --- a/test/JsonRpc.Tests/ServiceCollectionSupportTests.cs +++ b/test/JsonRpc.Tests/ServiceCollectionSupportTests.cs @@ -4,7 +4,6 @@ using System.Threading.Tasks; using FluentAssertions; using MediatR; -using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NSubstitute; @@ -91,8 +90,10 @@ public async Task Handlers_Can_Be_Added_From_The_Service_Collection() .WithInput(pipe.Reader) .WithOutput(pipe.Writer) .WithServices( - services => - services.AddJsonRpcHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }) + serviceCollection => + serviceCollection.AddJsonRpcHandler( + new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial } + ) ); } ) @@ -122,8 +123,8 @@ public async Task Handlers_Can_Access_External_Service_Provider() .WithInput(pipe.Reader) .WithOutput(pipe.Writer) .WithServices( - services => - services + serviceCollection => + serviceCollection .AddSingleton(new OutsideService("inside")) .AddJsonRpcHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }) .AddJsonRpcHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }) @@ -160,8 +161,8 @@ public async Task Handlers_Can_Access_External_Service_Provider_And_Access_New_V .WithInput(pipe.Reader) .WithOutput(pipe.Writer) .WithServices( - services => - services + serviceCollection => + serviceCollection .AddSingleton(new OutsideService("inside")) .AddJsonRpcHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }) .AddJsonRpcHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }) @@ -261,7 +262,6 @@ public async Task Should_Register_Private_Classes_With_Dry_Ioc() { var server = await JsonRpcServer.From( options => { - var pipe = new Pipe(); options .WithInput(pipe.Reader) @@ -319,7 +319,6 @@ private class OutsideService internal class TestClass { - } internal class InternalTestClass : TestClass diff --git a/test/JsonRpc.Tests/TestLanguageServerRegistry.cs b/test/JsonRpc.Tests/TestLanguageServerRegistry.cs index f38b96755..d6be30d3c 100644 --- a/test/JsonRpc.Tests/TestLanguageServerRegistry.cs +++ b/test/JsonRpc.Tests/TestLanguageServerRegistry.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Composition; using OmniSharp.Extensions.JsonRpc; namespace JsonRpc.Tests @@ -21,7 +20,7 @@ public override IJsonRpcServerRegistry AddHandler(string method, IJsonRpcHandler public override IJsonRpcServerRegistry AddHandler(IJsonRpcHandler handler, JsonRpcHandlerOptions? options = null) => throw new NotImplementedException(); - public override IJsonRpcServerRegistry AddHandler(JsonRpcHandlerOptions options) => throw new NotImplementedException(); + public override IJsonRpcServerRegistry AddHandler(JsonRpcHandlerOptions? options = null) => throw new NotImplementedException(); public override IJsonRpcServerRegistry AddHandler(string method, JsonRpcHandlerOptions? options = null) => throw new NotImplementedException(); diff --git a/test/Lsp.Tests/Capabilities/Client/CompletionItemCapabilityTests.cs b/test/Lsp.Tests/Capabilities/Client/CompletionItemCapabilityTests.cs index 101668cdb..43f269d0d 100644 --- a/test/Lsp.Tests/Capabilities/Client/CompletionItemCapabilityTests.cs +++ b/test/Lsp.Tests/Capabilities/Client/CompletionItemCapabilityTests.cs @@ -30,7 +30,7 @@ public void TagSupportTrue() var deresult = new Serializer(ClientVersion.Lsp3).DeserializeObject("{\"tagSupport\":true}"); deresult.Should().BeEquivalentTo( new CompletionItemCapabilityOptions { - TagSupport = new Supports(true) + TagSupport = new Supports(true) } ); } @@ -40,7 +40,7 @@ public void TagSupportObject() { var deresult = new Serializer(ClientVersion.Lsp3).DeserializeObject("{\"tagSupport\":{\"valueSet\": [1]}}"); deresult.TagSupport.IsSupported.Should().Be(true); - deresult.TagSupport.Value.ValueSet.Should().Contain(CompletionItemTag.Deprecated); + deresult.TagSupport.Value!.ValueSet.Should().Contain(CompletionItemTag.Deprecated); } } } diff --git a/test/Lsp.Tests/Capabilities/Client/PublishDiagnosticsCapabilityTests.cs b/test/Lsp.Tests/Capabilities/Client/PublishDiagnosticsCapabilityTests.cs index c3747bd95..e76faee07 100644 --- a/test/Lsp.Tests/Capabilities/Client/PublishDiagnosticsCapabilityTests.cs +++ b/test/Lsp.Tests/Capabilities/Client/PublishDiagnosticsCapabilityTests.cs @@ -15,7 +15,7 @@ public void TagSupportTrue() var deresult = new Serializer(ClientVersion.Lsp3).DeserializeObject("{\"tagSupport\":true}"); deresult.Should().BeEquivalentTo( new PublishDiagnosticsCapability { - TagSupport = new Supports(true) + TagSupport = new Supports(true) } ); } @@ -25,7 +25,7 @@ public void TagSupportObject() { var deresult = new Serializer(ClientVersion.Lsp3).DeserializeObject("{\"tagSupport\":{\"valueSet\": [2,1]}}"); deresult.TagSupport.IsSupported.Should().Be(true); - deresult.TagSupport.Value.ValueSet.Should().ContainInOrder(DiagnosticTag.Deprecated, DiagnosticTag.Unnecessary); + deresult.TagSupport.Value!.ValueSet.Should().ContainInOrder(DiagnosticTag.Deprecated, DiagnosticTag.Unnecessary); } } } diff --git a/test/Lsp.Tests/Capabilities/Server/CodeLensOptionsTests.cs b/test/Lsp.Tests/Capabilities/Server/CodeLensOptionsTests.cs index 699a540af..427a5b710 100644 --- a/test/Lsp.Tests/Capabilities/Server/CodeLensOptionsTests.cs +++ b/test/Lsp.Tests/Capabilities/Server/CodeLensOptionsTests.cs @@ -2,7 +2,6 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; -using OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities; using Xunit; namespace Lsp.Tests.Capabilities.Server diff --git a/test/Lsp.Tests/Capabilities/Server/CompletionOptionsTests.cs b/test/Lsp.Tests/Capabilities/Server/CompletionOptionsTests.cs index 4561db2a2..5468ce7aa 100644 --- a/test/Lsp.Tests/Capabilities/Server/CompletionOptionsTests.cs +++ b/test/Lsp.Tests/Capabilities/Server/CompletionOptionsTests.cs @@ -2,7 +2,6 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; -using OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities; using Xunit; namespace Lsp.Tests.Capabilities.Server diff --git a/test/Lsp.Tests/Capabilities/Server/DocumentLinkOptionsTests.cs b/test/Lsp.Tests/Capabilities/Server/DocumentLinkOptionsTests.cs index e794e5981..b17df3637 100644 --- a/test/Lsp.Tests/Capabilities/Server/DocumentLinkOptionsTests.cs +++ b/test/Lsp.Tests/Capabilities/Server/DocumentLinkOptionsTests.cs @@ -2,7 +2,6 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; -using OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities; using Xunit; namespace Lsp.Tests.Capabilities.Server diff --git a/test/Lsp.Tests/Capabilities/Server/DocumentOnTypeFormattingOptionsTests.cs b/test/Lsp.Tests/Capabilities/Server/DocumentOnTypeFormattingOptionsTests.cs index 3212b117a..507209746 100644 --- a/test/Lsp.Tests/Capabilities/Server/DocumentOnTypeFormattingOptionsTests.cs +++ b/test/Lsp.Tests/Capabilities/Server/DocumentOnTypeFormattingOptionsTests.cs @@ -3,7 +3,6 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; -using OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities; using Xunit; namespace Lsp.Tests.Capabilities.Server diff --git a/test/Lsp.Tests/Capabilities/Server/ExecuteCommandOptionsTests.cs b/test/Lsp.Tests/Capabilities/Server/ExecuteCommandOptionsTests.cs index 90ccf221c..a68cc7b68 100644 --- a/test/Lsp.Tests/Capabilities/Server/ExecuteCommandOptionsTests.cs +++ b/test/Lsp.Tests/Capabilities/Server/ExecuteCommandOptionsTests.cs @@ -2,7 +2,6 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; -using OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities; using Xunit; namespace Lsp.Tests.Capabilities.Server diff --git a/test/Lsp.Tests/Capabilities/Server/SignatureHelpOptionsTests.cs b/test/Lsp.Tests/Capabilities/Server/SignatureHelpOptionsTests.cs index 1957c46f0..9ae6e01a3 100644 --- a/test/Lsp.Tests/Capabilities/Server/SignatureHelpOptionsTests.cs +++ b/test/Lsp.Tests/Capabilities/Server/SignatureHelpOptionsTests.cs @@ -2,7 +2,6 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; -using OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities; using Xunit; namespace Lsp.Tests.Capabilities.Server diff --git a/test/Lsp.Tests/ClientCapabilityProviderFixture.cs b/test/Lsp.Tests/ClientCapabilityProviderFixture.cs index f15d78bdb..10b6815d6 100644 --- a/test/Lsp.Tests/ClientCapabilityProviderFixture.cs +++ b/test/Lsp.Tests/ClientCapabilityProviderFixture.cs @@ -1,5 +1,4 @@ using DryIoc; -using Microsoft.Extensions.DependencyInjection; using NSubstitute; using OmniSharp.Extensions.LanguageServer.Client; using OmniSharp.Extensions.LanguageServer.Protocol; diff --git a/test/Lsp.Tests/ClientCapabilityProviderTests.cs b/test/Lsp.Tests/ClientCapabilityProviderTests.cs index a695dc9db..2426a5c43 100644 --- a/test/Lsp.Tests/ClientCapabilityProviderTests.cs +++ b/test/Lsp.Tests/ClientCapabilityProviderTests.cs @@ -4,7 +4,6 @@ using System.Reflection; using DryIoc; using FluentAssertions; -using Microsoft.Extensions.DependencyInjection; using NSubstitute; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Client; @@ -12,7 +11,6 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Shared; using OmniSharp.Extensions.LanguageServer.Server; using OmniSharp.Extensions.LanguageServer.Shared; @@ -47,7 +45,7 @@ public void Should_AllowSupportedCapabilities(IJsonRpcHandler handler, object in HasHandler(provider, instance).Should().BeTrue(); } - public static IEnumerable AllowSupportedCapabilities() => + public static IEnumerable AllowSupportedCapabilities() => GetItems( Capabilities, type => { var handlerTypes = GetHandlerTypes(type); @@ -78,7 +76,7 @@ public void Should_AllowUnsupportedCapabilities(IJsonRpcHandler handler, object HasHandler(provider, instance).Should().BeTrue(); } - public static IEnumerable AllowUnsupportedCapabilities() => + public static IEnumerable AllowUnsupportedCapabilities() => GetItems( Capabilities, type => { var handlerTypes = GetHandlerTypes(type); @@ -103,7 +101,7 @@ public void Should_AllowNullSupportedCapabilities(IJsonRpcHandler handler, objec HasHandler(provider, instance).Should().BeTrue(); } - public static IEnumerable AllowNullSupportsCapabilities() => + public static IEnumerable AllowNullSupportsCapabilities() => GetItems( Capabilities, type => { var handlerTypes = GetHandlerTypes(type); @@ -129,7 +127,7 @@ public void Should_DisallowDynamicSupportedCapabilities(IJsonRpcHandler handler, HasHandler(provider, instance).Should().BeFalse(); } - public static IEnumerable DisallowDynamicSupportsCapabilities() => + public static IEnumerable DisallowDynamicSupportsCapabilities() => GetItems( Capabilities, type => { var handlerTypes = GetHandlerTypes(type); @@ -158,12 +156,12 @@ public void Should_Handle_Mixed_Capabilities() var provider = new ClientCapabilityProvider(collection, true); var capabilities = new ClientCapabilities { TextDocument = new TextDocumentClientCapabilities { - CodeAction = new Supports( + CodeAction = new Supports( true, new CodeActionCapability { DynamicRegistration = false, } ), - TypeDefinition = new Supports( + TypeDefinition = new Supports( true, new TypeDefinitionCapability { DynamicRegistration = true, } @@ -234,15 +232,15 @@ public void GH162_TextDocumentSync_Should_Work_With_WillSave_Or_WillSaveWaitUnti private static bool HasHandler(ClientCapabilityProvider provider, object instance) => (bool) typeof(ClientCapabilityProviderTests).GetTypeInfo() - .GetMethod(nameof(GenericHasHandler), BindingFlags.Static | BindingFlags.NonPublic) + .GetMethod(nameof(GenericHasHandler), BindingFlags.Static | BindingFlags.NonPublic)! .MakeGenericMethod(instance.GetType().GetTypeInfo().GetGenericArguments()[0]) - .Invoke(null, new[] { provider, instance }); + .Invoke(null, new[] { provider, instance })!; private static bool GenericHasHandler(ClientCapabilityProvider provider, Supports supports) where T : DynamicCapability, ConnectedCapability => provider.HasStaticHandler(supports); - private static IEnumerable GetItems(IEnumerable types, Func> func) => types.Select(x => func(x).ToArray()); + private static IEnumerable GetItems(IEnumerable types, Func> func) => types.Select(x => func(x).ToArray()); private static IEnumerable GetHandlerTypes(Type type) => type.GetTypeInfo().ImplementedInterfaces diff --git a/test/Lsp.Tests/CodeActionKindTests.cs b/test/Lsp.Tests/CodeActionKindTests.cs index 6c3643bc2..48c0c08e8 100644 --- a/test/Lsp.Tests/CodeActionKindTests.cs +++ b/test/Lsp.Tests/CodeActionKindTests.cs @@ -30,7 +30,7 @@ public void CustomBehavior_When_SymbolKind_Defined_By_Client() serializer.SetClientCapabilities( ClientVersion.Lsp3, new ClientCapabilities { TextDocument = new TextDocumentClientCapabilities { - CodeAction = new Supports( + CodeAction = new Supports( true, new CodeActionCapability { DynamicRegistration = true, CodeActionLiteralSupport = new CodeActionLiteralSupportOptions { diff --git a/test/Lsp.Tests/CompletionItemKindTests.cs b/test/Lsp.Tests/CompletionItemKindTests.cs index c81992e81..6a13c4d8d 100644 --- a/test/Lsp.Tests/CompletionItemKindTests.cs +++ b/test/Lsp.Tests/CompletionItemKindTests.cs @@ -44,7 +44,7 @@ public void CustomBehavior_When_CompletionItemKinds_Defined_By_Client() serializer.SetClientCapabilities( ClientVersion.Lsp3, new ClientCapabilities { TextDocument = new TextDocumentClientCapabilities { - Completion = new Supports( + Completion = new Supports( true, new CompletionCapability { DynamicRegistration = true, CompletionItemKind = new CompletionItemKindCapabilityOptions { @@ -73,7 +73,7 @@ public void CustomBehavior_When_CompletionItemTags_Defined_By_Client() serializer.SetClientCapabilities( ClientVersion.Lsp3, new ClientCapabilities { TextDocument = new TextDocumentClientCapabilities { - Completion = new Supports( + Completion = new Supports( true, new CompletionCapability { DynamicRegistration = true, CompletionItem = new CompletionItemCapabilityOptions { diff --git a/test/Lsp.Tests/DiagnosticKindTests.cs b/test/Lsp.Tests/DiagnosticKindTests.cs index 45cfb16bb..058e1216a 100644 --- a/test/Lsp.Tests/DiagnosticKindTests.cs +++ b/test/Lsp.Tests/DiagnosticKindTests.cs @@ -30,7 +30,7 @@ public void CustomBehavior_When_DiagnosticTag_Defined_By_Client() serializer.SetClientCapabilities( ClientVersion.Lsp3, new ClientCapabilities { TextDocument = new TextDocumentClientCapabilities { - PublishDiagnostics = new Supports( + PublishDiagnostics = new Supports( true, new PublishDiagnosticsCapability { TagSupport = new PublishDiagnosticsTagSupportCapabilityOptions { ValueSet = new Container() diff --git a/test/Lsp.Tests/DocumentSymbolKindTests.cs b/test/Lsp.Tests/DocumentSymbolKindTests.cs index 4e5f13d21..b270ffc8b 100644 --- a/test/Lsp.Tests/DocumentSymbolKindTests.cs +++ b/test/Lsp.Tests/DocumentSymbolKindTests.cs @@ -46,7 +46,7 @@ public void CustomBehavior_When_SymbolKind_Defined_By_Client() serializer.SetClientCapabilities( ClientVersion.Lsp3, new ClientCapabilities { TextDocument = new TextDocumentClientCapabilities { - DocumentSymbol = new Supports( + DocumentSymbol = new Supports( true, new DocumentSymbolCapability { DynamicRegistration = true, SymbolKind = new SymbolKindCapabilityOptions { @@ -75,7 +75,7 @@ public void CustomBehavior_When_SymbolTag_Defined_By_Client() serializer.SetClientCapabilities( ClientVersion.Lsp3, new ClientCapabilities { TextDocument = new TextDocumentClientCapabilities { - DocumentSymbol = new Supports( + DocumentSymbol = new Supports( true, new DocumentSymbolCapability { DynamicRegistration = true, TagSupport = new TagSupportCapabilityOptions { diff --git a/test/Lsp.Tests/Fixture.cs b/test/Lsp.Tests/Fixture.cs index fc37f0036..08f5255db 100644 --- a/test/Lsp.Tests/Fixture.cs +++ b/test/Lsp.Tests/Fixture.cs @@ -13,14 +13,14 @@ internal static class Fixture { public static string SerializeObject(object value, ClientVersion version = ClientVersion.Lsp3) => SerializeObject(value, null, null, version); - public static string SerializeObject(object value, Type type, JsonSerializerSettings settings, ClientVersion version = ClientVersion.Lsp3) + public static string SerializeObject(object value, Type? type, JsonSerializerSettings? settings, ClientVersion version = ClientVersion.Lsp3) { var jsonSerializer = new Serializer(version); return SerializeObjectInternal(value, type, jsonSerializer); } - private static string SerializeObjectInternal(object value, Type type, ISerializer serializer) + private static string SerializeObjectInternal(object value, Type? type, ISerializer serializer) { var sb = new StringBuilder(256); var sw = new StringWriter(sb, CultureInfo.InvariantCulture); @@ -32,7 +32,7 @@ private static string SerializeObjectInternal(object value, Type type, ISerializ serializer.JsonSerializer.Serialize(jsonWriter, value, type); } - return sw.ToString()?.Replace("\r\n", "\n")?.TrimEnd(); //?.Replace("\n", "\r\n"); + return sw.ToString().Replace("\r\n", "\n").TrimEnd(); //?.Replace("\n", "\r\n"); } } } diff --git a/test/Lsp.Tests/FluentAssertionsExtensions.cs b/test/Lsp.Tests/FluentAssertionsExtensions.cs index d342bd7c8..befb2cd27 100644 --- a/test/Lsp.Tests/FluentAssertionsExtensions.cs +++ b/test/Lsp.Tests/FluentAssertionsExtensions.cs @@ -9,7 +9,7 @@ namespace Lsp.Tests { public static class FluentAssertionsExtensions { - public static EquivalencyAssertionOptions ConfigureForSupports(this EquivalencyAssertionOptions options, ILogger logger = null) => + public static EquivalencyAssertionOptions ConfigureForSupports(this EquivalencyAssertionOptions options, ILogger? logger = null) => options .WithTracing(new TraceWriter(logger ?? NullLogger.Instance)) .ComparingByMembers>() diff --git a/test/Lsp.Tests/FoundationTests.cs b/test/Lsp.Tests/FoundationTests.cs index 962269adb..059ef0cc4 100644 --- a/test/Lsp.Tests/FoundationTests.cs +++ b/test/Lsp.Tests/FoundationTests.cs @@ -128,9 +128,9 @@ public ActionDelegate(string name, Action method) public void Debugger_Display_Should_Not_Throw(Type type) { var instance = Activator.CreateInstance(type); - var property = type.GetProperty("DebuggerDisplay", BindingFlags.NonPublic | BindingFlags.Instance); - Func a1 = () => property.GetValue(instance) as string; - Func a2 = () => instance.ToString(); + var property = type.GetProperty("DebuggerDisplay", BindingFlags.NonPublic | BindingFlags.Instance)!; + Func a1 = () => (property.GetValue(instance) as string)!; + Func a2 = () => instance!.ToString()!; a1.Should().NotThrow().And.NotBeNull(); a2.Should().NotThrow().And.NotBeNull(); @@ -142,8 +142,8 @@ public DebuggerDisplayTypes() { foreach (var item in typeof(DocumentSymbol).Assembly.ExportedTypes .Where(z => !z.IsGenericTypeDefinition) - .Where(z => z.GetCustomAttributes().Any(z => z.Value.StartsWith("{DebuggerDisplay"))) - .Where(z => z.GetConstructors().Any(z => z.GetParameters().Length == 0)) + .Where(z => z.GetCustomAttributes().Any(x => x.Value.StartsWith("{DebuggerDisplay"))) + .Where(z => z.GetConstructors().Any(x => x.GetParameters().Length == 0)) ) { Add(item); @@ -169,8 +169,8 @@ public void HandlersShouldMatchParamsMethodAttribute(Type type) { var paramsType = HandlerTypeDescriptorHelper.GetHandlerInterface(type).GetGenericArguments()[0]; - var lhs = MethodAttribute.From(type); - var rhs = MethodAttribute.From(paramsType); + var lhs = MethodAttribute.From(type)!; + var rhs = MethodAttribute.From(paramsType)!; lhs.Method.Should().Be(rhs.Method, $"{type.FullName} method does not match {paramsType.FullName}"); lhs.Direction.Should().Be(rhs.Direction, $"{type.FullName} direction does not match {paramsType.FullName}"); } @@ -179,7 +179,7 @@ public void HandlersShouldMatchParamsMethodAttribute(Type type) [ClassData(typeof(RegistrationConverters))] public void Registration_Converters_Should_Have_THe_Same_Properties(Type type) { - var types = type.BaseType.GetGenericArguments(); + var types = type.BaseType?.GetGenericArguments() ?? Array.Empty(); var source = types[0].GetProperties().Select(z => z.Name); var destination = types[1].GetProperties().Select(z => z.Name).Except(new [] { "Id" }); source.Should().Contain(destination); @@ -211,7 +211,7 @@ public void HandlersShouldAbstractClass(ILspHandlerTypeDescriptor descriptor) { _logger.LogInformation("Delegating Handler: {Type}", delegatingHandler); delegatingHandler.DeclaringType.Should().NotBeNull(); - delegatingHandler.DeclaringType.GetMethods(BindingFlags.Public | BindingFlags.Static).Any(z => z.Name.StartsWith("On")).Should() + delegatingHandler.DeclaringType!.GetMethods(BindingFlags.Public | BindingFlags.Static).Any(z => z.Name.StartsWith("On")).Should() .BeTrue($"{descriptor.HandlerType.FullName} is missing delegating extension method"); } } @@ -363,28 +363,22 @@ Func ForAnyParameter(Func m) return info => info.GetParameters().Any(m); } - Func ForParameter(int index, Func m) - { - return info => m(info.GetParameters()[index]); - } - var containsCancellationToken = ForAnyParameter(info => info.ParameterType.GetGenericArguments().Reverse().Take(2).Any(x => x == typeof(CancellationToken))); - var returnType = descriptor.HasResponseType ? typeof(Task<>).MakeGenericType(descriptor.ResponseType) : typeof(Task); + var returnType = descriptor.HasResponseType ? typeof(Task<>).MakeGenericType(descriptor.ResponseType!) : typeof(Task); var returns = ForAnyParameter(info => info.ParameterType.GetGenericArguments().LastOrDefault() == returnType); var isAction = ForAnyParameter(info => info.ParameterType.Name.StartsWith(nameof(Action))); var isFunc = ForAnyParameter(info => info.ParameterType.Name.StartsWith("Func")); var takesParameter = ForAnyParameter(info => info.ParameterType.GetGenericArguments().FirstOrDefault() == descriptor.ParamsType); var takesCapability = ForAnyParameter(info => info.ParameterType.GetGenericArguments().Skip(1).FirstOrDefault() == descriptor.CapabilityType); - var returnsTask = ForAnyParameter(info => info.ParameterType.GetGenericArguments().LastOrDefault() == typeof(Task)); if (descriptor.IsRequest && TypeHandlerExtensionData.HandlersToSkip.All(z => descriptor.HandlerType != z)) { - matcher.Match($"Func<{descriptor.ParamsType.Name}, {returnType.Name}>", isFunc, takesParameter, returns); + matcher.Match($"Func<{descriptor.ParamsType!.Name}, {returnType.Name}>", isFunc, takesParameter, returns); matcher.Match($"Func<{descriptor.ParamsType.Name}, CancellationToken, {returnType.Name}>", isFunc, takesParameter, containsCancellationToken, returns); if (descriptor.HasCapability) { matcher.Match( - $"Func<{descriptor.ParamsType.Name}, {descriptor.CapabilityType.Name}, CancellationToken, {returnType.Name}>", isFunc, takesParameter, + $"Func<{descriptor.ParamsType.Name}, {descriptor.CapabilityType!.Name}, CancellationToken, {returnType.Name}>", isFunc, takesParameter, takesCapability, containsCancellationToken, returns ); } @@ -394,10 +388,10 @@ Func ForParameter(int index, Func m) var capability = ForAnyParameter(info => info.ParameterType.GetGenericArguments().Skip(2).FirstOrDefault() == descriptor.CapabilityType); var observesPartialResultType = ForAnyParameter( info => - info.ParameterType.GetGenericArguments().Skip(1).FirstOrDefault() == typeof(IObserver<>).MakeGenericType(descriptor.PartialItemType) + info.ParameterType.GetGenericArguments().Skip(1).FirstOrDefault() == typeof(IObserver<>).MakeGenericType(descriptor.PartialItemType!) ); - matcher.Match($"Action<{descriptor.ParamsType.Name}, IObserver<{descriptor.PartialItemType.Name}>>", isAction, takesParameter, observesPartialResultType); + matcher.Match($"Action<{descriptor.ParamsType.Name}, IObserver<{descriptor.PartialItemType!.Name}>>", isAction, takesParameter, observesPartialResultType); // matcher.Match($"Func<{descriptor.ParamsType.Name}, IObserver<{descriptor.PartialItemType.Name}>, Task>", isFunc, takesParameter, observesPartialResultType, returnsTask); matcher.Match( $"Action<{descriptor.ParamsType.Name}, IObserver<{descriptor.PartialItemType.Name}>, CancellationToken>", isAction, takesParameter, @@ -408,7 +402,7 @@ Func ForParameter(int index, Func m) if (descriptor.HasCapability) { matcher.Match( - $"Action<{descriptor.ParamsType.Name}, IObserver<{descriptor.PartialItemType.Name}>, {descriptor.CapabilityType.Name}, CancellationToken>", + $"Action<{descriptor.ParamsType.Name}, IObserver<{descriptor.PartialItemType.Name}>, {descriptor.CapabilityType!.Name}, CancellationToken>", isAction, takesParameter, capability, containsCancellationToken, observesPartialResultType @@ -427,11 +421,11 @@ Func ForParameter(int index, Func m) var observesPartialResultType = ForAnyParameter( info => info.ParameterType.GetGenericArguments().Skip(1).FirstOrDefault() == - typeof(IObserver<>).MakeGenericType(typeof(IEnumerable<>).MakeGenericType(descriptor.PartialItemsType)) + typeof(IObserver<>).MakeGenericType(typeof(IEnumerable<>).MakeGenericType(descriptor.PartialItemsType!)) ); matcher.Match( - $"Action<{descriptor.ParamsType.Name}, IObserver>>", isAction, takesParameter, + $"Action<{descriptor.ParamsType.Name}, IObserver>>", isAction, takesParameter, observesPartialResultType ); // matcher.Match($"Func<{descriptor.ParamsType.Name}, IObserver>, Task>", isFunc, takesParameter, @@ -447,7 +441,7 @@ Func ForParameter(int index, Func m) if (descriptor.HasCapability) { matcher.Match( - $"Action<{descriptor.ParamsType.Name}, IObserver<{descriptor.PartialItemsType.Name}>, {descriptor.CapabilityType.Name}, CancellationToken>", + $"Action<{descriptor.ParamsType.Name}, IObserver<{descriptor.PartialItemsType.Name}>, {descriptor.CapabilityType!.Name}, CancellationToken>", isAction, takesParameter, capability, containsCancellationToken, observesPartialResultType @@ -463,14 +457,14 @@ Func ForParameter(int index, Func m) if (descriptor.IsNotification) { - matcher.Match($"Func<{descriptor.ParamsType.Name}, {returnType.Name}>", isFunc, takesParameter, returns); + matcher.Match($"Func<{descriptor.ParamsType!.Name}, {returnType.Name}>", isFunc, takesParameter, returns); matcher.Match($"Func<{descriptor.ParamsType.Name}, CancellationToken, {returnType.Name}>", isFunc, takesParameter, containsCancellationToken, returns); matcher.Match($"Action<{descriptor.ParamsType.Name}>", isAction, takesParameter); matcher.Match($"Action<{descriptor.ParamsType.Name}, CancellationToken>", isAction, takesParameter, containsCancellationToken); if (descriptor.HasCapability) { matcher.Match( - $"Func<{descriptor.ParamsType.Name}, {descriptor.CapabilityType.Name}, CancellationToken, {returnType.Name}>", isFunc, takesParameter, + $"Func<{descriptor.ParamsType.Name}, {descriptor.CapabilityType!.Name}, CancellationToken, {returnType.Name}>", isFunc, takesParameter, takesCapability, containsCancellationToken, returns ); matcher.Match( @@ -483,7 +477,7 @@ Func ForParameter(int index, Func m) { var matcher = new MethodMatcher(sendMethodRegistries, descriptor, extensionClass); Func containsCancellationToken = info => info.GetParameters().Reverse().Take(2).Any(x => x.ParameterType == typeof(CancellationToken)); - var returnType = descriptor.HasResponseType ? typeof(Task<>).MakeGenericType(descriptor.ResponseType) : typeof(Task); + var returnType = descriptor.HasResponseType ? typeof(Task<>).MakeGenericType(descriptor.ResponseType!) : typeof(Task); Func returns = info => info.ReturnType == returnType; Func isAction = info => info.ReturnType.Name == "Void"; Func takesParameter = info => info.GetParameters().Skip(1).Any(z => z.ParameterType == descriptor.ParamsType); @@ -491,29 +485,29 @@ Func ForParameter(int index, Func m) if (descriptor.IsRequest && descriptor.HasPartialItems) { Func partialReturnType = info => - typeof(IRequestProgressObservable<,>).MakeGenericType(typeof(IEnumerable<>).MakeGenericType(descriptor.PartialItemsType), descriptor.ResponseType) + typeof(IRequestProgressObservable<,>).MakeGenericType(typeof(IEnumerable<>).MakeGenericType(descriptor.PartialItemsType!), descriptor.ResponseType!) .IsAssignableFrom(info.ReturnType); matcher.Match( - $"Func<{descriptor.ParamsType.Name}, CancellationToken, IProgressObservable, {descriptor.ResponseType.Name}>>", + $"Func<{descriptor.ParamsType!.Name}, CancellationToken, IProgressObservable, {descriptor.ResponseType!.Name}>>", takesParameter, containsCancellationToken, partialReturnType ); } else if (descriptor.IsRequest && descriptor.HasPartialItem) { Func partialReturnType = info => - typeof(IRequestProgressObservable<,>).MakeGenericType(descriptor.PartialItemType, descriptor.ResponseType).IsAssignableFrom(info.ReturnType); + typeof(IRequestProgressObservable<,>).MakeGenericType(descriptor.PartialItemType!, descriptor.ResponseType!).IsAssignableFrom(info.ReturnType); matcher.Match( - $"Func<{descriptor.ParamsType.Name}, CancellationToken, IProgressObservable<{descriptor.PartialItemType.Name}, {descriptor.ResponseType.Name}>>", + $"Func<{descriptor.ParamsType!.Name}, CancellationToken, IProgressObservable<{descriptor.PartialItemType!.Name}, {descriptor.ResponseType!.Name}>>", takesParameter, containsCancellationToken, partialReturnType ); } else if (descriptor.IsRequest) { - matcher.Match($"Func<{descriptor.ParamsType.Name}, CancellationToken, {returnType.Name}>", takesParameter, containsCancellationToken, returns); + matcher.Match($"Func<{descriptor.ParamsType!.Name}, CancellationToken, {returnType.Name}>", takesParameter, containsCancellationToken, returns); } else if (descriptor.IsNotification) { - matcher.Match($"Action<{descriptor.ParamsType.Name}>", isAction, takesParameter); + matcher.Match($"Action<{descriptor.ParamsType!.Name}>", isAction, takesParameter); } } } @@ -524,11 +518,11 @@ private class MethodMatcher private readonly IEnumerable _registries; private readonly ILspHandlerTypeDescriptor _descriptor; private readonly Type _extensionClass; - private readonly string _methodName; + private readonly string? _methodName; public MethodMatcher( IEnumerable registries, - ILspHandlerTypeDescriptor descriptor, Type extensionClass, string methodName = null + ILspHandlerTypeDescriptor descriptor, Type extensionClass, string? methodName = null ) { _registries = registries; @@ -616,7 +610,7 @@ public ParamsShouldHaveMethodAttributeData() { foreach (var type in typeof(CompletionParams).Assembly.ExportedTypes.Where( z => - z.IsClass && !z.IsAbstract && z.GetInterfaces().Any(z => z.IsGenericType && typeof(IRequest<>).IsAssignableFrom(z.GetGenericTypeDefinition())) + z.IsClass && !z.IsAbstract && z.GetInterfaces().Any(x => x.IsGenericType && typeof(IRequest<>).IsAssignableFrom(x.GetGenericTypeDefinition())) )) { Add(type); @@ -673,7 +667,7 @@ public TypeHandlerData() ) { if (type.IsGenericTypeDefinition && !MethodAttribute.AllFrom(type).Any()) continue; - Add(handlerTypeDescriptorProvider.GetHandlerTypeDescriptor(type)); + Add(handlerTypeDescriptorProvider.GetHandlerTypeDescriptor(type)!); } } } @@ -731,7 +725,7 @@ public TypeHandlerExtensionData() private static string SpecialCasedHandlerName(IHandlerTypeDescriptor descriptor) => new Regex(@"(\w+(?:\`\d)?)$") .Replace( - descriptor.HandlerType.Name ?? string.Empty, + descriptor.HandlerType.Name, descriptor.HandlerType.Name.Substring(1, descriptor.HandlerType.Name.IndexOf("Handler", StringComparison.Ordinal) - 1) ); @@ -739,7 +733,7 @@ private static Type GetExtensionClass(IHandlerTypeDescriptor descriptor) { var name = GetExtensionClassName(descriptor); return descriptor.HandlerType.Assembly.GetExportedTypes() - .FirstOrDefault(z => z.IsClass && z.IsAbstract && ( z.Name == name || z.Name == name + "Base" )); + .FirstOrDefault(z => z.IsClass && z.IsAbstract && ( z.Name == name || z.Name == name + "Base" ))!; } private static string GetOnMethodName(IHandlerTypeDescriptor descriptor) => "On" + SpecialCasedHandlerName(descriptor); diff --git a/test/Lsp.Tests/HandlerResolverTests.cs b/test/Lsp.Tests/HandlerResolverTests.cs index f370bbce2..a62ea0c59 100644 --- a/test/Lsp.Tests/HandlerResolverTests.cs +++ b/test/Lsp.Tests/HandlerResolverTests.cs @@ -4,7 +4,6 @@ using DryIoc; using FluentAssertions; using MediatR; -using Microsoft.Extensions.DependencyInjection; using NSubstitute; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Client; @@ -225,7 +224,7 @@ public void Should_DealWithClassesThatImplementMultipleHandlers_BySettingKeyAcco var handler = new SharedHandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), Substitute.For(), new LspHandlerTypeDescriptorProvider(new [] { typeof(FoundationTests).Assembly, typeof(LanguageServer).Assembly, typeof(LanguageClient).Assembly, typeof(IRegistrationManager).Assembly, typeof(LspRequestRouter).Assembly })); - handler.Add(codeLensHandler as IJsonRpcHandler); + handler.Add((codeLensHandler as IJsonRpcHandler)!); var descriptor = handler.OfType().Select(x => x.Key); descriptor.Should().BeEquivalentTo("[foo]", "[foo]"); diff --git a/test/Lsp.Tests/Integration/ConnectionAndDisconnectionTests.cs b/test/Lsp.Tests/Integration/ConnectionAndDisconnectionTests.cs index 9239e8f13..3e70c133b 100644 --- a/test/Lsp.Tests/Integration/ConnectionAndDisconnectionTests.cs +++ b/test/Lsp.Tests/Integration/ConnectionAndDisconnectionTests.cs @@ -9,6 +9,7 @@ using OmniSharp.Extensions.LanguageServer.Server; using Xunit; using Xunit.Abstractions; +#pragma warning disable CS0162 namespace Lsp.Tests.Integration { @@ -23,7 +24,7 @@ public ConnectionAndDisconnectionTests(ITestOutputHelper outputHelper) : base( [Fact] public async Task Server_Should_Stay_Alive_When_Requests_Throw_An_Exception() { - var (client, server) = await Initialize(ConfigureClient, ConfigureServer); + var (client, _) = await Initialize(ConfigureClient, ConfigureServer); var result = await client.SendRequest("keepalive").Returning(CancellationToken); result.Should().BeTrue(); @@ -38,7 +39,7 @@ public async Task Server_Should_Stay_Alive_When_Requests_Throw_An_Exception() [Fact] public async Task Client_Should_Stay_Alive_When_Requests_Throw_An_Exception() { - var (client, server) = await Initialize(ConfigureClient, ConfigureServer); + var (_, server) = await Initialize(ConfigureClient, ConfigureServer); var result = await server.SendRequest("keepalive").Returning(CancellationToken); result.Should().BeTrue(); @@ -53,7 +54,7 @@ public async Task Client_Should_Stay_Alive_When_Requests_Throw_An_Exception() [Fact] public async Task Server_Should_Support_Links() { - var (client, server) = await Initialize(ConfigureClient, ConfigureServer); + var (client, _) = await Initialize(ConfigureClient, ConfigureServer); var result = await client.SendRequest("ka").Returning(CancellationToken); result.Should().BeTrue(); @@ -68,7 +69,7 @@ public async Task Server_Should_Support_Links() [Fact] public async Task Client_Should_Support_Links() { - var (client, server) = await Initialize(ConfigureClient, ConfigureServer); + var (_, server) = await Initialize(ConfigureClient, ConfigureServer); var result = await server.SendRequest("ka").Returning(CancellationToken); result.Should().BeTrue(); diff --git a/test/Lsp.Tests/Integration/DynamicRegistrationTests.cs b/test/Lsp.Tests/Integration/DynamicRegistrationTests.cs index 901cf6296..5712480a8 100644 --- a/test/Lsp.Tests/Integration/DynamicRegistrationTests.cs +++ b/test/Lsp.Tests/Integration/DynamicRegistrationTests.cs @@ -1,9 +1,6 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Reactive; using System.Reactive.Linq; -using System.Reactive.Threading.Tasks; using System.Threading.Tasks; using FluentAssertions; using Lsp.Tests.Integration.Fixtures; @@ -12,14 +9,11 @@ using OmniSharp.Extensions.LanguageProtocol.Testing; using OmniSharp.Extensions.LanguageServer.Client; using OmniSharp.Extensions.LanguageServer.Protocol; -using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Document.Proposals; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Models.Proposals; -using OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities; -using OmniSharp.Extensions.LanguageServer.Protocol.Shared; using OmniSharp.Extensions.LanguageServer.Server; using TestingUtils; using Xunit; @@ -34,7 +28,7 @@ public class DynamicRegistrationTests : LanguageProtocolTestBase [Fact] public async Task Should_Register_Dynamically_After_Initialization() { - var (client, server) = await Initialize(new ConfigureClient().Configure, new ConfigureServer().Configure); + var (client, _) = await Initialize(new ConfigureClient().Configure, new ConfigureServer().Configure); await client.RegistrationManager.Registrations.Take(1); client.ServerSettings.Capabilities.CompletionProvider.Should().BeNull(); @@ -140,12 +134,12 @@ await TestHelper.DelayUntil( ); } - private bool SelectorMatches(Registration registration, Func documentFilter) => SelectorMatches(registration.RegisterOptions, documentFilter); + private bool SelectorMatches(Registration registration, Func documentFilter) => SelectorMatches(registration.RegisterOptions!, documentFilter); private bool SelectorMatches(object options, Func documentFilter) { if (options is Registration registration) - return SelectorMatches(registration.RegisterOptions, documentFilter); + return SelectorMatches(registration.RegisterOptions!, documentFilter); if (options is ITextDocumentRegistrationOptions tdro) return tdro.DocumentSelector?.Any(documentFilter) == true; if (options is DocumentSelector selector) @@ -169,7 +163,7 @@ public StaticDynamicRegistrationTests(ITestOutputHelper testOutputHelper) : base [Fact] public async Task Should_Gather_Static_Registrations() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( new ConfigureClient().Configure, options => { new ConfigureServer().Configure(options); @@ -218,7 +212,7 @@ public async Task Should_Register_Static_When_Dynamic_Is_Disabled() AllCommitCharacters = new Container("1", "2"), }, x => x.Excluding(z => z.WorkDoneProgress) ); - server.ClientSettings.Capabilities.TextDocument.Completion.Value.Should().BeEquivalentTo( + server.ClientSettings.Capabilities!.TextDocument!.Completion.Value.Should().BeEquivalentTo( new CompletionCapability { CompletionItem = new CompletionItemCapabilityOptions { DeprecatedSupport = true, @@ -241,7 +235,7 @@ public async Task Should_Register_Static_When_Dynamic_Is_Disabled() } }, x => x.ConfigureForSupports().Excluding(z => z.DynamicRegistration) ); - client.ClientSettings.Capabilities.TextDocument.Completion.Value.Should().BeEquivalentTo( + client.ClientSettings.Capabilities!.TextDocument!.Completion.Value.Should().BeEquivalentTo( new CompletionCapability { CompletionItem = new CompletionItemCapabilityOptions { DeprecatedSupport = true, diff --git a/test/Lsp.Tests/Integration/EventingTests.cs b/test/Lsp.Tests/Integration/EventingTests.cs index ab41e21df..6e6493779 100644 --- a/test/Lsp.Tests/Integration/EventingTests.cs +++ b/test/Lsp.Tests/Integration/EventingTests.cs @@ -16,6 +16,7 @@ using Xunit; using Xunit.Abstractions; using Arg = NSubstitute.Arg; +// ReSharper disable SuspiciousTypeConversion.Global namespace Lsp.Tests.Integration { @@ -57,13 +58,12 @@ public async Task Initialize_Delegate_Is_Supported() public async Task Initialize_Interface_Is_Supported_On_Handlers() { var onLanguageClientInitialize = - Substitute.For(new[] { typeof(IOnLanguageClientInitialize), typeof(PublishDiagnosticsHandler) }, Array.Empty()) as IOnLanguageClientInitialize; + (IOnLanguageClientInitialize) Substitute.For(new[] { typeof(IOnLanguageClientInitialize), typeof(PublishDiagnosticsHandler) }, Array.Empty()); var onLanguageServerInitialize = - Substitute.For(new[] { typeof(IOnLanguageServerInitialize), typeof(CompletionHandler) }, new object[] { new CompletionRegistrationOptions() }) as - IOnLanguageServerInitialize; + (IOnLanguageServerInitialize) Substitute.For(new[] { typeof(IOnLanguageServerInitialize), typeof(CompletionHandler) }, new object[] { new CompletionRegistrationOptions() }); var (client, server) = await Initialize( - options => options.AddHandler(onLanguageClientInitialize as IJsonRpcHandler), - options => options.AddHandler(onLanguageServerInitialize as IJsonRpcHandler) + options => options.AddHandler((IJsonRpcHandler) onLanguageClientInitialize!), + options => options.AddHandler((IJsonRpcHandler) onLanguageServerInitialize!) ); await onLanguageClientInitialize.Received(1).OnInitialize(client, client.ClientSettings, Arg.Any()); @@ -74,17 +74,16 @@ public async Task Initialize_Interface_Is_Supported_On_Handlers() public async Task Initialize_Interface_Is_Supported_On_Handlers_After_Startup() { var onLanguageClientInitialize = - Substitute.For(new[] { typeof(IOnLanguageClientInitialize), typeof(PublishDiagnosticsHandler) }, Array.Empty()) as IOnLanguageClientInitialize; + (IOnLanguageClientInitialize) Substitute.For(new[] { typeof(IOnLanguageClientInitialize), typeof(PublishDiagnosticsHandler) }, Array.Empty()); var onLanguageServerInitialize = - Substitute.For(new[] { typeof(IOnLanguageServerInitialize), typeof(CompletionHandler) }, new object[] { new CompletionRegistrationOptions() }) as - IOnLanguageServerInitialize; + (IOnLanguageServerInitialize) Substitute.For(new[] { typeof(IOnLanguageServerInitialize), typeof(CompletionHandler) }, new object[] { new CompletionRegistrationOptions() }); var (client, server) = await Initialize(o => { }, o => { }); await onLanguageClientInitialize.Received(0).OnInitialize(client, client.ClientSettings, Arg.Any()); await onLanguageServerInitialize.Received(0).OnInitialize(server, server.ClientSettings, Arg.Any()); - client.Register(r => r.AddHandler(onLanguageClientInitialize as IJsonRpcHandler)); - server.Register(r => r.AddHandler(onLanguageServerInitialize as IJsonRpcHandler)); + client.Register(r => r.AddHandler((IJsonRpcHandler) onLanguageClientInitialize!)); + server.Register(r => r.AddHandler((IJsonRpcHandler) onLanguageServerInitialize!)); await onLanguageClientInitialize.Received(1).OnInitialize(client, client.ClientSettings, Arg.Any()); await onLanguageServerInitialize.Received(1).OnInitialize(server, server.ClientSettings, Arg.Any()); @@ -122,13 +121,12 @@ public async Task Initialized_Delegate_Is_Supported() public async Task Initialized_Interface_Is_Supported_On_Handlers() { var onLanguageClientInitialized = - Substitute.For(new[] { typeof(IOnLanguageClientInitialized), typeof(PublishDiagnosticsHandler) }, Array.Empty()) as IOnLanguageClientInitialized; + (IOnLanguageClientInitialized) Substitute.For(new[] { typeof(IOnLanguageClientInitialized), typeof(PublishDiagnosticsHandler) }, Array.Empty()); var onLanguageServerInitialized = - Substitute.For(new[] { typeof(IOnLanguageServerInitialized), typeof(CompletionHandler) }, new object[] { new CompletionRegistrationOptions() }) as - IOnLanguageServerInitialized; + (IOnLanguageServerInitialized) Substitute.For(new[] { typeof(IOnLanguageServerInitialized), typeof(CompletionHandler) }, new object[] { new CompletionRegistrationOptions() }); var (client, server) = await Initialize( - options => options.AddHandler(onLanguageClientInitialized as IJsonRpcHandler), - options => options.AddHandler(onLanguageServerInitialized as IJsonRpcHandler) + options => options.AddHandler((IJsonRpcHandler) onLanguageClientInitialized!), + options => options.AddHandler((IJsonRpcHandler) onLanguageServerInitialized!) ); await onLanguageClientInitialized.Received(1).OnInitialized(client, client.ClientSettings, client.ServerSettings, Arg.Any()); @@ -139,17 +137,16 @@ public async Task Initialized_Interface_Is_Supported_On_Handlers() public async Task Initialized_Interface_Is_Supported_On_Handlers_After_Startup() { var onLanguageClientInitialized = - Substitute.For(new[] { typeof(IOnLanguageClientInitialized), typeof(PublishDiagnosticsHandler) }, Array.Empty()) as IOnLanguageClientInitialized; + (IOnLanguageClientInitialized) Substitute.For(new[] { typeof(IOnLanguageClientInitialized), typeof(PublishDiagnosticsHandler) }, Array.Empty()); var onLanguageServerInitialized = - Substitute.For(new[] { typeof(IOnLanguageServerInitialized), typeof(CompletionHandler) }, new object[] { new CompletionRegistrationOptions() }) as - IOnLanguageServerInitialized; + (IOnLanguageServerInitialized) Substitute.For(new[] { typeof(IOnLanguageServerInitialized), typeof(CompletionHandler) }, new object[] { new CompletionRegistrationOptions() }); var (client, server) = await Initialize(o => { }, o => { }); await onLanguageClientInitialized.Received(0).OnInitialized(client, client.ClientSettings, client.ServerSettings, Arg.Any()); await onLanguageServerInitialized.Received(0).OnInitialized(server, server.ClientSettings, server.ServerSettings, Arg.Any()); - client.Register(r => r.AddHandler(onLanguageClientInitialized as IJsonRpcHandler)); - server.Register(r => r.AddHandler(onLanguageServerInitialized as IJsonRpcHandler)); + client.Register(r => r.AddHandler((IJsonRpcHandler) onLanguageClientInitialized!)); + server.Register(r => r.AddHandler((IJsonRpcHandler) onLanguageServerInitialized!)); await onLanguageClientInitialized.Received(1).OnInitialized(client, client.ClientSettings, client.ServerSettings, Arg.Any()); await onLanguageServerInitialized.Received(1).OnInitialized(server, server.ClientSettings, server.ServerSettings, Arg.Any()); @@ -187,13 +184,12 @@ public async Task Started_Delegate_Is_Supported() public async Task Started_Interface_Is_Supported_On_Handlers() { var onLanguageClientStarted = - Substitute.For(new[] { typeof(IOnLanguageClientStarted), typeof(PublishDiagnosticsHandler) }, Array.Empty()) as IOnLanguageClientStarted; + (IOnLanguageClientStarted) Substitute.For(new[] { typeof(IOnLanguageClientStarted), typeof(PublishDiagnosticsHandler) }, Array.Empty()); var onLanguageServerStarted = - Substitute.For(new[] { typeof(IOnLanguageServerStarted), typeof(CompletionHandler) }, new object[] { new CompletionRegistrationOptions() }) as - IOnLanguageServerStarted; + (IOnLanguageServerStarted) Substitute.For(new[] { typeof(IOnLanguageServerStarted), typeof(CompletionHandler) }, new object[] { new CompletionRegistrationOptions() }); var (client, server) = await Initialize( - options => options.AddHandler(onLanguageClientStarted as IJsonRpcHandler), - options => options.AddHandler(onLanguageServerStarted as IJsonRpcHandler) + options => options.AddHandler((IJsonRpcHandler) onLanguageClientStarted!), + options => options.AddHandler((IJsonRpcHandler) onLanguageServerStarted!) ); await onLanguageClientStarted.Received(1).OnStarted(client, Arg.Any()); @@ -204,17 +200,16 @@ public async Task Started_Interface_Is_Supported_On_Handlers() public async Task Started_Interface_Is_Supported_On_Handlers_After_Startup() { var onLanguageClientStarted = - Substitute.For(new[] { typeof(IOnLanguageClientStarted), typeof(PublishDiagnosticsHandler) }, Array.Empty()) as IOnLanguageClientStarted; + (IOnLanguageClientStarted) Substitute.For(new[] { typeof(IOnLanguageClientStarted), typeof(PublishDiagnosticsHandler) }, Array.Empty()); var onLanguageServerStarted = - Substitute.For(new[] { typeof(IOnLanguageServerStarted), typeof(CompletionHandler) }, new object[] { new CompletionRegistrationOptions() }) as - IOnLanguageServerStarted; + (IOnLanguageServerStarted) Substitute.For(new[] { typeof(IOnLanguageServerStarted), typeof(CompletionHandler) }, new object[] { new CompletionRegistrationOptions() }); var (client, server) = await Initialize(o => { }, o => { }); await onLanguageClientStarted.Received(0).OnStarted(client, Arg.Any()); await onLanguageServerStarted.Received(0).OnStarted(server, Arg.Any()); - client.Register(r => r.AddHandler(onLanguageClientStarted as IJsonRpcHandler)); - server.Register(r => r.AddHandler(onLanguageServerStarted as IJsonRpcHandler)); + client.Register(r => r.AddHandler((IJsonRpcHandler) onLanguageClientStarted!)); + server.Register(r => r.AddHandler((IJsonRpcHandler) onLanguageServerStarted!)); await onLanguageClientStarted.Received(1).OnStarted(client, Arg.Any()); await onLanguageServerStarted.Received(1).OnStarted(server, Arg.Any()); diff --git a/test/Lsp.Tests/Integration/ExecuteCommandTests.cs b/test/Lsp.Tests/Integration/ExecuteCommandTests.cs index e682f8a54..3871443a3 100644 --- a/test/Lsp.Tests/Integration/ExecuteCommandTests.cs +++ b/test/Lsp.Tests/Integration/ExecuteCommandTests.cs @@ -31,7 +31,7 @@ public ExecuteCommandTests(ITestOutputHelper outputHelper) : base(new JsonRpcTes public async Task Should_Execute_A_Command() { var command = Substitute.For>(); - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( x => { @@ -59,7 +59,7 @@ public async Task Should_Execute_A_Command() item.Command.Should().NotBeNull(); - await client.ExecuteCommand(item.Command); + await client.ExecuteCommand(item.Command!); await command.Received(1).Invoke(Arg.Any()); } @@ -69,7 +69,7 @@ public async Task Should_Execute_The_Correct_Command() { var commanda = Substitute.For>(); var commandb = Substitute.For>(); - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { options.WithCapability( new ExecuteCommandCapability { @@ -109,7 +109,7 @@ public async Task Should_Execute_The_Correct_Command() item.Command.Should().NotBeNull(); - await client.ExecuteCommand(item.Command); + await client.ExecuteCommand(item.Command!); await commanda.Received(0).Invoke(Arg.Any()); await commandb.Received(1).Invoke(Arg.Any(), Arg.Any(), Arg.Any()); @@ -120,7 +120,7 @@ public async Task Should_Execute_The_Correct_Command() [Fact] public async Task Should_Fail_To_Execute_A_Command_When_No_Command_Is_Defined() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( x => { @@ -142,7 +142,7 @@ public async Task Should_Fail_To_Execute_A_Command_When_No_Command_Is_Defined() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command); + Func action = () => client.ExecuteCommand(item.Command!); await action.Should().ThrowAsync(); } @@ -150,7 +150,7 @@ public async Task Should_Fail_To_Execute_A_Command_When_No_Command_Is_Defined() public async Task Should_Fail_To_Execute_A_Command_When_No_Command_Name_Is_Given() { var command = Substitute.For>(); - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( x => { @@ -180,7 +180,7 @@ public async Task Should_Fail_To_Execute_A_Command_When_No_Command_Name_Is_Given item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command); + Func action = () => client.ExecuteCommand(item.Command!); await action.Should().ThrowAsync(); await command.Received(0).Invoke(Arg.Any()); @@ -191,7 +191,7 @@ public async Task Should_Fail_To_Execute_A_Command() { var commandc = Substitute.For>(); var commandb = Substitute.For>(); - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( x => { @@ -225,7 +225,7 @@ public async Task Should_Fail_To_Execute_A_Command() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command); + Func action = () => client.ExecuteCommand(item.Command!); await action.Should().ThrowAsync(); await commandc.Received(0).Invoke(Arg.Any()); @@ -235,7 +235,7 @@ public async Task Should_Fail_To_Execute_A_Command() [Fact] public async Task Should_Execute_1_Args() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( x => { @@ -265,14 +265,14 @@ public async Task Should_Execute_1_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command); + Func action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } [Fact] public async Task Should_Execute_2_Args() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( x => { @@ -303,14 +303,14 @@ public async Task Should_Execute_2_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command); + Func action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } [Fact] public async Task Should_Execute_3_Args() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( x => { @@ -342,14 +342,14 @@ public async Task Should_Execute_3_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command); + Func action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } [Fact] public async Task Should_Execute_4_Args() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( x => { @@ -382,14 +382,14 @@ public async Task Should_Execute_4_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command); + Func action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } [Fact] public async Task Should_Execute_5_Args() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( x => { @@ -425,14 +425,14 @@ public async Task Should_Execute_5_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command); + Func action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } [Fact] public async Task Should_Execute_6_Args() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( x => { @@ -470,14 +470,14 @@ public async Task Should_Execute_6_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command); + Func action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } [Fact] public async Task Should_Execute_1_With_Missing_Args() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( x => { @@ -507,14 +507,14 @@ public async Task Should_Execute_1_With_Missing_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command); + Func action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } [Fact] public async Task Should_Execute_2_With_Missing_Args() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( x => { @@ -545,14 +545,14 @@ public async Task Should_Execute_2_With_Missing_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command); + Func action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } [Fact] public async Task Should_Execute_3_With_Missing_Args() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( x => { @@ -584,14 +584,14 @@ public async Task Should_Execute_3_With_Missing_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command); + Func action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } [Fact] public async Task Should_Execute_4_With_Missing_Args() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( x => { @@ -624,14 +624,14 @@ public async Task Should_Execute_4_With_Missing_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command); + Func action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } [Fact] public async Task Should_Execute_5_With_Missing_Args() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( x => { @@ -665,14 +665,14 @@ public async Task Should_Execute_5_With_Missing_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command); + Func action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } [Fact] public async Task Should_Execute_6_With_Missing_Args() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( x => { @@ -707,14 +707,14 @@ public async Task Should_Execute_6_With_Missing_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command); + Func action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } [Fact] public async Task Should_Execute_1_Null_Args() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( x => { @@ -744,14 +744,14 @@ public async Task Should_Execute_1_Null_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command); + Func action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } [Fact] public async Task Should_Execute_2_Null_Args() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( x => { @@ -782,14 +782,14 @@ public async Task Should_Execute_2_Null_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command); + Func action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } [Fact] public async Task Should_Execute_3_Null_Args() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( x => { @@ -821,14 +821,14 @@ public async Task Should_Execute_3_Null_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command); + Func action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } [Fact] public async Task Should_Execute_4_Null_Args() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( x => { @@ -861,14 +861,14 @@ public async Task Should_Execute_4_Null_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command); + Func action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } [Fact] public async Task Should_Execute_5_Null_Args() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( x => { @@ -902,14 +902,14 @@ public async Task Should_Execute_5_Null_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command); + Func action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } [Fact] public async Task Should_Execute_6_Null_Args() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( x => { @@ -944,7 +944,7 @@ public async Task Should_Execute_6_Null_Args() item.Command.Should().NotBeNull(); - Func action = () => client.ExecuteCommand(item.Command); + Func action = () => client.ExecuteCommand(item.Command!); await action.Should().NotThrowAsync(); } } diff --git a/test/Lsp.Tests/Integration/ExtensionTests.cs b/test/Lsp.Tests/Integration/ExtensionTests.cs index cc26f7f7e..ddbd94d42 100644 --- a/test/Lsp.Tests/Integration/ExtensionTests.cs +++ b/test/Lsp.Tests/Integration/ExtensionTests.cs @@ -8,13 +8,10 @@ using OmniSharp.Extensions.JsonRpc.Testing; using OmniSharp.Extensions.LanguageProtocol.Testing; using OmniSharp.Extensions.LanguageServer.Client; -using OmniSharp.Extensions.LanguageServer.Protocol.Window; -using OmniSharp.Extensions.LanguageServer.Server; using Serilog.Events; using Xunit; using Xunit.Abstractions; using Lsp.Tests.Integration.Fixtures; -using MediatR; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; @@ -55,12 +52,12 @@ public async Task Should_Support_Custom_Capabilities() ); { - var capability = client.ClientSettings.Capabilities.Workspace.ExtensionData["unitTests"].ToObject(); + var capability = client.ClientSettings.Capabilities!.Workspace!.ExtensionData["unitTests"].ToObject(); capability.Property.Should().Be("Abcd"); } { - var capability = server.ClientSettings.Capabilities.Workspace.ExtensionData["unitTests"].ToObject(); + var capability = server.ClientSettings.Capabilities!.Workspace!.ExtensionData["unitTests"].ToObject(); capability.Property.Should().Be("Abcd"); } @@ -75,7 +72,7 @@ public async Task Should_Support_Custom_Capabilities() client.RegistrationManager.CurrentRegistrations.Should().Contain(z => z.Method == "tests/run"); } - var unitTests = await client.RequestDiscoverUnitTests(new DiscoverUnitTestsParams(), CancellationToken); + await client.RequestDiscoverUnitTests(new DiscoverUnitTestsParams(), CancellationToken); await client.RunUnitTest(new UnitTest(), CancellationToken); onDiscoverHandler.Received(1).Invoke(Arg.Any(), Arg.Is(x => x.Property == "Abcd"), Arg.Any()); @@ -94,7 +91,7 @@ public async Task Should_Support_Custom_Capabilities_Using_Json() .Invoke(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask); var (client, server) = await Initialize( - options => { options.ClientCapabilities.Workspace.ExtensionData["unitTests"] = JToken.FromObject(new { property = "Abcd", dynamicRegistration = true }); }, + options => { options.ClientCapabilities.Workspace!.ExtensionData["unitTests"] = JToken.FromObject(new { property = "Abcd", dynamicRegistration = true }); }, options => { options.OnDiscoverUnitTests(onDiscoverHandler, new UnitTestRegistrationOptions()); options.OnRunUnitTest(onRunUnitHandler, new UnitTestRegistrationOptions()); @@ -102,7 +99,7 @@ public async Task Should_Support_Custom_Capabilities_Using_Json() ); { - var capability = server.ClientSettings.Capabilities.Workspace.ExtensionData["unitTests"].ToObject(); + var capability = server.ClientSettings.Capabilities!.Workspace!.ExtensionData["unitTests"].ToObject(); capability.Property.Should().Be("Abcd"); } @@ -117,7 +114,7 @@ public async Task Should_Support_Custom_Capabilities_Using_Json() client.RegistrationManager.CurrentRegistrations.Should().Contain(z => z.Method == "tests/run"); } - var unitTests = await client.RequestDiscoverUnitTests(new DiscoverUnitTestsParams(), CancellationToken); + await client.RequestDiscoverUnitTests(new DiscoverUnitTestsParams(), CancellationToken); await client.RunUnitTest(new UnitTest(), CancellationToken); onDiscoverHandler.Received(1).Invoke(Arg.Any(), Arg.Is(x => x.Property == "Abcd"), Arg.Any()); @@ -129,7 +126,7 @@ public async Task Should_Support_Custom_Static_Options() { var onDiscoverHandler = Substitute.For>>>(); var onRunUnitHandler = Substitute.For>(); - var (client, server) = await Initialize( + var (_, server) = await Initialize( options => options.WithCapability( new UnitTestCapability() { @@ -143,7 +140,7 @@ public async Task Should_Support_Custom_Static_Options() ); { - var capability = server.ClientSettings.Capabilities.Workspace.ExtensionData["unitTests"].ToObject(); + var capability = server.ClientSettings.Capabilities!.Workspace!.ExtensionData["unitTests"].ToObject(); capability.Property.Should().Be("Abcd"); } @@ -162,7 +159,7 @@ public async Task Should_Support_Custom_Static_Options() [Fact] public async Task Should_Convert_Registration_Options_Into_Static_Options_As_Required() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { options.DisableDynamicRegistration(); options.WithCapability( @@ -201,7 +198,7 @@ public async Task Should_Convert_Registration_Options_Into_Static_Options_As_Req ); client.ServerSettings.Capabilities.CodeActionProvider.Should().NotBeNull(); - client.ServerSettings.Capabilities.CodeActionProvider.IsValue.Should().Be(true); + client.ServerSettings.Capabilities.CodeActionProvider!.IsValue.Should().Be(true); client.ServerSettings.Capabilities.CodeActionProvider.Value.CodeActionKinds.Should().ContainInOrder( CodeActionKind.RefactorExtract, CodeActionKind.RefactorInline, diff --git a/test/Lsp.Tests/Integration/Fixtures/DefaultClient.cs b/test/Lsp.Tests/Integration/Fixtures/DefaultClient.cs index 5df60da81..187006600 100644 --- a/test/Lsp.Tests/Integration/Fixtures/DefaultClient.cs +++ b/test/Lsp.Tests/Integration/Fixtures/DefaultClient.cs @@ -4,12 +4,8 @@ namespace Lsp.Tests.Integration.Fixtures { public sealed class DefaultClient : IConfigureLanguageClientOptions { - public DefaultClient() - { - } - public void Configure(LanguageClientOptions options) { } } -} \ No newline at end of file +} diff --git a/test/Lsp.Tests/Integration/Fixtures/DefaultServer.cs b/test/Lsp.Tests/Integration/Fixtures/DefaultServer.cs index 8cbcc496d..c8f37e8d4 100644 --- a/test/Lsp.Tests/Integration/Fixtures/DefaultServer.cs +++ b/test/Lsp.Tests/Integration/Fixtures/DefaultServer.cs @@ -4,12 +4,8 @@ namespace Lsp.Tests.Integration.Fixtures { public sealed class DefaultServer : IConfigureLanguageServerOptions { - public DefaultServer() - { - } - public void Configure(LanguageServerOptions options) { } } -} \ No newline at end of file +} diff --git a/test/Lsp.Tests/Integration/Fixtures/ExampleExtensions.cs b/test/Lsp.Tests/Integration/Fixtures/ExampleExtensions.cs index 7a2c3211a..2a4850c6b 100644 --- a/test/Lsp.Tests/Integration/Fixtures/ExampleExtensions.cs +++ b/test/Lsp.Tests/Integration/Fixtures/ExampleExtensions.cs @@ -13,13 +13,13 @@ namespace Lsp.Tests.Integration.Fixtures [Parallel, Method("tests/run", Direction.ClientToServer)] public class UnitTest : IRequest { - public string Name { get; set; } + public string Name { get; set; } = null!; } [CapabilityKey("workspace", "unitTests")] public class UnitTestCapability : DynamicCapability { - public string Property { get; set; } + public string Property { get; set; } = null!; } public class UnitTestRegistrationOptions : IWorkDoneProgressOptions, IRegistrationOptions @@ -32,7 +32,7 @@ public class StaticOptions : WorkDoneProgressOptions [Optional] public bool SupportsDebugging { get; set; } } - class Converter : RegistrationOptionsConverterBase + private class Converter : RegistrationOptionsConverterBase { public Converter() : base("unitTests") { @@ -51,8 +51,8 @@ public override StaticOptions Convert(UnitTestRegistrationOptions source) [Parallel, Method("tests/discover", Direction.ClientToServer)] public class DiscoverUnitTestsParams : IPartialItemsRequest, UnitTest>, IWorkDoneProgressParams { - public ProgressToken PartialResultToken { get; set; } - public ProgressToken WorkDoneToken { get; set; } + public ProgressToken? PartialResultToken { get; set; } = null!; + public ProgressToken? WorkDoneToken { get; set; } = null!; } [Parallel, Method("tests/discover", Direction.ClientToServer)] diff --git a/test/Lsp.Tests/Integration/Fixtures/LanguageProtocolFixture.cs b/test/Lsp.Tests/Integration/Fixtures/LanguageProtocolFixture.cs index 3edd43cc5..4b7c7a84b 100644 --- a/test/Lsp.Tests/Integration/Fixtures/LanguageProtocolFixture.cs +++ b/test/Lsp.Tests/Integration/Fixtures/LanguageProtocolFixture.cs @@ -1,6 +1,4 @@ using System.Threading.Tasks; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Logging.Abstractions; using NSubstitute; using OmniSharp.Extensions.JsonRpc.Testing; using OmniSharp.Extensions.LanguageProtocol.Testing; @@ -21,7 +19,7 @@ public class LanguageProtocolFixture {}, options => {}); + var (_, server) = await Initialize(options => {}, options => {}); var handlersManager = server.GetRequiredService(); handlersManager.Descriptors.Should().HaveCount(8); @@ -32,9 +32,9 @@ public async Task Should_Return_Default_Handlers() [Fact] public async Task Should_Return_Additional_Handlers() { - var (client, server) = await Initialize(options => {}, options => {}); + var (_, server) = await Initialize(options => {}, options => {}); - server.Register(o => o.AddHandler(Substitute.For(new Type[] { typeof (ICompletionHandler), typeof(ICompletionResolveHandler) }, Array.Empty()) as IJsonRpcHandler)); + server.Register(o => o.AddHandler((IJsonRpcHandler) Substitute.For(new[] { typeof (ICompletionHandler), typeof(ICompletionResolveHandler) }, Array.Empty()))); var handlersManager = server.GetRequiredService(); handlersManager.Descriptors.Should().HaveCount(10); handlersManager.GetHandlers().Should().HaveCount(6); @@ -43,7 +43,7 @@ public async Task Should_Return_Additional_Handlers() [Fact] public async Task Link_Should_Fail_If_No_Handler_Is_Defined() { - var (client, server) = await Initialize(options => {}, options => {}); + var (_, server) = await Initialize(options => {}, options => {}); var handlersManager = server.GetRequiredService(); @@ -54,9 +54,9 @@ public async Task Link_Should_Fail_If_No_Handler_Is_Defined() [Fact] public async Task Link_Should_Fail_If_Link_Is_On_The_Wrong_Side() { - var (client, server) = await Initialize(options => {}, options => {}); + var (_, server) = await Initialize(options => {}, options => {}); - server.Register(o => o.AddHandler(Substitute.For(new Type[] { typeof (ICompletionHandler), typeof(ICompletionResolveHandler) }, Array.Empty()) as IJsonRpcHandler)); + server.Register(o => o.AddHandler((IJsonRpcHandler) Substitute.For(new[] { typeof (ICompletionHandler), typeof(ICompletionResolveHandler) }, Array.Empty()))); var handlersManager = server.GetRequiredService(); Action a = () => handlersManager.AddLink("my/completion", TextDocumentNames.Completion); diff --git a/test/Lsp.Tests/Integration/InitializationTests.cs b/test/Lsp.Tests/Integration/InitializationTests.cs index b32cf0661..35aac1804 100644 --- a/test/Lsp.Tests/Integration/InitializationTests.cs +++ b/test/Lsp.Tests/Integration/InitializationTests.cs @@ -29,7 +29,7 @@ public InitializationTests(ITestOutputHelper outputHelper) : base(new JsonRpcTes [Fact] public async Task Logs_should_be_allowed_during_startup() { - var (client, server) = await Initialize(ConfigureClient, ConfigureServer); + await Initialize(ConfigureClient, ConfigureServer); _logs.Should().HaveCount(2); _logs.Should().ContainInOrder("OnInitialize", "OnInitialized"); @@ -71,7 +71,7 @@ await Observable.FromAsync(client.Initialize) class CodeLensHandlerA : CodeLensHandler { - public CodeLensHandlerA(ILanguageServerFacade languageServerFacade) : base(new CodeLensRegistrationOptions() { }) + public CodeLensHandlerA(ILanguageServerFacade languageServerFacade) : base(new CodeLensRegistrationOptions()) { languageServerFacade.Should().NotBeNull(); } diff --git a/test/Lsp.Tests/Integration/LanguageServerConfigurationTests.cs b/test/Lsp.Tests/Integration/LanguageServerConfigurationTests.cs index b572afdaf..1a25ae43c 100644 --- a/test/Lsp.Tests/Integration/LanguageServerConfigurationTests.cs +++ b/test/Lsp.Tests/Integration/LanguageServerConfigurationTests.cs @@ -3,7 +3,6 @@ using FluentAssertions; using Microsoft.Extensions.Configuration; using NSubstitute; -using NSubstitute.Extensions; using OmniSharp.Extensions.JsonRpc.Testing; using OmniSharp.Extensions.LanguageProtocol.Testing; using OmniSharp.Extensions.LanguageServer.Client; @@ -26,7 +25,7 @@ public LanguageServerConfigurationTests(ITestOutputHelper outputHelper) : base(n [Fact] public async Task Should_Not_Support_Configuration_It_Not_Configured() { - var (client, server, configuration) = await InitializeWithConfiguration(ConfigureClient, o => { }); + var (_, server, configuration) = await InitializeWithConfiguration(ConfigureClient, o => { }); server.Configuration.AsEnumerable().Should().BeEmpty(); configuration.Update("mysection", new Dictionary { ["key"] = "value" }); @@ -40,7 +39,7 @@ public async Task Should_Not_Support_Configuration_It_Not_Configured() [Fact] public async Task Should_Update_Configuration_On_Server() { - var (client, server, configuration) = await InitializeWithConfiguration(ConfigureClient, ConfigureServer); + var (_, server, configuration) = await InitializeWithConfiguration(ConfigureClient, ConfigureServer); server.Configuration.AsEnumerable().Should().BeEmpty(); configuration.Update("mysection", new Dictionary { ["key"] = "value" }); @@ -55,7 +54,7 @@ public async Task Should_Update_Configuration_On_Server() [Fact] public async Task Should_Update_Configuration_On_Server_After_Starting() { - var (client, server, configuration) = await InitializeWithConfiguration(ConfigureClient, options => {}); + var (_, server, configuration) = await InitializeWithConfiguration(ConfigureClient, options => {}); server.Configuration.AsEnumerable().Should().BeEmpty(); server.Configuration.AddSection("mysection", "othersection"); @@ -71,7 +70,7 @@ public async Task Should_Update_Configuration_On_Server_After_Starting() [Fact] public async Task Should_Update_Configuration_Should_Stop_Watching_Sections() { - var (client, server, configuration) = await InitializeWithConfiguration(ConfigureClient, ConfigureServer); + var (_, server, configuration) = await InitializeWithConfiguration(ConfigureClient, ConfigureServer); server.Configuration.AsEnumerable().Should().BeEmpty(); configuration.Update("mysection", new Dictionary { ["key"] = "value" }); @@ -93,7 +92,7 @@ public async Task Should_Update_Configuration_Should_Stop_Watching_Sections() [Fact] public async Task Should_Update_Scoped_Configuration() { - var (client, server, configuration) = await InitializeWithConfiguration(ConfigureClient, ConfigureServer); + var (_, server, configuration) = await InitializeWithConfiguration(ConfigureClient, ConfigureServer); var scopedConfiguration = await server.Configuration.GetScopedConfiguration(DocumentUri.From("/my/file.cs"), CancellationToken); configuration.Update("mysection", new Dictionary { ["key"] = "value" }); @@ -115,7 +114,7 @@ public async Task Should_Update_Scoped_Configuration() [Fact] public async Task Should_Fallback_To_Original_Configuration() { - var (client, server, configuration) = await InitializeWithConfiguration(ConfigureClient, ConfigureServer); + var (_, server, configuration) = await InitializeWithConfiguration(ConfigureClient, ConfigureServer); var scopedConfiguration = await server.Configuration.GetScopedConfiguration(DocumentUri.From("/my/file.cs"), CancellationToken); configuration.Update("mysection", new Dictionary { ["key"] = "value" }); @@ -147,7 +146,7 @@ public async Task Should_Fallback_To_Original_Configuration() [Fact] public async Task Should_Only_Update_Configuration_Items_That_Are_Defined() { - var (client, server, configuration) = await InitializeWithConfiguration(ConfigureClient, ConfigureServer); + var (_, server, configuration) = await InitializeWithConfiguration(ConfigureClient, ConfigureServer); server.Configuration.AsEnumerable().Should().BeEmpty(); configuration.Update("mysection", new Dictionary { ["key"] = "value" }); diff --git a/test/Lsp.Tests/Integration/LanguageServerLoggingTests.cs b/test/Lsp.Tests/Integration/LanguageServerLoggingTests.cs index 2fdd38407..0090d8b6e 100644 --- a/test/Lsp.Tests/Integration/LanguageServerLoggingTests.cs +++ b/test/Lsp.Tests/Integration/LanguageServerLoggingTests.cs @@ -7,12 +7,10 @@ using NSubstitute; using OmniSharp.Extensions.JsonRpc.Testing; using OmniSharp.Extensions.LanguageProtocol.Testing; -using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Server; using OmniSharp.Extensions.LanguageServer.Protocol.Window; using OmniSharp.Extensions.LanguageServer.Server; -using Serilog.Events; using TestingUtils; using Xunit; using Xunit.Abstractions; diff --git a/test/Lsp.Tests/Integration/LogMessageTests.cs b/test/Lsp.Tests/Integration/LogMessageTests.cs index 88399dc7f..6a4869a85 100644 --- a/test/Lsp.Tests/Integration/LogMessageTests.cs +++ b/test/Lsp.Tests/Integration/LogMessageTests.cs @@ -26,7 +26,7 @@ public LogMessageTests(ITestOutputHelper outputHelper) : base(new JsonRpcTestOpt [Fact] public async Task Should_Log_Messages_Through_Window_Extension_Methods() { - var (client, server) = await Initialize(ConfigureClient, ConfigureServer); + var (_, server) = await Initialize(ConfigureClient, ConfigureServer); server.Window.LogError("Something bad happened..."); server.Window.LogInfo("Here's something cool..."); @@ -55,7 +55,7 @@ public async Task Should_Log_Messages_Through_Window_Extension_Methods() [Fact] public async Task Should_Log_Messages_Through_Server_Extension_Methods() { - var (client, server) = await Initialize(ConfigureClient, ConfigureServer); + var (_, server) = await Initialize(ConfigureClient, ConfigureServer); server.LogError("Something bad happened..."); server.LogInfo("Here's something cool..."); diff --git a/test/Lsp.Tests/Integration/MonikerTests.cs b/test/Lsp.Tests/Integration/MonikerTests.cs index 6add1ab28..11a0a5212 100644 --- a/test/Lsp.Tests/Integration/MonikerTests.cs +++ b/test/Lsp.Tests/Integration/MonikerTests.cs @@ -19,10 +19,10 @@ namespace Lsp.Tests.Integration { public class MonikerTests : LanguageProtocolTestBase { - private readonly Func>> _request; + private readonly Func?>> _request; public MonikerTests(ITestOutputHelper outputHelper) : base(new JsonRpcTestOptions().ConfigureForXUnit(outputHelper, LogEventLevel.Verbose)) { - _request = Substitute.For>>>(); + _request = Substitute.For?>>>(); } [Fact] @@ -41,7 +41,7 @@ public async Task Should_Get_Monikers() )); - var (client, server) = await Initialize(ClientOptionsAction, ServerOptionsAction); + var (client, _) = await Initialize(ClientOptionsAction, ServerOptionsAction); var result = await client.RequestMoniker(new MonikerParams(), CancellationToken); diff --git a/test/Lsp.Tests/Integration/OverrideHandlerTests.cs b/test/Lsp.Tests/Integration/OverrideHandlerTests.cs index a7ffc3a4f..79be3846c 100644 --- a/test/Lsp.Tests/Integration/OverrideHandlerTests.cs +++ b/test/Lsp.Tests/Integration/OverrideHandlerTests.cs @@ -26,7 +26,7 @@ public OverrideHandlerTests(ITestOutputHelper testOutputHelper) : base(new JsonR [Fact] public async Task Should_Support_Custom_Execute_Command_Handlers() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { @@ -46,7 +46,7 @@ public async Task Should_Support_Custom_Execute_Command_Handlers() [Fact] public async Task Should_Support_Mixed_Execute_Command_Handlers() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { @@ -75,7 +75,8 @@ public async Task Should_Support_Mixed_Execute_Command_Handlers() [Method(WorkspaceNames.ExecuteCommand)] public class CustomExecuteCommandHandler : IJsonRpcRequestHandler, IRegistration, ICapability { - private ExecuteCommandCapability _capability; + // ReSharper disable once NotAccessedField.Local + private ExecuteCommandCapability? _capability; private readonly ExecuteCommandRegistrationOptions _executeCommandRegistrationOptions = new ExecuteCommandRegistrationOptions() { WorkDoneProgress = true, Commands = new Container("mycommand") @@ -96,17 +97,17 @@ public Task Handle(CustomExecuteCommandParams request, CancellationToken /// /// The identifier of the actual command handler. /// - public string Command { get; set; } + public string Command { get; set; } = null!; /// /// Arguments that the command should be invoked with. /// [Optional] - public JArray Arguments { get; set; } + public JArray? Arguments { get; set; } = null!; /// [Optional] - public ProgressToken WorkDoneToken { get; set; } + public ProgressToken? WorkDoneToken { get; set; } = null!; } } } diff --git a/test/Lsp.Tests/Integration/PartialItemTests.cs b/test/Lsp.Tests/Integration/PartialItemTests.cs index 11808c881..bd6dd4c7b 100644 --- a/test/Lsp.Tests/Integration/PartialItemTests.cs +++ b/test/Lsp.Tests/Integration/PartialItemTests.cs @@ -6,15 +6,9 @@ using System.Threading.Tasks; using FluentAssertions; using Lsp.Tests.Integration.Fixtures; -using NSubstitute; -using OmniSharp.Extensions.JsonRpc.Testing; -using OmniSharp.Extensions.LanguageProtocol.Testing; -using OmniSharp.Extensions.LanguageServer.Client; -using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Document.Proposals; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Models.Proposals; -using OmniSharp.Extensions.LanguageServer.Protocol.Server; using OmniSharp.Extensions.LanguageServer.Server; using TestingUtils; using Xunit; @@ -37,7 +31,7 @@ public async Task Should_Behave_Like_A_Task() new SemanticTokensParams() { TextDocument = new TextDocumentIdentifier(@"c:\test.cs") }, CancellationToken ); result.Should().NotBeNull(); - result.Data.Should().HaveCount(3); + result!.Data.Should().HaveCount(3); } [FactWithSkipOn(SkipOnPlatform.All)] @@ -65,7 +59,7 @@ public async Task Should_Behave_Like_An_Observable_Without_Progress_Support() var response = await Client.SendRequest(new SemanticTokensParams { TextDocument = new TextDocumentIdentifier(@"c:\test.cs") }, CancellationToken); response.Should().NotBeNull(); - response.Data.Should().HaveCount(3); + response!.Data.Should().HaveCount(3); } public class DelegateServer : IConfigureLanguageServerOptions @@ -76,8 +70,7 @@ public void Configure(LanguageServerOptions options) => options.OnSemanticTokens observer.OnNext(new SemanticTokensPartialResult() { Data = new[] { 0, 1 }.ToImmutableArray() }); observer.OnNext(new SemanticTokensPartialResult() { Data = new[] { 0, 1, 2 }.ToImmutableArray() }); observer.OnCompleted(); - }, new SemanticTokensRegistrationOptions() { - } + }, new SemanticTokensRegistrationOptions() ); } } diff --git a/test/Lsp.Tests/Integration/PartialItemsTests.cs b/test/Lsp.Tests/Integration/PartialItemsTests.cs index a29d0b9ad..31544c274 100644 --- a/test/Lsp.Tests/Integration/PartialItemsTests.cs +++ b/test/Lsp.Tests/Integration/PartialItemsTests.cs @@ -8,7 +8,6 @@ using System.Threading.Tasks; using FluentAssertions; using Lsp.Tests.Integration.Fixtures; -using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Client.WorkDone; using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Models; @@ -39,7 +38,7 @@ public async Task Should_Behave_Like_A_Task() ); result.Should().HaveCount(3); - result.Select(z => z.Command.Name).Should().ContainInOrder("CodeLens 1", "CodeLens 2", "CodeLens 3"); + result.Select(z => z.Command!.Name).Should().ContainInOrder("CodeLens 1", "CodeLens 2", "CodeLens 3"); } [FactWithSkipOn(SkipOnPlatform.All)] @@ -60,7 +59,7 @@ public async Task Should_Behave_Like_An_Observable() .ToTask(CancellationToken); items.Should().HaveCount(3); - items.Select(z => z.Command.Name).Should().ContainInOrder("CodeLens 1", "CodeLens 2", "CodeLens 3"); + items.Select(z => z.Command!.Name).Should().ContainInOrder("CodeLens 1", "CodeLens 2", "CodeLens 3"); } [Fact] @@ -73,7 +72,7 @@ public async Task Should_Behave_Like_An_Observable_Without_Progress_Support() ); response.Should().HaveCount(3); - response.Select(z => z.Command.Name).Should().ContainInOrder("CodeLens 1", "CodeLens 2", "CodeLens 3"); + response.Select(z => z.Command!.Name).Should().ContainInOrder("CodeLens 1", "CodeLens 2", "CodeLens 3"); } public class DelegateServer : IConfigureLanguageServerOptions @@ -128,7 +127,7 @@ public async Task Should_Behave_Like_An_Observable_With_WorkDone() Client.TextDocument .ObserveWorkDone( new CodeLensParams { TextDocument = new TextDocumentIdentifier(@"c:\test.cs") }, - (client, request) => CodeLensExtensions.RequestCodeLens((ITextDocumentLanguageClient) client, request, CancellationToken), + (client, request) => CodeLensExtensions.RequestCodeLens(client, request, CancellationToken), Observer.Create(z => work.Add(z)) ).Subscribe(x => items.AddRange(x)); @@ -139,7 +138,7 @@ public async Task Should_Behave_Like_An_Observable_With_WorkDone() var workResults = work.Select(z => z.Message); items.Should().HaveCount(4); - items.Select(z => z.Command.Name).Should().ContainInOrder("CodeLens 1", "CodeLens 2", "CodeLens 3", "CodeLens 4"); + items.Select(z => z.Command!.Name).Should().ContainInOrder("CodeLens 1", "CodeLens 2", "CodeLens 3", "CodeLens 4"); workResults.Should().ContainInOrder("Begin", "Report 1", "Report 2", "Report 3", "Report 4", "End"); } diff --git a/test/Lsp.Tests/Integration/ProgressTests.cs b/test/Lsp.Tests/Integration/ProgressTests.cs index 2f713b99e..c7841d015 100644 --- a/test/Lsp.Tests/Integration/ProgressTests.cs +++ b/test/Lsp.Tests/Integration/ProgressTests.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; using System.Reactive; using System.Reactive.Disposables; using System.Reactive.Linq; @@ -9,14 +7,8 @@ using FluentAssertions; using Lsp.Tests.Integration.Fixtures; using Microsoft.Extensions.DependencyInjection; -using NSubstitute; -using OmniSharp.Extensions.JsonRpc.Testing; -using OmniSharp.Extensions.LanguageProtocol.Testing; -using OmniSharp.Extensions.LanguageServer.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; -using OmniSharp.Extensions.LanguageServer.Server; -using TestingUtils; using Xunit; using Xunit.Abstractions; @@ -70,8 +62,8 @@ public async Task Should_Send_Progress_From_Server_To_Client() ); await Observable.Create( - observer => new CompositeDisposable() { - observable.Select(z => z.Value).Take(5).Subscribe(_ => observer.OnNext(Unit.Default), observer.OnCompleted), + innerObserver => new CompositeDisposable() { + observable.Select(z => z.Value).Take(5).Subscribe(v => innerObserver.OnNext(Unit.Default), innerObserver.OnCompleted), workDoneObservable } ).ToTask(CancellationToken); @@ -118,8 +110,8 @@ public async Task Should_Send_Progress_From_Client_To_Server() ); await Observable.Create( - observer => new CompositeDisposable() { - observable.Select(z => z.Value).Take(5).Subscribe(_ => observer.OnNext(Unit.Default), observer.OnCompleted), + innerObserver => new CompositeDisposable() { + observable.Select(z => z.Value).Take(5).Subscribe(v => innerObserver.OnNext(Unit.Default), innerObserver.OnCompleted), workDoneObservable } ).ToTask(CancellationToken); @@ -191,6 +183,7 @@ public async Task Should_Support_Creating_Work_Done_From_Sever_To_Client() WorkDoneProgressBegin begin => begin.Message, WorkDoneProgressReport begin => begin.Message, WorkDoneProgressEnd begin => begin.Message, + _ => throw new NotSupportedException() } ).ToArray().ToTask(CancellationToken); @@ -252,6 +245,7 @@ public async Task Should_Support_Observing_Work_Done_From_Client_To_Server_Reque WorkDoneProgressBegin begin => begin.Message, WorkDoneProgressReport begin => begin.Message, WorkDoneProgressEnd begin => begin.Message, + _ => throw new NotSupportedException() } ).ToArray().ToTask(CancellationToken); @@ -317,6 +311,7 @@ public async Task Should_Support_Cancelling_Work_Done_From_Client_To_Server_Requ WorkDoneProgressBegin begin => begin.Message, WorkDoneProgressReport begin => begin.Message, WorkDoneProgressEnd begin => begin.Message, + _ => throw new NotSupportedException() } ).ToArray().ToTask(CancellationToken); diff --git a/test/Lsp.Tests/Integration/RecursiveResolutionTests.cs b/test/Lsp.Tests/Integration/RecursiveResolutionTests.cs index 9fe20dc48..46b9072af 100644 --- a/test/Lsp.Tests/Integration/RecursiveResolutionTests.cs +++ b/test/Lsp.Tests/Integration/RecursiveResolutionTests.cs @@ -336,6 +336,7 @@ public class ClassRequest : IRequest [Method(nameof(ClassRequest))] class ClassHandler : IJsonRpcRequestHandler where T : class { + // ReSharper disable once NotAccessedField.Local private readonly T _jsonRpcServer; public ClassHandler(T jsonRpcServer) @@ -354,6 +355,7 @@ public class InterfaceRequest : IRequest [Method(nameof(InterfaceRequest))] class InterfaceHandler : IJsonRpcRequestHandler { + // ReSharper disable once NotAccessedField.Local private readonly T _jsonRpcServer; public InterfaceHandler(T jsonRpcServer) @@ -372,6 +374,7 @@ public class NestedRequest : IRequest [Method(nameof(NestedRequest))] class NestedClientHandler : IJsonRpcRequestHandler { + // ReSharper disable once NotAccessedField.Local private readonly ILanguageClientFacade _languageClientFacade; public NestedClientHandler(ILanguageClientFacade languageClientFacade) @@ -386,6 +389,7 @@ public NestedClientHandler(ILanguageClientFacade languageClientFacade) [Method(nameof(NestedRequest))] class NestedServerHandler : IJsonRpcRequestHandler { + // ReSharper disable once NotAccessedField.Local private readonly ILanguageServerFacade _languageClientFacade; public NestedServerHandler(ILanguageServerFacade languageClientFacade) diff --git a/test/Lsp.Tests/Integration/RenameTests.cs b/test/Lsp.Tests/Integration/RenameTests.cs index 0fe55902d..6534a6afd 100644 --- a/test/Lsp.Tests/Integration/RenameTests.cs +++ b/test/Lsp.Tests/Integration/RenameTests.cs @@ -9,7 +9,6 @@ using OmniSharp.Extensions.LanguageServer.Client; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Document; -using OmniSharp.Extensions.LanguageServer.Protocol.Document.Proposals; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Server; using Serilog.Events; @@ -21,13 +20,13 @@ namespace Lsp.Tests.Integration { public class RenameTests : LanguageProtocolTestBase { - private readonly Func> _prepareRename; - private readonly Func> _rename; + private readonly Func> _prepareRename; + private readonly Func> _rename; public RenameTests(ITestOutputHelper outputHelper) : base(new JsonRpcTestOptions().ConfigureForXUnit(outputHelper, LogEventLevel.Verbose)) { - _prepareRename = Substitute.For>>(); - _rename = Substitute.For>>(); + _prepareRename = Substitute.For>>(); + _rename = Substitute.For>>(); } [Fact] @@ -55,7 +54,7 @@ public async Task Should_Handle_Rename_With_No_Value() } ); - var (client, server) = await Initialize(ClientOptionsAction, ServerOptionsAction); + var (client, _) = await Initialize(ClientOptionsAction, ServerOptionsAction); var result = await client.PrepareRename( new PrepareRenameParams() { @@ -69,13 +68,13 @@ public async Task Should_Handle_Rename_With_No_Value() var renameResponse = await client.RequestRename( new RenameParams() { - Position = result.Range.Start, + Position = result!.Range!.Start, NewName = "newname", TextDocument = DocumentUri.FromFileSystemPath("/abcd/file.cs") } ); - renameResponse.DocumentChanges.Should().HaveCount(1); + renameResponse!.DocumentChanges.Should().HaveCount(1); renameResponse.DocumentChanges.Should().Match(z => z.Any(x => x.IsCreateFile)); } @@ -83,8 +82,8 @@ public async Task Should_Handle_Rename_With_No_Value() public async Task Should_Handle_Prepare_Rename_With_No_Value() { _prepareRename.Invoke(Arg.Any(), Arg.Any()) - .Returns(Task.FromResult(null)); - var (client, server) = await Initialize(ClientOptionsAction, ServerOptionsAction); + .Returns(Task.FromResult(null)!); + var (client, _) = await Initialize(ClientOptionsAction, ServerOptionsAction); var result = await client.PrepareRename( new PrepareRenameParams() { @@ -113,7 +112,7 @@ public async Task Should_Handle_Prepare_Rename_With_Range() } ); - var (client, server) = await Initialize(ClientOptionsAction, ServerOptionsAction); + var (client, _) = await Initialize(ClientOptionsAction, ServerOptionsAction); var result = await client.PrepareRename( new PrepareRenameParams() { @@ -123,7 +122,7 @@ public async Task Should_Handle_Prepare_Rename_With_Range() CancellationToken ); - result.IsRange.Should().BeTrue(); + result!.IsRange.Should().BeTrue(); } [Fact] @@ -146,7 +145,7 @@ public async Task Should_Handle_Prepare_Rename_With_PlaceholderRange() } ); - var (client, server) = await Initialize(ClientOptionsAction, ServerOptionsAction); + var (client, _) = await Initialize(ClientOptionsAction, ServerOptionsAction); var result = await client.PrepareRename( new PrepareRenameParams() { @@ -156,7 +155,7 @@ public async Task Should_Handle_Prepare_Rename_With_PlaceholderRange() CancellationToken ); - result.IsPlaceholderRange.Should().BeTrue(); + result!.IsPlaceholderRange.Should().BeTrue(); } [Fact] @@ -164,17 +163,14 @@ public async Task Should_Handle_Prepare_Rename_With_DefaultBehavior() { _prepareRename.Invoke(Arg.Any(), Arg.Any()) .Returns( - call => { - var pos = call.Arg().Position; - return new RangeOrPlaceholderRange( - new RenameDefaultBehavior() { - DefaultBehavior = true - } - ); - } + call => new RangeOrPlaceholderRange( + new RenameDefaultBehavior() { + DefaultBehavior = true + } + ) ); - var (client, server) = await Initialize(ClientOptionsAction, ServerOptionsAction); + var (client, _) = await Initialize(ClientOptionsAction, ServerOptionsAction); var result = await client.PrepareRename( new PrepareRenameParams() { @@ -184,7 +180,7 @@ public async Task Should_Handle_Prepare_Rename_With_DefaultBehavior() CancellationToken ); - result.IsDefaultBehavior.Should().BeTrue(); + result!.IsDefaultBehavior.Should().BeTrue(); } private void ServerOptionsAction(LanguageServerOptions obj) diff --git a/test/Lsp.Tests/Integration/RequestCancellationTests.cs b/test/Lsp.Tests/Integration/RequestCancellationTests.cs index ae8e8fec0..1a071d9c8 100644 --- a/test/Lsp.Tests/Integration/RequestCancellationTests.cs +++ b/test/Lsp.Tests/Integration/RequestCancellationTests.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; -using System.Reactive.Linq; using System.Threading; using System.Threading.Tasks; using FluentAssertions; @@ -30,7 +29,7 @@ public RequestCancellationTests(ITestOutputHelper outputHelper) : base(new JsonR [Fact] public async Task Should_Cancel_Pending_Requests() { - var (client, server) = await Initialize(ConfigureClient, ConfigureServer); + var (client, _) = await Initialize(ConfigureClient, ConfigureServer); Func> action = () => { var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(10)); @@ -47,7 +46,7 @@ public async Task Should_Cancel_Pending_Requests() [Fact] public async Task Should_Abandon_Pending_Requests_For_Text_Changes() { - var (client, server) = await Initialize(ConfigureClient, ConfigureServer); + var (client, _) = await Initialize(ConfigureClient, ConfigureServer); var request1 = client.TextDocument.RequestCompletion( new CompletionParams { @@ -73,7 +72,7 @@ public async Task Should_Abandon_Pending_Requests_For_Text_Changes() public async Task Should_Cancel_Requests_After_Timeout() { Func action = async () => { - var (client, server) = await Initialize( + var (client, _) = await Initialize( ConfigureClient, x => { ConfigureServer(x); x.WithMaximumRequestTimeout(TimeSpan.FromMilliseconds(3000)); @@ -93,7 +92,7 @@ await client.TextDocument.RequestCompletion( public void Should_Cancel_Requests_After_Timeout_without_Content_Modified() { Func action = async () => { - var (client, server) = await Initialize( + var (client, _) = await Initialize( ConfigureClient, x => { ConfigureServer(x); x.WithContentModifiedSupport(false).WithMaximumRequestTimeout(TimeSpan.FromMilliseconds(3000)); @@ -112,7 +111,7 @@ await client.TextDocument.RequestCompletion( [Fact] public async Task Can_Publish_Diagnostics_Delayed() { - var (client, server) = await Initialize( + var (_, server) = await Initialize( ConfigureClient, x => { ConfigureServer(x); x.WithMaximumRequestTimeout(TimeSpan.FromMilliseconds(10000)); diff --git a/test/Lsp.Tests/Integration/ShowMessageTests.cs b/test/Lsp.Tests/Integration/ShowMessageTests.cs index 60a2cdcca..92cd016af 100644 --- a/test/Lsp.Tests/Integration/ShowMessageTests.cs +++ b/test/Lsp.Tests/Integration/ShowMessageTests.cs @@ -27,7 +27,7 @@ public ShowMessageTests(ITestOutputHelper outputHelper) : base(new JsonRpcTestOp [Fact] public async Task Should_Show_Messages_Through_Window_Extension_Methods() { - var (client, server) = await Initialize(ConfigureClient, ConfigureServer); + var (_, server) = await Initialize(ConfigureClient, ConfigureServer); server.Window.ShowError("Something bad happened..."); server.Window.ShowInfo("Here's something cool..."); @@ -56,7 +56,7 @@ public async Task Should_Show_Messages_Through_Window_Extension_Methods() [Fact] public async Task Should_Show_Messages_Through_Server_Extension_Methods() { - var (client, server) = await Initialize(ConfigureClient, ConfigureServer); + var (_, server) = await Initialize(ConfigureClient, ConfigureServer); server.ShowError("Something bad happened..."); server.ShowInfo("Here's something cool..."); diff --git a/test/Lsp.Tests/Integration/TypedCodeActionTests.cs b/test/Lsp.Tests/Integration/TypedCodeActionTests.cs index 6d90fa9d1..2ccb077c9 100644 --- a/test/Lsp.Tests/Integration/TypedCodeActionTests.cs +++ b/test/Lsp.Tests/Integration/TypedCodeActionTests.cs @@ -27,7 +27,7 @@ public TypedCodeActionTests(ITestOutputHelper outputHelper) : base(new JsonRpcTe [Fact] public async Task Should_Aggregate_With_All_Related_Handlers() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { var identifier = Substitute.For(); identifier.GetTextDocumentAttributes(Arg.Any()).Returns( @@ -57,9 +57,9 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ) ); }, - codeAction => { - codeAction.Command.Name = "resolved-a"; - return Task.FromResult(codeAction); + action => { + action.Command!.Name = "resolved-a"; + return Task.FromResult(action); }, new CodeActionRegistrationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") @@ -84,9 +84,9 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ) ); }, - codeAction => { - codeAction.Command.Name = "resolved-b"; - return Task.FromResult(codeAction); + action => { + action.Command!.Name = "resolved-b"; + return Task.FromResult(action); }, new CodeActionRegistrationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") @@ -108,9 +108,9 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ) ); }, - codeAction => { - codeAction.Command.Name = "resolved-c"; - return Task.FromResult(codeAction); + action => { + action.Command!.Name = "resolved-c"; + return Task.FromResult(action); }, new CodeActionRegistrationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") @@ -132,9 +132,9 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ) ); }, - codeAction => { - codeAction.Command.Name = "resolved-d"; - return Task.FromResult(codeAction); + action => { + action.Command!.Name = "resolved-d"; + return Task.FromResult(action); }, new CodeActionRegistrationOptions { DocumentSelector = DocumentSelector.ForLanguage("vb") @@ -152,15 +152,15 @@ public async Task Should_Aggregate_With_All_Related_Handlers() var actions = codeAction.GetCodeActions().ToArray(); var responses = await Task.WhenAll(actions.Select(z => client.ResolveCodeAction(z))); - responses.Select(z => z.Command.Name).Should().Contain(new[] { "resolved-a", "resolved-b", "resolved-c" }); - responses.Select(z => z.Command.Name).Should().NotContain("resolved-d"); + responses.Select(z => z.Command!.Name).Should().Contain(new[] { "resolved-a", "resolved-b", "resolved-c" }); + responses.Select(z => z.Command!.Name).Should().NotContain("resolved-d"); actions.Length.Should().Be(3); } [Fact] public async Task Should_Resolve_With_Data_Capability() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCodeAction( (codeActionParams, capability, token) => { @@ -188,7 +188,7 @@ public async Task Should_Resolve_With_Data_Capability() codeAction.Data.Id.Should().NotBeEmpty(); codeAction.Data.Child.Should().NotBeNull(); codeAction.Data.Name.Should().Be("name"); - codeAction.Command.Name = "resolved"; + codeAction.Command!.Name = "resolved"; return Task.FromResult(codeAction); }, new CodeActionRegistrationOptions() @@ -201,13 +201,13 @@ public async Task Should_Resolve_With_Data_Capability() var item = items.Single(); item = await client.ResolveCodeAction(item.CodeAction!); - item.CodeAction!.Command.Name.Should().Be("resolved"); + item.CodeAction!.Command!.Name.Should().Be("resolved"); } [FactWithSkipOn(SkipOnPlatform.Mac)] public async Task Should_Resolve_With_Partial_Data_Capability() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCodeAction( (codeActionParams, observer, capability, token) => { @@ -236,7 +236,7 @@ public async Task Should_Resolve_With_Partial_Data_Capability() codeAction.Data.Id.Should().NotBeEmpty(); codeAction.Data.Child.Should().NotBeNull(); codeAction.Data.Name.Should().Be("name"); - codeAction.Command.Name = "resolved"; + codeAction.Command!.Name = "resolved"; return Task.FromResult(codeAction); }, new CodeActionRegistrationOptions() @@ -247,13 +247,13 @@ public async Task Should_Resolve_With_Partial_Data_Capability() var item = await client.RequestCodeAction(new CodeActionParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); item = await client.ResolveCodeAction(item.CodeAction!); - item.CodeAction!.Command.Name.Should().Be("resolved"); + item.CodeAction!.Command!.Name.Should().Be("resolved"); } [Fact] public async Task Should_Resolve_With_Data_CancellationToken() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCodeAction( (codeActionParams, token) => { @@ -281,7 +281,7 @@ public async Task Should_Resolve_With_Data_CancellationToken() codeAction.Data.Id.Should().NotBeEmpty(); codeAction.Data.Child.Should().NotBeNull(); codeAction.Data.Name.Should().Be("name"); - codeAction.Command.Name = "resolved"; + codeAction.Command!.Name = "resolved"; return Task.FromResult(codeAction); }, new CodeActionRegistrationOptions() @@ -294,13 +294,13 @@ public async Task Should_Resolve_With_Data_CancellationToken() var item = items.Single(); item = await client.ResolveCodeAction(item.CodeAction!); - item.CodeAction!.Command.Name.Should().Be("resolved"); + item.CodeAction!.Command!.Name.Should().Be("resolved"); } [Fact] public async Task Should_Resolve_With_Partial_Data_CancellationToken() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCodeAction( (codeActionParams, observer, token) => { @@ -329,7 +329,7 @@ public async Task Should_Resolve_With_Partial_Data_CancellationToken() codeAction.Data.Id.Should().NotBeEmpty(); codeAction.Data.Child.Should().NotBeNull(); codeAction.Data.Name.Should().Be("name"); - codeAction.Command.Name = "resolved"; + codeAction.Command!.Name = "resolved"; return Task.FromResult(codeAction); }, new CodeActionRegistrationOptions() @@ -340,13 +340,13 @@ public async Task Should_Resolve_With_Partial_Data_CancellationToken() var item = await client.RequestCodeAction(new CodeActionParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); item = await client.ResolveCodeAction(item.CodeAction!); - item.CodeAction!.Command.Name.Should().Be("resolved"); + item.CodeAction!.Command!.Name.Should().Be("resolved"); } [Fact] public async Task Should_Resolve_With_Data() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCodeAction( codeActionParams => { @@ -374,7 +374,7 @@ public async Task Should_Resolve_With_Data() codeAction.Data.Id.Should().NotBeEmpty(); codeAction.Data.Child.Should().NotBeNull(); codeAction.Data.Name.Should().Be("name"); - codeAction.Command.Name = "resolved"; + codeAction.Command!.Name = "resolved"; return Task.FromResult(codeAction); }, new CodeActionRegistrationOptions() @@ -387,13 +387,13 @@ public async Task Should_Resolve_With_Data() var item = items.Single(); item = await client.ResolveCodeAction(item.CodeAction!); - item.CodeAction!.Command.Name.Should().Be("resolved"); + item.CodeAction!.Command!.Name.Should().Be("resolved"); } [Fact] public async Task Should_Resolve_With_Partial_Data() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCodeAction( (codeActionParams, observer) => { @@ -422,7 +422,7 @@ public async Task Should_Resolve_With_Partial_Data() codeAction.Data.Id.Should().NotBeEmpty(); codeAction.Data.Child.Should().NotBeNull(); codeAction.Data.Name.Should().Be("name"); - codeAction.Command.Name = "resolved"; + codeAction.Command!.Name = "resolved"; return Task.FromResult(codeAction); }, new CodeActionRegistrationOptions() @@ -433,14 +433,14 @@ public async Task Should_Resolve_With_Partial_Data() var item = await client.RequestCodeAction(new CodeActionParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); item = await client.ResolveCodeAction(item.CodeAction!); - item.CodeAction!.Command.Name.Should().Be("resolved"); + item.CodeAction!.Command!.Name.Should().Be("resolved"); } [Fact] public async Task Should_Resolve_Capability() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCodeAction( (codeActionParams, capability, token) => { @@ -458,7 +458,7 @@ public async Task Should_Resolve_Capability() ); }, (codeAction, capability, token) => { - codeAction.Command.Name = "resolved"; + codeAction.Command!.Name = "resolved"; return Task.FromResult(codeAction); }, new CodeActionRegistrationOptions() @@ -471,13 +471,13 @@ public async Task Should_Resolve_Capability() var item = items.Single(); item = await client.ResolveCodeAction(item.CodeAction!); - item.CodeAction!.Command.Name.Should().Be("resolved"); + item.CodeAction!.Command!.Name.Should().Be("resolved"); } [Fact] public async Task Should_Resolve_Partial_Capability() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCodeAction( (codeActionParams, observer, capability, token) => { @@ -496,7 +496,7 @@ public async Task Should_Resolve_Partial_Capability() observer.OnCompleted(); }, (codeAction, capability, token) => { - codeAction.Command.Name = "resolved"; + codeAction.Command!.Name = "resolved"; return Task.FromResult(codeAction); }, new CodeActionRegistrationOptions() @@ -507,13 +507,13 @@ public async Task Should_Resolve_Partial_Capability() var item = await client.RequestCodeAction(new CodeActionParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); item = await client.ResolveCodeAction(item.CodeAction!); - item.CodeAction!.Command.Name.Should().Be("resolved"); + item.CodeAction!.Command!.Name.Should().Be("resolved"); } [Fact] public async Task Should_Resolve_CancellationToken() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCodeAction( (codeActionParams, token) => { @@ -531,7 +531,7 @@ public async Task Should_Resolve_CancellationToken() ); }, (codeAction, token) => { - codeAction.Command.Name = "resolved"; + codeAction.Command!.Name = "resolved"; return Task.FromResult(codeAction); }, new CodeActionRegistrationOptions() @@ -544,13 +544,13 @@ public async Task Should_Resolve_CancellationToken() var item = items.Single(); item = await client.ResolveCodeAction(item.CodeAction!); - item.CodeAction!.Command.Name.Should().Be("resolved"); + item.CodeAction!.Command!.Name.Should().Be("resolved"); } [Fact] public async Task Should_Resolve_Partial_CancellationToken() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCodeAction( (codeActionParams, observer, token) => { @@ -569,7 +569,7 @@ public async Task Should_Resolve_Partial_CancellationToken() observer.OnCompleted(); }, (codeAction, token) => { - codeAction.Command.Name = "resolved"; + codeAction.Command!.Name = "resolved"; return Task.FromResult(codeAction); }, new CodeActionRegistrationOptions() @@ -580,13 +580,13 @@ public async Task Should_Resolve_Partial_CancellationToken() var item = await client.RequestCodeAction(new CodeActionParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); item = await client.ResolveCodeAction(item.CodeAction!); - item.CodeAction!.Command.Name.Should().Be("resolved"); + item.CodeAction!.Command!.Name.Should().Be("resolved"); } [Fact] public async Task Should_Resolve() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCodeAction( codeActionParams => { @@ -604,7 +604,7 @@ public async Task Should_Resolve() ); }, codeAction => { - codeAction.Command.Name = "resolved"; + codeAction.Command!.Name = "resolved"; return Task.FromResult(codeAction); }, new CodeActionRegistrationOptions() @@ -617,13 +617,13 @@ public async Task Should_Resolve() var item = items.Single(); item = await client.ResolveCodeAction(item.CodeAction!); - item.CodeAction!.Command.Name.Should().Be("resolved"); + item.CodeAction!.Command!.Name.Should().Be("resolved"); } [Fact] public async Task Should_Resolve_Partial() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCodeAction( (codeActionParams, observer) => { @@ -642,7 +642,7 @@ public async Task Should_Resolve_Partial() observer.OnCompleted(); }, codeAction => { - codeAction.Command.Name = "resolved"; + codeAction.Command!.Name = "resolved"; return Task.FromResult(codeAction); }, new CodeActionRegistrationOptions() @@ -653,18 +653,20 @@ public async Task Should_Resolve_Partial() var item = await client.RequestCodeAction(new CodeActionParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); item = await client.ResolveCodeAction(item.CodeAction!); - item.CodeAction!.Command.Name.Should().Be("resolved"); + item.CodeAction!.Command!.Name.Should().Be("resolved"); } private class Data : HandlerIdentity { - public string Name { get; set; } + public string Name { get; set; } = null!; + // ReSharper disable once UnusedAutoPropertyAccessor.Local public Guid Id { get; set; } - public Nested Child { get; set; } + public Nested Child { get; set; } = null!; } private class Nested : HandlerIdentity { + // ReSharper disable once UnusedAutoPropertyAccessor.Local public DateTimeOffset Date { get; set; } } } diff --git a/test/Lsp.Tests/Integration/TypedCodeLensTests.cs b/test/Lsp.Tests/Integration/TypedCodeLensTests.cs index 884e06984..8f52e5a2a 100644 --- a/test/Lsp.Tests/Integration/TypedCodeLensTests.cs +++ b/test/Lsp.Tests/Integration/TypedCodeLensTests.cs @@ -28,7 +28,7 @@ public TypedCodeLensTests(ITestOutputHelper outputHelper) : base(new JsonRpcTest [Fact] public async Task Should_Aggregate_With_All_Related_Handlers() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { var identifier = Substitute.For(); identifier.GetTextDocumentAttributes(Arg.Any()).Returns( @@ -56,9 +56,9 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ) ); }, - codeLens => { - codeLens.Command.Name = "resolved-a"; - return Task.FromResult(codeLens); + l => { + l.Command!.Name = "resolved-a"; + return Task.FromResult(l); }, new CodeLensRegistrationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") @@ -81,9 +81,9 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ) ); }, - codeLens => { - codeLens.Command.Name = "resolved-b"; - return Task.FromResult(codeLens); + l => { + l.Command!.Name = "resolved-b"; + return Task.FromResult(l); }, new CodeLensRegistrationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") @@ -103,9 +103,9 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ) ); }, - codeLens => { - codeLens.Command.Name = "resolved-c"; - return Task.FromResult(codeLens); + l => { + l.Command!.Name = "resolved-c"; + return Task.FromResult(l); }, new CodeLensRegistrationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") @@ -125,9 +125,9 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ) ); }, - codeLens => { - codeLens.Command.Name = "resolved-d"; - return Task.FromResult(codeLens); + l => { + l.Command!.Name = "resolved-d"; + return Task.FromResult(l); }, new CodeLensRegistrationOptions { DocumentSelector = DocumentSelector.ForLanguage("vb") @@ -145,15 +145,15 @@ public async Task Should_Aggregate_With_All_Related_Handlers() var lens = codeLens.ToArray(); var responses = await Task.WhenAll(lens.Select(z => client.ResolveCodeLens(z))); - responses.Select(z => z.Command.Name).Should().Contain(new[] { "resolved-a", "resolved-b", "resolved-c" }); - responses.Select(z => z.Command.Name).Should().NotContain("resolved-d"); + responses.Select(z => z.Command!.Name).Should().Contain(new[] { "resolved-a", "resolved-b", "resolved-c" }); + responses.Select(z => z.Command!.Name).Should().NotContain("resolved-d"); lens.Length.Should().Be(3); } [Fact] public async Task Should_Resolve_With_Data_Capability() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCodeLens( (codeLensParams, capability, token) => { @@ -175,12 +175,12 @@ public async Task Should_Resolve_With_Data_Capability() ) ); }, - (codeLens, capability, token) => { - codeLens.Data.Id.Should().NotBeEmpty(); - codeLens.Data.Child.Should().NotBeNull(); - codeLens.Data.Name.Should().Be("name"); - codeLens.Command.Name = "resolved"; - return Task.FromResult(codeLens); + (lens, capability, token) => { + lens.Data.Id.Should().NotBeEmpty(); + lens.Data.Child.Should().NotBeNull(); + lens.Data.Name.Should().Be("name"); + lens.Command!.Name = "resolved"; + return Task.FromResult(lens); }, new CodeLensRegistrationOptions() ); @@ -192,13 +192,13 @@ public async Task Should_Resolve_With_Data_Capability() var item = items.Single(); item = await client.ResolveCodeLens(item); - item.Command.Name.Should().Be("resolved"); + item.Command!.Name.Should().Be("resolved"); } [FactWithSkipOn(SkipOnPlatform.Mac)] public async Task Should_Resolve_With_Partial_Data_Capability() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCodeLens( (codeLensParams, observer, capability, token) => { @@ -225,7 +225,7 @@ public async Task Should_Resolve_With_Partial_Data_Capability() codeLens.Data.Id.Should().NotBeEmpty(); codeLens.Data.Child.Should().NotBeNull(); codeLens.Data.Name.Should().Be("name"); - codeLens.Command.Name = "resolved"; + codeLens.Command!.Name = "resolved"; return Task.FromResult(codeLens); }, new CodeLensRegistrationOptions() @@ -236,13 +236,13 @@ public async Task Should_Resolve_With_Partial_Data_Capability() var item = await client.RequestCodeLens(new CodeLensParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); item = await client.ResolveCodeLens(item); - item.Command.Name.Should().Be("resolved"); + item.Command!.Name.Should().Be("resolved"); } [Fact] public async Task Should_Resolve_With_Data_CancellationToken() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCodeLens( (codeLensParams, token) => { @@ -268,7 +268,7 @@ public async Task Should_Resolve_With_Data_CancellationToken() codeLens.Data.Id.Should().NotBeEmpty(); codeLens.Data.Child.Should().NotBeNull(); codeLens.Data.Name.Should().Be("name"); - codeLens.Command.Name = "resolved"; + codeLens.Command!.Name = "resolved"; return Task.FromResult(codeLens); }, new CodeLensRegistrationOptions() @@ -281,13 +281,13 @@ public async Task Should_Resolve_With_Data_CancellationToken() var item = items.Single(); item = await client.ResolveCodeLens(item); - item.Command.Name.Should().Be("resolved"); + item.Command!.Name.Should().Be("resolved"); } [Fact] public async Task Should_Resolve_With_Partial_Data_CancellationToken() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCodeLens( (codeLensParams, observer, token) => { @@ -314,7 +314,7 @@ public async Task Should_Resolve_With_Partial_Data_CancellationToken() codeLens.Data.Id.Should().NotBeEmpty(); codeLens.Data.Child.Should().NotBeNull(); codeLens.Data.Name.Should().Be("name"); - codeLens.Command.Name = "resolved"; + codeLens.Command!.Name = "resolved"; return Task.FromResult(codeLens); }, new CodeLensRegistrationOptions() @@ -325,13 +325,13 @@ public async Task Should_Resolve_With_Partial_Data_CancellationToken() var item = await client.RequestCodeLens(new CodeLensParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); item = await client.ResolveCodeLens(item); - item.Command.Name.Should().Be("resolved"); + item.Command!.Name.Should().Be("resolved"); } [Fact] public async Task Should_Resolve_With_Data() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCodeLens( codeLensParams => { @@ -357,7 +357,7 @@ public async Task Should_Resolve_With_Data() codeLens.Data.Id.Should().NotBeEmpty(); codeLens.Data.Child.Should().NotBeNull(); codeLens.Data.Name.Should().Be("name"); - codeLens.Command.Name = "resolved"; + codeLens.Command!.Name = "resolved"; return Task.FromResult(codeLens); }, new CodeLensRegistrationOptions() @@ -370,13 +370,13 @@ public async Task Should_Resolve_With_Data() var item = items.Single(); item = await client.ResolveCodeLens(item); - item.Command.Name.Should().Be("resolved"); + item.Command!.Name.Should().Be("resolved"); } [Fact] public async Task Should_Resolve_With_Partial_Data() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCodeLens( (codeLensParams, observer) => { @@ -403,7 +403,7 @@ public async Task Should_Resolve_With_Partial_Data() codeLens.Data.Id.Should().NotBeEmpty(); codeLens.Data.Child.Should().NotBeNull(); codeLens.Data.Name.Should().Be("name"); - codeLens.Command.Name = "resolved"; + codeLens.Command!.Name = "resolved"; return Task.FromResult(codeLens); }, new CodeLensRegistrationOptions() @@ -414,14 +414,14 @@ public async Task Should_Resolve_With_Partial_Data() var item = await client.RequestCodeLens(new CodeLensParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); item = await client.ResolveCodeLens(item); - item.Command.Name.Should().Be("resolved"); + item.Command!.Name.Should().Be("resolved"); } [Fact] public async Task Should_Resolve_Capability() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCodeLens( (codeLensParams, capability, token) => { @@ -437,7 +437,7 @@ public async Task Should_Resolve_Capability() ); }, (codeLens, capability, token) => { - codeLens.Command.Name = "resolved"; + codeLens.Command!.Name = "resolved"; return Task.FromResult(codeLens); }, new CodeLensRegistrationOptions() @@ -450,13 +450,13 @@ public async Task Should_Resolve_Capability() var item = items.Single(); item = await client.ResolveCodeLens(item); - item.Command.Name.Should().Be("resolved"); + item.Command!.Name.Should().Be("resolved"); } [Fact] public async Task Should_Resolve_Partial_Capability() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCodeLens( (codeLensParams, observer, capability, token) => { @@ -473,7 +473,7 @@ public async Task Should_Resolve_Partial_Capability() observer.OnCompleted(); }, (codeLens, capability, token) => { - codeLens.Command.Name = "resolved"; + codeLens.Command!.Name = "resolved"; return Task.FromResult(codeLens); }, new CodeLensRegistrationOptions() @@ -484,13 +484,13 @@ public async Task Should_Resolve_Partial_Capability() var item = await client.RequestCodeLens(new CodeLensParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); item = await client.ResolveCodeLens(item); - item.Command.Name.Should().Be("resolved"); + item.Command!.Name.Should().Be("resolved"); } [Fact] public async Task Should_Resolve_CancellationToken() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCodeLens( (codeLensParams, token) => { @@ -506,7 +506,7 @@ public async Task Should_Resolve_CancellationToken() ); }, (codeLens, token) => { - codeLens.Command.Name = "resolved"; + codeLens.Command!.Name = "resolved"; return Task.FromResult(codeLens); }, new CodeLensRegistrationOptions() @@ -519,13 +519,13 @@ public async Task Should_Resolve_CancellationToken() var item = items.Single(); item = await client.ResolveCodeLens(item); - item.Command.Name.Should().Be("resolved"); + item.Command!.Name.Should().Be("resolved"); } [Fact] public async Task Should_Resolve_Partial_CancellationToken() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCodeLens( (codeLensParams, observer, token) => { @@ -542,7 +542,7 @@ public async Task Should_Resolve_Partial_CancellationToken() observer.OnCompleted(); }, (codeLens, token) => { - codeLens.Command.Name = "resolved"; + codeLens.Command!.Name = "resolved"; return Task.FromResult(codeLens); }, new CodeLensRegistrationOptions() @@ -553,13 +553,13 @@ public async Task Should_Resolve_Partial_CancellationToken() var item = await client.RequestCodeLens(new CodeLensParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); item = await client.ResolveCodeLens(item); - item.Command.Name.Should().Be("resolved"); + item.Command!.Name.Should().Be("resolved"); } [Fact] public async Task Should_Resolve() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCodeLens( codeLensParams => { @@ -575,7 +575,7 @@ public async Task Should_Resolve() ); }, codeLens => { - codeLens.Command.Name = "resolved"; + codeLens.Command!.Name = "resolved"; return Task.FromResult(codeLens); }, new CodeLensRegistrationOptions() @@ -588,13 +588,13 @@ public async Task Should_Resolve() var item = items.Single(); item = await client.ResolveCodeLens(item); - item.Command.Name.Should().Be("resolved"); + item.Command!.Name.Should().Be("resolved"); } [Fact] public async Task Should_Resolve_Partial() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCodeLens( (codeLensParams, observer) => { @@ -611,7 +611,7 @@ public async Task Should_Resolve_Partial() observer.OnCompleted(); }, codeLens => { - codeLens.Command.Name = "resolved"; + codeLens.Command!.Name = "resolved"; return Task.FromResult(codeLens); }, new CodeLensRegistrationOptions() @@ -622,18 +622,19 @@ public async Task Should_Resolve_Partial() var item = await client.RequestCodeLens(new CodeLensParams()).SelectMany(z => z).Take(1).ToTask(CancellationToken); item = await client.ResolveCodeLens(item); - item.Command.Name.Should().Be("resolved"); + item.Command!.Name.Should().Be("resolved"); } private class Data : HandlerIdentity { - public string Name { get; set; } + public string Name { get; set; } = null!; public Guid Id { get; set; } - public Nested Child { get; set; } + public Nested Child { get; set; } = null!; } private class Nested : HandlerIdentity { + // ReSharper disable once UnusedAutoPropertyAccessor.Local public DateTimeOffset Date { get; set; } } } diff --git a/test/Lsp.Tests/Integration/TypedCompletionTests.cs b/test/Lsp.Tests/Integration/TypedCompletionTests.cs index 513ad8152..df40d3ed6 100644 --- a/test/Lsp.Tests/Integration/TypedCompletionTests.cs +++ b/test/Lsp.Tests/Integration/TypedCompletionTests.cs @@ -28,7 +28,7 @@ public TypedCompletionTests(ITestOutputHelper outputHelper) : base(new JsonRpcTe [Fact] public async Task Should_Aggregate_With_All_Related_Handlers() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { var identifier = Substitute.For(); identifier.GetTextDocumentAttributes(Arg.Any()).Returns( @@ -56,9 +56,9 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ) ); }, - codeLens => { - codeLens.Command.Name = "resolved-a"; - return Task.FromResult(codeLens); + completionItem => { + completionItem.Command!.Name = "resolved-a"; + return Task.FromResult(completionItem); }, new CompletionRegistrationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") @@ -81,9 +81,9 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ) ); }, - codeLens => { - codeLens.Command.Name = "resolved-b"; - return Task.FromResult(codeLens); + completionItem => { + completionItem.Command!.Name = "resolved-b"; + return Task.FromResult(completionItem); }, new CompletionRegistrationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") @@ -103,9 +103,9 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ) ); }, - codeLens => { - codeLens.Command.Name = "resolved-c"; - return Task.FromResult(codeLens); + completionItem => { + completionItem.Command!.Name = "resolved-c"; + return Task.FromResult(completionItem); }, new CompletionRegistrationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") @@ -125,9 +125,9 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ) ); }, - codeLens => { - codeLens.Command.Name = "resolved-d"; - return Task.FromResult(codeLens); + completionItem => { + completionItem.Command!.Name = "resolved-d"; + return Task.FromResult(completionItem); }, new CompletionRegistrationOptions { DocumentSelector = DocumentSelector.ForLanguage("vb") @@ -136,24 +136,24 @@ public async Task Should_Aggregate_With_All_Related_Handlers() } ); - var codeLens = await client.RequestCompletion( + var items = await client.RequestCompletion( new CompletionParams { TextDocument = new TextDocumentIdentifier("/some/path/file.cs"), } ); - var lens = codeLens.ToArray(); + var lens = items.ToArray(); var responses = await Task.WhenAll(lens.Select(z => client.ResolveCompletion(z))); - responses.Select(z => z.Command.Name).Should().Contain(new[] { "resolved-a", "resolved-b", "resolved-c" }); - responses.Select(z => z.Command.Name).Should().NotContain("resolved-d"); + responses.Select(z => z.Command!.Name).Should().Contain(new[] { "resolved-a", "resolved-b", "resolved-c" }); + responses.Select(z => z.Command!.Name).Should().NotContain("resolved-d"); lens.Length.Should().Be(3); } [Fact] public async Task Should_Resolve_With_Data_Capability() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( (completionParams, capability, token) => { @@ -176,9 +176,9 @@ public async Task Should_Resolve_With_Data_Capability() ); }, (completionItem, capability, token) => { - completionItem.Data.Id.Should().NotBeEmpty(); - completionItem.Data.Child.Should().NotBeNull(); - completionItem.Data.Name.Should().Be("name"); + completionItem.Data!.Id.Should().NotBeEmpty(); + completionItem.Data!.Child.Should().NotBeNull(); + completionItem.Data!.Name.Should().Be("name"); completionItem.Detail = "resolved"; return Task.FromResult(completionItem); }, @@ -198,7 +198,7 @@ public async Task Should_Resolve_With_Data_Capability() [FactWithSkipOn(SkipOnPlatform.Mac)] public async Task Should_Resolve_With_Partial_Data_Capability() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( (completionParams, observer, capability, token) => { @@ -222,9 +222,9 @@ public async Task Should_Resolve_With_Partial_Data_Capability() observer.OnCompleted(); }, (completionItem, capability, token) => { - completionItem.Data.Id.Should().NotBeEmpty(); - completionItem.Data.Child.Should().NotBeNull(); - completionItem.Data.Name.Should().Be("name"); + completionItem.Data!.Id.Should().NotBeEmpty(); + completionItem.Data!.Child.Should().NotBeNull(); + completionItem.Data!.Name.Should().Be("name"); completionItem.Detail = "resolved"; return Task.FromResult(completionItem); }, @@ -242,7 +242,7 @@ public async Task Should_Resolve_With_Partial_Data_Capability() [Fact] public async Task Should_Resolve_With_Data_CancellationToken() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( (completionParams, token) => { @@ -265,9 +265,9 @@ public async Task Should_Resolve_With_Data_CancellationToken() ); }, (completionItem, token) => { - completionItem.Data.Id.Should().NotBeEmpty(); - completionItem.Data.Child.Should().NotBeNull(); - completionItem.Data.Name.Should().Be("name"); + completionItem.Data!.Id.Should().NotBeEmpty(); + completionItem.Data!.Child.Should().NotBeNull(); + completionItem.Data!.Name.Should().Be("name"); completionItem.Detail = "resolved"; return Task.FromResult(completionItem); }, @@ -287,7 +287,7 @@ public async Task Should_Resolve_With_Data_CancellationToken() [Fact] public async Task Should_Resolve_With_Partial_Data_CancellationToken() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( (completionParams, observer, token) => { @@ -311,9 +311,9 @@ public async Task Should_Resolve_With_Partial_Data_CancellationToken() observer.OnCompleted(); }, (completionItem, token) => { - completionItem.Data.Id.Should().NotBeEmpty(); - completionItem.Data.Child.Should().NotBeNull(); - completionItem.Data.Name.Should().Be("name"); + completionItem.Data!.Id.Should().NotBeEmpty(); + completionItem.Data!.Child.Should().NotBeNull(); + completionItem.Data!.Name.Should().Be("name"); completionItem.Detail = "resolved"; return Task.FromResult(completionItem); }, @@ -331,7 +331,7 @@ public async Task Should_Resolve_With_Partial_Data_CancellationToken() [Fact] public async Task Should_Resolve_With_Data() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( completionParams => { @@ -354,9 +354,9 @@ public async Task Should_Resolve_With_Data() ); }, completionItem => { - completionItem.Data.Id.Should().NotBeEmpty(); - completionItem.Data.Child.Should().NotBeNull(); - completionItem.Data.Name.Should().Be("name"); + completionItem.Data!.Id.Should().NotBeEmpty(); + completionItem.Data!.Child.Should().NotBeNull(); + completionItem.Data!.Name.Should().Be("name"); completionItem.Detail = "resolved"; return Task.FromResult(completionItem); }, @@ -376,7 +376,7 @@ public async Task Should_Resolve_With_Data() [Fact] public async Task Should_Resolve_With_Partial_Data() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( (completionParams, observer) => { @@ -400,9 +400,9 @@ public async Task Should_Resolve_With_Partial_Data() observer.OnCompleted(); }, completionItem => { - completionItem.Data.Id.Should().NotBeEmpty(); - completionItem.Data.Child.Should().NotBeNull(); - completionItem.Data.Name.Should().Be("name"); + completionItem.Data!.Id.Should().NotBeEmpty(); + completionItem.Data!.Child.Should().NotBeNull(); + completionItem.Data!.Name.Should().Be("name"); completionItem.Detail = "resolved"; return Task.FromResult(completionItem); }, @@ -421,7 +421,7 @@ public async Task Should_Resolve_With_Partial_Data() [Fact] public async Task Should_Resolve_Capability() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( (completionParams, capability, token) => { @@ -456,7 +456,7 @@ public async Task Should_Resolve_Capability() [Fact] public async Task Should_Resolve_Partial_Capability() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( (completionParams, observer, capability, token) => { @@ -490,7 +490,7 @@ public async Task Should_Resolve_Partial_Capability() [Fact] public async Task Should_Resolve_CancellationToken() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( (completionParams, token) => { @@ -525,7 +525,7 @@ public async Task Should_Resolve_CancellationToken() [Fact] public async Task Should_Resolve_Partial_CancellationToken() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( (completionParams, observer, token) => { @@ -559,7 +559,7 @@ public async Task Should_Resolve_Partial_CancellationToken() [Fact] public async Task Should_Resolve() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( completionParams => { @@ -594,7 +594,7 @@ public async Task Should_Resolve() [Fact] public async Task Should_Resolve_Partial() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnCompletion( (completionParams, observer) => { @@ -627,13 +627,14 @@ public async Task Should_Resolve_Partial() private class Data : HandlerIdentity { - public string Name { get; set; } + public string Name { get; set; } = null!; public Guid Id { get; set; } - public Nested Child { get; set; } + public Nested Child { get; set; } = null!; } private class Nested : HandlerIdentity { + // ReSharper disable once UnusedAutoPropertyAccessor.Local public DateTimeOffset Date { get; set; } } } diff --git a/test/Lsp.Tests/Integration/TypedDocumentLinkTests.cs b/test/Lsp.Tests/Integration/TypedDocumentLinkTests.cs index 90e195793..ef8c00b88 100644 --- a/test/Lsp.Tests/Integration/TypedDocumentLinkTests.cs +++ b/test/Lsp.Tests/Integration/TypedDocumentLinkTests.cs @@ -26,7 +26,7 @@ public TypedDocumentLinkTests(ITestOutputHelper outputHelper) : base(new JsonRpc [Fact] public async Task Should_Aggregate_With_All_Related_Handlers() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { var identifier = Substitute.For(); identifier.GetTextDocumentAttributes(Arg.Any()).Returns( @@ -51,9 +51,9 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ) ); }, - codeLens => { - codeLens.Tooltip = "resolved-a"; - return Task.FromResult(codeLens); + documentLink => { + documentLink.Tooltip = "resolved-a"; + return Task.FromResult(documentLink); }, new DocumentLinkRegistrationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") @@ -73,9 +73,9 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ) ); }, - codeLens => { - codeLens.Tooltip = "resolved-b"; - return Task.FromResult(codeLens); + documentLink => { + documentLink.Tooltip = "resolved-b"; + return Task.FromResult(documentLink); }, new DocumentLinkRegistrationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") @@ -92,9 +92,9 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ) ); }, - codeLens => { - codeLens.Tooltip = "resolved-c"; - return Task.FromResult(codeLens); + documentLink => { + documentLink.Tooltip = "resolved-c"; + return Task.FromResult(documentLink); }, new DocumentLinkRegistrationOptions { DocumentSelector = DocumentSelector.ForPattern("**/*.cs") @@ -111,9 +111,9 @@ public async Task Should_Aggregate_With_All_Related_Handlers() ) ); }, - codeLens => { - codeLens.Tooltip = "resolved-d"; - return Task.FromResult(codeLens); + documentLink => { + documentLink.Tooltip = "resolved-d"; + return Task.FromResult(documentLink); }, new DocumentLinkRegistrationOptions { DocumentSelector = DocumentSelector.ForLanguage("vb") @@ -122,13 +122,13 @@ public async Task Should_Aggregate_With_All_Related_Handlers() } ); - var codeLens = await client.RequestDocumentLink( + var items = await client.RequestDocumentLink( new DocumentLinkParams { TextDocument = new TextDocumentIdentifier("/some/path/file.cs"), } ); - var lens = codeLens.ToArray(); + var lens = items.ToArray(); var responses = await Task.WhenAll(lens.Select(z => client.ResolveDocumentLink(z))); responses.Select(z => z.Tooltip).Should().Contain(new[] { "resolved-a", "resolved-b", "resolved-c" }); @@ -139,7 +139,7 @@ public async Task Should_Aggregate_With_All_Related_Handlers() [Fact] public async Task Should_Resolve_With_Data_Capability() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnDocumentLink( (documentLinkParams, capability, token) => { @@ -181,7 +181,7 @@ public async Task Should_Resolve_With_Data_Capability() [FactWithSkipOn(SkipOnPlatform.Mac)] public async Task Should_Resolve_With_Partial_Data_Capability() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnDocumentLink( (documentLinkParams, observer, capability, token) => { @@ -222,7 +222,7 @@ public async Task Should_Resolve_With_Partial_Data_Capability() [Fact] public async Task Should_Resolve_With_Data_CancellationToken() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnDocumentLink( (documentLinkParams, token) => { @@ -264,7 +264,7 @@ public async Task Should_Resolve_With_Data_CancellationToken() [Fact] public async Task Should_Resolve_With_Partial_Data_CancellationToken() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnDocumentLink( (documentLinkParams, observer, token) => { @@ -305,7 +305,7 @@ public async Task Should_Resolve_With_Partial_Data_CancellationToken() [Fact] public async Task Should_Resolve_With_Data() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnDocumentLink( documentLinkParams => { @@ -347,7 +347,7 @@ public async Task Should_Resolve_With_Data() [Fact] public async Task Should_Resolve_With_Partial_Data() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnDocumentLink( (documentLinkParams, observer) => { @@ -389,7 +389,7 @@ public async Task Should_Resolve_With_Partial_Data() [Fact] public async Task Should_Resolve_Capability() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnDocumentLink( (documentLinkParams, capability, token) => { @@ -421,7 +421,7 @@ public async Task Should_Resolve_Capability() [Fact] public async Task Should_Resolve_Partial_Capability() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnDocumentLink( (documentLinkParams, observer, capability, token) => { @@ -452,7 +452,7 @@ public async Task Should_Resolve_Partial_Capability() [Fact] public async Task Should_Resolve_CancellationToken() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnDocumentLink( (documentLinkParams, token) => { @@ -484,7 +484,7 @@ public async Task Should_Resolve_CancellationToken() [Fact] public async Task Should_Resolve_Partial_CancellationToken() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnDocumentLink( (documentLinkParams, observer, token) => { @@ -515,7 +515,7 @@ public async Task Should_Resolve_Partial_CancellationToken() [Fact] public async Task Should_Resolve() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnDocumentLink( documentLinkParams => { @@ -547,7 +547,7 @@ public async Task Should_Resolve() [Fact] public async Task Should_Resolve_Partial() { - var (client, server) = await Initialize( + var (client, _) = await Initialize( options => { }, options => { options.OnDocumentLink( (documentLinkParams, observer) => { @@ -577,13 +577,14 @@ public async Task Should_Resolve_Partial() private class Data : HandlerIdentity { - public string Name { get; set; } + public string Name { get; set; } = null!; public Guid Id { get; set; } - public Nested Child { get; set; } + public Nested Child { get; set; } = null!; } private class Nested : HandlerIdentity { + // ReSharper disable once UnusedAutoPropertyAccessor.Local public DateTimeOffset Date { get; set; } } } diff --git a/test/Lsp.Tests/Integration/WorkspaceFolderTests.cs b/test/Lsp.Tests/Integration/WorkspaceFolderTests.cs index 5fe3005a8..59457a8cf 100644 --- a/test/Lsp.Tests/Integration/WorkspaceFolderTests.cs +++ b/test/Lsp.Tests/Integration/WorkspaceFolderTests.cs @@ -14,7 +14,6 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Server; -using OmniSharp.Extensions.LanguageServer.Protocol.Workspace; using OmniSharp.Extensions.LanguageServer.Server; using Serilog.Events; using Xunit; @@ -35,10 +34,10 @@ public WorkspaceFolderTests(ITestOutputHelper outputHelper) : base( [Fact] public async Task Should_Disable_If_Not_Supported() { - var (client, server) = await Initialize( + var (_, server) = await Initialize( options => { options.DisableAllCapabilities(); - options.OnInitialize(async (languageClient, request, token) => { request.Capabilities.Workspace.WorkspaceFolders = false; }); + options.OnInitialize(async (languageClient, request, token) => { request.Capabilities!.Workspace!.WorkspaceFolders = false; }); }, ConfigureServer ); server.WorkspaceFolderManager.IsSupported.Should().Be(false); @@ -49,7 +48,7 @@ public async Task Should_Disable_If_Not_Supported() [Fact] public async Task Should_Enable_If_Supported() { - var (client, server) = await Initialize(ConfigureClient, ConfigureServer); + var (_, server) = await Initialize(ConfigureClient, ConfigureServer); server.WorkspaceFolderManager.IsSupported.Should().Be(true); } @@ -73,7 +72,7 @@ public async Task Should_Add_A_Workspace_Folder() [Fact] public async Task Should_Have_Workspace_Folder_At_Startup() { - var (client, server) = await Initialize(options => { options.WithWorkspaceFolder("/abcd/", nameof(Should_Have_Workspace_Folder_At_Startup)); }, ConfigureServer); + var (_, server) = await Initialize(options => { options.WithWorkspaceFolder("/abcd/", nameof(Should_Have_Workspace_Folder_At_Startup)); }, ConfigureServer); var folder = server.WorkspaceFolderManager.CurrentWorkspaceFolders.Should().HaveCount(1).And.Subject.First(); folder.Name.Should().Be(nameof(Should_Have_Workspace_Folder_At_Startup)); @@ -154,7 +153,7 @@ public async Task Should_Handle_Null_Workspace_Folders_On_Refresh() WorkspaceFolders = null } ); - languageServer.SendRequest(Arg.Any(), Arg.Any()).Returns((Container ) null); + languageServer.SendRequest(Arg.Any(), Arg.Any()).Returns((Container? ) null); var workspaceFolders = new LanguageServerWorkspaceFolderManager(workspaceLanguageServer); var started = (IOnLanguageServerStarted) workspaceFolders; await started.OnStarted(languageServer, CancellationToken); diff --git a/test/Lsp.Tests/JsonFixtureAttribute.cs b/test/Lsp.Tests/JsonFixtureAttribute.cs index a95f88fc3..12e5499bb 100644 --- a/test/Lsp.Tests/JsonFixtureAttribute.cs +++ b/test/Lsp.Tests/JsonFixtureAttribute.cs @@ -10,18 +10,18 @@ internal class JsonFixtureAttribute : DataAttribute { public Assembly Resources = typeof(JsonFixtureAttribute).GetTypeInfo().Assembly; - public override IEnumerable GetData(MethodInfo testMethod) + public override IEnumerable GetData(MethodInfo testMethod) { - var fileName = $"{testMethod.DeclaringType.FullName}_${testMethod.Name}.json"; + var fileName = $"{testMethod.DeclaringType!.FullName}_${testMethod.Name}.json"; if (!Resources.GetManifestResourceNames().Contains(fileName)) { throw new XunitException($"Could find fixture for {testMethod.DeclaringType.Name}.${testMethod.Name}"); } - using (var streamReader = new StreamReader(Resources.GetManifestResourceStream(fileName))) + using (var streamReader = new StreamReader(Resources.GetManifestResourceStream(fileName)!)) { - yield return new object[] { streamReader.ReadToEnd()?.Replace("\r\n", "\n")?.TrimEnd() }; + yield return new object?[] { streamReader.ReadToEnd().Replace("\r\n", "\n").TrimEnd() }; } } } diff --git a/test/Lsp.Tests/JsonRpcTestContainer.cs b/test/Lsp.Tests/JsonRpcTestContainer.cs index 47bdff36d..aafee9790 100644 --- a/test/Lsp.Tests/JsonRpcTestContainer.cs +++ b/test/Lsp.Tests/JsonRpcTestContainer.cs @@ -6,7 +6,7 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using Xunit.Abstractions; -namespace JsonRpc.Tests +namespace Lsp.Tests { internal static class LspTestContainer { diff --git a/test/Lsp.Tests/LanguageClientServiceCollectionSupportTests.cs b/test/Lsp.Tests/LanguageClientServiceCollectionSupportTests.cs index 9de191bc1..a471af654 100644 --- a/test/Lsp.Tests/LanguageClientServiceCollectionSupportTests.cs +++ b/test/Lsp.Tests/LanguageClientServiceCollectionSupportTests.cs @@ -57,8 +57,8 @@ public void Handlers_Can_Be_Added_From_The_Service_Collection() .WithInput(pipe.Reader) .WithOutput(pipe.Writer) .WithServices( - services => - services.AddJsonRpcHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }) + serviceCollection => + serviceCollection.AddJsonRpcHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }) ); } ) @@ -146,6 +146,7 @@ private class Request : IRequest private class Response { + // ReSharper disable once UnusedAutoPropertyAccessor.Local public string Value { get; } public Response(string value) => Value = value; diff --git a/test/Lsp.Tests/LanguageServerServiceCollectionSupportTests.cs b/test/Lsp.Tests/LanguageServerServiceCollectionSupportTests.cs index ae46059a6..64a87c486 100644 --- a/test/Lsp.Tests/LanguageServerServiceCollectionSupportTests.cs +++ b/test/Lsp.Tests/LanguageServerServiceCollectionSupportTests.cs @@ -57,8 +57,8 @@ public void Handlers_Can_Be_Added_From_The_Service_Collection() .WithInput(pipe.Reader) .WithOutput(pipe.Writer) .WithServices( - services => - services.AddJsonRpcHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }) + serviceCollection => + serviceCollection.AddJsonRpcHandler(new JsonRpcHandlerOptions { RequestProcessType = RequestProcessType.Serial }) ); } ) @@ -146,6 +146,7 @@ private class Request : IRequest private class Response { + // ReSharper disable once UnusedAutoPropertyAccessor.Local public string Value { get; } public Response(string value) => Value = value; diff --git a/test/Lsp.Tests/LspRequestRouterTests.cs b/test/Lsp.Tests/LspRequestRouterTests.cs index 99873e030..85436343b 100644 --- a/test/Lsp.Tests/LspRequestRouterTests.cs +++ b/test/Lsp.Tests/LspRequestRouterTests.cs @@ -1,12 +1,9 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Threading; using System.Threading.Tasks; using DryIoc; -using JsonRpc.Tests; using MediatR; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -21,7 +18,6 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using OmniSharp.Extensions.LanguageServer.Protocol.Server; -using OmniSharp.Extensions.LanguageServer.Protocol.Server.WorkDone; using OmniSharp.Extensions.LanguageServer.Protocol.Shared; using OmniSharp.Extensions.LanguageServer.Server; using OmniSharp.Extensions.LanguageServer.Server.Matchers; @@ -29,34 +25,12 @@ using Xunit; using Xunit.Abstractions; using Arg = NSubstitute.Arg; -using ISerializer = OmniSharp.Extensions.JsonRpc.ISerializer; using Request = OmniSharp.Extensions.JsonRpc.Server.Request; namespace Lsp.Tests { public class TestLanguageServerRegistry : JsonRpcOptionsRegistryBase, ILanguageServerRegistry { - internal List Handlers = new List(); - public ISerializer Serializer => new Serializer(); - - public ILanguageServerRegistry AddTextDocumentIdentifier(params ITextDocumentIdentifier[] handlers) => this; - - public ILanguageServerRegistry AddTextDocumentIdentifier() where T : ITextDocumentIdentifier => this; - - public ILanguageServerRegistry AddHandler(Func handlerFunc, JsonRpcHandlerOptions options = null) where T : IJsonRpcHandler - { - var sp = new ServiceCollection() - .AddSingleton( - Substitute - .For>>() - ) - .AddSingleton(Substitute.For()) - .AddSingleton(Substitute.For>()) - .AddSingleton(new CodeActionRegistrationOptions()) - .BuildServiceProvider(); - AddHandler(handlerFunc(sp)); - return this; - } } public class LspRequestRouterTests : AutoTestBase @@ -237,7 +211,6 @@ public async Task ShouldRouteToCorrect_Request_WithManyHandlers() ) ) { textDocumentSyncHandler, textDocumentSyncHandler2, codeActionHandler }; - handlerCollection.Add(registry.Handlers.ToArray()); AutoSubstitute.Provide(handlerCollection); AutoSubstitute.Provide>(handlerCollection); AutoSubstitute.Provide(new TextDocumentMatcher(LoggerFactory.CreateLogger(), textDocumentIdentifiers)); diff --git a/test/Lsp.Tests/Matchers/ExecuteCommandHandlerMatcherTests.cs b/test/Lsp.Tests/Matchers/ExecuteCommandHandlerMatcherTests.cs index a8dbc49ec..65ce6f8b3 100644 --- a/test/Lsp.Tests/Matchers/ExecuteCommandHandlerMatcherTests.cs +++ b/test/Lsp.Tests/Matchers/ExecuteCommandHandlerMatcherTests.cs @@ -78,8 +78,9 @@ public void Should_Return_Handler_Descriptor() ); // Then - result.Should().NotBeNullOrEmpty(); - result.Should().Contain(x => x.Method == "workspace/executeCommand"); + var lspHandlerDescriptors = result as ILspHandlerDescriptor[] ?? result.ToArray(); + lspHandlerDescriptors.Should().NotBeNullOrEmpty(); + lspHandlerDescriptors.Should().Contain(x => x.Method == "workspace/executeCommand"); } } } diff --git a/test/Lsp.Tests/Matchers/ResolveCommandMatcherTests.cs b/test/Lsp.Tests/Matchers/ResolveCommandMatcherTests.cs index 2d783b471..add3fd3ef 100644 --- a/test/Lsp.Tests/Matchers/ResolveCommandMatcherTests.cs +++ b/test/Lsp.Tests/Matchers/ResolveCommandMatcherTests.cs @@ -21,8 +21,8 @@ namespace Lsp.Tests.Matchers { public class ResolveCommandMatcherTests : AutoTestBase { - private readonly Guid TrueId = Guid.NewGuid(); - private readonly Guid FalseId = Guid.NewGuid(); + private readonly Guid _trueId = Guid.NewGuid(); + private readonly Guid _falseId = Guid.NewGuid(); public ResolveCommandMatcherTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) { @@ -90,15 +90,15 @@ public void Should_Return_CodeLensResolve_Descriptor() { // Given var handlerMatcher = AutoSubstitute.Resolve(); - var resolveHandler = Substitute.For(new[] { typeof(ICodeLensResolveHandler), typeof(ICanBeIdentifiedHandler) }, Array.Empty()) as ICodeLensResolveHandler; - var resolveHandler2 = Substitute.For(new[] { typeof(ICodeLensResolveHandler), typeof(ICanBeIdentifiedHandler) }, Array.Empty()) as ICodeLensResolveHandler; - ( (ICanBeIdentifiedHandler) resolveHandler )?.Id.Returns(FalseId); - ( (ICanBeIdentifiedHandler) resolveHandler2 )?.Id.Returns(TrueId); + var resolveHandler = (ICodeLensResolveHandler) Substitute.For(new[] { typeof(ICodeLensResolveHandler), typeof(ICanBeIdentifiedHandler) }, Array.Empty()); + var resolveHandler2 = (ICodeLensResolveHandler) Substitute.For(new[] { typeof(ICodeLensResolveHandler), typeof(ICanBeIdentifiedHandler) }, Array.Empty()); + resolveHandler.Id.Returns(_falseId); + resolveHandler2.Id.Returns(_trueId); // When var result = handlerMatcher.FindHandler( new CodeLens { - Data = JObject.FromObject(new Dictionary { [Constants.PrivateHandlerId] = TrueId, ["a"] = 1 }) + Data = JObject.FromObject(new Dictionary { [Constants.PrivateHandlerId] = _trueId, ["a"] = 1 }) }, new List { new LspHandlerDescriptor( @@ -118,7 +118,7 @@ public void Should_Return_CodeLensResolve_Descriptor() new LspHandlerDescriptor( TextDocumentNames.CodeLensResolve, "Key2", - resolveHandler2!, + resolveHandler2, typeof(ICodeLensResolveHandler), typeof(CodeLens), null, @@ -178,13 +178,13 @@ public void Should_Return_CompletionResolve_Descriptor() var handlerMatcher = AutoSubstitute.Resolve(); var resolveHandler = Substitute.For(new[] { typeof(ICompletionResolveHandler), typeof(ICanBeIdentifiedHandler) }, Array.Empty()) as ICompletionResolveHandler; var resolveHandler2 = Substitute.For(new[] { typeof(ICompletionResolveHandler), typeof(ICanBeIdentifiedHandler) }, Array.Empty()) as ICompletionResolveHandler; - ( (ICanBeIdentifiedHandler) resolveHandler )?.Id.Returns(FalseId); - ( (ICanBeIdentifiedHandler) resolveHandler2 )?.Id.Returns(TrueId); + ( (ICanBeIdentifiedHandler) resolveHandler! ).Id.Returns(_falseId); + ( (ICanBeIdentifiedHandler) resolveHandler2! ).Id.Returns(_trueId); // When var result = handlerMatcher.FindHandler( new CompletionItem { - Data = JObject.FromObject(new Dictionary { [Constants.PrivateHandlerId] = TrueId, ["a"] = 1 }) + Data = JObject.FromObject(new Dictionary { [Constants.PrivateHandlerId] = _trueId, ["a"] = 1 }) }, new List { new LspHandlerDescriptor( @@ -235,7 +235,7 @@ public async Task Should_Update_CompletionItems_With_HandlerType() typeof(ICanBeIdentifiedHandler) }, new object[0] ); - ( resolveHandler as ICanBeIdentifiedHandler )?.Id.Returns(TrueId); + ( resolveHandler as ICanBeIdentifiedHandler )?.Id.Returns(_trueId); var descriptor = new LspHandlerDescriptor( TextDocumentNames.Completion, "Key", @@ -260,6 +260,7 @@ public async Task Should_Update_CompletionItems_With_HandlerType() }; var list = new CompletionList(item); + // ReSharper disable once IsExpressionAlwaysTrue ( list is IEnumerable ).Should().BeTrue(); // When @@ -269,8 +270,8 @@ public async Task Should_Update_CompletionItems_With_HandlerType() response.Should().BeEquivalentTo(list); response.Items.Should().Contain(item); var responseItem = response.Items.First(); - responseItem.Data[Constants.PrivateHandlerId].Value().Should().Be(TrueId); - responseItem.Data["hello"].Value().Should().Be("world"); + responseItem.Data![Constants.PrivateHandlerId].Value().Should().Be(_trueId); + responseItem.Data!["hello"].Value().Should().Be("world"); } [Fact] @@ -284,7 +285,7 @@ public async Task Should_Update_CodeLensContainer_With_HandlerType() typeof(ICanBeIdentifiedHandler) }, new object[0] ); - ( resolveHandler as ICanBeIdentifiedHandler )?.Id.Returns(TrueId); + ( resolveHandler as ICanBeIdentifiedHandler )?.Id.Returns(_trueId); var descriptor = new LspHandlerDescriptor( TextDocumentNames.CodeLens, "Key", @@ -309,6 +310,7 @@ public async Task Should_Update_CodeLensContainer_With_HandlerType() }; var list = new CodeLensContainer(item); + // ReSharper disable once IsExpressionAlwaysTrue ( list is IEnumerable ).Should().BeTrue(); // When @@ -318,7 +320,7 @@ public async Task Should_Update_CodeLensContainer_With_HandlerType() response.Should().BeEquivalentTo(list); response.Should().Contain(item); var responseItem = response.First(); - responseItem.Data[Constants.PrivateHandlerId].Value().Should().Be(TrueId); + responseItem.Data![Constants.PrivateHandlerId].Value().Should().Be(_trueId); responseItem.Data["hello"].Value().Should().Be("world"); } @@ -333,11 +335,11 @@ public async Task Should_Update_CodeLens_Removing_HandlerType() typeof(ICanBeIdentifiedHandler) }, new object[0] ); - ( resolveHandler as ICanBeIdentifiedHandler )?.Id.Returns(TrueId); + ( resolveHandler as ICanBeIdentifiedHandler )?.Id.Returns(_trueId); var descriptor = new LspHandlerDescriptor( TextDocumentNames.CodeLensResolve, "Key", - resolveHandler as IJsonRpcHandler, + (resolveHandler as IJsonRpcHandler)!, resolveHandler.GetType(), typeof(CodeLens), null, @@ -364,7 +366,7 @@ public async Task Should_Update_CodeLens_Removing_HandlerType() // Then response.Should().BeEquivalentTo(item); item.Data?[Constants.PrivateHandlerId].Value().Should().BeEmpty(); - item.Data["hello"].Value().Should().Be("world"); + item.Data?["hello"].Value().Should().Be("world"); } } } diff --git a/test/Lsp.Tests/Matchers/TextDocumentMatcherTests.cs b/test/Lsp.Tests/Matchers/TextDocumentMatcherTests.cs index 37b0481ae..d9f72ab0a 100644 --- a/test/Lsp.Tests/Matchers/TextDocumentMatcherTests.cs +++ b/test/Lsp.Tests/Matchers/TextDocumentMatcherTests.cs @@ -3,7 +3,6 @@ using System.Linq; using DryIoc; using FluentAssertions; -using Microsoft.Extensions.DependencyInjection; using NSubstitute; using OmniSharp.Extensions.LanguageServer.Client; using OmniSharp.Extensions.LanguageServer.Protocol; @@ -79,8 +78,9 @@ public void Should_Return_Did_Open_Text_Document_Handler_Descriptor() ); // Then - result.Should().NotBeNullOrEmpty(); - result.Should().Contain(x => x.Method == TextDocumentNames.DidOpen); + var lspHandlerDescriptors = result as ILspHandlerDescriptor[] ?? result.ToArray(); + lspHandlerDescriptors.Should().NotBeNullOrEmpty(); + lspHandlerDescriptors.Should().Contain(x => x.Method == TextDocumentNames.DidOpen); } [Fact] @@ -109,8 +109,9 @@ public void Should_Return_Did_Open_Text_Document_Handler_Descriptor_With_Sepcial ); // Then - result.Should().NotBeNullOrEmpty(); - result.Should().Contain(x => x.Method == TextDocumentNames.DidOpen); + var lspHandlerDescriptors = result as ILspHandlerDescriptor[] ?? result.ToArray(); + lspHandlerDescriptors.Should().NotBeNullOrEmpty(); + lspHandlerDescriptors.Should().Contain(x => x.Method == TextDocumentNames.DidOpen); } [Fact] @@ -137,8 +138,9 @@ public void Should_Return_Did_Change_Text_Document_Descriptor() ); // Then - result.Should().NotBeNullOrEmpty(); - result.Should().Contain(x => x.Method == TextDocumentNames.DidChange); + var lspHandlerDescriptors = result as ILspHandlerDescriptor[] ?? result.ToArray(); + lspHandlerDescriptors.Should().NotBeNullOrEmpty(); + lspHandlerDescriptors.Should().Contain(x => x.Method == TextDocumentNames.DidChange); } [Fact] @@ -165,8 +167,9 @@ public void Should_Return_Did_Save_Text_Document_Descriptor() ); // Then - result.Should().NotBeNullOrEmpty(); - result.Should().Contain(x => x.Method == TextDocumentNames.DidSave); + var lspHandlerDescriptors = result as ILspHandlerDescriptor[] ?? result.ToArray(); + lspHandlerDescriptors.Should().NotBeNullOrEmpty(); + lspHandlerDescriptors.Should().Contain(x => x.Method == TextDocumentNames.DidSave); } [Fact] @@ -193,8 +196,9 @@ public void Should_Return_Did_Close_Text_Document_Descriptor() ); // Then - result.Should().NotBeNullOrEmpty(); - result.Should().Contain(x => x.Method == TextDocumentNames.DidClose); + var lspHandlerDescriptors = result as ILspHandlerDescriptor[] ?? result.ToArray(); + lspHandlerDescriptors.Should().NotBeNullOrEmpty(); + lspHandlerDescriptors.Should().Contain(x => x.Method == TextDocumentNames.DidClose); } [Fact] @@ -212,7 +216,7 @@ public void Should_Return_Code_Lens_Descriptor() AutoSubstitute.Provide>(collection); var handlerMatcher = AutoSubstitute.Resolve(); - var codeLensHandler = Substitute.For(new[] { typeof(ICodeLensHandler), typeof(ICodeLensResolveHandler) }, new object[0]) as ICodeLensHandler; + var codeLensHandler = (ICodeLensHandler) Substitute.For(new[] { typeof(ICodeLensHandler), typeof(ICodeLensResolveHandler) }, new object[0]); codeLensHandler.GetRegistrationOptions() .Returns( new CodeLensRegistrationOptions { @@ -220,7 +224,7 @@ public void Should_Return_Code_Lens_Descriptor() } ); - var codeLensHandler2 = Substitute.For(new[] { typeof(ICodeLensHandler), typeof(ICodeLensResolveHandler) }, new object[0]) as ICodeLensHandler; + var codeLensHandler2 = (ICodeLensHandler) Substitute.For(new[] { typeof(ICodeLensHandler), typeof(ICodeLensResolveHandler) }, new object[0]); codeLensHandler2.GetRegistrationOptions() .Returns( new CodeLensRegistrationOptions { @@ -238,9 +242,10 @@ public void Should_Return_Code_Lens_Descriptor() ); // Then - result.Should().NotBeNullOrEmpty(); - result.Should().Contain(x => x.Method == TextDocumentNames.CodeLens); - result.Should().Contain(x => ( (LspHandlerDescriptor) x ).Key == "[**/*.cs]"); + var lspHandlerDescriptors = result as ILspHandlerDescriptor[] ?? result.ToArray(); + lspHandlerDescriptors.Should().NotBeNullOrEmpty(); + lspHandlerDescriptors.Should().Contain(x => x.Method == TextDocumentNames.CodeLens); + lspHandlerDescriptors.Should().Contain(x => ( (LspHandlerDescriptor) x ).Key == "[**/*.cs]"); } } @@ -282,8 +287,9 @@ public void Should_Return_Did_Folding_Range_handler() ); // Then - result.Should().NotBeNullOrEmpty(); - result.Should().Contain(x => x.Method == TextDocumentNames.DidOpen); + var lspHandlerDescriptors = result as ILspHandlerDescriptor[] ?? result.ToArray(); + lspHandlerDescriptors.Should().NotBeNullOrEmpty(); + lspHandlerDescriptors.Should().Contain(x => x.Method == TextDocumentNames.DidOpen); } } } diff --git a/test/Lsp.Tests/MediatorTestsRequestHandlerOfTRequestTResponse.cs b/test/Lsp.Tests/MediatorTestsRequestHandlerOfTRequestTResponse.cs index f7b95ddf5..aecd58409 100644 --- a/test/Lsp.Tests/MediatorTestsRequestHandlerOfTRequestTResponse.cs +++ b/test/Lsp.Tests/MediatorTestsRequestHandlerOfTRequestTResponse.cs @@ -4,9 +4,7 @@ using System.Threading.Tasks; using DryIoc; using FluentAssertions; -using JsonRpc.Tests; using MediatR; -using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NSubstitute; @@ -26,6 +24,7 @@ using Arg = NSubstitute.Arg; using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; using Request = OmniSharp.Extensions.JsonRpc.Server.Request; +#pragma warning disable CS0162 namespace Lsp.Tests { @@ -71,7 +70,7 @@ public async Task RequestsCancellation() var cts = new CancellationTokenSource(); cts.Cancel(); - var response = ( (IRequestRouter) mediator ).RouteRequest(mediator.GetDescriptors(request), request, cts.Token); + ( (IRequestRouter) mediator ).RouteRequest(mediator.GetDescriptors(request), request, cts.Token); Func action = () => ( (IRequestRouter) mediator ).RouteRequest(mediator.GetDescriptors(request), request, cts.Token); await action.Should().ThrowAsync(); } diff --git a/test/Lsp.Tests/Minimatch/BasicTests.cs b/test/Lsp.Tests/Minimatch/BasicTests.cs index ca4b5ec5e..d6c9d77c7 100644 --- a/test/Lsp.Tests/Minimatch/BasicTests.cs +++ b/test/Lsp.Tests/Minimatch/BasicTests.cs @@ -35,9 +35,9 @@ public class BasicTests { private static readonly List> actualRegexes = new List>(); - private static void TestCase(string pattern, IList expected, Options options = null, IEnumerable input = null) + private static void TestCase(string pattern, IList expected, Options? options = null, IEnumerable? input = null) { - input ??= files; + input ??= Files; Assert.Equal( string.Join(Environment.NewLine, expected.OrderBy(s => s)), @@ -48,6 +48,7 @@ private static void TestCase(string pattern, IList expected, Options opt actualRegexes.Add(Tuple.Create(pattern, regex == null ? "false" : "/" + regex + "/" + ( regex.Options == RegexOptions.IgnoreCase ? "i" : "" ))); } + // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local private static void AssertRegexes(params string[] expectedRegexes) { Assert.Equal(expectedRegexes.Length, actualRegexes.Count); @@ -57,15 +58,15 @@ private static void AssertRegexes(params string[] expectedRegexes) } } - private static void AddFiles(params string[] entries) => files.AddRange(entries); + private static void AddFiles(params string[] entries) => Files.AddRange(entries); private static void ReplaceFiles(params string[] entries) { - files.Clear(); - files.AddRange(entries); + Files.Clear(); + Files.AddRange(entries); } - private static readonly List files = new List(); + private static readonly List Files = new List(); public BasicTests() { @@ -97,7 +98,7 @@ public void BashCookBook() TestCase("b*/", new[] { "bdir/" }); TestCase("c*", new[] { "c", "ca", "cb" }); - TestCase("**", files); + TestCase("**", Files); TestCase("\\.\\./*/", new[] { "\\.\\./*/" }, new Options { NoNull = true }); TestCase("s/\\..*//", new[] { "s/\\..*//" }, new Options { NoNull = true }); diff --git a/test/Lsp.Tests/Models/FoldingRangeKindTests.cs b/test/Lsp.Tests/Models/FoldingRangeKindTests.cs index fc74091a8..852686243 100644 --- a/test/Lsp.Tests/Models/FoldingRangeKindTests.cs +++ b/test/Lsp.Tests/Models/FoldingRangeKindTests.cs @@ -3,7 +3,7 @@ using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using Xunit; -namespace Lsp.Tests +namespace Lsp.Tests.Models { public class FoldingRangeKindTests { diff --git a/test/Lsp.Tests/Models/InitializeParamsTests.cs b/test/Lsp.Tests/Models/InitializeParamsTests.cs index 68c9d6ec8..1cb1602e4 100644 --- a/test/Lsp.Tests/Models/InitializeParamsTests.cs +++ b/test/Lsp.Tests/Models/InitializeParamsTests.cs @@ -64,7 +64,7 @@ public void SimpleTest(string expected) Symbol = new WorkspaceSymbolCapability { DynamicRegistration = true }, } }, - InitializationOptions = null, + InitializationOptions = null!, ProcessId = 1234, RootUri = new Uri("file:///file/abc/12.cs"), Trace = InitializeTrace.Verbose diff --git a/test/Lsp.Tests/RequestProcessIdentifierTests.cs b/test/Lsp.Tests/RequestProcessIdentifierTests.cs index 1f4d21e8d..128a32dd2 100644 --- a/test/Lsp.Tests/RequestProcessIdentifierTests.cs +++ b/test/Lsp.Tests/RequestProcessIdentifierTests.cs @@ -13,8 +13,6 @@ namespace Lsp.Tests { public class RequestProcessIdentifierTests : AutoTestBase { - private readonly TestLoggerFactory _testLoggerFactory; - public RequestProcessIdentifierTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) { } diff --git a/test/Lsp.Tests/SemanticTokensDocumentTests.cs b/test/Lsp.Tests/SemanticTokensDocumentTests.cs index 0a6a8dc26..d7338059f 100644 --- a/test/Lsp.Tests/SemanticTokensDocumentTests.cs +++ b/test/Lsp.Tests/SemanticTokensDocumentTests.cs @@ -21,13 +21,11 @@ namespace Lsp.Tests { public class SemanticTokensDocumentTests { - private readonly ITestOutputHelper _testOutputHelper; private readonly ILogger _logger; private readonly SemanticTokensLegend _legend; public SemanticTokensDocumentTests(ITestOutputHelper testOutputHelper) { - _testOutputHelper = testOutputHelper; var loggerFactory = new TestLoggerFactory(testOutputHelper); _logger = loggerFactory.CreateLogger(); _legend = new SemanticTokensLegend { @@ -105,7 +103,7 @@ public void ReturnDocumentTokensFromScratch() } [Theory] - [ClassData(typeof(ReturnDocumentTokensFromScratch_ForRange_Data))] + [ClassData(typeof(ReturnDocumentTokensFromScratchForRangeData))] public void ReturnDocumentTokensFromScratch_ForRange(Range range, IEnumerable expectedTokens) { var document = new SemanticTokensDocument(_legend); @@ -123,9 +121,9 @@ public void ReturnDocumentTokensFromScratch_ForRange(Range range, IEnumerable> + public class ReturnDocumentTokensFromScratchForRangeData : TheoryData> { - public ReturnDocumentTokensFromScratch_ForRange_Data() + public ReturnDocumentTokensFromScratchForRangeData() { Add( new Range { @@ -179,7 +177,7 @@ public ReturnDocumentTokensFromScratch_ForRange_Data() } [Theory] - [ClassData(typeof(ReturnDocumentEdits_Data))] + [ClassData(typeof(ReturnDocumentEditsData))] public void ReturnDocumentEdits( string originalText, string modifiedText, IEnumerable expectedTokens @@ -205,7 +203,7 @@ IEnumerable expectedTokens var result = document.GetSemanticTokensEdits(); result.IsDelta.Should().BeTrue(); - var edits = result.Delta; + var edits = result.Delta!; edits.ResultId.Should().Be(document.Id); edits.Edits.Should().HaveCount(1); @@ -220,9 +218,9 @@ IEnumerable expectedTokens edit1Data.Should().ContainInOrder(expectedTokens); } - public class ReturnDocumentEdits_Data : TheoryData> + public class ReturnDocumentEditsData : TheoryData> { - public ReturnDocumentEdits_Data() + public ReturnDocumentEditsData() { Add( ExampleDocumentText, @@ -253,18 +251,19 @@ public ReturnDocumentEdits_Data() } } - private class TokenizationValue { - public SemanticTokenType type { get; set; } - public SemanticTokenModifier[] Modifiers { get; set; } + // ReSharper disable once UnusedAutoPropertyAccessor.Local + public SemanticTokenType Type { get; set; } + // ReSharper disable once UnusedAutoPropertyAccessor.Local + public SemanticTokenModifier[] Modifiers { get; set; } = Array.Empty(); } private void Tokenize(string document, SemanticTokensBuilder builder) { var faker = new Faker() .RuleFor( - z => z.type, + z => z.Type, f => f.PickRandom(SemanticTokenType.Defaults).OrNull(f, 0.2f) ?? new SemanticTokenType("none") ) .RuleFor( @@ -293,12 +292,12 @@ private void Tokenize(string document, SemanticTokensBuilder builder) var item = faker.Generate(); if (index % 2 == 0) { - builder.Push(line, index, part.Length, item.type, item.Modifiers); + builder.Push(line, index, part.Length, item.Type, item.Modifiers); } else { // ensure range gets some love - builder.Push(( ( line, index ), ( line, part.Length + index ) ), item.type, item.Modifiers); + builder.Push(( ( line, index ), ( line, part.Length + index ) ), item.Type, item.Modifiers); } } } @@ -329,16 +328,16 @@ public NormalizedToken(string text, SemanticTokenType type, params SemanticToken Modifiers = modifiers; } - public bool Equals(string other) => string.Equals(ToString(), other); + public bool Equals(string? other) => string.Equals(ToString(), other); - public bool Equals(NormalizedToken other) + public bool Equals(NormalizedToken? other) { if (other is null) return false; if (ReferenceEquals(this, other)) return true; return other.ToString() == ToString(); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj is null) return false; if (ReferenceEquals(this, obj)) return true; @@ -355,14 +354,7 @@ public override string ToString() sb.Append(Type); sb.Append(":"); - if (Modifiers?.Any() == true) - { - sb.Append(string.Join("|", Modifiers)); - } - else - { - sb.Append("none"); - } + sb.Append(Modifiers.Any() ? string.Join("|", Modifiers) : "none"); sb.Append(")"); @@ -392,7 +384,7 @@ public static implicit operator NormalizedToken(string value) public SemanticTokenModifier[] Modifiers { get; } } - private IReadOnlyList Normalize(string document, IReadOnlyList values) + private IReadOnlyList Normalize(string document, IReadOnlyList values) { var parts = Decompose(values).ToArray(); return parts @@ -401,7 +393,7 @@ private IReadOnlyList Normalize(string document, IReadOnlyList< .ToArray(); } - private NormalizedToken GetNormalizedToken( + private NormalizedToken? GetNormalizedToken( string document, IReadOnlyList<(int lineOffset, int charOffset, int length, int type, int modifiers)> tokens, int tokenIndex ) diff --git a/test/Lsp.Tests/SupportedCapabilitiesFixture.cs b/test/Lsp.Tests/SupportedCapabilitiesFixture.cs index a448522c0..4b075296d 100644 --- a/test/Lsp.Tests/SupportedCapabilitiesFixture.cs +++ b/test/Lsp.Tests/SupportedCapabilitiesFixture.cs @@ -14,6 +14,8 @@ public class SupportedCapabilitiesFixture private class AlwaysTrueSupportedCapabilities : ISupportedCapabilities { + // ReSharper disable once UnusedParameter.Local + // ReSharper disable once UnusedMember.Local public bool AllowsDynamicRegistration(ILspHandlerDescriptor descriptor) => true; public bool AllowsDynamicRegistration(Type capabilityType) => true; @@ -31,6 +33,8 @@ public void Add(ICapability capability) {} private class AlwaysFalseSupportedCapabilities : ISupportedCapabilities { + // ReSharper disable once UnusedParameter.Local + // ReSharper disable once UnusedMember.Local public bool AllowsDynamicRegistration(ILspHandlerDescriptor descriptor) => false; public bool AllowsDynamicRegistration(Type capabilityType) => false; diff --git a/test/Lsp.Tests/TextDocumentSyncHandlerExtensions.cs b/test/Lsp.Tests/TextDocumentSyncHandlerExtensions.cs index 79b0cc530..4fe2e3658 100644 --- a/test/Lsp.Tests/TextDocumentSyncHandlerExtensions.cs +++ b/test/Lsp.Tests/TextDocumentSyncHandlerExtensions.cs @@ -25,16 +25,5 @@ public static ITextDocumentSyncHandler With(this ITextDocumentSyncHandler handle return handler; } - - private static void For(this ITextDocumentSyncHandler handler, DocumentSelector documentSelector) - where T : class, IRegistration - { - var me = handler as T; - me.GetRegistrationOptions().Returns(GetOptions(me, documentSelector)); - } - - private static TextDocumentRegistrationOptions GetOptions(IRegistration handler, DocumentSelector documentSelector) - where R : TextDocumentRegistrationOptions, new() => - new R { DocumentSelector = documentSelector }; } } diff --git a/test/Lsp.Tests/VsCodeDocumentUriTests.cs b/test/Lsp.Tests/VsCodeDocumentUriTests.cs index 3a16f8644..16cc559bd 100644 --- a/test/Lsp.Tests/VsCodeDocumentUriTests.cs +++ b/test/Lsp.Tests/VsCodeDocumentUriTests.cs @@ -3,16 +3,11 @@ using FluentAssertions; using OmniSharp.Extensions.LanguageServer.Protocol; using Xunit; -using Xunit.Abstractions; namespace Lsp.Tests { public class VsCodeDocumentUriTests { - private readonly ITestOutputHelper _testOutputHelper; - - public VsCodeDocumentUriTests(ITestOutputHelper testOutputHelper) => _testOutputHelper = testOutputHelper; - [Fact(DisplayName = "file#toString")] public void FileToString() { diff --git a/test/Lsp.Tests/WorkspaceSymbolKindTests.cs b/test/Lsp.Tests/WorkspaceSymbolKindTests.cs index 945ae4b68..f3250e6dc 100644 --- a/test/Lsp.Tests/WorkspaceSymbolKindTests.cs +++ b/test/Lsp.Tests/WorkspaceSymbolKindTests.cs @@ -46,7 +46,7 @@ public void CustomBehavior_When_SymbolKind_Defined_By_Client() serializer.SetClientCapabilities( ClientVersion.Lsp3, new ClientCapabilities { Workspace = new WorkspaceClientCapabilities { - Symbol = new Supports( + Symbol = new Supports( true, new WorkspaceSymbolCapability { DynamicRegistration = true, SymbolKind = new SymbolKindCapabilityOptions { @@ -74,7 +74,7 @@ public void CustomBehavior_When_SymbolTag_Defined_By_Client() serializer.SetClientCapabilities( ClientVersion.Lsp3, new ClientCapabilities { Workspace = new WorkspaceClientCapabilities { - Symbol = new Supports( + Symbol = new Supports( true, new WorkspaceSymbolCapability { DynamicRegistration = true, TagSupport = new TagSupportCapabilityOptions { diff --git a/test/TestingUtils/AutoNSubstitute/AutoSubstitute.cs b/test/TestingUtils/AutoNSubstitute/AutoSubstitute.cs index f7b02c4b6..9fe76b9d1 100644 --- a/test/TestingUtils/AutoNSubstitute/AutoSubstitute.cs +++ b/test/TestingUtils/AutoNSubstitute/AutoSubstitute.cs @@ -17,8 +17,8 @@ internal class AutoSubstitute : IDisposable /// /// internal AutoSubstitute( - IContainer container = null, - Func configureAction = null + IContainer? container = null, + Func? configureAction = null ) { Container = container ?? new Container(); diff --git a/test/TestingUtils/AutoNSubstitute/AutoTestBase.cs b/test/TestingUtils/AutoNSubstitute/AutoTestBase.cs index 91d86aa77..81e3e0b53 100644 --- a/test/TestingUtils/AutoNSubstitute/AutoTestBase.cs +++ b/test/TestingUtils/AutoNSubstitute/AutoTestBase.cs @@ -10,7 +10,7 @@ namespace NSubstitute { public abstract class AutoTestBase { - private AutoSubstitute _autoSubstitute; + private AutoSubstitute? _autoSubstitute; private readonly Action _action; protected AutoTestBase(ITestOutputHelper testOutputHelper) diff --git a/test/TestingUtils/AutoNSubstitute/TestLoggerFactory.cs b/test/TestingUtils/AutoNSubstitute/TestLoggerFactory.cs index 12a2f0b3b..2d9d844a4 100644 --- a/test/TestingUtils/AutoNSubstitute/TestLoggerFactory.cs +++ b/test/TestingUtils/AutoNSubstitute/TestLoggerFactory.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Threading; using Microsoft.Extensions.Logging; using Serilog; @@ -17,12 +16,11 @@ public class TestLoggerFactory : ILoggerFactory private readonly InnerTestOutputHelper _testOutputHelper; public TestLoggerFactory( - ITestOutputHelper testOutputHelper, string outputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}", + ITestOutputHelper? testOutputHelper, string outputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}", LogEventLevel logEventLevel = LogEventLevel.Debug ) { - _testOutputHelper = new InnerTestOutputHelper(); - _testOutputHelper.Swap(testOutputHelper); + _testOutputHelper = new InnerTestOutputHelper(testOutputHelper); _loggerProvider = new SerilogLoggerProvider( new LoggerConfiguration() @@ -50,7 +48,12 @@ public void Swap(ITestOutputHelper testOutputHelper) class InnerTestOutputHelper : ITestOutputHelper { - private ITestOutputHelper _testOutputHelper; + private ITestOutputHelper? _testOutputHelper; + + public InnerTestOutputHelper(ITestOutputHelper? testOutputHelper) + { + _testOutputHelper = testOutputHelper; + } public void Swap(ITestOutputHelper testOutputHelper) { Interlocked.Exchange(ref _testOutputHelper, testOutputHelper); diff --git a/test/TestingUtils/FactWithSkipOnAttribute.cs b/test/TestingUtils/FactWithSkipOnAttribute.cs index f19c0ddf3..f1524aeb3 100644 --- a/test/TestingUtils/FactWithSkipOnAttribute.cs +++ b/test/TestingUtils/FactWithSkipOnAttribute.cs @@ -1,6 +1,5 @@ using System; using System.Collections; -using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -11,14 +10,14 @@ namespace TestingUtils public class FactWithSkipOnAttribute : FactAttribute { private readonly SkipOnPlatform[] _platformsToSkip; - private string _skip; + private string? _skip; public FactWithSkipOnAttribute(params SkipOnPlatform[] platformsToSkip) { _platformsToSkip = platformsToSkip; } - public override string Skip + public override string? Skip { get => !UnitTestDetector.IsCI() && _platformsToSkip.Any(UnitTestDetector.PlatformToSkipPredicate) ? "Skipped on platform" + ( string.IsNullOrWhiteSpace(_skip) ? "" : " because " + _skip ) diff --git a/test/TestingUtils/TheoryWithSkipOnAttribute.cs b/test/TestingUtils/TheoryWithSkipOnAttribute.cs index 66fc1f2fa..8fd6feae6 100644 --- a/test/TestingUtils/TheoryWithSkipOnAttribute.cs +++ b/test/TestingUtils/TheoryWithSkipOnAttribute.cs @@ -6,14 +6,14 @@ namespace TestingUtils public class TheoryWithSkipOnAttribute : TheoryAttribute { private readonly SkipOnPlatform[] _platformsToSkip; - private string _skip; + private string? _skip; public TheoryWithSkipOnAttribute(params SkipOnPlatform[] platformsToSkip) { _platformsToSkip = platformsToSkip; } - public override string Skip + public override string? Skip { get => /*!UnitTestDetector.IsCI() && */_platformsToSkip.Any(UnitTestDetector.PlatformToSkipPredicate) ? "Skipped on platform" + ( string.IsNullOrWhiteSpace(_skip) ? "" : " because " + _skip ) diff --git a/test/TestingUtils/UnitTestDetector.cs b/test/TestingUtils/UnitTestDetector.cs index e61df15dc..5a0c5abf6 100644 --- a/test/TestingUtils/UnitTestDetector.cs +++ b/test/TestingUtils/UnitTestDetector.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; @@ -7,6 +6,7 @@ namespace TestingUtils { class UnitTestDetector { + // ReSharper disable once InconsistentNaming public static bool IsCI() => string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("CI")) && string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("TF_BUILD"));