public void SerializeRequestTest()
        {
            using (ConnectionMock connection = new ConnectionMock("test"))
            {
                BuildExcerptsCommand target = new BuildExcerptsCommand(connection);
                var       accessor          = GetCommandAccessor(target);
                ArrayList values            = new ArrayList();

                IBinaryWriter writer = new ArrayListWriterMock(values);
                accessor.SerializeRequest(writer);

                Assert.AreEqual(values.Count, 15);
                Assert.AreEqual(values[0], BuildExcerptsCommand_Accessor.MODE);
                Assert.AreEqual(values[1], (int)target.Options);
                Assert.AreEqual(values[2], target.Index);
                // Keywords skipped, will be tested in unit-test for StringList class
                Assert.AreEqual(values[4], target.BeforeMatch);
                Assert.AreEqual(values[5], target.AfterMatch);
                Assert.AreEqual(values[6], target.SnippetsDelimiter);
                Assert.AreEqual(values[7], target.SnippetSizeLimit);
                Assert.AreEqual(values[8], target.WordsAroundKeyword);
                Assert.AreEqual(values[9], target.SnippetsCountLimit);
                Assert.AreEqual(values[10], target.WordsCountLimit);
                Assert.AreEqual(values[11], target.StartPassageId);
                Assert.AreEqual(values[12], target.HtmlStripMode.ToString().ToLowerInvariant());
                Assert.AreEqual(values[13], target.PassageBoundary.ToString().ToLowerInvariant());
                // Documents skipped, for same reason
            }
        }
Example #2
0
        public void ConfMsgTest()
        {
            ConnectionMock mc     = new ConnectionMock();
            sHGG           ggmock = new sHGG(mc);
            string         msg    = "Conference message output test";

            int[] recs = new int[] { 12345, 67890, 98765, 4321, 100001 };
            ggmock.GGSendMessage(recs, msg);
            Assert.AreEqual(mc.data.Length, (20 + 1 + msg.Length + 5 + (4 * recs.Length)) * recs.Length);
            for (int i = 0; i < recs.Length; i++)
            {
                Assert.AreEqual(mc.ReadUInt(), 0xb);                                         // type
                Assert.AreEqual(mc.ReadUInt(), 12 + 1 + msg.Length + 5 + (4 * recs.Length)); // size
                Assert.AreEqual(mc.ReadUInt(), recs[i]);                                     // rec
                mc.ReadUInt();                                                               // seq
                mc.ReadUInt();                                                               // msg class
                for (int j = 0; j < msg.Length; j++)
                {
                    Assert.AreEqual(mc.ReadByte(), Convert.ToByte(msg[j]));
                }
                Assert.AreEqual(mc.ReadByte(), 0); // null char
                Assert.AreEqual(mc.ReadByte(), 1); // conf flag
                Assert.AreEqual(mc.ReadUInt(), recs.Length);
                for (int m = 0; m < recs.Length; m++)
                {
                    Assert.AreEqual(mc.ReadUInt(), recs[m]);
                }
            }
            Assert.IsTrue(mc.IsEnd);
        }
        public void SerializeTest()
        {
            using (ConnectionMock connection = new ConnectionMock())
            {
                ArrayList calls  = new ArrayList();
                ArrayList buffer = new ArrayList();
                connection.SetFormatterFactory(new ArrayListFormatterFactoryMock(buffer));

                const string commandinfoSerializeIsCalled = "commandInfo Serialize is called";
                MCommandInfo commandInfo = new MCommandInfo
                {
                    SerializeIBinaryWriter = (writer) => calls.Add(commandinfoSerializeIsCalled)
                };

                var target = CreateCommandWithResultBase(connection);
                target.CommandInfoGet = () => commandInfo;
                const string serializeRequestIsCalled = "SerializeRequest is called";
                target.SerializeRequestIBinaryWriter = (writer) => calls.Add(serializeRequestIsCalled);
                var          accessor           = GetCommandAccessor(target);
                const string writebytesIsCalled = "WriteBytes is called";
                var          streamAdapter      = new SStreamAdapter(new MemoryStream())
                {
                    WriteBytesByteArrayInt32 = (array, len) => calls.Add(writebytesIsCalled)
                };

                accessor.Serialize(streamAdapter);

                CollectionAssert.AreEqual(buffer, new int[] { 0 });
                CollectionAssert.AreEqual(calls, new [] { commandinfoSerializeIsCalled, serializeRequestIsCalled, writebytesIsCalled });
            }
        }
Example #4
0
        public void FakeLogin60Test()
        {
            ConnectionMock mc       = new ConnectionMock();
            sHGG           mockGG   = new sHGG(mc);
            string         pass     = "******";
            uint           fakeSeed = 674456;

            mockGG.GGNumber   = "100001";
            mockGG.GGPassword = pass;
            mockGG.OutLogin60(fakeSeed);
            Assert.AreEqual(mc.data.Length, 39);
            Assert.AreEqual(mc.ReadUInt(), 0x15); // type
            Assert.AreEqual(mc.ReadUInt(), 31);   // size
            Assert.AreEqual(mc.ReadUInt(), 100001);
            Assert.AreEqual(mc.ReadUInt(), sHGG.Hash(pass, fakeSeed));
            Assert.AreEqual(mc.ReadUInt(), 0x14);
            mc.ReadUInt();                       // gg ver
            Assert.AreEqual(mc.ReadByte(), 0x0); // unknown byte
            mc.ReadUInt();                       // local ip
            mc.ReadShort();                      // local port
            mc.ReadUInt();                       // external ip
            mc.ReadShort();                      // external port
            byte imageSize = mc.ReadByte();

            Assert.AreEqual(mc.ReadByte(), 0xbe); // unknown
            Assert.IsTrue(mc.IsEnd);
        }
Example #5
0
        public async Task DispatchFaultAsync_SendsFaultWithoutAssociatedRequestId()
        {
            using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator))
                using (var connection = new ConnectionMock())
                    using (var messageSentEvent = new ManualResetEventSlim(initialState: false))
                    {
                        dispatcher.SetConnection(connection);

                        var fault = new Fault(message: "a");

                        Message message = null;

                        connection.MessageSent += (object sender, MessageEventArgs e) =>
                        {
                            message = e.Message;

                            messageSentEvent.Set();
                        };

                        await dispatcher.DispatchFaultAsync(
                            request : null,
                            fault : fault,
                            cancellationToken : CancellationToken.None);

                        Assert.NotNull(message);
                        Assert.Equal(_idGenerator.Id, message.RequestId);
                        Assert.Equal(MessageType.Fault, message.Type);
                        Assert.Equal(MessageMethod.None, message.Method);
                        Assert.Equal("{\"Message\":\"a\"}", message.Payload.ToString(Formatting.None));
                    }
        }
Example #6
0
        public async Task DispatchCancelAsync_SendsProgressWithAssociatedRequestId()
        {
            using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator))
                using (var connection = new ConnectionMock())
                {
                    dispatcher.SetConnection(connection);

                    Message message = null;

                    connection.MessageSent += (object sender, MessageEventArgs e) =>
                    {
                        message = e.Message;
                    };

                    var request = new Message(_idGenerator.Id, MessageType.Request, MessageMethod.GetOperationClaims);

                    var requestTask = dispatcher.DispatchRequestAsync <Request, Response>(
                        request.Method,
                        new Request(),
                        cancellationToken: CancellationToken.None);

                    await dispatcher.DispatchCancelAsync(request, CancellationToken.None);

                    Assert.NotNull(message);
                    Assert.Equal(_idGenerator.Id, message.RequestId);
                    Assert.Equal(MessageType.Cancel, message.Type);
                    Assert.Equal(request.Method, message.Method);
                    Assert.Null(message.Payload);
                }
        }
Example #7
0
        public async Task DispatchResponseAsync_ReturnsResponse()
        {
            using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator))
                using (var connection = new ConnectionMock())
                {
                    dispatcher.SetConnection(connection);

                    var requestTask = dispatcher.DispatchRequestAsync <Request, Response>(
                        _method,
                        new Request(),
                        CancellationToken.None);

                    var response = new Message(
                        _idGenerator.Id,
                        MessageType.Response,
                        _method,
                        JObject.FromObject(new Response()));

                    connection.SimulateResponse(response);

                    await requestTask;

                    Assert.IsType <Response>(requestTask.Result);
                }
        }
Example #8
0
        public void SetUp()
        {
            ConnectionMock.SetupDapperAsync(x => x.QueryAsync <Core.Entities.Category>(It.IsAny <string>(), null, null, null, null))
            .ReturnsAsync(CategorySamples.All);

            Assert.DoesNotThrow(() => _result = UnderTest.GetAllAsync());
        }
        private void SetupMocks()
        {
            if (_connectionFactoryShouldThrow)
            {
                ConnectionFactoryMock.Setup(_ => _.CreateConnection(It.IsAny <IList <AmqpTcpEndpoint> >()))
                .Throws <ProtocolViolationException>();
            }
            else
            {
                ConnectionFactoryMock.Setup(_ => _.CreateConnection(It.IsAny <IList <AmqpTcpEndpoint> >()))
                .Returns(ConnectionMock.Object);
            }

            ConnectionFactoryMock.SetupSet(_ => _.Password = It.IsAny <string>());
            ConnectionFactoryMock.SetupSet(_ => _.UserName = It.IsAny <string>());

            if (_connectionShouldThrow)
            {
                ConnectionMock.Setup(_ => _.CreateModel()).Throws <ProtocolViolationException>();
            }
            else
            {
                ConnectionMock.Setup(_ => _.CreateModel()).Returns(ModelMock.Object);
            }

            AmqpConsumerFactoryMock.Setup(_ => _.CreateReceiveConsumer(It.IsAny <IModel>()))
            .Returns(AmqpReceiveConsumerMock.Object);

            MaskinportenClientMock.Setup(_ => _.GetAccessToken(It.IsAny <string>()))
            .ReturnsAsync(new MaskinportenToken(_token, 100));
        }
Example #10
0
        public void UnmanagedReadMockTest()
        {
            ConnectionMock  mock = new ConnectionMock();
            UnmanagedStruct ustr = new UnmanagedStruct()
            {
                ByteArr = new byte[] { 3, 5, 7 },
                Number  = UInt32.MaxValue,
                Str     = "Unmanaged!"
            };

            mock.Write(sHGG.RawSerialize(ustr));
            Assert.AreEqual(mock.data.Length, 18);
            Assert.AreEqual(mock.ReadUInt(), UInt32.MaxValue);
            // byte[]
            Assert.AreEqual(mock.ReadByte(), 3);
            Assert.AreEqual(mock.ReadByte(), 5);
            Assert.AreEqual(mock.ReadByte(), 7);
            // string + 0 char
            Assert.AreEqual(mock.ReadByte(), Convert.ToByte('U'));
            Assert.AreEqual(mock.ReadByte(), Convert.ToByte('n'));
            Assert.AreEqual(mock.ReadByte(), Convert.ToByte('m'));
            Assert.AreEqual(mock.ReadByte(), Convert.ToByte('a'));
            Assert.AreEqual(mock.ReadByte(), Convert.ToByte('n'));
            Assert.AreEqual(mock.ReadByte(), Convert.ToByte('a'));
            Assert.AreEqual(mock.ReadByte(), Convert.ToByte('g'));
            Assert.AreEqual(mock.ReadByte(), Convert.ToByte('e'));
            Assert.AreEqual(mock.ReadByte(), Convert.ToByte('d'));
            Assert.AreEqual(mock.ReadByte(), Convert.ToByte('!'));
            Assert.AreEqual(mock.ReadByte(), 0);
        }
Example #11
0
 public void ConstructorTest()
 {
     using (ConnectionBase connection = new ConnectionMock())
     {
         var commandBase = CreateCommandBase(connection);
         Assert.AreEqual(commandBase.Connection, connection);
     }
 }
 public void DocumentsTest()
 {
     using (ConnectionMock connection = new ConnectionMock("test"))
     {
         BuildExcerptsCommand target = new BuildExcerptsCommand(connection);
         Assert.IsNotNull(target.Documents);
         Assert.IsInstanceOfType(target.Documents, typeof(IList <string>));
     }
 }
Example #13
0
        public static GcConnection CreateMockConnection(ServerImplementationMock serverMock)
        {
            var clientToServer = serverMock.MockClientToServerLink();
            // Create a link from client to server
            var connectionMock = new ConnectionMock(serverMock, clientToServer.Item2);

            // Create a link from server to client
            clientToServer.Item1.SetConnectionMock(connectionMock);
            return(new GcConnection(connectionMock));
        }
 public void CommandInfoTest()
 {
     using (ConnectionMock connection = new ConnectionMock("test"))
     {
         BuildExcerptsCommand          target   = new BuildExcerptsCommand(connection);
         BuildExcerptsCommand_Accessor accessor = GetCommandAccessor(target);
         Assert.IsNotNull(accessor.CommandInfo);
         Assert.AreEqual(accessor.CommandInfo.Id, ServerCommand.Excerpt);
         Assert.AreEqual(accessor.CommandInfo.Version, BuildExcerptsCommand_Accessor.COMMAND_VERSION);
     }
 }
Example #15
0
        public void TransactionAttribute_Begins_Transaction_On_Action_Executing_With_No_Isolation_Level()
        {
            var attr = new TransactionAttribute {
                Connection = ConnectionMock.Object
            };

            attr.OnActionExecuting(new ActionExecutingContext());

            ConnectionMock.Verify(c => c.BeginTransaction());
            ContextMock.Verify(cx => cx.Bind(TransactionMock.Object));
        }
 public void ResultTest()
 {
     using (ConnectionBase connection = new ConnectionMock())
     {
         var target   = CreateCommandWithResultBase(connection);
         var accessor = GetCommandAccessor(target);
         var expected = new CommandResultBaseMock();
         accessor.Result = expected;
         Assert.AreEqual(expected, target.Result);
     }
 }
Example #17
0
        public void FakePingTest()
        {
            ConnectionMock mc     = new ConnectionMock();
            sHGG           mockGG = new sHGG(mc);

            mockGG.OutPing(new object(), EventArgs.Empty);
            Assert.AreEqual(mc.data.Length, 8);
            Assert.AreEqual(mc.ReadUInt(), 0x8);
            Assert.AreEqual(mc.ReadUInt(), 0);
            Assert.IsTrue(mc.IsEnd);
        }
Example #18
0
        public void TransactionAttribute_Begins_Transaction_With_Specified_Isolation_Level()
        {
            var attr = new TransactionAttribute {
                Connection = ConnectionMock.Object, IsolationLevel = IsolationLevel.Snapshot
            };

            attr.OnActionExecuting(new ActionExecutingContext());

            ConnectionMock.Verify(c => c.BeginTransaction(IsolationLevel.Snapshot));
            ContextMock.Verify(cx => cx.Bind(TransactionMock.Object));
        }
 public void HtmlStripModeTest()
 {
     using (ConnectionBase connection = new ConnectionMock())
     {
         BuildExcerptsCommand target = new BuildExcerptsCommand(connection);
         // default value
         Assert.AreEqual(target.HtmlStripMode, BuildExcerptsCommand_Accessor.DEFAULT_HTML_STRIP_MODE);
         // valid value
         HtmlStripMode expected = HtmlStripMode.Retain;
         target.HtmlStripMode = expected;
         Assert.AreEqual(expected, target.HtmlStripMode);
     }
 }
 public void PassageBoundaryTest()
 {
     using (ConnectionBase connection = new ConnectionMock())
     {
         BuildExcerptsCommand target = new BuildExcerptsCommand(connection);
         // default value
         Assert.AreEqual(target.PassageBoundary, BuildExcerptsCommand_Accessor.DEFAULT_PASSAGE_BOUNDARY);
         // valid value
         PassageBoundary expected = PassageBoundary.Paragraph;
         target.PassageBoundary = expected;
         Assert.AreEqual(expected, target.PassageBoundary);
     }
 }
Example #21
0
        public async Task DispatchCancelAsync_ThrowsWithoutAssociatedRequestId()
        {
            using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator))
                using (var connection = new ConnectionMock())
                {
                    dispatcher.SetConnection(connection);

                    var request = new Message(_idGenerator.Id, MessageType.Request, _method);

                    await Assert.ThrowsAsync <ProtocolException>(
                        () => dispatcher.DispatchCancelAsync(request, CancellationToken.None));
                }
        }
 public void OptionsTest()
 {
     using (ConnectionBase connection = new ConnectionMock())
     {
         BuildExcerptsCommand target = new BuildExcerptsCommand(connection);
         // default value
         Assert.AreEqual(target.Options, BuildExcerptsCommand_Accessor.DEFAULT_OPTIONS);
         // valid value
         BuildExcerptsOptions expected = BuildExcerptsOptions.OrderByWeight;
         target.Options = expected;
         Assert.AreEqual(expected, target.Options);
     }
 }
Example #23
0
        public void ThrowOverflowTest()
        {
            basic bstr = new basic()
            {
                one = 0xe
            };
            ConnectionMock mock = new ConnectionMock();

            mock.Write(sHGG.RawSerialize(bstr));
            byte oneRe = mock.ReadByte();

            Assert.AreEqual(oneRe, bstr.one);
            mock.ReadByte(); // throw
        }
Example #24
0
        public void MockCtorTest()
        {
            sHGG ggNormal = new sHGG();

            Assert.IsFalse(ggNormal.mock);
            Assert.IsNull(ggNormal.mockObj);
            ConnectionMock mock   = new ConnectionMock();
            sHGG           ggMock = new sHGG(mock);

            Assert.IsTrue(ggMock.mock);
            Assert.IsNotNull(ggMock.mockObj);
            Assert.AreEqual(ggMock.mockObj, mock);
            Assert.AreSame(ggMock.mockObj, mock);
        }
        public void DeserializeTest()
        {
            using (ConnectionMock connection = new ConnectionMock())
            {
                ArrayList calls  = new ArrayList();
                ArrayList buffer = new ArrayList();
                connection.SetFormatterFactory(new ArrayListFormatterFactoryMock(buffer));
                const CommandStatus expectedStatus = CommandStatus.Ok;
                buffer.Add((short)expectedStatus);
                const short expectedCommandVersion = 1;
                buffer.Add(expectedCommandVersion);
                const int expectedLength = 1;
                buffer.Add(expectedLength);
                buffer.Add(1);                 // body stub

                var          target = CreateCommandWithResultBase(connection);
                const string validateResponseIsCalled = "ValidateResponse is called";
                target.ValidateResponseIBinaryReaderInt16 = (bodyReader, serverCommandVersion) =>
                {
                    if (serverCommandVersion == expectedCommandVersion)
                    {
                        calls.Add(validateResponseIsCalled);
                    }
                };
                const string deserializeResponseIsCalled = "DeserializeResponse is called";
                target.DeserializeResponseIBinaryReader = (bodyReader) =>
                {
                    calls.Add(deserializeResponseIsCalled);
                };
                const string streamAdapterReadBytesIsCalled = "ReadBytes is called";
                var          streamAdapter = new SStreamAdapter(new MemoryStream())
                {
                    ReadBytesByteArrayInt32 = (array, len) =>
                    {
                        if (len == expectedLength)
                        {
                            calls.Add(streamAdapterReadBytesIsCalled);
                        }
                        return(len);
                    }
                };
                var accessor = GetCommandAccessor(target);
                accessor.Result = new CommandResultBaseMock();

                accessor.Deserialize(streamAdapter);

                Assert.AreEqual(expectedStatus, target.Result.Status);
                CollectionAssert.AreEqual(calls, new[] { streamAdapterReadBytesIsCalled, validateResponseIsCalled, deserializeResponseIsCalled });
            }
        }
Example #26
0
        public void RichMsgTest()
        {
            ConnectionMock mc     = new ConnectionMock();
            sHGG           ggmock = new sHGG(mc);
            int            rec    = 234567;
            string         msg    = "Rich message output test";
            SortedDictionary <short, string> format = new SortedDictionary <short, string>()
            {
                { 5, "<u><green>" },
                { 10, "<b><gray>" },
                { 15, "<n>" }
            };

            ggmock.GGSendMessage(rec, msg, format);
            Assert.AreEqual(mc.data.Length, 38 + msg.Length + 1);
            // msg
            Assert.AreEqual(mc.ReadUInt(), 0xb);                 // type
            Assert.AreEqual(mc.ReadUInt(), 30 + msg.Length + 1); // size
            Assert.AreEqual(mc.ReadUInt(), rec);                 // rec
            mc.ReadUInt();                                       // seq
            mc.ReadUInt();                                       // msg class
            for (int i = 0; i < msg.Length; i++)
            {
                Assert.AreEqual(mc.ReadByte(), Convert.ToByte(msg[i]));
            }
            Assert.AreEqual(mc.ReadByte(), 0); // null char
            Assert.IsFalse(mc.IsEnd);
            // rich info
            Assert.AreEqual(mc.ReadByte(), 2);   // rich info flag
            Assert.AreEqual(mc.ReadShort(), 15); // rich length

            // rich format list
            // { 5, "<u><green>" }
            Assert.AreEqual(mc.ReadShort(), 5);        // pos
            Assert.AreEqual(mc.ReadByte(), 0x4 | 0x8); // font
            Assert.AreEqual(mc.ReadByte(), 91);        // color: R
            Assert.AreEqual(mc.ReadByte(), 164);       // color: G
            Assert.AreEqual(mc.ReadByte(), 42);        // color: B
            // { 10, "<b><gray>" }
            Assert.AreEqual(mc.ReadShort(), 10);       // pos
            Assert.AreEqual(mc.ReadByte(), 0x1 | 0x8); // font
            Assert.AreEqual(mc.ReadByte(), 128);       // color: R
            Assert.AreEqual(mc.ReadByte(), 128);       // color: G
            Assert.AreEqual(mc.ReadByte(), 128);       // color: B
            // { 15, "<n>" }
            Assert.AreEqual(mc.ReadShort(), 15);       // pos
            Assert.AreEqual(mc.ReadByte(), 0x0);       // font

            Assert.IsTrue(mc.IsEnd);
        }
        public void Constructor_PassValidArguments_CopyValues()
        {
            using (ConnectionBase connection = new ConnectionMock())
            {
                string[] documents = new string[] { "doc 1", "doc 2", "doc 3" };
                string[] keywords  = new string[] { "keyword1", "keyword2" };
                string   index     = "test";

                BuildExcerptsCommand target = new BuildExcerptsCommand(connection, documents, keywords, index);

                target.Documents.Should().Have.SameValuesAs(documents);
                target.Keywords.Should().Have.SameValuesAs(keywords);
                target.Index.Should().Be.EqualTo(index);
            }
        }
Example #28
0
        public async Task DispatchProgressAsync_ThrowsWithoutAssociatedRequestId()
        {
            using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator))
                using (var connection = new ConnectionMock())
                {
                    dispatcher.SetConnection(connection);

                    var payload  = JObject.FromObject(new Request());
                    var request  = new Message(_idGenerator.Id, MessageType.Request, _method, payload);
                    var progress = new Progress(percentage: 0.5);

                    await Assert.ThrowsAsync <ProtocolException>(
                        () => dispatcher.DispatchProgressAsync(request, progress, CancellationToken.None));
                }
        }
        public void ExecuteTest()
        {
            bool baseExecuteIsCalled = false;

            MCommandBase.AllInstances.Execute = delegate { baseExecuteIsCalled = true; };
            using (ConnectionBase connection = new ConnectionMock())
            {
                var target = CreateCommandWithResultBase(connection);

                target.Execute();

                Assert.IsNotNull(target.Result);
                Assert.IsTrue(baseExecuteIsCalled);
            }
        }
 public void IndexTest()
 {
     using (ConnectionBase connection = new ConnectionMock())
     {
         BuildExcerptsCommand target = new BuildExcerptsCommand(connection);
         // default value
         Assert.AreEqual(target.Index, null);
         // valid value
         string expected = "test";
         target.Index = expected;
         Assert.AreEqual(expected, target.Index);
         // invalid value
         target.Index = null;
     }
 }