mirror of
https://github.com/ckaczor/sqltoolsservice.git
synced 2026-01-24 09:35:39 -05:00
Move unused forked code to external directory (#1192)
* Move unused forked code to external directory * Fix SLN build errors * Add back resource provider core since it's referenced by main resource provider project * Update PackageProjects step of pipeline
This commit is contained in:
@@ -1,77 +0,0 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
//
|
||||
|
||||
using System;
|
||||
using Microsoft.SqlTools.Hosting.Contracts;
|
||||
using Microsoft.SqlTools.Hosting.Contracts.Internal;
|
||||
using Microsoft.SqlTools.Hosting.Protocol;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using NUnit.Framework.Interfaces;
|
||||
|
||||
namespace Microsoft.SqlTools.Hosting.UnitTests
|
||||
{
|
||||
public static class CommonObjects
|
||||
{
|
||||
public const string MessageId = "123";
|
||||
|
||||
public static readonly RequestType<TestMessageContents, TestMessageContents> RequestType =
|
||||
RequestType<TestMessageContents, TestMessageContents>.Create("test/request");
|
||||
|
||||
public static readonly EventType<TestMessageContents> EventType =
|
||||
EventType<TestMessageContents>.Create("test/event");
|
||||
|
||||
public static readonly Message RequestMessage =
|
||||
Message.CreateRequest(RequestType, MessageId, TestMessageContents.DefaultInstance);
|
||||
|
||||
public static readonly Message ResponseMessage =
|
||||
Message.CreateResponse(MessageId, TestMessageContents.DefaultInstance);
|
||||
|
||||
public static readonly Message EventMessage =
|
||||
Message.CreateEvent(EventType, TestMessageContents.DefaultInstance);
|
||||
|
||||
public static class TestErrorContents
|
||||
{
|
||||
public static readonly JToken SerializedContents = JToken.Parse("{\"code\": 123, \"message\": \"error\"}");
|
||||
public static readonly Error DefaultInstance = new Error {Code = 123, Message = "error"};
|
||||
}
|
||||
|
||||
public class TestMessageContents : IEquatable<TestMessageContents>
|
||||
{
|
||||
public const string JsonContents = "{\"someField\": \"Some value\", \"number\": 42}";
|
||||
public static readonly JToken SerializedContents = JToken.Parse(JsonContents);
|
||||
public static readonly TestMessageContents DefaultInstance = new TestMessageContents {Number = 42, SomeField = "Some value"};
|
||||
|
||||
public string SomeField { get; set; }
|
||||
public int Number { get; set; }
|
||||
|
||||
public bool Equals(TestMessageContents other)
|
||||
{
|
||||
return string.Equals(SomeField, other.SomeField)
|
||||
&& Number == other.Number;
|
||||
}
|
||||
|
||||
public override bool Equals(object obj)
|
||||
{
|
||||
return Equals(obj as TestMessageContents);
|
||||
}
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
return SomeField.GetHashCode() ^ Number;
|
||||
}
|
||||
public static bool operator ==(TestMessageContents obj1, TestMessageContents obj2)
|
||||
{
|
||||
bool bothNull = ReferenceEquals(obj1, null) && ReferenceEquals(obj2, null);
|
||||
bool someNull = ReferenceEquals(obj1, null) || ReferenceEquals(obj2, null);
|
||||
return bothNull || !someNull && obj1.Equals(obj2);
|
||||
}
|
||||
|
||||
public static bool operator !=(TestMessageContents obj1, TestMessageContents obj2)
|
||||
{
|
||||
return !(obj1 == obj2);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
//
|
||||
|
||||
using Microsoft.SqlTools.DataProtocol.Contracts.Utilities;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace Microsoft.SqlTools.Hosting.UnitTests.Contracts.Utilities
|
||||
{
|
||||
[TestFixture]
|
||||
public class FlagsIntConverterTests
|
||||
{
|
||||
[Test]
|
||||
public void NullableValueCanBeDeserialized()
|
||||
{
|
||||
var jsonObject = JObject.Parse("{\"optionalValue\": [1, 2]}");
|
||||
var contract = jsonObject.ToObject<DataContract>();
|
||||
Assert.NotNull(contract);
|
||||
Assert.NotNull(contract.OptionalValue);
|
||||
Assert.AreEqual(TestFlags.FirstItem | TestFlags.SecondItem, contract.OptionalValue);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RegularValueCanBeDeserialized()
|
||||
{
|
||||
var jsonObject = JObject.Parse("{\"Value\": [1, 3]}");
|
||||
var contract = jsonObject.ToObject<DataContract>();
|
||||
Assert.NotNull(contract);
|
||||
Assert.AreEqual(TestFlags.FirstItem | TestFlags.ThirdItem, contract.Value);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ExplicitNullCanBeDeserialized()
|
||||
{
|
||||
var jsonObject = JObject.Parse("{\"optionalValue\": null}");
|
||||
var contract = jsonObject.ToObject<DataContract>();
|
||||
Assert.NotNull(contract);
|
||||
Assert.Null(contract.OptionalValue);
|
||||
}
|
||||
|
||||
[Flags]
|
||||
[JsonConverter(typeof(FlagsIntConverter))]
|
||||
private enum TestFlags
|
||||
{
|
||||
[FlagsIntConverter.SerializeValue(1)]
|
||||
FirstItem = 1 << 0,
|
||||
|
||||
[FlagsIntConverter.SerializeValue(2)]
|
||||
SecondItem = 1 << 1,
|
||||
|
||||
[FlagsIntConverter.SerializeValue(3)]
|
||||
ThirdItem = 1 << 2,
|
||||
}
|
||||
|
||||
private class DataContract
|
||||
{
|
||||
public TestFlags? OptionalValue { get; set; }
|
||||
|
||||
public TestFlags Value { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
//
|
||||
|
||||
using System;
|
||||
using Microsoft.SqlTools.DataProtocol.Contracts.Utilities;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace Microsoft.SqlTools.Hosting.UnitTests.Contracts.Utilities
|
||||
{
|
||||
[TestFixture]
|
||||
public class FlagsStringConverterTests
|
||||
{
|
||||
[Test]
|
||||
public void NullableValueCanBeDeserialized()
|
||||
{
|
||||
var jsonObject = JObject.Parse("{\"optionalValue\": [\"First\", \"Second\"]}");
|
||||
var contract = jsonObject.ToObject<DataContract>();
|
||||
Assert.NotNull(contract);
|
||||
Assert.NotNull(contract.OptionalValue);
|
||||
Assert.AreEqual(TestFlags.FirstItem | TestFlags.SecondItem, contract.OptionalValue);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RegularValueCanBeDeserialized()
|
||||
{
|
||||
var jsonObject = JObject.Parse("{\"Value\": [\"First\", \"Third\"]}");
|
||||
var contract = jsonObject.ToObject<DataContract>();
|
||||
Assert.NotNull(contract);
|
||||
Assert.AreEqual(TestFlags.FirstItem | TestFlags.ThirdItem, contract.Value);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ExplicitNullCanBeDeserialized()
|
||||
{
|
||||
var jsonObject = JObject.Parse("{\"optionalValue\": null}");
|
||||
var contract = jsonObject.ToObject<DataContract>();
|
||||
Assert.NotNull(contract);
|
||||
Assert.Null(contract.OptionalValue);
|
||||
}
|
||||
|
||||
[Flags]
|
||||
[JsonConverter(typeof(FlagsStringConverter))]
|
||||
private enum TestFlags
|
||||
{
|
||||
[FlagsStringConverter.SerializeValue("First")]
|
||||
FirstItem = 1 << 0,
|
||||
|
||||
[FlagsStringConverter.SerializeValue("Second")]
|
||||
SecondItem = 1 << 1,
|
||||
|
||||
[FlagsStringConverter.SerializeValue("Third")]
|
||||
ThirdItem = 1 << 2,
|
||||
}
|
||||
|
||||
private class DataContract
|
||||
{
|
||||
public TestFlags? OptionalValue { get; set; }
|
||||
|
||||
public TestFlags Value { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
//
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using Microsoft.SqlTools.Hosting.Extensibility;
|
||||
using Microsoft.SqlTools.Hosting.Utility;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace Microsoft.SqlTools.Hosting.UnitTests.ExtensibilityTests
|
||||
{
|
||||
|
||||
[TestFixture]
|
||||
public class ServiceProviderTests
|
||||
{
|
||||
private RegisteredServiceProvider provider;
|
||||
|
||||
[SetUp]
|
||||
public void SetupServiceProviderTests()
|
||||
{
|
||||
provider = new RegisteredServiceProvider();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetServiceShouldReturnNullIfNoServicesRegistered()
|
||||
{
|
||||
// Given no service registered
|
||||
// When I call GetService
|
||||
var service = provider.GetService<MyProviderService>();
|
||||
// Then I expect null to be returned
|
||||
Assert.Null(service);
|
||||
}
|
||||
|
||||
|
||||
[Test]
|
||||
public void GetSingleServiceThrowsMultipleServicesRegistered()
|
||||
{
|
||||
// Given 2 services registered
|
||||
provider.Register(() => new[] { new MyProviderService(), new MyProviderService() });
|
||||
// When I call GetService
|
||||
// Then I expect to throw
|
||||
Assert.Throws<InvalidOperationException>(() => provider.GetService<MyProviderService>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetServicesShouldReturnEmptyIfNoServicesRegistered()
|
||||
{
|
||||
// Given no service regisstered
|
||||
// When I call GetService
|
||||
var services = provider.GetServices<MyProviderService>();
|
||||
Assert.That(services, Is.Empty, "provider.GetServices with no service registered");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetServiceShouldReturnRegisteredService()
|
||||
{
|
||||
MyProviderService service = new MyProviderService();
|
||||
provider.RegisterSingleService(service);
|
||||
|
||||
var returnedService = provider.GetService<MyProviderService>();
|
||||
Assert.AreEqual(service, returnedService);
|
||||
}
|
||||
|
||||
// DEVNOTE: The name of this test doesn't match the code, which is pretty much the same as the one above.
|
||||
[Test]
|
||||
public void GetServicesShouldReturnRegisteredServiceWhenMultipleServicesRegistered()
|
||||
{
|
||||
MyProviderService service = new MyProviderService();
|
||||
provider.RegisterSingleService(service);
|
||||
|
||||
var returnedServices = provider.GetServices<MyProviderService>();
|
||||
Assert.AreEqual(service, returnedServices.Single());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RegisterServiceProviderShouldThrowIfServiceIsIncompatible()
|
||||
{
|
||||
MyProviderService service = new MyProviderService();
|
||||
Assert.Throws<InvalidOperationException>(() => provider.RegisterSingleService(typeof(OtherService), service));
|
||||
}
|
||||
[Test]
|
||||
public void RegisterServiceProviderShouldThrowIfServiceAlreadyRegistered()
|
||||
{
|
||||
MyProviderService service = new MyProviderService();
|
||||
provider.RegisterSingleService(service);
|
||||
|
||||
Assert.Throws<InvalidOperationException>(() => provider.RegisterSingleService(service));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RegisterShouldThrowIfServiceAlreadyRegistered()
|
||||
{
|
||||
MyProviderService service = new MyProviderService();
|
||||
provider.RegisterSingleService(service);
|
||||
|
||||
Assert.Throws<InvalidOperationException>(() => provider.Register(() => service.AsSingleItemEnumerable()));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RegisterShouldThrowIfServicesAlreadyRegistered()
|
||||
{
|
||||
provider.Register(() => new [] { new MyProviderService(), new MyProviderService() });
|
||||
Assert.Throws<InvalidOperationException>(() => provider.Register(() => new MyProviderService().AsSingleItemEnumerable()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public class MyProviderService
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public class OtherService
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>$(TestProjectsTargetFramework)</TargetFramework>
|
||||
<IsPackable>false</IsPackable>
|
||||
<TargetLatestRuntimePatch>true</TargetLatestRuntimePatch>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||
<PackageReference Include="Moq"/>
|
||||
<PackageReference Include="nunit"/>
|
||||
<PackageReference Include="nunit3testadapter"/>
|
||||
<PackageReference Include="nunit.console"/>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\Microsoft.SqlTools.DataProtocol.Contracts\Microsoft.SqlTools.DataProtocol.Contracts.csproj" />
|
||||
<ProjectReference Include="..\..\src\Microsoft.SqlTools.Hosting.Contracts\Microsoft.SqlTools.Hosting.Contracts.csproj" />
|
||||
<ProjectReference Include="..\..\src\Microsoft.SqlTools.Hosting.v2\Microsoft.SqlTools.Hosting.v2.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,32 +0,0 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
//
|
||||
|
||||
using System.Collections.Concurrent;
|
||||
using System.Linq;
|
||||
using Microsoft.SqlTools.Hosting.Protocol;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
|
||||
{
|
||||
[TestFixture]
|
||||
public class EventContextTests
|
||||
{
|
||||
[Test]
|
||||
public void SendEvent()
|
||||
{
|
||||
// Setup: Create collection
|
||||
var bc = new BlockingCollection<Message>(new ConcurrentQueue<Message>());
|
||||
|
||||
// If: I construct an event context with a message writer
|
||||
// And send an event with it
|
||||
var eventContext = new EventContext(bc);
|
||||
eventContext.SendEvent(CommonObjects.EventType, CommonObjects.TestMessageContents.DefaultInstance);
|
||||
|
||||
// Then: The message should be added to the queue
|
||||
var messages = bc.ToArray().Select(m => m.MessageType);
|
||||
Assert.That(messages, Is.EqualTo(new[] { MessageType.Event }), "Single message of type event in the queue after SendEvent");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,807 +0,0 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
//
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.SqlTools.Hosting.Channels;
|
||||
using Microsoft.SqlTools.Hosting.Protocol;
|
||||
using Microsoft.SqlTools.ServiceLayer.Test.Common;
|
||||
using Moq;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
|
||||
{
|
||||
[TestFixture]
|
||||
public class JsonRpcHostTests
|
||||
{
|
||||
[Test]
|
||||
public void ConstructWithNullProtocolChannel()
|
||||
{
|
||||
// If: I construct a JSON RPC host with a null protocol channel
|
||||
// Then: I should get an exception
|
||||
Assert.Throws<ArgumentNullException>(() => new JsonRpcHost(null));
|
||||
}
|
||||
|
||||
#region SetRequestHandler Tests
|
||||
|
||||
[Test]
|
||||
public void SetAsyncRequestHandlerNullRequestType()
|
||||
{
|
||||
// If: I assign a request handler on the JSON RPC host with a null request type
|
||||
// Then: I should get an exception
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
|
||||
Assert.Throws<ArgumentNullException>(() =>
|
||||
jh.SetAsyncRequestHandler<object, object>(null, (a, b) => Task.FromResult(false)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SetAsyncRequestHandlerNullRequestHandler()
|
||||
{
|
||||
// If: I assign a request handler on the JSON RPC host with a null request handler
|
||||
// Then: I should get an exception
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
|
||||
Assert.Throws<ArgumentNullException>(() => jh.SetAsyncRequestHandler(CommonObjects.RequestType, null));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SetSyncRequestHandlerNullRequestHandler()
|
||||
{
|
||||
// If: I assign a request handler on the JSON RPC host with a null request handler
|
||||
// Then: I should get an exception
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
|
||||
Assert.Throws<ArgumentNullException>(() => jh.SetRequestHandler(CommonObjects.RequestType, null));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SetAsyncRequestHandler([Values]bool nullContents)
|
||||
{
|
||||
// Setup: Create a mock request handler
|
||||
var requestHandler = new Mock<Func<CommonObjects.TestMessageContents, RequestContext<CommonObjects.TestMessageContents>, Task>>();
|
||||
var message = nullContents
|
||||
? Message.CreateRequest(CommonObjects.RequestType, CommonObjects.MessageId, null)
|
||||
: CommonObjects.RequestMessage;
|
||||
|
||||
// If: I assign a request handler on the JSON RPC host
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
|
||||
jh.SetAsyncRequestHandler(CommonObjects.RequestType, requestHandler.Object);
|
||||
|
||||
// Then: It should be the only request handler set
|
||||
Assert.That(jh.requestHandlers.Keys, Is.EqualTo(new[] { CommonObjects.RequestType.MethodName }), "requestHandlers.Keys after SetAsyncRequestHandler");
|
||||
|
||||
// If: I call the stored request handler
|
||||
await jh.requestHandlers[CommonObjects.RequestType.MethodName](message);
|
||||
await jh.requestHandlers[CommonObjects.RequestType.MethodName](message);
|
||||
|
||||
// Then: The request handler should have been called with the params and a proper request context
|
||||
var expectedContents = nullContents
|
||||
? null
|
||||
: CommonObjects.TestMessageContents.DefaultInstance;
|
||||
requestHandler.Verify(a => a(
|
||||
It.Is<CommonObjects.TestMessageContents>(p => p == expectedContents),
|
||||
It.Is<RequestContext<CommonObjects.TestMessageContents>>(rc => rc.messageQueue == jh.outputQueue && rc.requestMessage == message)
|
||||
), Times.Exactly(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SetSyncRequestHandler([Values]bool nullContents)
|
||||
{
|
||||
// Setup: Create a mock request handler
|
||||
var requestHandler = new Mock<Action<CommonObjects.TestMessageContents, RequestContext<CommonObjects.TestMessageContents>>>();
|
||||
var message = nullContents
|
||||
? Message.CreateRequest(CommonObjects.RequestType, CommonObjects.MessageId, null)
|
||||
: CommonObjects.RequestMessage;
|
||||
|
||||
// If: I assign a request handler on the JSON RPC host
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
|
||||
jh.SetRequestHandler(CommonObjects.RequestType, requestHandler.Object);
|
||||
|
||||
// Then: It should be the only request handler set
|
||||
Assert.That(jh.requestHandlers.Keys, Is.EqualTo(new[] { CommonObjects.RequestType.MethodName }), "requestHandlers.Keys after SetRequestHandler");
|
||||
|
||||
// If: I call the stored request handler
|
||||
await jh.requestHandlers[CommonObjects.RequestType.MethodName](message);
|
||||
await jh.requestHandlers[CommonObjects.RequestType.MethodName](message);
|
||||
|
||||
// Then: The request handler should have been called with the params and a proper request context
|
||||
var expectedContents = nullContents
|
||||
? null
|
||||
: CommonObjects.TestMessageContents.DefaultInstance;
|
||||
requestHandler.Verify(a => a(
|
||||
It.Is<CommonObjects.TestMessageContents>(p => p == expectedContents),
|
||||
It.Is<RequestContext<CommonObjects.TestMessageContents>>(rc => rc.messageQueue == jh.outputQueue && rc.requestMessage == message)
|
||||
), Times.Exactly(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SetAsyncRequestHandlerOverrideTrue()
|
||||
{
|
||||
// Setup: Create two mock request handlers
|
||||
var requestHandler1 = new Mock<Func<CommonObjects.TestMessageContents, RequestContext<CommonObjects.TestMessageContents>, Task>>();
|
||||
var requestHandler2 = new Mock<Func<CommonObjects.TestMessageContents, RequestContext<CommonObjects.TestMessageContents>, Task>>();
|
||||
|
||||
// If:
|
||||
// ... I assign a request handler on the JSON RPC host
|
||||
// ... And I reassign the request handler with an override
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
|
||||
jh.SetAsyncRequestHandler(CommonObjects.RequestType, requestHandler1.Object);
|
||||
jh.SetAsyncRequestHandler(CommonObjects.RequestType, requestHandler2.Object, true);
|
||||
|
||||
// Then: There should only be one request handler
|
||||
Assert.That(jh.requestHandlers.Keys, Is.EqualTo(new[] { CommonObjects.RequestType.MethodName }), "requestHandlers.Keys after SetAsyncRequestHandler with override");
|
||||
|
||||
// If: I call the stored request handler
|
||||
await jh.requestHandlers[CommonObjects.RequestType.MethodName](CommonObjects.RequestMessage);
|
||||
|
||||
// Then: The correct request handler should have been called
|
||||
requestHandler2.Verify(a => a(
|
||||
It.Is<CommonObjects.TestMessageContents>(p => p.Equals(CommonObjects.TestMessageContents.DefaultInstance)),
|
||||
It.Is<RequestContext<CommonObjects.TestMessageContents>>(p => p.messageQueue == jh.outputQueue && p.requestMessage == CommonObjects.RequestMessage)
|
||||
), Times.Once);
|
||||
requestHandler1.Verify(a => a(
|
||||
It.IsAny<CommonObjects.TestMessageContents>(),
|
||||
It.IsAny<RequestContext<CommonObjects.TestMessageContents>>()
|
||||
), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SetAsyncRequestHandlerOverrideFalse()
|
||||
{
|
||||
// Setup: Create a mock request handler
|
||||
var requestHandler = new Mock<Func<CommonObjects.TestMessageContents, RequestContext<CommonObjects.TestMessageContents>, Task>>();
|
||||
|
||||
// If:
|
||||
// ... I assign a request handler on the JSON RPC host
|
||||
// ... And I reassign the request handler without overriding
|
||||
// Then: I should get an exception
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
|
||||
jh.SetAsyncRequestHandler(CommonObjects.RequestType, requestHandler.Object);
|
||||
Assert.That(() => jh.SetAsyncRequestHandler(CommonObjects.RequestType, requestHandler.Object), Throws.InstanceOf<Exception>(), "Reassign request handler without overriding");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region SetEventHandler Tests
|
||||
|
||||
[Test]
|
||||
public void SetAsyncEventHandlerNullEventType()
|
||||
{
|
||||
// If: I assign an event handler on the JSON RPC host with a null event type
|
||||
// Then: I should get an exception
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
|
||||
Assert.Throws<ArgumentNullException>(() =>
|
||||
jh.SetAsyncEventHandler<object>(null, (a, b) => Task.FromResult(false)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SetAsyncEventHandlerNull()
|
||||
{
|
||||
// If: I assign an event handler on the message gispatcher with a null event handler
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
|
||||
Assert.Throws<ArgumentNullException>(() => jh.SetAsyncEventHandler(CommonObjects.EventType, null));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SetSyncEventHandlerNull()
|
||||
{
|
||||
// If: I assign an event handler on the message gispatcher with a null event handler
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
|
||||
Assert.Throws<ArgumentNullException>(() => jh.SetEventHandler(CommonObjects.EventType, null));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SetAsyncEventHandler([Values]bool nullContents)
|
||||
{
|
||||
// Setup: Create a mock request handler
|
||||
var eventHandler = new Mock<Func<CommonObjects.TestMessageContents, EventContext, Task>>();
|
||||
var message = nullContents
|
||||
? Message.CreateEvent(CommonObjects.EventType, null)
|
||||
: CommonObjects.EventMessage;
|
||||
|
||||
// If: I assign an event handler on the JSON RPC host
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
|
||||
jh.SetAsyncEventHandler(CommonObjects.EventType, eventHandler.Object);
|
||||
|
||||
// Then: It should be the only event handler set
|
||||
Assert.That(jh.eventHandlers.Keys, Is.EqualTo(new[] { CommonObjects.EventType.MethodName }), "eventHandlers.Keys after SetAsyncRequestHandler");
|
||||
|
||||
// If: I call the stored event handler
|
||||
await jh.eventHandlers[CommonObjects.EventType.MethodName](message);
|
||||
await jh.eventHandlers[CommonObjects.EventType.MethodName](message);
|
||||
|
||||
// Then: The event handler should have been called with the params and a proper event context
|
||||
var expectedContents = nullContents
|
||||
? null
|
||||
: CommonObjects.TestMessageContents.DefaultInstance;
|
||||
eventHandler.Verify(a => a(
|
||||
It.Is<CommonObjects.TestMessageContents>(p => p == expectedContents),
|
||||
It.Is<EventContext>(p => p.messageQueue == jh.outputQueue)
|
||||
), Times.Exactly(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SetSyncEventHandler([Values]bool nullContents)
|
||||
{
|
||||
// Setup: Create a mock request handler
|
||||
var eventHandler = new Mock<Action<CommonObjects.TestMessageContents, EventContext>>();
|
||||
var message = nullContents
|
||||
? Message.CreateEvent(CommonObjects.EventType, null)
|
||||
: CommonObjects.EventMessage;
|
||||
|
||||
// If: I assign an event handler on the JSON RPC host
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
|
||||
jh.SetEventHandler(CommonObjects.EventType, eventHandler.Object);
|
||||
|
||||
// Then: It should be the only event handler set
|
||||
Assert.That(jh.eventHandlers.Keys, Is.EqualTo(new object[] { CommonObjects.EventType.MethodName }), "eventHandlers.Keys after SetEventHandler");
|
||||
|
||||
// If: I call the stored event handler
|
||||
await jh.eventHandlers[CommonObjects.EventType.MethodName](message);
|
||||
await jh.eventHandlers[CommonObjects.EventType.MethodName](message);
|
||||
|
||||
// Then: The event handler should have been called with the params and a proper event context
|
||||
var expectedContents = nullContents
|
||||
? null
|
||||
: CommonObjects.TestMessageContents.DefaultInstance;
|
||||
eventHandler.Verify(a => a(
|
||||
It.Is<CommonObjects.TestMessageContents>(p => p == expectedContents),
|
||||
It.Is<EventContext>(p => p.messageQueue == jh.outputQueue)
|
||||
), Times.Exactly(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SetAsyncEventHandlerOverrideTrue()
|
||||
{
|
||||
// Setup: Create two mock event handlers
|
||||
var eventHandler1 = new Mock<Func<CommonObjects.TestMessageContents, EventContext, Task>>();
|
||||
var eventHandler2 = new Mock<Func<CommonObjects.TestMessageContents, EventContext, Task>>();
|
||||
|
||||
// If:
|
||||
// ... I assign an event handler on the JSON RPC host
|
||||
// ... And I reassign the event handler with an override
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
|
||||
|
||||
jh.SetAsyncEventHandler(CommonObjects.EventType, eventHandler1.Object);
|
||||
jh.SetAsyncEventHandler(CommonObjects.EventType, eventHandler2.Object, true);
|
||||
|
||||
// Then: There should only be one event handler
|
||||
Assert.That(jh.eventHandlers.Keys, Is.EqualTo(new[] { CommonObjects.EventType.MethodName }), "requestHandlers.Keys after SetAsyncEventHandler with override");
|
||||
|
||||
// If: I call the stored event handler
|
||||
await jh.eventHandlers[CommonObjects.EventType.MethodName](CommonObjects.EventMessage);
|
||||
|
||||
// Then: The correct event handler should have been called
|
||||
eventHandler2.Verify(a => a(
|
||||
It.Is<CommonObjects.TestMessageContents>(p => p.Equals(CommonObjects.TestMessageContents.DefaultInstance)),
|
||||
It.Is<EventContext>(p => p.messageQueue == jh.outputQueue)
|
||||
), Times.Once);
|
||||
eventHandler1.Verify(a => a(
|
||||
It.IsAny<CommonObjects.TestMessageContents>(),
|
||||
It.IsAny<EventContext>()
|
||||
), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SetAsyncEventHandlerOverrideFalse()
|
||||
{
|
||||
// Setup: Create a mock event handler
|
||||
var eventHandler = new Mock<Func<CommonObjects.TestMessageContents, EventContext, Task>>();
|
||||
|
||||
// If:
|
||||
// ... I assign an event handler on the JSON RPC host
|
||||
// ... And I reassign the event handler without overriding
|
||||
// Then: I should get an exception
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
|
||||
jh.SetAsyncEventHandler(CommonObjects.EventType, eventHandler.Object);
|
||||
Assert.That(() => jh.SetAsyncEventHandler(CommonObjects.EventType, eventHandler.Object), Throws.InstanceOf<Exception>(), "SetAsyncEventHandler without overriding");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region SendEvent Tests
|
||||
|
||||
[Test]
|
||||
public void SendEventNotConnected()
|
||||
{
|
||||
// If: I send an event when the protocol channel isn't connected
|
||||
// Then: I should get an exception
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
|
||||
Assert.Throws<InvalidOperationException>(() => jh.SendEvent(CommonObjects.EventType, CommonObjects.TestMessageContents.DefaultInstance));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SendEvent()
|
||||
{
|
||||
// Setup: Create a Json RPC Host with a connected channel
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, null, true).Object);
|
||||
|
||||
// If: I send an event
|
||||
jh.SendEvent(CommonObjects.EventType, CommonObjects.TestMessageContents.DefaultInstance);
|
||||
|
||||
// Then: The message should be added to the output queue
|
||||
Assert.That(jh.outputQueue.ToArray().Select(m => (m.Contents, m.Method)),
|
||||
Is.EqualTo(new[] { (CommonObjects.TestMessageContents.SerializedContents, CommonObjects.EventType.MethodName) }), "outputQueue after SendEvent");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region SendRequest Tests
|
||||
|
||||
[Test]
|
||||
public async Task SendRequestNotConnected()
|
||||
{
|
||||
// If: I send an event when the protocol channel isn't connected
|
||||
// Then: I should get an exception
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
|
||||
Assert.ThrowsAsync<InvalidOperationException>(() => jh.SendRequest(CommonObjects.RequestType, CommonObjects.TestMessageContents.DefaultInstance));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SendRequest()
|
||||
{
|
||||
// If: I send a request with the JSON RPC host
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, null, true).Object);
|
||||
Task<CommonObjects.TestMessageContents> requestTask = jh.SendRequest(CommonObjects.RequestType, CommonObjects.TestMessageContents.DefaultInstance);
|
||||
|
||||
// Then: There should be a pending request
|
||||
Assert.That(jh.pendingRequests.Count, Is.EqualTo(1), "pendingRequests.Count after SendRequest");
|
||||
|
||||
// If: I then trick it into completing the request
|
||||
jh.pendingRequests.First().Value.SetResult(CommonObjects.ResponseMessage);
|
||||
var responseContents = await requestTask;
|
||||
|
||||
// Then: The returned results should be the contents of the message
|
||||
Assert.AreEqual(CommonObjects.TestMessageContents.DefaultInstance, responseContents);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region DispatchMessage Tests
|
||||
|
||||
[Test]
|
||||
public async Task DispatchMessageRequestWithoutHandler()
|
||||
{
|
||||
// Setup: Create a JSON RPC host without a request handler
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
|
||||
|
||||
// If: I dispatch a request that doesn't have a handler
|
||||
// Then: I should get an exception
|
||||
Assert.ThrowsAsync<MethodHandlerDoesNotExistException>(() => jh.DispatchMessage(CommonObjects.RequestMessage));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DispatchMessageRequestException()
|
||||
{
|
||||
// Setup: Create a JSON RPC host with a request handler that throws an unhandled exception every time
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
|
||||
var mockHandler = new Mock<Func<CommonObjects.TestMessageContents, RequestContext<CommonObjects.TestMessageContents>, Task>>();
|
||||
mockHandler.Setup(f => f(
|
||||
It.IsAny<CommonObjects.TestMessageContents>(),
|
||||
It.IsAny<RequestContext<CommonObjects.TestMessageContents>>()
|
||||
))
|
||||
.Returns(Task.FromException(new Exception()));
|
||||
jh.SetAsyncRequestHandler(CommonObjects.RequestType, mockHandler.Object);
|
||||
|
||||
// If: I dispatch a message whose handler throws
|
||||
// Then: I should get an exception
|
||||
Assert.ThrowsAsync<Exception>(() => jh.DispatchMessage(CommonObjects.RequestMessage));
|
||||
}
|
||||
|
||||
[TestCaseSource(nameof(DispatchMessageWithHandlerData))]
|
||||
public async Task DispatchMessageRequestWithHandler(Task result)
|
||||
{
|
||||
// Setup: Create a JSON RPC host with a request handler setup
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
|
||||
var mockHandler = new Mock<Func<CommonObjects.TestMessageContents, RequestContext<CommonObjects.TestMessageContents>, Task>>();
|
||||
mockHandler.Setup(f => f(
|
||||
It.Is<CommonObjects.TestMessageContents>(m => m == CommonObjects.TestMessageContents.DefaultInstance),
|
||||
It.Is<RequestContext<CommonObjects.TestMessageContents>>(rc => rc.messageQueue == jh.outputQueue)
|
||||
)).Returns(result);
|
||||
jh.SetAsyncRequestHandler(CommonObjects.RequestType, mockHandler.Object);
|
||||
|
||||
// If: I dispatch a request
|
||||
await jh.DispatchMessage(CommonObjects.RequestMessage);
|
||||
|
||||
// Then: The request handler should have been called
|
||||
mockHandler.Verify(f => f(
|
||||
It.Is<CommonObjects.TestMessageContents>(m => m == CommonObjects.TestMessageContents.DefaultInstance),
|
||||
It.IsAny<RequestContext<CommonObjects.TestMessageContents>>()
|
||||
), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DispatchmessageResponseWithoutHandler()
|
||||
{
|
||||
// Setup: Create a new JSON RPC host without any pending requests
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
|
||||
|
||||
// If: I dispatch a response that doesn't have a pending request
|
||||
// Then: I should get an exception
|
||||
Assert.ThrowsAsync<MethodHandlerDoesNotExistException>(() => jh.DispatchMessage(CommonObjects.ResponseMessage));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DispatchMessageResponseWithHandler()
|
||||
{
|
||||
// Setup: Create a new JSON RPC host that has a pending request handler
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
|
||||
var mockPendingRequest = new TaskCompletionSource<Message>();
|
||||
jh.pendingRequests.TryAdd(CommonObjects.MessageId, mockPendingRequest);
|
||||
|
||||
// If: I dispatch a response
|
||||
await jh.DispatchMessage(CommonObjects.ResponseMessage);
|
||||
|
||||
// Then: The task completion source should have completed with the message that was given
|
||||
await mockPendingRequest.Task.WithTimeout(TimeSpan.FromSeconds(1));
|
||||
Assert.AreEqual(CommonObjects.ResponseMessage, mockPendingRequest.Task.Result);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DispatchMessageEventWithoutHandler()
|
||||
{
|
||||
// Setup: Create a JSON RPC host without a request handler
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
|
||||
|
||||
// If: I dispatch a request that doesn't have a handler
|
||||
// Then: I should get an exception
|
||||
Assert.ThrowsAsync<MethodHandlerDoesNotExistException>(() => jh.DispatchMessage(CommonObjects.EventMessage));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DispatchMessageEventException()
|
||||
{
|
||||
// Setup: Create a JSON RPC host with a request handler that throws an unhandled exception every time
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
|
||||
var mockHandler = new Mock<Func<CommonObjects.TestMessageContents, EventContext, Task>>();
|
||||
mockHandler.Setup(f => f(It.IsAny<CommonObjects.TestMessageContents>(), It.IsAny<EventContext>()))
|
||||
.Returns(Task.FromException(new Exception()));
|
||||
jh.SetAsyncEventHandler(CommonObjects.EventType, mockHandler.Object);
|
||||
|
||||
// If: I dispatch a message whose handler throws
|
||||
// Then: I should get an exception
|
||||
Assert.ThrowsAsync<Exception>(() => jh.DispatchMessage(CommonObjects.EventMessage));
|
||||
}
|
||||
|
||||
[TestCaseSource(nameof(DispatchMessageWithHandlerData))]
|
||||
public async Task DispatchMessageEventWithHandler(Task result)
|
||||
{
|
||||
// Setup: Create a JSON RPC host with an event handler setup
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
|
||||
var mockHandler = new Mock<Func<CommonObjects.TestMessageContents, EventContext, Task>>();
|
||||
mockHandler.Setup(f => f(
|
||||
It.Is<CommonObjects.TestMessageContents>(m => m == CommonObjects.TestMessageContents.DefaultInstance),
|
||||
It.Is<EventContext>(ec => ec.messageQueue == jh.outputQueue)
|
||||
)).Returns(result);
|
||||
jh.SetAsyncEventHandler(CommonObjects.EventType, mockHandler.Object);
|
||||
|
||||
// If: I dispatch an event
|
||||
await jh.DispatchMessage(CommonObjects.EventMessage);
|
||||
|
||||
// Then: The event handler should have been called
|
||||
mockHandler.Verify(f => f(
|
||||
It.Is<CommonObjects.TestMessageContents>(m => m == CommonObjects.TestMessageContents.DefaultInstance),
|
||||
It.IsAny<EventContext>()
|
||||
));
|
||||
}
|
||||
|
||||
public static IEnumerable<object[]> DispatchMessageWithHandlerData
|
||||
{
|
||||
get
|
||||
{
|
||||
yield return new object[] {Task.FromResult(true)}; // Successful completion
|
||||
yield return new object[] {Task.FromException(new TaskCanceledException())}; // Cancelled result
|
||||
yield return new object[] {Task.FromException(new AggregateException(new TaskCanceledException()))}; // Cancelled somewhere inside
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region ConsumeInput Loop Tests
|
||||
|
||||
[Test]
|
||||
public async Task ConsumeInput()
|
||||
{
|
||||
// Setup:
|
||||
// ... Create a message reader that will return a message every time
|
||||
var mr = new Mock<MessageReader>(Stream.Null, null);
|
||||
var waitForRead = new TaskCompletionSource<bool>();
|
||||
mr.Setup(o => o.ReadMessage())
|
||||
.Callback(() => waitForRead.TrySetResult(true))
|
||||
.ReturnsAsync(CommonObjects.EventMessage);
|
||||
|
||||
// ... Create a no-op event handler to handle the message from the message reader
|
||||
var noOpHandler = new Mock<Func<Message, Task>>();
|
||||
noOpHandler.Setup(f => f(It.IsAny<Message>())).Returns(Task.FromResult(true));
|
||||
|
||||
// ... Wire up the event handler to a new JSON RPC host
|
||||
var jh = new JsonRpcHost(GetChannelBase(mr.Object, null).Object);
|
||||
jh.eventHandlers[CommonObjects.EventType.MethodName] = noOpHandler.Object;
|
||||
|
||||
// If:
|
||||
// ... I start the input consumption thread
|
||||
Task consumeInputTask = jh.ConsumeInput();
|
||||
|
||||
// ... Wait for the handler to be called once, indicating the message was processed
|
||||
await waitForRead.Task.WithTimeout(TimeSpan.FromSeconds(1));
|
||||
|
||||
// ... Stop the input consumption thread (the hard way) and wait for completion
|
||||
jh.cancellationTokenSource.Cancel();
|
||||
await consumeInputTask.WithTimeout(TimeSpan.FromSeconds(1));
|
||||
|
||||
// Then: The event handler and read message should have been called at least once
|
||||
noOpHandler.Verify(f => f(It.IsAny<Message>()), Times.AtLeastOnce);
|
||||
mr.Verify(o => o.ReadMessage(), Times.AtLeastOnce);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ConsumeInputEndOfStream()
|
||||
{
|
||||
// Setup: Create a message reader that will throw an end of stream exception on read
|
||||
var mr = new Mock<MessageReader>(Stream.Null, null);
|
||||
mr.Setup(o => o.ReadMessage()).Returns(Task.FromException<Message>(new EndOfStreamException()));
|
||||
|
||||
// If: I start the input consumption thread
|
||||
// Then:
|
||||
// ... It should stop gracefully
|
||||
var jh = new JsonRpcHost(GetChannelBase(mr.Object, null).Object);
|
||||
await jh.ConsumeInput().WithTimeout(TimeSpan.FromSeconds(1));
|
||||
|
||||
// ... The read message should have only been called once
|
||||
mr.Verify(o => o.ReadMessage(), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ConsumeInputException()
|
||||
{
|
||||
// Setup:
|
||||
// ... Create a message reader that will throw an exception on first read
|
||||
// ... throw an end of stream on second read
|
||||
var mr = new Mock<MessageReader>(Stream.Null, null);
|
||||
mr.SetupSequence(o => o.ReadMessage())
|
||||
.Returns(Task.FromException<Message>(new Exception()))
|
||||
.Returns(Task.FromException<Message>(new EndOfStreamException()));
|
||||
|
||||
// If: I start the input consumption loop
|
||||
var jh = new JsonRpcHost(GetChannelBase(mr.Object, null).Object);
|
||||
await jh.ConsumeInput().WithTimeout(TimeSpan.FromSeconds(1));
|
||||
|
||||
// Then:
|
||||
// ... Read message should have been called twice
|
||||
mr.Verify(o => o.ReadMessage(), Times.Exactly(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ConsumeInputRequestMethodNotFound()
|
||||
{
|
||||
// Setup: Create a message reader that will return a request with method that doesn't exist
|
||||
var mr = new Mock<MessageReader>(Stream.Null, null);
|
||||
mr.SetupSequence(o => o.ReadMessage())
|
||||
.ReturnsAsync(CommonObjects.RequestMessage)
|
||||
.Returns(Task.FromException<Message>(new EndOfStreamException()));
|
||||
|
||||
// If: I start the input consumption loop
|
||||
var jh = new JsonRpcHost(GetChannelBase(mr.Object, null).Object);
|
||||
await jh.ConsumeInput().WithTimeout(TimeSpan.FromSeconds(1));
|
||||
|
||||
// Then:
|
||||
// ... Read message should have been called twice
|
||||
mr.Verify(o => o.ReadMessage(), Times.Exactly(2));
|
||||
|
||||
// ...
|
||||
var outgoing = jh.outputQueue.ToArray();
|
||||
Assert.That(outgoing.Select(m => (m.MessageType, m.Id, m.Contents.Value<int>("code"))), Is.EqualTo(new[] { (MessageType.ResponseError, CommonObjects.MessageId, -32601) }), "There should be an outgoing message with the error");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ConsumeInputRequestException()
|
||||
{
|
||||
// Setup:
|
||||
// ... Create a message reader that will return a request
|
||||
var mr = new Mock<MessageReader>(Stream.Null, null);
|
||||
mr.SetupSequence(o => o.ReadMessage())
|
||||
.ReturnsAsync(CommonObjects.RequestMessage)
|
||||
.Returns(Task.FromException<Message>(new EndOfStreamException()));
|
||||
|
||||
// ... Create a JSON RPC host and register the request handler to throw exception
|
||||
var jh = new JsonRpcHost(GetChannelBase(mr.Object, null).Object);
|
||||
var mockHandler = new Mock<Action<CommonObjects.TestMessageContents, RequestContext<CommonObjects.TestMessageContents>>>();
|
||||
mockHandler.Setup(m => m(It.IsAny<CommonObjects.TestMessageContents>(),
|
||||
It.IsAny<RequestContext<CommonObjects.TestMessageContents>>()))
|
||||
.Throws(new Exception());
|
||||
jh.SetRequestHandler(CommonObjects.RequestType, mockHandler.Object);
|
||||
|
||||
// If: I start the input consumption loop
|
||||
await jh.ConsumeInput().WithTimeout(TimeSpan.FromSeconds(1));
|
||||
|
||||
// Then:
|
||||
// ... Read message should have been called twice
|
||||
mr.Verify(o => o.ReadMessage(), Times.Exactly(2));
|
||||
|
||||
var outgoing = jh.outputQueue.ToArray();
|
||||
Assert.That(outgoing, Is.Empty, "outputQueue after ConsumeInput should not have any outgoing messages");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region ConsumeOutput Loop Tests
|
||||
|
||||
[Test]
|
||||
public async Task ConsumeOutput()
|
||||
{
|
||||
// Setup:
|
||||
// ... Create a mock message writer
|
||||
var mw = new Mock<MessageWriter>(Stream.Null);
|
||||
mw.Setup(o => o.WriteMessage(CommonObjects.ResponseMessage)).Returns(Task.FromResult(true));
|
||||
|
||||
// ... Create the JSON RPC host and add an item to the output queue
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, mw.Object).Object);
|
||||
jh.outputQueue.Add(CommonObjects.ResponseMessage);
|
||||
jh.outputQueue.CompleteAdding(); // This will cause the thread to stop after processing the items
|
||||
|
||||
// If: I start the output consumption thread
|
||||
Task consumeOutputTask = jh.ConsumeOutput();
|
||||
await consumeOutputTask.WithTimeout(TimeSpan.FromSeconds(1));
|
||||
|
||||
// Then: The message writer should have been called once
|
||||
mw.Verify(o => o.WriteMessage(CommonObjects.ResponseMessage), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ConsumeOutputCancelled()
|
||||
{
|
||||
// NOTE: This test validates that the blocking collection breaks out when cancellation is requested
|
||||
|
||||
// Setup: Create a mock message writer
|
||||
var mw = new Mock<MessageWriter>(Stream.Null);
|
||||
mw.Setup(o => o.WriteMessage(It.IsAny<Message>())).Returns(Task.FromResult(true));
|
||||
|
||||
// If:
|
||||
// ... I start the output consumption thread
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, mw.Object).Object);
|
||||
Task consumeOuputTask = jh.ConsumeOutput();
|
||||
|
||||
// ... and I stop the thread via cancellation and wait for completion
|
||||
jh.cancellationTokenSource.Cancel();
|
||||
await consumeOuputTask.WithTimeout(TimeSpan.FromSeconds(1));
|
||||
|
||||
// Then: The message writer should not have been called
|
||||
mw.Verify(o => o.WriteMessage(It.IsAny<Message>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ConsumeOutputException()
|
||||
{
|
||||
// Setup: Create a mock message writer
|
||||
var mw = new Mock<MessageWriter>(Stream.Null);
|
||||
mw.Setup(o => o.WriteMessage(It.IsAny<Message>())).Returns(Task.FromResult(true));
|
||||
|
||||
// If: I start the output consumption thread with a completed blocking collection
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, mw.Object).Object);
|
||||
jh.outputQueue.CompleteAdding();
|
||||
await jh.ConsumeOutput().WithTimeout(TimeSpan.FromSeconds(1));
|
||||
|
||||
// Then: The message writer should not have been called
|
||||
mw.Verify(o => o.WriteMessage(It.IsAny<Message>()), Times.Never);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Start/Stop Tests
|
||||
|
||||
[Test]
|
||||
public async Task StartStop()
|
||||
{
|
||||
// Setup: Create mocked message reader and writer
|
||||
var mr = new Mock<MessageReader>(Stream.Null, null);
|
||||
var mw = new Mock<MessageWriter>(Stream.Null);
|
||||
|
||||
// If: I start a JSON RPC host
|
||||
var cb = GetChannelBase(mr.Object, mw.Object);
|
||||
var jh = new JsonRpcHost(cb.Object);
|
||||
jh.Start();
|
||||
|
||||
// Then: The channel protocol should have been
|
||||
cb.Verify(o => o.Start(), Times.Once);
|
||||
cb.Verify(o => o.WaitForConnection(), Times.Once);
|
||||
|
||||
// If: I stop the JSON RPC host
|
||||
jh.Stop();
|
||||
|
||||
// Then: The long running tasks should stop gracefully
|
||||
await Task.WhenAll(jh.consumeInputTask, jh.consumeOutputTask).WithTimeout(TimeSpan.FromSeconds(1));
|
||||
cb.Verify(o => o.Stop(), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task StartMultiple()
|
||||
{
|
||||
// Setup: Create mocked message reader and writer
|
||||
var mr = new Mock<MessageReader>(Stream.Null, null);
|
||||
var mw = new Mock<MessageWriter>(Stream.Null);
|
||||
|
||||
// If:
|
||||
// ... I start a JSON RPC host
|
||||
var cb = GetChannelBase(mr.Object, mw.Object);
|
||||
var jh = new JsonRpcHost(cb.Object);
|
||||
jh.Start();
|
||||
|
||||
// ... And I start it again
|
||||
// Then: I should get an exception
|
||||
Assert.Throws<InvalidOperationException>(() => jh.Start());
|
||||
|
||||
// Cleanup: Stop the JSON RPC host
|
||||
jh.Stop();
|
||||
await Task.WhenAll(jh.consumeInputTask, jh.consumeOutputTask).WithTimeout(TimeSpan.FromSeconds(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void StopMultiple()
|
||||
{
|
||||
// Setup: Create json rpc host and start it
|
||||
var mr = new Mock<MessageReader>(Stream.Null, null);
|
||||
var mw = new Mock<MessageWriter>(Stream.Null);
|
||||
var jh = new JsonRpcHost(GetChannelBase(mr.Object, mw.Object).Object);
|
||||
jh.Start();
|
||||
|
||||
// If: I stop the JSON RPC host after stopping it
|
||||
// Then: I should get an exception
|
||||
jh.Stop();
|
||||
Assert.Throws<InvalidOperationException>(() => jh.Stop());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void StopBeforeStarting()
|
||||
{
|
||||
// If: I stop the JSON RPC host without starting it first
|
||||
// Then: I should get an exception
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
|
||||
Assert.Throws<InvalidOperationException>(() => jh.Stop());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WaitForExit()
|
||||
{
|
||||
// Setup: Create json rpc host and start it
|
||||
var mr = new Mock<MessageReader>(Stream.Null, null);
|
||||
var mw = new Mock<MessageWriter>(Stream.Null);
|
||||
var jh = new JsonRpcHost(GetChannelBase(mr.Object, mw.Object).Object);
|
||||
jh.Start();
|
||||
|
||||
// If: I wait for JSON RPC host to exit and stop it
|
||||
// NOTE: We are wrapping this execution in a task to make sure we can properly stop the host
|
||||
Task waitForExit = Task.Run(() => { jh.WaitForExit(); });
|
||||
jh.Stop();
|
||||
|
||||
// Then: The host should be stopped
|
||||
await waitForExit.WithTimeout(TimeSpan.FromSeconds(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void WaitForExitNotStarted()
|
||||
{
|
||||
// If: I wait for exit on the JSON RPC host without starting it
|
||||
// Then: I should get an exception
|
||||
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
|
||||
Assert.Throws<InvalidOperationException>(() => jh.WaitForExit());
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private static Mock<ChannelBase> GetChannelBase(MessageReader reader, MessageWriter writer, bool isConnected = false)
|
||||
{
|
||||
var cb = new Mock<ChannelBase>();
|
||||
cb.Object.MessageReader = reader;
|
||||
cb.Object.MessageWriter = writer;
|
||||
cb.Object.IsConnected = isConnected;
|
||||
cb.Setup(o => o.Start());
|
||||
cb.Setup(o => o.Stop());
|
||||
cb.Setup(o => o.WaitForConnection()).Returns(Task.FromResult(true));
|
||||
|
||||
return cb;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,220 +0,0 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
//
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.SqlTools.Hosting.Protocol;
|
||||
using Microsoft.SqlTools.ServiceLayer.Test.Common;
|
||||
using Newtonsoft.Json;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
|
||||
{
|
||||
[TestFixture]
|
||||
public class MessageReaderTests
|
||||
{
|
||||
#region Construction Tests
|
||||
|
||||
[Test]
|
||||
public void CreateReaderNullStream()
|
||||
{
|
||||
// If: I create a message reader with a null stream reader
|
||||
// Then: It should throw
|
||||
Assert.Throws<ArgumentNullException>(() => new MessageReader(null));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CreateReaderStandardEncoding()
|
||||
{
|
||||
// If: I create a message reader without including a message encoding
|
||||
var mr = new MessageReader(Stream.Null);
|
||||
|
||||
// Then: The reader's encoding should be UTF8
|
||||
Assert.AreEqual(Encoding.UTF8, mr.MessageEncoding);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CreateReaderNonStandardEncoding()
|
||||
{
|
||||
// If: I create a message reader with a specific message encoding
|
||||
var mr = new MessageReader(Stream.Null, Encoding.ASCII);
|
||||
|
||||
// Then: The reader's encoding should be ASCII
|
||||
Assert.AreEqual(Encoding.ASCII, mr.MessageEncoding);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region ReadMessage Tests
|
||||
|
||||
[Test]
|
||||
public async Task ReadMessageSingleRead([Values(512,10,25)]int bufferSize)
|
||||
{
|
||||
// Setup: Reader with a stream that has an entire message in it
|
||||
byte[] testBytes = Encoding.UTF8.GetBytes("Content-Length: 50\r\n\r\n{\"jsonrpc\": \"2.0\", \"method\":\"test\", \"params\":null}");
|
||||
using (Stream testStream = new MemoryStream(testBytes))
|
||||
{
|
||||
var mr = new MessageReader(testStream) {MessageBuffer = new byte[bufferSize]};
|
||||
|
||||
// If: I reade a message with the reader
|
||||
var output = await mr.ReadMessage();
|
||||
|
||||
// Then:
|
||||
// ... I should have a successful message read
|
||||
Assert.NotNull(output);
|
||||
|
||||
// ... The reader should be back in header mode
|
||||
Assert.AreEqual(MessageReader.ReadState.Headers, mr.CurrentState);
|
||||
|
||||
// ... The buffer should have been trimmed
|
||||
Assert.AreEqual(MessageReader.DefaultBufferSize, mr.MessageBuffer.Length);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ReadMessageInvalidHeaders(
|
||||
[Values(
|
||||
"Content-Type: application/json\r\n\r\n",// Missing content-length header
|
||||
"Content-Length: abc\r\n\r\n"// Content-length is not a number
|
||||
)]string testString)
|
||||
{
|
||||
// Setup: Reader with a stream that has an invalid header in it
|
||||
byte[] testBytes = Encoding.UTF8.GetBytes(testString);
|
||||
using (Stream testStream = new MemoryStream(testBytes))
|
||||
{
|
||||
var mr = new MessageReader(testStream) {MessageBuffer = new byte[20]};
|
||||
|
||||
// If: I read a message with invalid headers
|
||||
// Then: ... I should get an exception
|
||||
Assert.ThrowsAsync<MessageParseException>(() => mr.ReadMessage());
|
||||
|
||||
// ... The buffer should have been trashed (reset to it's original tiny size)
|
||||
Assert.AreEqual(MessageReader.DefaultBufferSize, mr.MessageBuffer.Length);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ReadMessageInvalidJson()
|
||||
{
|
||||
// Setup: Reader with a stream that has an invalid json message in it
|
||||
byte[] testBytes = Encoding.UTF8.GetBytes("Content-Length: 10\r\n\r\nabcdefghij");
|
||||
using (Stream testStream = new MemoryStream(testBytes))
|
||||
{
|
||||
// ... Buffer size is small to validate if the buffer has been trashed at the end
|
||||
var mr = new MessageReader(testStream) {MessageBuffer = new byte[20]};
|
||||
|
||||
// If: I read a message with an invalid JSON in it
|
||||
// Then:
|
||||
// ... I should get an exception
|
||||
Assert.ThrowsAsync<JsonReaderException>(() => mr.ReadMessage());
|
||||
|
||||
// ... The buffer should have been trashed (reset to it's original tiny size)
|
||||
Assert.AreEqual(MessageReader.DefaultBufferSize, mr.MessageBuffer.Length);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ReadMultipleMessages()
|
||||
{
|
||||
// Setup: Reader with a stream that has multiple messages in it
|
||||
const string testString = "Content-Length: 50\r\n\r\n{\"jsonrpc\": \"2.0\", \"method\":\"test\", \"params\":null}";
|
||||
byte[] testBytes = Encoding.UTF8.GetBytes(testString + testString);
|
||||
using (Stream testStream = new MemoryStream(testBytes))
|
||||
{
|
||||
var mr = new MessageReader(testStream);
|
||||
|
||||
// If:
|
||||
// ... I read a message
|
||||
var msg1 = await mr.ReadMessage();
|
||||
|
||||
// ... And I read another message
|
||||
var msg2 = await mr.ReadMessage();
|
||||
|
||||
// Then:
|
||||
// ... The messages should be real messages
|
||||
Assert.NotNull(msg1);
|
||||
Assert.NotNull(msg2);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ReadMultipleMessagesBeforeWriting()
|
||||
{
|
||||
// Setup: Reader with a stream that will have multiple messages in it
|
||||
const string testString = "Content-Length: 50\r\n\r\n{\"jsonrpc\": \"2.0\", \"method\":\"test\", \"params\":null}";
|
||||
byte[] testBytes = Encoding.UTF8.GetBytes(testString);
|
||||
using (Stream testStream = new MemoryStream())
|
||||
{
|
||||
var mr = new MessageReader(testStream);
|
||||
|
||||
// If: I start reading a message then write the message to the stream
|
||||
var readTask1 = mr.ReadMessage();
|
||||
await testStream.WriteAsync(testBytes, 0, testBytes.Length);
|
||||
var msg1 = await readTask1.WithTimeout(TimeSpan.FromSeconds(1));
|
||||
|
||||
// Then: The message should be real
|
||||
Assert.NotNull(msg1);
|
||||
|
||||
// If: I do it again
|
||||
var readTask2 = mr.ReadMessage();
|
||||
await testStream.WriteAsync(testBytes, 0, testBytes.Length);
|
||||
var msg2 = await readTask2.WithTimeout(TimeSpan.FromSeconds(1));
|
||||
|
||||
// Then: The message should be real
|
||||
Assert.NotNull(msg2);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ReadRecoverFromInvalidHeaderMessage()
|
||||
{
|
||||
// Setup: Reader with a stream that has incorrect message formatting
|
||||
const string testString = "Content-Type: application/json\r\n\r\n" +
|
||||
"Content-Length: 50\r\n\r\n{\"jsonrpc\": \"2.0\", \"method\":\"test\", \"params\":null}";
|
||||
byte[] testBytes = Encoding.UTF8.GetBytes(testString);
|
||||
using (Stream testStream = new MemoryStream(testBytes))
|
||||
{
|
||||
var mr = new MessageReader(testStream);
|
||||
|
||||
// If: I read a message with invalid headers
|
||||
// Then: I should get an exception
|
||||
Assert.ThrowsAsync<MessageParseException>(() => mr.ReadMessage());
|
||||
|
||||
// If: I read another, valid, message
|
||||
var msg = await mr.ReadMessage();
|
||||
|
||||
// Then: I should have a valid message
|
||||
Assert.NotNull(msg);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ReadRecoverFromInvalidContentMessage()
|
||||
{
|
||||
// Setup: Reader with a stream that has incorrect message formatting
|
||||
const string testString = "Content-Length: 10\r\n\r\nabcdefghij" +
|
||||
"Content-Length: 50\r\n\r\n{\"jsonrpc\": \"2.0\", \"method\":\"test\", \"params\":null}";
|
||||
byte[] testBytes = Encoding.UTF8.GetBytes(testString);
|
||||
using (Stream testStream = new MemoryStream(testBytes))
|
||||
{
|
||||
var mr = new MessageReader(testStream);
|
||||
|
||||
// If: I read a message with invalid content
|
||||
// Then: I should get an exception
|
||||
Assert.ThrowsAsync<JsonReaderException>(() => mr.ReadMessage());
|
||||
|
||||
// If: I read another, valid, message
|
||||
var msg = await mr.ReadMessage();
|
||||
|
||||
// Then: I should have a valid message
|
||||
Assert.NotNull(msg);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,292 +0,0 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
//
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Microsoft.SqlTools.Hosting.Protocol;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
|
||||
{
|
||||
[TestFixture]
|
||||
public class MessageTests
|
||||
{
|
||||
#region Construction/Serialization Tests
|
||||
|
||||
[Test]
|
||||
public void CreateRequest()
|
||||
{
|
||||
// If: I create a request
|
||||
var message = Message.CreateRequest(CommonObjects.RequestType, CommonObjects.MessageId, CommonObjects.TestMessageContents.DefaultInstance);
|
||||
|
||||
// Then:
|
||||
// ... The message should have all the properties I defined
|
||||
// ... The JObject should have the same properties
|
||||
var expectedResults = new MessagePropertyResults
|
||||
{
|
||||
MessageType = MessageType.Request,
|
||||
IdSet = true,
|
||||
MethodSetAs = CommonObjects.RequestType.MethodName,
|
||||
ContentsSetAs = "params",
|
||||
ErrorSet = false
|
||||
};
|
||||
AssertPropertiesSet(expectedResults, message);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CreateError()
|
||||
{
|
||||
// If: I create an error
|
||||
var message = Message.CreateResponseError(CommonObjects.MessageId, CommonObjects.TestErrorContents.DefaultInstance);
|
||||
|
||||
// Then: Message and JObject should have appropriate properties set
|
||||
var expectedResults = new MessagePropertyResults
|
||||
{
|
||||
MessageType = MessageType.ResponseError,
|
||||
IdSet = true,
|
||||
MethodSetAs = null,
|
||||
ContentsSetAs = null,
|
||||
ErrorSet = true
|
||||
};
|
||||
AssertPropertiesSet(expectedResults, message);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CreateResponse()
|
||||
{
|
||||
// If: I create a response
|
||||
var message = Message.CreateResponse(CommonObjects.MessageId, CommonObjects.TestMessageContents.DefaultInstance);
|
||||
|
||||
// Then: Message and JObject should have appropriate properties set
|
||||
var expectedResults = new MessagePropertyResults
|
||||
{
|
||||
MessageType = MessageType.Response,
|
||||
IdSet = true,
|
||||
MethodSetAs = null,
|
||||
ContentsSetAs = "result",
|
||||
ErrorSet = false
|
||||
};
|
||||
AssertPropertiesSet(expectedResults, message);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CreateEvent()
|
||||
{
|
||||
// If: I create an event
|
||||
var message = Message.CreateEvent(CommonObjects.EventType, CommonObjects.TestMessageContents.DefaultInstance);
|
||||
|
||||
// Then: Message and JObject should have appropriate properties set
|
||||
var expectedResults = new MessagePropertyResults
|
||||
{
|
||||
MessageType = MessageType.Event,
|
||||
IdSet = false,
|
||||
MethodSetAs = CommonObjects.EventType.MethodName,
|
||||
ContentsSetAs = "params",
|
||||
ErrorSet = false
|
||||
};
|
||||
AssertPropertiesSet(expectedResults, message);
|
||||
}
|
||||
|
||||
private static void AssertPropertiesSet(MessagePropertyResults results, Message message)
|
||||
{
|
||||
Assert.NotNull(message);
|
||||
|
||||
// Serialize the message and deserialize back into a JObject
|
||||
string messageJson = message.Serialize();
|
||||
Assert.NotNull(messageJson);
|
||||
JObject jObject = JObject.Parse(messageJson);
|
||||
|
||||
// JSON RPC Version
|
||||
List<string> expectedProperties = new List<string> {"jsonrpc"};
|
||||
Assert.AreEqual("2.0", jObject["jsonrpc"].Value<string>());
|
||||
|
||||
// Message Type
|
||||
Assert.AreEqual(results.MessageType, message.MessageType);
|
||||
|
||||
// ID
|
||||
if (results.IdSet)
|
||||
{
|
||||
Assert.AreEqual(CommonObjects.MessageId, message.Id);
|
||||
Assert.AreEqual(CommonObjects.MessageId, jObject["id"].Value<string>());
|
||||
expectedProperties.Add("id");
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.Null(message.Id);
|
||||
}
|
||||
|
||||
// Method
|
||||
if (results.MethodSetAs != null)
|
||||
{
|
||||
Assert.AreEqual(results.MethodSetAs, message.Method);
|
||||
Assert.AreEqual(results.MethodSetAs, jObject["method"].Value<string>());
|
||||
expectedProperties.Add("method");
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.Null(message.Method);
|
||||
}
|
||||
|
||||
// Contents
|
||||
if (results.ContentsSetAs != null)
|
||||
{
|
||||
Assert.AreEqual(CommonObjects.TestMessageContents.SerializedContents, message.Contents);
|
||||
Assert.AreEqual(CommonObjects.TestMessageContents.SerializedContents, jObject[results.ContentsSetAs]);
|
||||
expectedProperties.Add(results.ContentsSetAs);
|
||||
}
|
||||
|
||||
// Error
|
||||
if (results.ErrorSet)
|
||||
{
|
||||
Assert.AreEqual(CommonObjects.TestErrorContents.SerializedContents, message.Contents);
|
||||
Assert.AreEqual(CommonObjects.TestErrorContents.SerializedContents, jObject["error"]);
|
||||
expectedProperties.Add("error");
|
||||
}
|
||||
|
||||
// Look for any extra properties set in the JObject
|
||||
IEnumerable<string> setProperties = jObject.Properties().Select(p => p.Name);
|
||||
Assert.That(setProperties.Except(expectedProperties), Is.Empty, "extra properties in jObject");
|
||||
}
|
||||
|
||||
private class MessagePropertyResults
|
||||
{
|
||||
public MessageType MessageType { get; set; }
|
||||
public bool IdSet { get; set; }
|
||||
public string MethodSetAs { get; set; }
|
||||
public string ContentsSetAs { get; set; }
|
||||
public bool ErrorSet { get; set; }
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Deserialization Tests
|
||||
|
||||
[Test]
|
||||
public void DeserializeMissingJsonRpc()
|
||||
{
|
||||
// If: I deserialize a json string that doesn't have a JSON RPC version
|
||||
// Then: I should get an exception
|
||||
Assert.Throws<MessageParseException>(() => Message.Deserialize("{\"id\": 123}"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeserializeEvent()
|
||||
{
|
||||
// If: I deserialize an event json string
|
||||
Message m = Message.Deserialize("{\"jsonrpc\": \"2.0\", \"params\": {}, \"method\": \"event\"}");
|
||||
|
||||
// Then: I should get an event message back
|
||||
Assert.NotNull(m);
|
||||
Assert.AreEqual(MessageType.Event, m.MessageType);
|
||||
Assert.AreEqual("event", m.Method);
|
||||
Assert.NotNull(m.Contents);
|
||||
Assert.Null(m.Id);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeserializeEventMissingMethod()
|
||||
{
|
||||
// If: I deserialize an event json string that is missing a method
|
||||
// Then: I should get an exception
|
||||
Assert.Throws<MessageParseException>(() => Message.Deserialize("{\"jsonrpc\": \"2.0\", \"params\": {}}"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeserializeResponse()
|
||||
{
|
||||
// If: I deserialize a response json string
|
||||
Message m = Message.Deserialize("{\"jsonrpc\": \"2.0\", \"result\": {}, \"id\": \"123\"}");
|
||||
|
||||
// Then: I should get a response message back
|
||||
Assert.NotNull(m);
|
||||
Assert.AreEqual(MessageType.Response, m.MessageType);
|
||||
Assert.AreEqual("123", m.Id);
|
||||
Assert.NotNull(m.Contents);
|
||||
Assert.Null(m.Method);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeserializeErrorResponse()
|
||||
{
|
||||
// If: I deserialize an error response
|
||||
Message m = Message.Deserialize("{\"jsonrpc\": \"2.0\", \"error\": {}, \"id\": \"123\"}");
|
||||
|
||||
// Then: I should get an error response message back
|
||||
Assert.NotNull(m);
|
||||
Assert.AreEqual(MessageType.ResponseError, m.MessageType);
|
||||
Assert.AreEqual("123", m.Id);
|
||||
Assert.NotNull(m.Contents);
|
||||
Assert.Null(m.Method);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeserializeRequest()
|
||||
{
|
||||
// If: I deserialize a request
|
||||
Message m = Message.Deserialize("{\"jsonrpc\": \"2.0\", \"params\": {}, \"method\": \"request\", \"id\": \"123\"}");
|
||||
|
||||
// Then: I should get a request message back
|
||||
Assert.NotNull(m);
|
||||
Assert.AreEqual(MessageType.Request, m.MessageType);
|
||||
Assert.AreEqual("123", m.Id);
|
||||
Assert.AreEqual("request", m.Method);
|
||||
Assert.NotNull(m.Contents);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeserializeRequestMissingMethod()
|
||||
{
|
||||
// If: I deserialize a request that doesn't have a method parameter
|
||||
// Then: I should get an exception
|
||||
Assert.Throws<MessageParseException>(() => Message.Deserialize("{\"jsonrpc\": \"2.0\", \"params\": {}, \"id\": \"123\"}"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetTypedContentsNull()
|
||||
{
|
||||
// If: I have a message that has a null contents, and I get the typed contents of it
|
||||
var m = Message.CreateResponse<CommonObjects.TestMessageContents>(CommonObjects.MessageId, null);
|
||||
var c = m.GetTypedContents<CommonObjects.TestMessageContents>();
|
||||
|
||||
// Then: I should get null back as the test message contents
|
||||
Assert.Null(c);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetTypedContentsSimpleValue()
|
||||
{
|
||||
// If: I have a message that has simple contents, and I get the typed contents of it
|
||||
var m = Message.CreateResponse(CommonObjects.MessageId, 123);
|
||||
var c = m.GetTypedContents<int>();
|
||||
|
||||
// Then: I should get an int back
|
||||
Assert.AreEqual(123, c);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetTypedContentsClassValue()
|
||||
{
|
||||
// If: I have a message that has complex contents, and I get the typed contents of it
|
||||
var m = Message.CreateResponse(CommonObjects.MessageId, CommonObjects.TestMessageContents.DefaultInstance);
|
||||
var c = m.GetTypedContents<CommonObjects.TestMessageContents>();
|
||||
|
||||
// Then: I should get the default instance back
|
||||
Assert.AreEqual(CommonObjects.TestMessageContents.DefaultInstance, c);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetTypedContentsInvalid()
|
||||
{
|
||||
// If: I have a message that has contents and I get incorrectly typed contents from it
|
||||
// Then: I should get an exception back
|
||||
var m = Message.CreateResponse(CommonObjects.MessageId, CommonObjects.TestMessageContents.DefaultInstance);
|
||||
Assert.Throws<ArgumentException>(() => m.GetTypedContents<int>());
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
//
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.SqlTools.Hosting.Protocol;
|
||||
using Newtonsoft.Json;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
|
||||
{
|
||||
[TestFixture]
|
||||
public class MessageWriterTests
|
||||
{
|
||||
#region Construction Tests
|
||||
|
||||
[Test]
|
||||
public void ConstructMissingOutputStream()
|
||||
{
|
||||
// If: I attempt to create a message writer without an output stream
|
||||
// Then: I should get an exception
|
||||
Assert.Throws<ArgumentNullException>(() => new MessageWriter(null));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region WriteMessageTests
|
||||
|
||||
[Test]
|
||||
public async Task WriteMessageNullMessage()
|
||||
{
|
||||
// If: I write a null message
|
||||
// Then: I should get an exception
|
||||
var mw = new MessageWriter(Stream.Null);
|
||||
Assert.ThrowsAsync<ArgumentNullException>(() => mw.WriteMessage(null));
|
||||
}
|
||||
|
||||
[TestCaseSource(nameof(WriteMessageData))]
|
||||
public async Task WriteMessage(object contents, Dictionary<string, object> expectedDict)
|
||||
{
|
||||
// NOTE: This technically tests the ability of the Message class to properly serialize
|
||||
// various types of message contents. This *should* be part of the message tests
|
||||
// but it is simpler to test it here.
|
||||
|
||||
// Setup: Create a stream to capture the output
|
||||
var output = new byte[8192];
|
||||
using (var outputStream = new MemoryStream(output))
|
||||
{
|
||||
// If: I write a message
|
||||
var mw = new MessageWriter(outputStream);
|
||||
await mw.WriteMessage(Message.CreateResponse(CommonObjects.MessageId, contents));
|
||||
|
||||
// Then:
|
||||
// ... The returned bytes on the stream should compose a valid message
|
||||
Assert.That(outputStream.Position, Is.Not.EqualTo(0), "outputStream.Position after WriteMessage");
|
||||
var messageDict = ValidateMessageHeaders(output, (int) outputStream.Position);
|
||||
|
||||
// ... ID, Params, Method should be present
|
||||
AssertMessage(messageDict, expectedDict);
|
||||
}
|
||||
}
|
||||
|
||||
public static IEnumerable<object[]> WriteMessageData
|
||||
{
|
||||
get
|
||||
{
|
||||
yield return new object[]
|
||||
{
|
||||
null,
|
||||
new Dictionary<string, object> {{"id", "123"}, {"result", null}}
|
||||
};
|
||||
yield return new object[]
|
||||
{
|
||||
"simple param",
|
||||
new Dictionary<string, object> {{"id", "123"}, {"result", "simple param"}}
|
||||
};
|
||||
yield return new object[]
|
||||
{
|
||||
CommonObjects.TestMessageContents.DefaultInstance,
|
||||
new Dictionary<string, object> {{"id", "123"}, {"result", CommonObjects.TestMessageContents.SerializedContents}}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private Helpers
|
||||
|
||||
private static void AssertMessage(Dictionary<string, object> messageDict, Dictionary<string, object> expectedDict)
|
||||
{
|
||||
// Add the jsonrpc property to the expected dict
|
||||
expectedDict.Add("jsonrpc", "2.0");
|
||||
|
||||
// Make sure the number of elements in both dictionaries are the same
|
||||
Assert.AreEqual(expectedDict.Count, messageDict.Count);
|
||||
|
||||
// Make sure the elements match
|
||||
foreach (var kvp in expectedDict)
|
||||
{
|
||||
Assert.AreEqual(expectedDict[kvp.Key], messageDict[kvp.Key]);
|
||||
}
|
||||
}
|
||||
|
||||
private static Dictionary<string, object> ValidateMessageHeaders(byte[] outputBytes, int bytesWritten)
|
||||
{
|
||||
// Convert the written bytes to a string
|
||||
string outputString = Encoding.UTF8.GetString(outputBytes, 0, bytesWritten);
|
||||
|
||||
// There should be two sections to the message
|
||||
string[] outputParts = outputString.Split("\r\n\r\n");
|
||||
Assert.AreEqual(2, outputParts.Length);
|
||||
|
||||
// The first section is the headers
|
||||
string[] headers = outputParts[0].Split("\r\n");
|
||||
Assert.AreEqual(2, outputParts.Length);
|
||||
|
||||
// There should be a content-type and a content-length
|
||||
int? contentLength = null;
|
||||
bool contentTypeCorrect = false;
|
||||
foreach (string header in headers)
|
||||
{
|
||||
// Headers should look like "Header-Key: HeaderValue"
|
||||
string[] headerParts = header.Split(':');
|
||||
Assert.AreEqual(2, headerParts.Length);
|
||||
|
||||
string headerKey = headerParts[0];
|
||||
string headerValue = headerParts[1].Trim();
|
||||
|
||||
if (headerKey == "Content-Type" && headerValue.StartsWith("application/json"))
|
||||
{
|
||||
contentTypeCorrect = true;
|
||||
}
|
||||
else if (headerKey == "Content-Length")
|
||||
{
|
||||
contentLength = int.Parse(headerValue);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception($"Invalid header provided: {headerKey}");
|
||||
}
|
||||
}
|
||||
|
||||
// Make sure the headers are correct
|
||||
Assert.True(contentTypeCorrect);
|
||||
Assert.AreEqual(outputParts[1].Length, contentLength);
|
||||
|
||||
// Deserialize the body into a dictionary
|
||||
return JsonConvert.DeserializeObject<Dictionary<string, object>>(outputParts[1]);
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
//
|
||||
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Linq;
|
||||
using Microsoft.SqlTools.Hosting.Contracts.Internal;
|
||||
using Microsoft.SqlTools.Hosting.Protocol;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
|
||||
{
|
||||
[TestFixture]
|
||||
public class RequestContextTests
|
||||
{
|
||||
#region Send Tests
|
||||
|
||||
[Test]
|
||||
public void SendResult()
|
||||
{
|
||||
// Setup: Create a blocking collection to collect the output
|
||||
var bc = new BlockingCollection<Message>(new ConcurrentQueue<Message>());
|
||||
|
||||
// If: I write a response with the request context
|
||||
var rc = new RequestContext<CommonObjects.TestMessageContents>(CommonObjects.RequestMessage, bc);
|
||||
rc.SendResult(CommonObjects.TestMessageContents.DefaultInstance);
|
||||
|
||||
Assert.That(bc.Select(m => m.MessageType), Is.EqualTo(new[] { MessageType.Response }), "The message writer should have sent a response");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SendEvent()
|
||||
{
|
||||
// Setup: Create a blocking collection to collect the output
|
||||
var bc = new BlockingCollection<Message>(new ConcurrentQueue<Message>());
|
||||
|
||||
// If: I write an event with the request context
|
||||
var rc = new RequestContext<CommonObjects.TestMessageContents>(CommonObjects.RequestMessage, bc);
|
||||
rc.SendEvent(CommonObjects.EventType, CommonObjects.TestMessageContents.DefaultInstance);
|
||||
|
||||
Assert.That(bc.Select(m => m.MessageType), Is.EqualTo(new[] { MessageType.Event }), "The message writer should have sent an event");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SendError()
|
||||
{
|
||||
// Setup: Create a blocking collection to collect the output
|
||||
const string errorMessage = "error";
|
||||
const int errorCode = 123;
|
||||
var bc = new BlockingCollection<Message>(new ConcurrentQueue<Message>());
|
||||
|
||||
// If: I write an error with the request context
|
||||
var rc = new RequestContext<CommonObjects.TestMessageContents>(CommonObjects.RequestMessage, bc);
|
||||
rc.SendError(errorMessage, errorCode);
|
||||
|
||||
Assert.That(bc.Select(m => m.MessageType), Is.EqualTo(new[] { MessageType.ResponseError }), "The message writer should have sent an error");
|
||||
|
||||
// ... The error object it built should have the reuired fields set
|
||||
var contents = bc.ToArray()[0].GetTypedContents<Error>();
|
||||
Assert.AreEqual(errorCode, contents.Code);
|
||||
Assert.AreEqual(errorMessage, contents.Message);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SendException()
|
||||
{
|
||||
// Setup: Create a blocking collection to collect the output
|
||||
var bc = new BlockingCollection<Message>(new ConcurrentQueue<Message>());
|
||||
|
||||
// If: I write an error as an exception with the request context
|
||||
const string errorMessage = "error";
|
||||
var e = new Exception(errorMessage);
|
||||
var rc = new RequestContext<CommonObjects.TestMessageContents>(CommonObjects.RequestMessage, bc);
|
||||
rc.SendError(e);
|
||||
|
||||
Assert.That(bc.Select(m => m.MessageType), Is.EqualTo(new[] { MessageType.ResponseError }), "The message writer should have sent an error");
|
||||
|
||||
// ... The error object it built should have the reuired fields set
|
||||
var contents = bc.First().GetTypedContents<Error>();
|
||||
Assert.AreEqual(e.HResult, contents.Code);
|
||||
Assert.AreEqual(errorMessage, contents.Message);
|
||||
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
//
|
||||
|
||||
using System;
|
||||
using Microsoft.SqlTools.Hosting.Channels;
|
||||
using Microsoft.SqlTools.Hosting.Extensibility;
|
||||
using Microsoft.SqlTools.Hosting.Protocol;
|
||||
using Moq;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
|
||||
{
|
||||
[TestFixture]
|
||||
public class ExtensibleServiceHostTest
|
||||
{
|
||||
[Test]
|
||||
public void CreateExtensibleHostNullProvider()
|
||||
{
|
||||
// If: I create an extensible host with a null provider
|
||||
// Then: I should get an exception
|
||||
var cb = new Mock<ChannelBase>();
|
||||
Assert.Throws<ArgumentNullException>(() => new ExtensibleServiceHost(null, cb.Object));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CreateExtensibleHost()
|
||||
{
|
||||
// Setup:
|
||||
// ... Create a mock hosted service that can initialize
|
||||
var hs = new Mock<IHostedService>();
|
||||
var mockType = typeof(Mock<IHostedService>);
|
||||
hs.Setup(o => o.InitializeService(It.IsAny<IServiceHost>()));
|
||||
hs.SetupGet(o => o.ServiceType).Returns(mockType);
|
||||
|
||||
// ... Create a service provider mock that will return some stuff
|
||||
var sp = new Mock<RegisteredServiceProvider>();
|
||||
sp.Setup(o => o.GetServices<IHostedService>())
|
||||
.Returns(new[] {hs.Object});
|
||||
sp.Setup(o => o.RegisterSingleService(mockType, hs.Object));
|
||||
|
||||
// If: I create an extensible host with a custom provider
|
||||
var cb = new Mock<ChannelBase>();
|
||||
var esh = new ExtensibleServiceHost(sp.Object, cb.Object);
|
||||
|
||||
// Then:
|
||||
|
||||
// ... The service should have been initialized
|
||||
hs.Verify(o => o.InitializeService(esh), Times.Once());
|
||||
// ... The service host should have it's provider exposed
|
||||
Assert.AreEqual(sp.Object, esh.ServiceProvider);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CreateDefaultExtensibleHostNullAssemblyList()
|
||||
{
|
||||
// If: I create a default server extensible host with a null provider
|
||||
// Then: I should get an exception
|
||||
var cb = new Mock<ChannelBase>();
|
||||
Assert.Throws<ArgumentNullException>(() => ExtensibleServiceHost.CreateDefaultExtensibleServer(".", null));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CreateDefaultExtensibleHost()
|
||||
{
|
||||
// If: I create a default server extensible host
|
||||
var esh = ExtensibleServiceHost.CreateDefaultExtensibleServer(".", new string[] { });
|
||||
|
||||
// Then:
|
||||
// ... The service provider should be setup
|
||||
Assert.NotNull(esh.ServiceProvider);
|
||||
|
||||
var jh = esh.jsonRpcHost as JsonRpcHost;
|
||||
Assert.NotNull(jh);
|
||||
Assert.That(jh.protocolChannel, Is.InstanceOf<StdioServerChannel>(), "The underlying rpc host should be using the stdio server channel ");
|
||||
Assert.False(jh.protocolChannel.IsConnected);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,321 +0,0 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
//
|
||||
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.SqlTools.DataProtocol.Contracts;
|
||||
using Microsoft.SqlTools.Hosting.Channels;
|
||||
using Microsoft.SqlTools.Hosting.Contracts;
|
||||
using Microsoft.SqlTools.Hosting.Contracts.Internal;
|
||||
using Microsoft.SqlTools.Hosting.Protocol;
|
||||
using Moq;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
|
||||
{
|
||||
[TestFixture]
|
||||
public class ServiceHostTests
|
||||
{
|
||||
#region Construction Tests
|
||||
|
||||
[Test]
|
||||
public void ServiceHostConstructDefaultServer()
|
||||
{
|
||||
// If: I construct a default server service host
|
||||
var sh = ServiceHost.CreateDefaultServer();
|
||||
|
||||
var jh = sh.jsonRpcHost as JsonRpcHost;
|
||||
Assert.NotNull(jh);
|
||||
Assert.That(jh.protocolChannel, Is.InstanceOf<StdioServerChannel>(), "The underlying json rpc host should be using the stdio server channel");
|
||||
Assert.False(jh.protocolChannel.IsConnected);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ServiceHostNullParameter()
|
||||
{
|
||||
// If: I create a service host with missing parameters
|
||||
// Then: I should get an exception
|
||||
Assert.Throws<ArgumentNullException>(() => new ServiceHost(null));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IServiceHost Tests
|
||||
|
||||
[Test]
|
||||
public void RegisterInitializeTask()
|
||||
{
|
||||
// Setup: Create mock initialize handler
|
||||
var mockHandler = new Mock<Func<InitializeParameters, IEventSender, Task>>().Object;
|
||||
|
||||
// If: I register a couple initialize tasks with the service host
|
||||
var sh = GetServiceHost();
|
||||
sh.RegisterInitializeTask(mockHandler);
|
||||
sh.RegisterInitializeTask(mockHandler);
|
||||
|
||||
// Then: There should be two initialize tasks registered
|
||||
Assert.AreEqual(2, sh.initCallbacks.Count);
|
||||
Assert.True(sh.initCallbacks.SequenceEqual(new[] {mockHandler, mockHandler}));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RegisterInitializeTaskNullHandler()
|
||||
{
|
||||
// If: I register a null initialize task
|
||||
// Then: I should get an exception
|
||||
var sh = GetServiceHost();
|
||||
Assert.Throws<ArgumentNullException>(() => sh.RegisterInitializeTask(null));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RegisterShutdownTask()
|
||||
{
|
||||
// Setup: Create mock initialize handler
|
||||
var mockHandler = new Mock<Func<object, IEventSender, Task>>().Object;
|
||||
|
||||
// If: I register a couple shutdown tasks with the service host
|
||||
var sh = GetServiceHost();
|
||||
sh.RegisterShutdownTask(mockHandler);
|
||||
sh.RegisterShutdownTask(mockHandler);
|
||||
|
||||
// Then: There should be two initialize tasks registered
|
||||
Assert.AreEqual(2, sh.shutdownCallbacks.Count);
|
||||
Assert.True(sh.shutdownCallbacks.SequenceEqual(new[] {mockHandler, mockHandler}));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RegisterShutdownTaskNullHandler()
|
||||
{
|
||||
// If: I register a null initialize task
|
||||
// Then: I should get an exception
|
||||
var sh = GetServiceHost();
|
||||
Assert.Throws<ArgumentNullException>(() => sh.RegisterShutdownTask(null));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IJsonRpcHost Tests
|
||||
|
||||
[Test]
|
||||
public void SendEvent()
|
||||
{
|
||||
// If: I send an event
|
||||
var jh = GetJsonRpcHostMock();
|
||||
var sh = GetServiceHost(jh.Object);
|
||||
sh.SendEvent(CommonObjects.EventType, CommonObjects.TestMessageContents.DefaultInstance);
|
||||
|
||||
// Then: The underlying json rpc host should have handled it
|
||||
jh.Verify(o => o.SendEvent(CommonObjects.EventType, CommonObjects.TestMessageContents.DefaultInstance), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SendRequest()
|
||||
{
|
||||
// If: I send a request
|
||||
var jh = GetJsonRpcHostMock();
|
||||
var sh = GetServiceHost(jh.Object);
|
||||
await sh.SendRequest(CommonObjects.RequestType, CommonObjects.TestMessageContents.DefaultInstance);
|
||||
|
||||
// Then: The underlying json rpc host should have handled it
|
||||
jh.Verify(o => o.SendRequest(CommonObjects.RequestType, CommonObjects.TestMessageContents.DefaultInstance), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SetAsyncEventHandler()
|
||||
{
|
||||
// If: I set an event handler
|
||||
var jh = GetJsonRpcHostMock();
|
||||
var sh = GetServiceHost(jh.Object);
|
||||
sh.SetAsyncEventHandler(CommonObjects.EventType, null, true);
|
||||
|
||||
// Then: The underlying json rpc host should have handled it
|
||||
jh.Verify(o => o.SetAsyncEventHandler(CommonObjects.EventType, null, true), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SetSyncEventHandler()
|
||||
{
|
||||
// If: I set an event handler
|
||||
var jh = GetJsonRpcHostMock();
|
||||
var sh = GetServiceHost(jh.Object);
|
||||
sh.SetEventHandler(CommonObjects.EventType, null, true);
|
||||
|
||||
// Then: The underlying json rpc host should have handled it
|
||||
jh.Verify(o => o.SetEventHandler(CommonObjects.EventType, null, true), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SetAsyncRequestHandler()
|
||||
{
|
||||
// If: I set a request handler
|
||||
var jh = GetJsonRpcHostMock();
|
||||
var sh = GetServiceHost(jh.Object);
|
||||
sh.SetAsyncRequestHandler(CommonObjects.RequestType, null, true);
|
||||
|
||||
// Then: The underlying json rpc host should have handled it
|
||||
jh.Verify(o => o.SetAsyncRequestHandler(CommonObjects.RequestType, null, true), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SetSyncRequestHandler()
|
||||
{
|
||||
// If: I set a request handler
|
||||
var jh = GetJsonRpcHostMock();
|
||||
var sh = GetServiceHost(jh.Object);
|
||||
sh.SetRequestHandler(CommonObjects.RequestType, null, true);
|
||||
|
||||
// Then: The underlying json rpc host should have handled it
|
||||
jh.Verify(o => o.SetRequestHandler(CommonObjects.RequestType, null, true), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Start()
|
||||
{
|
||||
// If: I start a service host
|
||||
var jh = GetJsonRpcHostMock();
|
||||
var sh = GetServiceHost(jh.Object);
|
||||
sh.Start();
|
||||
|
||||
// Then:
|
||||
// ... The underlying json rpc host should have handled it
|
||||
jh.Verify(o => o.Start(), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Stop()
|
||||
{
|
||||
// If: I stop a service host
|
||||
var jh = GetJsonRpcHostMock();
|
||||
var sh = GetServiceHost(jh.Object);
|
||||
sh.Stop();
|
||||
|
||||
// Then: The underlying json rpc host should have handled it
|
||||
jh.Verify(o => o.Stop(), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void WaitForExit()
|
||||
{
|
||||
// If: I wait for service host to exit
|
||||
var jh = GetJsonRpcHostMock();
|
||||
var sh = GetServiceHost(jh.Object);
|
||||
sh.WaitForExit();
|
||||
|
||||
// Then: The underlying json rpc host should have handled it
|
||||
jh.Verify(o => o.WaitForExit());
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Request Handling Tests
|
||||
|
||||
[Test]
|
||||
public void HandleExitNotification()
|
||||
{
|
||||
// If: I handle an exit notification
|
||||
var jh = GetJsonRpcHostMock();
|
||||
var sh = GetServiceHost(jh.Object);
|
||||
sh.HandleExitNotification(null, null);
|
||||
|
||||
// Then: The json rpc host should have been stopped
|
||||
jh.Verify(o => o.Stop(), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task HandleInitializeRequest()
|
||||
{
|
||||
// Setup:
|
||||
// ... Create an initialize handler and register it in the service host
|
||||
var mockHandler = new Mock<Func<InitializeParameters, IEventSender, Task>>();
|
||||
mockHandler.Setup(f => f(It.IsAny<InitializeParameters>(), It.IsAny<IEventSender>()))
|
||||
.Returns(Task.FromResult(true));
|
||||
|
||||
var sh = GetServiceHost();
|
||||
sh.RegisterInitializeTask(mockHandler.Object);
|
||||
sh.RegisterInitializeTask(mockHandler.Object);
|
||||
|
||||
// ... Set a dummy value to return as the initialize response
|
||||
var ir = new InitializeResponse();
|
||||
|
||||
// ... Create a mock request that will handle sending a result
|
||||
// TODO: Replace with event flow validation
|
||||
var initParams = new InitializeParameters();
|
||||
var bc = new BlockingCollection<Message>();
|
||||
var mockContext = new RequestContext<InitializeResponse>(Message.CreateRequest(InitializeRequest.Type, CommonObjects.MessageId, initParams), bc);
|
||||
|
||||
// If: I handle an initialize request
|
||||
await sh.HandleInitializeRequest(initParams, mockContext);
|
||||
|
||||
// Then:
|
||||
// ... The mock handler should have been called twice
|
||||
mockHandler.Verify(h => h(initParams, mockContext), Times.Exactly(2));
|
||||
|
||||
var outgoing = bc.ToArray();
|
||||
Assert.That(outgoing.Select(m => m.Id), Is.EqualTo(new[] { CommonObjects.MessageId }), "There should have been a response sent");
|
||||
Assert.AreEqual(JToken.FromObject(ir), JToken.FromObject(ir));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task HandleShutdownRequest()
|
||||
{
|
||||
// Setup:
|
||||
// ... Create a shutdown handler and register it in the service host
|
||||
var mockHandler = new Mock<Func<object, IEventSender, Task>>();
|
||||
mockHandler.Setup(f => f(It.IsAny<object>(), It.IsAny<IEventSender>()))
|
||||
.Returns(Task.FromResult(true));
|
||||
|
||||
var sh = GetServiceHost();
|
||||
sh.RegisterShutdownTask(mockHandler.Object);
|
||||
sh.RegisterShutdownTask(mockHandler.Object);
|
||||
|
||||
// ... Create a mock request that will handle sending a result
|
||||
// TODO: Replace with the event flow validation
|
||||
var shutdownParams = new object();
|
||||
var bc = new BlockingCollection<Message>();
|
||||
var mockContext = new RequestContext<object>(Message.CreateRequest(ShutdownRequest.Type, CommonObjects.MessageId, shutdownParams), bc);
|
||||
|
||||
// If: I handle a shutdown request
|
||||
await sh.HandleShutdownRequest(shutdownParams, mockContext);
|
||||
|
||||
mockHandler.Verify(h => h(shutdownParams, mockContext), Times.Exactly(2), "The mock handler should have been called twice");
|
||||
|
||||
|
||||
Assert.That(bc.Count, Is.EqualTo(1), "There should have been a response sent");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private static ServiceHost GetServiceHost(IJsonRpcHost jsonRpcHost = null)
|
||||
{
|
||||
return new ServiceHost
|
||||
{
|
||||
jsonRpcHost = jsonRpcHost
|
||||
};
|
||||
}
|
||||
|
||||
private static Mock<IJsonRpcHost> GetJsonRpcHostMock()
|
||||
{
|
||||
var anyEventType = It.IsAny<EventType<object>>();
|
||||
var anyRequestType = It.IsAny<RequestType<object, object>>();
|
||||
var anyParams = It.IsAny<object>();
|
||||
|
||||
var mock = new Mock<IJsonRpcHost>();
|
||||
mock.Setup(jh => jh.SendEvent(anyEventType, anyParams));
|
||||
mock.Setup(jh => jh.SendRequest(anyRequestType, anyParams)).ReturnsAsync(null);
|
||||
mock.Setup(jh => jh.SetAsyncEventHandler(anyEventType, It.IsAny<Func<object, EventContext, Task>>(), It.IsAny<bool>()));
|
||||
mock.Setup(jh => jh.SetEventHandler(anyEventType, It.IsAny<Action<object, EventContext>>(), It.IsAny<bool>()));
|
||||
mock.Setup(jh => jh.SetAsyncRequestHandler(anyRequestType, It.IsAny<Func<object, RequestContext<object>, Task>>(), It.IsAny<bool>()));
|
||||
mock.Setup(jh => jh.SetRequestHandler(anyRequestType, It.IsAny<Action<object, RequestContext<object>>>(), It.IsAny<bool>()));
|
||||
mock.Setup(jh => jh.Start());
|
||||
mock.Setup(jh => jh.Stop());
|
||||
mock.Setup(jh => jh.WaitForExit());
|
||||
|
||||
return mock;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
//
|
||||
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.Test.Common
|
||||
{
|
||||
public static class TaskExtensions
|
||||
{
|
||||
public static async Task<Task> WithTimeout(this Task task, TimeSpan timeout)
|
||||
{
|
||||
Task delayTask = Task.Delay(timeout);
|
||||
Task firstCompleted = await Task.WhenAny(task, delayTask);
|
||||
if (firstCompleted == delayTask)
|
||||
{
|
||||
throw new Exception("Task timed out");
|
||||
}
|
||||
|
||||
return task;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
//
|
||||
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.SqlTools.Hosting.Utility;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace Microsoft.SqlTools.Hosting.UnitTests.UtilityTests
|
||||
{
|
||||
[TestFixture]
|
||||
public class AsyncLockTests
|
||||
{
|
||||
[Test]
|
||||
public async Task AsyncLockSynchronizesAccess()
|
||||
{
|
||||
AsyncLock asyncLock = new AsyncLock();
|
||||
|
||||
Task<IDisposable> lockOne = asyncLock.LockAsync();
|
||||
Task<IDisposable> lockTwo = asyncLock.LockAsync();
|
||||
|
||||
Assert.AreEqual(TaskStatus.RanToCompletion, lockOne.Status);
|
||||
Assert.AreEqual(TaskStatus.WaitingForActivation, lockTwo.Status);
|
||||
lockOne.Result.Dispose();
|
||||
|
||||
await lockTwo;
|
||||
Assert.AreEqual(TaskStatus.RanToCompletion, lockTwo.Status);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AsyncLockCancelsWhenRequested()
|
||||
{
|
||||
CancellationTokenSource cts = new CancellationTokenSource();
|
||||
AsyncLock asyncLock = new AsyncLock();
|
||||
|
||||
Task<IDisposable> lockOne = asyncLock.LockAsync();
|
||||
Task<IDisposable> lockTwo = asyncLock.LockAsync(cts.Token);
|
||||
|
||||
// Cancel the second lock before the first is released
|
||||
cts.Cancel();
|
||||
lockOne.Result.Dispose();
|
||||
|
||||
Assert.AreEqual(TaskStatus.RanToCompletion, lockOne.Status);
|
||||
Assert.AreEqual(TaskStatus.Canceled, lockTwo.Status);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Microsoft.SqlTools.Hosting.Utility;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace Microsoft.SqlTools.Hosting.UnitTests.UtilityTests
|
||||
{
|
||||
[TestFixture]
|
||||
/// <summary>
|
||||
/// Logger test cases
|
||||
/// </summary>
|
||||
public class LoggerTests
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Test to verify that the logger initialization is generating a valid file
|
||||
/// </summary>
|
||||
[Test]
|
||||
public void LoggerDefaultFile()
|
||||
{
|
||||
// delete any existing log files from the current directory
|
||||
Directory.GetFiles(Directory.GetCurrentDirectory())
|
||||
.Where(fileName
|
||||
=> fileName.Contains("sqltools_")
|
||||
&& fileName.EndsWith(".log", StringComparison.OrdinalIgnoreCase))
|
||||
.ToList()
|
||||
.ForEach(File.Delete);
|
||||
|
||||
Logger.Initialize(
|
||||
logFilePath: Path.Combine(Directory.GetCurrentDirectory(), "sqltools"),
|
||||
tracingLevel: SourceLevels.Verbose);
|
||||
|
||||
// Write a test message.
|
||||
string logMessage = $"Message from {nameof(LoggerDefaultFile)} test";
|
||||
Logger.Write(TraceEventType.Information, logMessage);
|
||||
|
||||
// close the logger
|
||||
Logger.Close();
|
||||
|
||||
// find the name of the new log file
|
||||
string logFileName = Logger.LogFileFullPath;
|
||||
|
||||
// validate the log file was created with desired name
|
||||
Assert.True(!string.IsNullOrWhiteSpace(logFileName));
|
||||
if (!string.IsNullOrWhiteSpace(logFileName))
|
||||
{
|
||||
Assert.True(logFileName.Length > "sqltools_.log".Length);
|
||||
Assert.True(File.Exists(logFileName), $"the log file: {logFileName} must exist");
|
||||
//Ensure that our log message exists in the log file
|
||||
Assert.True(File.ReadAllText(logFileName).Contains(logMessage, StringComparison.InvariantCultureIgnoreCase), $"the log message:'{logMessage}' must be present in the log file");
|
||||
// delete the test log file
|
||||
if (File.Exists(logFileName))
|
||||
{
|
||||
File.Delete(logFileName);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user