using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Channels; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Internal; using Microsoft.Extensions.Primitives; using Xunit; namespace Microsoft.AspNetCore.Sockets.Tests { public class HttpConnectionDispatcherTests { [Fact] public async Task GetIdReservesConnectionIdAndReturnsIt() { var manager = new ConnectionManager(); using (var factory = new ChannelFactory()) { var dispatcher = new HttpConnectionDispatcher(manager, factory); var context = new DefaultHttpContext(); var ms = new MemoryStream(); context.Request.Path = "/getid"; context.Response.Body = ms; await dispatcher.Execute("", context); var id = Encoding.UTF8.GetString(ms.ToArray()); ConnectionState state; Assert.True(manager.TryGetConnection(id, out state)); Assert.Equal(id, state.Connection.ConnectionId); } } [Fact] public async Task SendingToReservedConnectionsThatHaveNotConnectedThrows() { var manager = new ConnectionManager(); var state = manager.ReserveConnection(); using (var factory = new ChannelFactory()) { var dispatcher = new HttpConnectionDispatcher(manager, factory); var context = new DefaultHttpContext(); context.Request.Path = "/send"; var values = new Dictionary(); values["id"] = state.Connection.ConnectionId; var qs = new QueryCollection(values); context.Request.Query = qs; await Assert.ThrowsAsync(async () => { await dispatcher.Execute("", context); }); } } [Fact] public async Task SendingToUnknownConnectionIdThrows() { var manager = new ConnectionManager(); using (var factory = new ChannelFactory()) { var dispatcher = new HttpConnectionDispatcher(manager, factory); var context = new DefaultHttpContext(); context.Request.Path = "/send"; var values = new Dictionary(); values["id"] = "unknown"; var qs = new QueryCollection(values); context.Request.Query = qs; await Assert.ThrowsAsync(async () => { await dispatcher.Execute("", context); }); } } [Fact] public async Task SendingWithoutConnectionIdThrows() { var manager = new ConnectionManager(); using (var factory = new ChannelFactory()) { var dispatcher = new HttpConnectionDispatcher(manager, factory); var context = new DefaultHttpContext(); context.Request.Path = "/send"; await Assert.ThrowsAsync(async () => { await dispatcher.Execute("", context); }); } } } public class TestEndPoint : EndPoint { public override Task OnConnected(Connection connection) { throw new NotImplementedException(); } } }