private void TestEnumForByUnderlyingValue <T>(SerializationContext context, T value, string property)
        {
            var serializer = context.GetSerializer <T>();

            using (var stream = new MemoryStream())
            {
                serializer.Pack(stream, value);
                stream.Position = 0;
                var deserialized = serializer.Unpack(stream);

                if (property == null)
                {
                    Assert.That(deserialized, Is.EqualTo(value));
                    stream.Position = 0;
                    var result = Unpacking.UnpackObject(stream);
                    Assert.That(
                        result.ToString().Equals((( IFormattable )value).ToString("D", null)),
                        result + " == " + (( IFormattable )value).ToString("D", null)
                        );
                }
                else
                {
                    var propertyInfo = typeof(T).GetProperty(property);
                    Assert.That(propertyInfo.GetValue(deserialized, null), Is.EqualTo(propertyInfo.GetValue(value, null)));
                    stream.Position = 0;
                    var result = Unpacking.UnpackArray(stream);
                    // Properties are sorted by lexical order
                    var index = Array.IndexOf(typeof(T).GetProperties().OrderBy(p => p.Name).ToArray(), propertyInfo);
                    Assert.That(
                        result[index].ToString().Equals((( IFormattable )propertyInfo.GetValue(value, null)).ToString("D", null)),
                        result[index] + " == " + (( IFormattable )propertyInfo.GetValue(value, null)).ToString("D", null)
                        );
                }
            }
        }
Ejemplo n.º 2
0
        private static void TestEnumForByUnderlyingValueCore <T>(Stream stream, T value, T deserialized, string property)
        {
            if (property == null)
            {
                Assert.That(deserialized, Is.EqualTo(value));
                stream.Position = 0;
                var result = Unpacking.UnpackObject(stream);
                Assert.That(
                    result.ToString().Equals((( IFormattable )value).ToString("D", null)),
                    result + " == " + (( IFormattable )value).ToString("D", null)
                    );
            }
            else
            {
                var propertyInfo = typeof(T).GetProperty(property);
#if !UNITY
                Assert.That(propertyInfo.GetValue(deserialized, null), Is.EqualTo(propertyInfo.GetValue(value, null)));
#else
                Assert.That(propertyInfo.GetGetMethod().Invoke(deserialized, null), Is.EqualTo(propertyInfo.GetGetMethod().Invoke(value, null)));
#endif // !UNITY
                stream.Position = 0;
                var result = Unpacking.UnpackArray(stream);
                // Properties are sorted by lexical order
                var index = Array.IndexOf(typeof(T).GetProperties().OrderBy(p => p.Name).ToArray(), propertyInfo);
                Assert.That(
#if !UNITY
                    result[index].ToString().Equals((( IFormattable )propertyInfo.GetValue(value, null)).ToString("D", null)),
                    result[index] + " == " + (( IFormattable )propertyInfo.GetValue(value, null)).ToString("D", null)
#else
                    result[index].ToString().Equals((( IFormattable )propertyInfo.GetGetMethod().Invoke(value, null)).ToString("D", null)),
                    result[index] + " == " + (( IFormattable )propertyInfo.GetGetMethod().Invoke(value, null)).ToString("D", null)
#endif // !UNITY
                    );
            }
        }
Ejemplo n.º 3
0
        private static void TestSendReceiveRequestCore(IPEndPoint endPoint, int count, CountdownEvent latch)
        {
            using (var udpClient = new UdpClient(AddressFamily.InterNetwork))
            {
                udpClient.Connect(endPoint);

                for (int i = 0; i < count; i++)
                {
                    if (latch != null)
                    {
                        latch.Reset();
                    }

                    var ids = Enumerable.Repeat(0, latch == null ? 1 : latch.InitialCount).Select(_ => Guid.NewGuid().ToString()).ToArray();

                    if (!Task.WaitAll(
                            ids.Select(
                                id =>
                                Task.Factory.StartNew(
                                    _ =>
                    {
                        using (var buffer = new MemoryStream())
                        {
                            using (var packer = Packer.Create(buffer, false))
                            {
                                PackRequest(packer, id);
                            }

                            buffer.Position = 0;

                            if (latch != null)
                            {
                                latch.Signal();
                                if (!latch.Wait(Debugger.IsAttached ? Timeout.Infinite : TimeoutMilliseconds))
                                {
                                    throw new TimeoutException();
                                }
                            }

                            // send
                            udpClient.Send(buffer.ToArray(), ( int )buffer.Length);
                        }
                    },
                                    id
                                    )
                                ).ToArray(),
                            Debugger.IsAttached ? Timeout.Infinite : TimeoutMilliseconds
                            ))
                    {
                        throw new TimeoutException();
                    }

                    // receive
                    IPEndPoint received = endPoint;
                    var        result   = Unpacking.UnpackArray(udpClient.Receive(ref endPoint)).Value;
                    AssertResponse(result, ids);
                }
            }
        }
        private void TestEchoRequestContinuousCore(bool[] serverStatus, CountdownEvent waitHandle, int count, string message)
        {
            using (var client = new TcpClient())
            {
                client.Connect(new IPEndPoint(IPAddress.Loopback, CallbackServer.PortNumber));

                var    now           = MessagePackConvert.FromDateTime(DateTime.Now);
                bool[] resposeStatus = new bool[count];

                using (var stream = client.GetStream())
                    using (var packer = Packer.Create(stream))
                    {
                        for (int i = 0; i < count; i++)
                        {
                            this._trace.TraceInformation("---- Client sending request ----");
                            packer.PackArrayHeader(4);
                            packer.Pack(0);
                            packer.Pack(i);
                            packer.Pack("Echo");
                            packer.PackArrayHeader(2);
                            packer.Pack(message);
                            packer.Pack(now);
                            this._trace.TraceInformation("---- Client sent request ----");
                        }

                        if (Debugger.IsAttached)
                        {
                            waitHandle.Wait();
                        }
                        else
                        {
                            Assert.That(waitHandle.Wait(TimeSpan.FromSeconds(count * 3)));
                        }

                        for (int i = 0; i < count; i++)
                        {
                            this._trace.TraceInformation("---- Client receiving response ----");
                            var array = Unpacking.UnpackArray(stream);
                            Assert.That(array.Count, Is.EqualTo(4));
                            Assert.That(array[0] == 1, array[0].ToString());
                            Assert.That(array[1].IsTypeOf <int>().GetValueOrDefault());
                            resposeStatus[array[1].AsInt32()] = true;
                            Assert.That(array[2] == MessagePackObject.Nil, array[2].ToString());
                            Assert.That(array[3].IsArray, array[3].ToString());
                            var returnValue = array[3].AsList();
                            Assert.That(returnValue.Count, Is.EqualTo(2));
                            Assert.That(returnValue[0] == message, returnValue[0].ToString());
                            Assert.That(returnValue[1] == now, returnValue[1].ToString());
                            this._trace.TraceInformation("---- Client received response ----");
                        }

                        lock ( serverStatus )
                        {
                            Assert.That(serverStatus, Is.All.True, String.Join(", ", serverStatus));
                        }
                        Assert.That(resposeStatus, Is.All.True);
                    }
            }
        }
Ejemplo n.º 5
0
        public void TestClientShutdown_NotAffectOthers()
        {
            TestSendReceiveRequest(
                endPoint =>
            {
                using (var activeTcpClient = new TcpClient(AddressFamily.InterNetwork))
                    using (var inactiveTcpClient = new TcpClient(AddressFamily.InterNetwork))
                    {
                        activeTcpClient.Connect(endPoint);
                        inactiveTcpClient.Connect(endPoint);

                        using (var stream = activeTcpClient.GetStream())
                        {
                            var id1 = Guid.NewGuid().ToString();

                            using (var buffer = new MemoryStream())
                            {
                                using (var packer = Packer.Create(buffer, false))
                                {
                                    PackRequest(packer, id1);
                                }

                                buffer.Position = 0;

                                // send
                                buffer.CopyTo(stream);
                            }

                            // receive
                            var result1 = Unpacking.UnpackArray(stream);
                            AssertResponse(result1, id1);

                            inactiveTcpClient.Client.Shutdown(SocketShutdown.Send);

                            var id2 = Guid.NewGuid().ToString();

                            using (var buffer = new MemoryStream())
                            {
                                using (var packer = Packer.Create(buffer, false))
                                {
                                    PackRequest(packer, id2);
                                }

                                buffer.Position = 0;

                                // send
                                buffer.CopyTo(stream);
                            }

                            // receive
                            var result2 = Unpacking.UnpackArray(stream);
                            AssertResponse(result2, id2);
                        }
                    }
            }
                );
        }
Ejemplo n.º 6
0
        public void TestClientShutdown_NotAffectOthers()
        {
            TestSendReceiveRequest(
                endPoint =>
            {
                using (var activeUdpClient = new UdpClient(AddressFamily.InterNetwork))
                    using (var inactiveUdpClient = new UdpClient(AddressFamily.InterNetwork))
                    {
                        activeUdpClient.Connect(endPoint);
                        inactiveUdpClient.Connect(endPoint);

                        var id1 = Guid.NewGuid().ToString();

                        using (var buffer = new MemoryStream())
                        {
                            using (var packer = Packer.Create(buffer, false))
                            {
                                PackRequest(packer, id1);
                            }

                            buffer.Position = 0;

                            // send
                            activeUdpClient.Send(buffer.ToArray(), ( int )buffer.Length);
                        }

                        // receive
                        IPEndPoint received1 = endPoint;
                        var result1          = Unpacking.UnpackArray(activeUdpClient.Receive(ref received1)).Value;
                        AssertResponse(result1, id1);

                        inactiveUdpClient.Client.Shutdown(SocketShutdown.Send);

                        var id2 = Guid.NewGuid().ToString();

                        using (var buffer = new MemoryStream())
                        {
                            using (var packer = Packer.Create(buffer, false))
                            {
                                PackRequest(packer, id2);
                            }

                            buffer.Position = 0;

                            // send
                            activeUdpClient.Send(buffer.ToArray(), ( int )buffer.Length);
                        }

                        // receive
                        IPEndPoint received = endPoint;
                        var result2         = Unpacking.UnpackArray(activeUdpClient.Receive(ref received)).Value;
                        AssertResponse(result2, id2);
                    }
            }
                );
        }
        public void TestIsGreatorThanQuota_MessagetooLongError()
        {
            long quota = 16;

            ServerTransportTest.TestFiltersCore(
                (argumentPacker, currentLength) =>
            {
                var remaining = quota - currentLength - 2;                         // header(FixArray) + header(FixRaw) = 2 byte
                argumentPacker.PackArrayHeader(1);
                argumentPacker.PackRaw(new byte[remaining + 1]);
            },
                null,
                (request, response) =>
            {
                // Error occurred.
                var responseMessage = Unpacking.UnpackArray(response).Value;
                Assert.That(responseMessage[2] == RpcError.MessageTooLargeError.Identifier, "{0}:{1}", responseMessage[2], responseMessage[3]);
            },
                new ServerQuotaMessageFilterProvider(quota)
                );
        }
        public void TestIsEqualToQuota_Ok()
        {
            long quota = 16;

            ServerTransportTest.TestFiltersCore(
                (argumentPacker, currentLength) =>
            {
                var remaining = quota - currentLength - 2;                         // header(FixArray) + header(FixRaw) = 2 byte
                argumentPacker.PackArrayHeader(1);
                argumentPacker.PackRaw(new byte[remaining]);
            },
                null,
                (request, response) =>
            {
                // No error occurred.
                var responseMessage = Unpacking.UnpackArray(response).Value;
                Assert.That(responseMessage[2].IsNil, "{0}:{1}", responseMessage[2], responseMessage[3]);
            },
                new ServerQuotaMessageFilterProvider(quota)
                );
        }
        private void TestEnumForByName <T>(SerializationContext context, T value, string property)
        {
            var serializer = context.GetSerializer <T>();

            using (var stream = new MemoryStream())
            {
                serializer.Pack(stream, value);
                stream.Position = 0;
                var deserialized = serializer.Unpack(stream);

                if (property == null)
                {
                    Assert.That(deserialized, Is.EqualTo(value));
                    stream.Position = 0;
                    Assert.That(Unpacking.UnpackString(stream), Is.EqualTo(value.ToString()));
                }
                else
                {
                    var propertyInfo = typeof(T).GetProperty(property);
#if !UNITY
                    Assert.That(propertyInfo.GetValue(deserialized, null), Is.EqualTo(propertyInfo.GetValue(value, null)));
#else
                    Assert.That(propertyInfo.GetGetMethod().Invoke(deserialized, null), Is.EqualTo(propertyInfo.GetGetMethod().Invoke(value, null)));
#endif // !UNITY
                    stream.Position = 0;
                    // Properties are sorted by lexical order
                    var index  = Array.IndexOf(typeof(T).GetProperties().OrderBy(p => p.Name).ToArray(), propertyInfo);
                    var result = Unpacking.UnpackArray(stream);
                    Assert.That(
#if !UNITY
                        result[index].Equals(propertyInfo.GetValue(value, null).ToString()),
                        result[index] + " == " + propertyInfo.GetValue(value, null)
#else
                        result[index].Equals(propertyInfo.GetGetMethod().Invoke(value, null).ToString()),
                        result[index] + " == " + propertyInfo.GetGetMethod().Invoke(value, null)
#endif // !UNITY
                        );
                }
            }
        }
Ejemplo n.º 10
0
        public void TestServerShutdown_Shutdowned()
        {
            TestSendReceiveRequest(
                (endPoint, manager) =>
            {
                using (var tcpClient = new TcpClient(AddressFamily.InterNetwork))
                {
                    tcpClient.Connect(endPoint);

                    using (var stream = tcpClient.GetStream())
                    {
                        var id = Guid.NewGuid().ToString();

                        using (var buffer = new MemoryStream())
                        {
                            using (var packer = Packer.Create(buffer, false))
                            {
                                PackRequest(packer, id);
                            }

                            buffer.Position = 0;

                            // send
                            buffer.CopyTo(stream);
                        }

                        // receive
                        var result = Unpacking.UnpackArray(stream);
                        AssertResponse(result, id);

                        manager.BeginShutdown();

                        byte[] bytes = new byte[1];
                        int received = stream.Read(bytes, 0, bytes.Length);
                        Assert.That(received, Is.EqualTo(0));
                    }
                }
            }
                );
        }
        private static void TestSendReceiveRequestCore(IPEndPoint endPoint, int count, int concurrency)
        {
            _SetUpFixture.EnsureThreadPoolCapacity();
            using (var clientTransportManager = new TcpClientTransportManager(new RpcClientConfiguration()))
            {
                var connectTask = clientTransportManager.ConnectAsync(endPoint);

                if (!connectTask.Wait(Debugger.IsAttached ? Timeout.Infinite : TimeoutMilliseconds))
                {
                    throw new TimeoutException();
                }

                using (var clientTransport = connectTask.Result)
                {
                    for (int i = 0; i < count; i++)
                    {
                        using (var latch = new CountdownEvent(concurrency))
                        {
                            var ids           = Enumerable.Range(i * concurrency, concurrency).ToArray();
                            var args          = Enumerable.Repeat(0, concurrency).Select(_ => Guid.NewGuid().ToString()).ToArray();
                            var idAndArgs     = ids.Zip(args, (id, arg) => new { MessageId = id, Guid = arg.ToString() });
                            var requestTable  = new ConcurrentDictionary <int, string>();
                            var responseTable = new ConcurrentDictionary <int, string>();
                            var exceptions    = new ConcurrentBag <Exception>();

                            if (!Task.Factory.ContinueWhenAll(
                                    idAndArgs.Select(
                                        idAndArg =>
                                        Task.Factory.StartNew(
                                            () =>
                            {
                                var requestContext = clientTransport.GetClientRequestContext();
                                requestTable[idAndArg.MessageId] = idAndArg.Guid;
                                requestContext.SetRequest(
                                    idAndArg.MessageId,
                                    "Dummy",
                                    (responseContext, exception, completedSynchronously) =>
                                {
                                    try
                                    {
                                        if (exception != null)
                                        {
                                            exceptions.Add(exception);
                                        }
                                        else
                                        {
                                            // Server returns args as array, so store only first element.
                                            responseTable[responseContext.MessageId.Value] = Unpacking.UnpackArray(responseContext.ResultBuffer)[0].AsString();
                                        }
                                    }
                                    finally
                                    {
                                        latch.Signal();
                                    }
                                }
                                    );
                                requestContext.ArgumentsPacker.PackArrayHeader(1);
                                requestContext.ArgumentsPacker.Pack(idAndArg.Guid);

                                return(requestContext);
                            }
                                            )
                                        ).ToArray(),
                                    previouses =>
                            {
                                var contexts = previouses.Select(previous => previous.Result).ToArray();
                                foreach (var context in contexts)
                                {
                                    clientTransport.Send(context);
                                }
                            }
                                    ).ContinueWith(
                                    previous =>
                            {
                                if (previous.IsFaulted)
                                {
                                    throw previous.Exception;
                                }

                                // receive
                                if (!latch.Wait(Debugger.IsAttached ? Timeout.Infinite : TimeoutMilliseconds))
                                {
                                    throw new TimeoutException("Receive");
                                }

                                if (exceptions.Any())
                                {
                                    throw new AggregateException(exceptions);
                                }

                                Assert.That(requestTable.Count, Is.EqualTo(concurrency));
                                Assert.That(requestTable, Is.EquivalentTo(responseTable));
                            }
                                    ).Wait(Debugger.IsAttached ? Timeout.Infinite : TimeoutMilliseconds))
                            {
                                throw new TimeoutException();
                            }
                        }
                    }
                }
            }
        }