public async Task ShouldStopClientAndThrowExceptionWhenProtocolErrorOccurs()
            {
                using (var harness = new SocketClientTestHarness(FakeUri, null))
                {
                    var messages = new IRequestMessage[]
                    {
                        new RunMessage("This will cause a syntax error"),
                        new PullAllMessage()
                    };

                    var messageHandler = new TestResponseHandler();

                    messageHandler.Register(new InitMessage("MyClient/1.1", new Dictionary <string, object>()));
                    messageHandler.Register(messages[0], new ResultBuilder());
                    messageHandler.Register(messages[1], new ResultBuilder());

                    harness.SetupReadStream("00 00 00 01" +
                                            "00 03 b1 70 a0 00 00");

                    harness.SetupWriteStream();

                    await harness.Client.Start();

                    messageHandler.Error = new ClientException("Neo.ClientError.Request.Invalid", "Test Message");

                    // When
                    var ex = Record.Exception(() => harness.Client.Send(messages, messageHandler));
                    ex.Should().BeOfType <ClientException>();

                    harness.MockTcpSocketClient.Verify(x => x.DisconnectAsync(), Times.Once);
                    harness.MockTcpSocketClient.Verify(x => x.Dispose(), Times.Once);
                }
            }
Пример #2
0
            public async void ShouldDisposeConnectionOnNewBeginTxIfBeginTxFailed()
            {
                // Given
                var mockProtocol = new Mock <IBoltProtocol>();
                var mockConn     = NewMockedConnection(mockProtocol.Object);
                var calls        = 0;

                mockProtocol.Setup(x =>
                                   x.BeginTransactionAsync(It.IsAny <IConnection>(), It.IsAny <string>(), It.IsAny <Bookmark>(),
                                                           It.IsAny <TransactionConfig>()))
                .Returns(Task.CompletedTask).Callback(() =>
                {
                    // only throw exception on the first beginTx call
                    calls++;
                    if (calls == 1)
                    {
                        throw new IOException("Triggered an error when beginTx");
                    }
                });

                var session = NewSession(mockConn.Object);
                var exc     = await Record.ExceptionAsync(() => session.BeginTransactionAsync());

                exc.Should().BeOfType <IOException>();

                // When
                await session.BeginTransactionAsync();

                // Then
                mockConn.Verify(x => x.CloseAsync(), Times.Once);
            }
Пример #3
0
            public async void ShouldDisposeConnectionOnRunIfBeginTxFailed()
            {
                // Given
                var mockConn = new Mock <IConnection>();

                mockConn.Setup(x => x.IsOpen).Returns(true);
                mockConn.Setup(x => x.Run(It.IsAny <string>(), It.IsAny <IDictionary <string, object> >(),
                                          It.IsAny <IMessageResponseCollector>(), It.IsAny <bool>())).Callback <string, IDictionary <string, object>, IMessageResponseCollector, bool>(
                    (s, d, c, b) =>
                {
                    c?.DoneSuccess();
                });
                mockConn.Setup(x => x.Run("BEGIN", null, null, true))
                .Throws(new IOException("Triggered an error when beginTx"));
                var session = NewSession(mockConn.Object);
                var exc     = await Record.ExceptionAsync(() => session.BeginTransactionAsync());

                exc.Should().BeOfType <IOException>();

                // When
                await session.RunAsync("lala");

                // Then
                mockConn.Verify(x => x.CloseAsync(), Times.Once);
            }
Пример #4
0
            public void ShouldServiceUnavailableWhenProcedureNotFound()
            {
                // Given
                var pairs = new List <Tuple <IRequestMessage, IResponseMessage> >
                {
                    MessagePair(InitMessage(), SuccessMessage()),
                    MessagePair(new RunMessage("CALL dbms.cluster.routing.getServers"),
                                new FailureMessage("Neo.ClientError.Procedure.ProcedureNotFound", "not found")),
                    MessagePair(PullAllMessage(), new IgnoredMessage())
                };

                var messagingClient = new MockedMessagingClient(pairs);
                var conn            = SocketConnectionTests.NewSocketConnection(messagingClient.Client);

                conn.Init();

                var manager = CreateDiscoveryManager(conn, null);

                // When
                var exception = Record.Exception(() => manager.Rediscovery());

                // Then
                exception.Should().BeOfType <ServiceUnavailableException>();
                exception.Message.Should().StartWith("Error when calling `getServers` procedure: ");
                messagingClient.ClientMock.Verify(x => x.Stop(), Times.Once);
            }
Пример #5
0
            public async Task ShouldStopClientAndThrowExceptionWhenProtocolErrorOccurs()
            {
                using (var harness = new SocketClientTestHarness(FakeUri))
                {
                    var messages = new IRequestMessage[]
                    {
                        new RunMessage("Any message"),
                    };

                    var messageHandler = new TestResponseHandler();

                    messageHandler.EnqueueMessage(messages[0]);
                    harness.SetupReadStream("00 00 00 01" +
                                            "00 02 b0 7e 00 00"); // read whatever message but not success

                    harness.SetupWriteStream();

                    await harness.Client.Start();

                    // force to recive an error
                    messageHandler.Error = new ClientException("Neo.ClientError.Request.Invalid", "Test Message");

                    // When
                    harness.Client.Send(messages);
                    var ex = Record.Exception(() => harness.Client.Receive(messageHandler));
                    ex.Should().BeOfType <ClientException>();

                    harness.MockTcpSocketClient.Verify(x => x.DisconnectAsync(), Times.Once);
                    harness.MockTcpSocketClient.Verify(x => x.Dispose(), Times.Once);
                }
            }
Пример #6
0
            public async Task ShouldCreateExceptionWhenErrorReceivedFromDatabase()
            {
                using (var harness = new SocketClientTestHarness(FakeUri, null))
                {
                    var messages       = new IRequestMessage[] { new RunMessage("This will cause a syntax error") };
                    var messageHandler = new MessageResponseHandler();
                    messageHandler.EnqueueMessage(new InitMessage("MyClient/1.1", new Dictionary <string, object>()));
                    messageHandler.EnqueueMessage(messages[0], new ResultBuilder());

                    harness.SetupReadStream("00 00 00 01" +
                                            "00 03 b1 70 a0 00 00" +
                                            "00a0b17fa284636f6465d0274e656f2e436c69656e744572726f722e53746174656d656e742e496e76616c696453796e746178876d657373616765d065496e76616c696420696e707574202754273a206578706563746564203c696e69743e20286c696e6520312c20636f6c756d6e203120286f66667365743a203029290a22546869732077696c6c20636175736520612073796e746178206572726f72220a205e0000");

                    harness.SetupWriteStream();

                    await harness.Client.Start();

                    harness.ResetCalls();

                    // When
                    harness.Client.Send(messages);
                    Record.Exception(() => harness.Client.Receive(messageHandler));

                    // Then
                    harness.VerifyWriteStreamUsages(2 /*write + flush*/);

                    messageHandler.HasError.Should().BeTrue();
                    messageHandler.Error.Code.Should().Be("Neo.ClientError.Statement.InvalidSyntax");
                    messageHandler.Error.Message.Should().Be(
                        "Invalid input 'T': expected <init> (line 1, column 1 (offset: 0))\n\"This will cause a syntax error\"\n ^");
                }
            }
Пример #7
0
            public async void ShouldDisposeConnectionOnNewBeginTxIfBeginTxFailed()
            {
                // Given
                var mockConn = new Mock <IConnection>();

                mockConn.Setup(x => x.IsOpen).Returns(true);
                var calls = 0;

                mockConn.Setup(x => x.Run("BEGIN", null, null, true))
                .Callback(() =>
                {
                    // only throw exception on the first beginTx call
                    calls++;
                    if (calls == 1)
                    {
                        throw new IOException("Triggered an error when beginTx");
                    }
                });
                var session = NewSession(mockConn.Object);
                var exc     = await Record.ExceptionAsync(() => session.BeginTransactionAsync());

                exc.Should().BeOfType <IOException>();

                // When
                await session.BeginTransactionAsync();

                // Then
                mockConn.Verify(x => x.CloseAsync(), Times.Once);
            }
Пример #8
0
            public void ShouldThrowExceptionIfProtocolIsNotSupported()
            {
                var ex = Record.Exception(() => new SocketClient(new Uri("http://localhost:1234"), null));

                ex.Should().BeOfType <NotSupportedException>();
                ex.Message.Should().Be("Unsupported protocol: http");
            }
        public void ShouldThrowIfSummaryBuilderIsNull()
        {
            var exc = Record.Exception(() => new RunResponseHandler(new Mock <IResultStreamBuilder>().Object, null));

            exc.Should().BeOfType <ArgumentNullException>().Which
            .ParamName.Should().Be("summaryBuilder");
        }
            public void ShouldThrowArgumentNullExceptionIfSocketClientIsNull()
            {
                var exception = Record.Exception(() => new SocketConnection(null, AuthTokens.None, Logger));

                exception.Should().NotBeNull();
                exception.Should().BeOfType <ArgumentNullException>();
            }
Пример #11
0
        public async Task SingleInvalidRequestAsync()
        {
            AmazonDynamoDBConfig config = new AmazonDynamoDBConfig
            {
                RegionEndpoint = Amazon.RegionEndpoint.USEast1
            };
            CSMTestUtilities testUtils = new CSMTestUtilities
            {
                Service             = "DynamoDB",
                ApiCall             = "DeleteTable",
                AttemptCount        = 1,
                Domain              = "dynamodb.us-east-1.amazonaws.com",
                Region              = "us-east-1",
                AWSException        = "ResourceNotFoundException",
                AWSExceptionMessage = "Requested resource not found",
                HttpStatusCode      = 400,
                MaxRetriesExceeded  = 0,
                StashCount          = 3
            };
            var task = Task.Run(() => testUtils.UDPListener());
            AmazonDynamoDBClient client = new AmazonDynamoDBClient(config);
            var exception = await Record.ExceptionAsync(async() => await client.DeleteTableAsync(new DeleteTableRequest
            {
                TableName = "foobar"
            }));

            Assert.NotNull(exception);
            Assert.IsType <ResourceNotFoundException>(exception);
            Thread.Sleep(10);
            testUtils.EndTest();
            task.Wait();
            testUtils.Validate(task.Result);
        }
Пример #12
0
 public async void ShouldNotAllowNewTxWhileOneIsRunning()
 {
     var mockConn = NewMockedConnection();
     var session = NewSession(mockConn.Object);
     await session.BeginTransactionAsync();
     var error = await Record.ExceptionAsync(() => session.BeginTransactionAsync());
     error.Should().BeOfType<ClientException>();
 }
Пример #13
0
            public async void ShouldNotBeAbleToUseSessionWhileOngoingTransaction()
            {
                var mockConn = NewMockedConnection();
                var session = NewSession(mockConn.Object);
                var tx = await session.BeginTransactionAsync();

                var error = await Record.ExceptionAsync(() => session.RunAsync("lalal"));
                error.Should().BeOfType<ClientException>();
            }
Пример #14
0
        public void op_ToEntity_whenNullValue()
        {
            var obj = new Record<string>
                          {
                              Value = null
                          };

            Assert.Null(obj.ToEntity());
        }
        public void ShouldThrowIfStreamBuilderIsNull()
        {
            var summaryBuilder =
                new Mock <SummaryBuilder>(new Query("stmt"), new ServerInfo(new Uri("bolt://localhost")));
            var exc = Record.Exception(() => new RunResponseHandler(null, summaryBuilder.Object));

            exc.Should().BeOfType <ArgumentNullException>().Which
            .ParamName.Should().Be("streamBuilder");
        }
Пример #16
0
            public void ShouldNotAllowMoreTransactionsInSessionWhileConnectionClosed()
            {
                var mockConn = new Mock <IConnection>();

                mockConn.Setup(x => x.IsOpen).Returns(false);
                var session = new Session(mockConn.Object, null);

                var error = Record.Exception(() => session.BeginTransaction());

                error.Should().BeOfType <ClientException>();
            }
Пример #17
0
            public void ShouldThrowExceptionWhenTryingToCollectBookmark()
            {
                var collector = NewSummaryCollector();
                var error     = Record.Exception(() =>
                                                 collector.CollectBookmark(new Dictionary <string, object> {
                    { "bookmark", "I shall not be here" }
                }));

                error.Should().BeOfType <NotSupportedException>();
                error.Message.Should().Contain("not get a bookmark on a result");
            }
Пример #18
0
            public void ShouldNotAllowMoreStatementsInSessionWhileConnectionClosed()
            {
                var mockConn = new Mock <IConnection>();

                mockConn.Setup(x => x.IsOpen).Returns(false);
                var session = new Session(null, null, null, mockConn.Object);

                var error = Record.Exception(() => session.Run("lalal"));

                error.Should().BeOfType <ClientException>();
            }
Пример #19
0
            public void ShouldNotAllowMoreTransactionsInSessionWhileConnectionHasUnrecoverableError()
            {
                var mockConn = new Mock <IPooledConnection>();

                mockConn.Setup(x => x.HasUnrecoverableError).Returns(true);
                var session = new Session(mockConn.Object, null);

                var error = Record.Exception(() => session.BeginTransaction());

                error.Should().BeOfType <ClientException>();
            }
Пример #20
0
            public void ShouldNotAllowMoreStatementsInSessionWhileConnectionHasUnrecoverableError()
            {
                var mockConn = new Mock <IConnection>();

                mockConn.Setup(x => x.HasUnrecoverableError).Returns(true);
                var session = new Session(mockConn.Object, null);

                var error = Record.Exception(() => session.Run("lalal"));

                error.Should().BeOfType <ClientException>();
            }
Пример #21
0
        public void op_ToEntity()
        {
            var obj = new Record<int>
                          {
                              Value = 123
                          };

            const string expected = "123";
            var actual = obj.ToEntity();

            Assert.Equal(expected, actual);
        }
Пример #22
0
            public void Valid_Ctor()
            {
                var originator = BankAccountTest.SampleOriginator();
                var destination = BankAccountTest.SampleDestination();
                var record = new Record(originator, destination, TransCode.Payment, 100.00m, "Ref");

                Assert.Equal(TransCode.Payment, record.TransCode);
                Assert.Equal(100.00m, record.Amount);
                Assert.Equal("Ref", record.Reference);
                Assert.Equal(originator, record.Originator);
                Assert.Equal(destination, record.Destination);
            }
Пример #23
0
            public void ShouldNotAllowNewTxWhileOneIsRunning()
            {
                var mockConn = new Mock <IConnection>();

                mockConn.Setup(x => x.IsOpen).Returns(true);
                var session = new Session(mockConn.Object, null);

                session.BeginTransaction();
                var error = Record.Exception(() => session.BeginTransaction());

                error.Should().BeOfType <ClientException>();
            }
Пример #24
0
            public void ShouldNotBeAbleToUseSessionWhileOngoingTransaction()
            {
                var mockConn = new Mock <IConnection>();

                mockConn.Setup(x => x.IsOpen).Returns(true);
                var session = new Session(mockConn.Object, null);
                var tx      = session.BeginTransaction();

                var error = Record.Exception(() => session.Run("lalal"));

                error.Should().BeOfType <ClientException>();
            }
Пример #25
0
        public void op_ToXml()
        {
            var obj = new Record<int>
                          {
                              Value = 123
                          };

            var expected = 123.XmlSerialize();
            var actual = obj.ToXml();

            Assert.Equal(expected, actual);
        }
        public void ShouldThrowIfValueIsOfWrongType()
        {
            var metadata = new Dictionary <string, object> {
                { Key, true }
            };
            var collector = new CountersCollector();

            var ex = Record.Exception(() => collector.Collect(metadata));

            ex.Should().BeOfType <ProtocolException>().Which
            .Message.Should()
            .Contain($"Expected '{Key}' metadata to be of type 'IDictionary<String,Object>', but got 'Boolean'.");
        }
Пример #27
0
        public void ShouldThrowIfValueIsOfWrongType()
        {
            var metadata = new Dictionary <string, object> {
                { Key, 1L }
            };
            var collector = new DatabaseInfoCollector();

            var ex = Record.Exception(() => collector.Collect(metadata));

            ex.Should().BeOfType <ProtocolException>().Which
            .Message.Should()
            .Contain($"Expected '{Key}' metadata to be of type 'string', but got 'Int64'.");
        }
Пример #28
0
            public async Task ShouldThrowWhenNoRecord()
            {
                // Given
                var connMock = SetupSocketConnection(new List <object[]>());
                var manager  = new ClusterDiscovery(null, null);

                // When
                var exception = await Record.ExceptionAsync(() => manager.DiscoverAsync(connMock.Object));

                // Then
                exception.Should().BeOfType <InvalidOperationException>().Which.Message.Should()
                .Be("The result is empty.");
                connMock.Verify(x => x.CloseAsync(), Times.Once);
            }
Пример #29
0
            public async Task ShouldThrowWhenRecordUnparsable()
            {
                // Given
                var connMock = SetupSocketConnection(new object[] { 1 });
                var manager  = new ClusterDiscovery(null, null);

                // When
                var exception = await Record.ExceptionAsync(() => manager.DiscoverAsync(connMock.Object));

                // Then
                exception.Should().BeOfType <ProtocolException>().Which.Message.Should()
                .Be("keys (2) does not equal to values (1)");
                connMock.Verify(x => x.CloseAsync(), Times.Once);
            }
Пример #30
0
            public void ShouldProtocolErrorWhenNoRecord()
            {
                // Given
                var connMock = SetupSocketConnection(new List <object[]>());
                var manager  = CreateDiscoveryManager(connMock.Object);

                // When
                var exception = Record.Exception(() => manager.Rediscovery());

                // Then
                exception.Should().BeOfType <ProtocolException>();
                exception.Message.Should().Be("Error when parsing `getServers` result: Sequence contains no elements.");
                connMock.Verify(x => x.Close(), Times.Once);
            }
            public void ShouldThrowExceptionWhenDisposingSessionMoreThanOnce()
            {
                // Given
                var mockConn = new Mock <IConnection>();
                var session  = NewSession(mockConn.Object);

                // When
                session.Dispose();
                var exception = Record.Exception(() => session.Dispose());

                // Then
                exception.Should().BeOfType <ObjectDisposedException>();
                exception.Message.Should().Contain("Failed to dispose this seesion as it has already been disposed.");
            }
Пример #32
0
            public void ShouldDisposeConnectionIfBeginTxFailed()
            {
                var mockConn = new Mock <IConnection>();

                mockConn.Setup(x => x.IsOpen).Returns(true);
                mockConn.Setup(x => x.Run("BEGIN", null, null, true))
                .Throws(new IOException("Triggered an error when beginTx"));
                var session = NewSession(mockConn.Object);

                Record.Exception(() => session.BeginTransaction()).Should().BeOfType <IOException>();
                session.Dispose();

                mockConn.Verify(x => x.Close(), Times.Once);
            }
Пример #33
0
            public async Task ShouldThrowExceptionIfReaderIsEmpty()
            {
                // Given
                var procedureReplyRecordFields = CreateGetServersResponseRecordFields(3, 1, 0);
                var connMock = SetupSocketConnection(procedureReplyRecordFields);
                var manager  = new ClusterDiscovery(null, null);

                // When
                var exception = await Record.ExceptionAsync(() => manager.DiscoverAsync(connMock.Object));

                // Then
                exception.Should().BeOfType <ProtocolException>().Which.Message.Should()
                .Contain("3 routers, 1 writers and 0 readers.");
                connMock.Verify(x => x.CloseAsync(), Times.Once);
            }
Пример #34
0
            public void ShouldProtocolErrorWhenRecordUnparsable()
            {
                // Given
                var connMock = SetupSocketConnection(new object[] { 1 });
                var manager  = CreateDiscoveryManager(connMock.Object);

                // When
                var exception = Record.Exception(() => manager.Rediscovery());

                // Then
                exception.Should().BeOfType <ProtocolException>();
                exception.Message.Should()
                .Be("Error when parsing `getServers` result: keys (2) does not equal to values (1).");
                connMock.Verify(x => x.Close(), Times.Once);
            }
Пример #35
0
        public void AscendingKeyThenDescendingKey()
        {
            Record[] source = new Record[]
            {
                new Record{ Name = "Jim", City = "Minneapolis", Country = "USA" },
                new Record{ Name = "Tim", City = "Seattle", Country = "USA" },
                new Record{ Name = "Philip", City = "Orlando", Country = "USA" },
                new Record{ Name = "Chris", City = "London", Country = "UK" },
                new Record{ Name = "Rob", City = "Kent", Country = "UK" }
            };
            Record[] expected = new Record[]
            {
                new Record{ Name = "Chris", City = "London", Country = "UK" },
                new Record{ Name = "Rob", City = "Kent", Country = "UK" },
                new Record{ Name = "Tim", City = "Seattle", Country = "USA" },
                new Record{ Name = "Philip", City = "Orlando", Country = "USA" },
                new Record{ Name = "Jim", City = "Minneapolis", Country = "USA" }
            };

            Assert.Equal(expected, source.OrderBy((e) => e.Country).ThenByDescending((e) => e.City));
        }
Пример #36
0
        public void op_ToEntity_whenIEntity()
        {
            const string expected = "123";

            var value = new Mock<IEntity>();
            value
                .Setup(x => x.ToEntity())
                .Returns(expected)
                .Verifiable();

            var obj = new Record<IEntity>
                          {
                              Value = value.Object
                          };

            var actual = obj.ToEntity();

            Assert.Equal(expected, actual);

            value.VerifyAll();
        }
Пример #37
0
        public void op_Load_FileSystemInfo()
        {
            var key = AlphaDecimal.Random();
            var expected = new Record<int>
                               {
                                   Cacheability = "public",
                                   Created = new DateTime(1999, 12, 31, 01, 00, 00, 00),
                                   Etag = "\"xyz\"",
                                   Expiration = "P1D",
                                   Key = key,
                                   Modified = new DateTime(2001, 12, 31, 01, 00, 00, 00),
                                   Status = 200,
                                   Urn = "urn://example.com/abc",
                                   Value = 123
                               };

            using (var file = new TempFile())
            {
                using (var stream = file.Info.Open(FileMode.Truncate, FileAccess.Write, FileShare.Read))
                {
                    using (var writer = new StreamWriter(stream))
                    {
                        writer.WriteLine("urn: urn://example.com/abc");
                        writer.WriteLine("key: " + key);
                        writer.WriteLine("etag: \"xyz\"");
                        writer.WriteLine("created: 1999-12-31T01:00:00Z");
                        writer.WriteLine("modified: 2001-12-31T01:00:00Z");
                        writer.WriteLine("cacheability: public");
                        writer.WriteLine("expiration: P1D");
                        writer.WriteLine("status: 200");
                        writer.WriteLine(string.Empty);
                        writer.Write("<int>123</int>");
                    }
                }

                var actual = RecordFile.Load(file.Info).ToRecord<int>();

                Assert.Equal(expected, actual);
            }
        }
 public GridForeignKeyDataCellBuilderTests()
 {
     record = new Record();
 }
Пример #39
0
        private async Task TransfertInternal(string from, string to, long amount, string asset)
        {
            var lAsset = LedgerPath.Parse(asset);
            var aFrom = new AccountKey(LedgerPath.Parse(from), lAsset);
            var aTo = new AccountKey(LedgerPath.Parse(to), lAsset);
            var accounts = await Engine.GetAccounts(new[] { aFrom, aTo });
            var adFrom = accounts[aFrom];
            var adTo = accounts[aTo];

            var rFrom = new Record(aFrom.Key.ToBinary(), LongToByteString(adFrom.Balance - amount), adFrom.Version);
            var rTo = new Record(aTo.Key.ToBinary(), LongToByteString(adTo.Balance + amount), adTo.Version);

            Mutation m = new Mutation(ByteString.Empty, new[] { rFrom, rTo }, ByteString.Empty);

            int c = System.Threading.Interlocked.Increment(ref gcounter);

            Transaction t = new Transaction(
                new ByteString(MessageSerializer.SerializeMutation(m)),
                DateTime.UtcNow,
                new ByteString(BitConverter.GetBytes(c))
            );

            await Engine.AddTransactions(new[] { new ByteString(MessageSerializer.SerializeTransaction(t)) });
            //Output.WriteLine($"{prefix} - {from} ==> {to} Success Retry : {tryCount}");
        }
Пример #40
0
                public void CSV_Fixed_Dp()
                {
                    var record = new Record(BankAccountTest.SampleOriginator(),
                            BankAccountTest.SampleDestination(), DirectDebitAlbany.TransCode.Payment,
                            1234m, "Ref");

                    var serialized = record.Serialize(SerializeMethod.CSV);

                    Assert.Equal("1234.00", serialized.Amount);
                }
Пример #41
0
 public void It_splits_Path_into_segments_separated_by_backslash_and_lowercased()
 {
     var record = new Record(@"Provider::C:\Program Files (x86)\Alteryx\Engine");
     record.PathSegments.ShouldEqual(new[] {"c:", "program files (x86)", "alteryx", "engine"});
 }
Пример #42
0
 public void It_splits_the_supplied_path_on_the_cons()
 {
     var record = new Record("provider::path", 0);
     record.Provider.ShouldEqual("provider");
     record.Path.ShouldEqual("path");
 }
Пример #43
0
        public void op_Save_FileSystemInfo()
        {
            var record = new Record<int>
                             {
                                 Cacheability = "public",
                                 Created = new DateTime(1999, 12, 31, 01, 00, 00, 00),
                                 Etag = "\"xyz\"",
                                 Expiration = "P1D",
                                 Key = AlphaDecimal.Random(),
                                 Modified = new DateTime(2001, 12, 31, 01, 00, 00, 00),
                                 Status = 200,
                                 Urn = "urn://example.com/abc",
                                 Value = 123
                             };

            var expected = new StringBuilder();
            expected.AppendLine("urn: urn://example.com/abc");
            expected.AppendLine("key: " + record.Key);
            expected.AppendLine("etag: \"xyz\"");
            expected.AppendLine("created: 1999-12-31T01:00:00Z");
            expected.AppendLine("modified: 2001-12-31T01:00:00Z");
            expected.AppendLine("cacheability: public");
            expected.AppendLine("expiration: P1D");
            expected.AppendLine("status: 200");
            expected.AppendLine(string.Empty);
            expected.Append("<int>123</int>");

            string actual;
            using (var root = new TempDirectory())
            {
                var obj = new RecordFile(record);
                obj.Save(root.Info);

                actual = new FileInfo(obj.Location.FullName).ReadToEnd();
            }

            Assert.Equal(expected.ToString(), actual);
        }
Пример #44
0
                public void Serialized()
                {
                    var originator = new Mock<IBankAccount>();
                    var serializedAccount = new Mock<ISerializedAccount>();

                    serializedAccount.Setup(x => x.Line).Returns("TESTTEST");
                    originator.Setup(x => x.Serialize(
                                It.IsAny<SerializeMethod>(), It.IsAny<string[]>()))
                        .Returns(serializedAccount.Object);

                    var record = new Record(originator.Object, BankAccountTest.SampleDestination(),
                            DirectDebitAlbany.TransCode.Payment, null, "abvc");

                    var serialized = record.Serialize(SerializeMethod.FixedWidth);

                    Assert.Equal("TESTTEST", serialized.Originator.Line);
                }
 private static void AssertRecord(Record record, ByteString key, ByteString value, ByteString version)
 {
     Assert.Equal(key, record.Key);
     Assert.Equal(value, record.Value);
     Assert.Equal(version, record.Version);
 }
Пример #46
0
        public void op_ToString_whenRecordNullXml()
        {
            var key = AlphaDecimal.Random();
            var record = new Record<string>
                             {
                                 Cacheability = "public",
                                 Created = new DateTime(1999, 12, 31, 01, 00, 00, 00),
                                 Etag = "\"xyz\"",
                                 Expiration = "P1D",
                                 Key = key,
                                 Modified = new DateTime(2001, 12, 31, 01, 00, 00, 00),
                                 Status = 200,
                                 Urn = "urn://example.com/abc",
                                 Value = null
                             };

            var obj = new RecordFile(record);

            var expected = new StringBuilder();
            expected.AppendLine("urn: urn://example.com/abc");
            expected.AppendLine("key: " + key);
            expected.AppendLine("etag: \"xyz\"");
            expected.AppendLine("created: 1999-12-31T01:00:00Z");
            expected.AppendLine("modified: 2001-12-31T01:00:00Z");
            expected.AppendLine("cacheability: public");
            expected.AppendLine("expiration: P1D");
            expected.AppendLine("status: 200");
            expected.AppendLine(string.Empty);

            var actual = obj.ToString();

            Assert.Equal(expected.ToString(), actual);
        }
Пример #47
0
        public void op_ToRecordOfT()
        {
            var expected = new Record<int>
                               {
                                   Cacheability = "public",
                                   Created = new DateTime(1999, 12, 31, 01, 00, 00, 00),
                                   Etag = "\"xyz\"",
                                   Expiration = "P1D",
                                   Key = AlphaDecimal.Random(),
                                   Modified = new DateTime(2001, 12, 31, 01, 00, 00, 00),
                                   Status = 200,
                                   Urn = "urn://example.com/abc",
                                   Value = 123
                               };

            var obj = new RecordFile(expected);

            var actual = obj.ToRecord<int>();

            Assert.Equal(expected, actual);
        }
Пример #48
0
                public void No_Pad_Csv()
                {
                    var reference = "abc";

                    var record = new Record(BankAccountTest.SampleOriginator(),
                            BankAccountTest.SampleDestination(), DirectDebitAlbany.TransCode.Payment,
                            null, reference);

                    var serialized = record.Serialize(SerializeMethod.CSV);

                    Assert.Equal("ABC", serialized.Reference);
                }
Пример #49
0
        public void op_Save_FileSystemInfo_whenNullUrn()
        {
            var record = new Record<int>
                             {
                                 Cacheability = "public",
                                 Created = new DateTime(1999, 12, 31, 01, 00, 00, 00),
                                 Etag = "\"xyz\"",
                                 Expiration = "P1D",
                                 Key = AlphaDecimal.Random(),
                                 Modified = new DateTime(2001, 12, 31, 01, 00, 00, 00),
                                 Status = 200,
                                 Urn = null,
                                 Value = 123
                             };

            var root = new DirectoryInfo(Path.GetTempPath());

            Assert.Throws<InvalidOperationException>(() => new RecordFile(record).Save(root));
        }
Пример #50
0
                public void CorrectCode(DirectDebitAlbany.TransCode tCode, string code)
                {
                    var record = new Record(BankAccountTest.SampleOriginator(),
                            BankAccountTest.SampleDestination(), tCode, 100.00m, "Ref");

                    var serialized = record.Serialize(SerializeMethod.FixedWidth);

                    Assert.Equal(code, serialized.TransCode);
                }
Пример #51
0
        public void op_Save_FileSystemInfoNull()
        {
            var record = new Record<int>
                             {
                                 Cacheability = "public",
                                 Created = new DateTime(1999, 12, 31, 01, 00, 00, 00),
                                 Etag = "\"xyz\"",
                                 Expiration = "P1D",
                                 Key = AlphaDecimal.Random(),
                                 Modified = new DateTime(2001, 12, 31, 01, 00, 00, 00),
                                 Status = 200,
                                 Urn = "urn://example.com/abc",
                                 Value = 123
                             };

            Assert.Throws<ArgumentNullException>(() => new RecordFile(record).Save(null));
        }
Пример #52
0
                public void Uppercase()
                {
                    var reference = "abcdefghijk mnopqr";

                    var record = new Record(BankAccountTest.SampleOriginator(),
                            BankAccountTest.SampleDestination(), DirectDebitAlbany.TransCode.Payment,
                            null, reference);

                    var serialized = record.Serialize(SerializeMethod.FixedWidth);

                    Assert.Equal("ABCDEFGHIJK MNOPQR", serialized.Reference);
                }
Пример #53
0
                public void In_Pence()
                {
                    var record = new Record(BankAccountTest.SampleOriginator(),
                            BankAccountTest.SampleDestination(), DirectDebitAlbany.TransCode.Payment,
                            1234m, "Ref");

                    var serialized = record.Serialize(SerializeMethod.FixedWidth);

                    Assert.Equal("00000123400", serialized.Amount);
                }
Пример #54
0
                public void Truncate()
                {
                    var reference = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

                    var record = new Record(BankAccountTest.SampleOriginator(),
                            BankAccountTest.SampleDestination(), DirectDebitAlbany.TransCode.Payment,
                            null, reference);

                    var serialized = record.Serialize(SerializeMethod.FixedWidth);

                    Assert.Equal("ABCDEFGHIJKLMNOPQR", serialized.Reference);
                }
        public async Task AddTransaction_MultipleTransactionsSuccess()
        {
            IList<Record> records1 = new Record[]
            {
                new Record(binaryData[0], binaryData[1], ByteString.Empty),
                new Record(binaryData[2], binaryData[3], ByteString.Empty),
            };

            ByteString mutation1 = new ByteString(MessageSerializer.SerializeMutation(new Mutation(ByteString.Empty, records1, ByteString.Empty)));
            ByteString mutationHash1 = new ByteString(MessageSerializer.ComputeHash(mutation1.ToByteArray()));

            IList<Record> records2 = new Record[]
            {
                new Record(binaryData[2], binaryData[5], mutationHash1),
                new Record(binaryData[6], binaryData[7], ByteString.Empty),
            };

            ByteString mutation2 = new ByteString(MessageSerializer.SerializeMutation(new Mutation(ByteString.Empty, records2, ByteString.Empty)));
            ByteString mutationHash2 = new ByteString(MessageSerializer.ComputeHash(mutation2.ToByteArray()));

            // Submit both transactions at once
            await this.Store.AddTransactions(new[]
            {
                new ByteString(MessageSerializer.SerializeTransaction(new Transaction(mutation1, new DateTime(), ByteString.Empty))),
                new ByteString(MessageSerializer.SerializeTransaction(new Transaction(mutation2, new DateTime(), ByteString.Empty)))
            });

            IReadOnlyList<Record> result1 = await this.Store.GetRecords(new[] { binaryData[0] });
            IReadOnlyList<Record> result2 = await this.Store.GetRecords(new[] { binaryData[2] });
            IReadOnlyList<Record> result3 = await this.Store.GetRecords(new[] { binaryData[6] });

            AssertRecord(result1[0], binaryData[0], binaryData[1], mutationHash1);
            AssertRecord(result2[0], binaryData[2], binaryData[5], mutationHash2);
            AssertRecord(result3[0], binaryData[6], binaryData[7], mutationHash2);
        }
Пример #56
0
        public void OrderByAndThenByOnSameField()
        {
            Record[] source = new Record[]
            {
                new Record{ Name = "Jim", City = "Minneapolis", Country = "USA" },
                new Record{ Name = "Prakash", City = "Chennai", Country = "India" },
                new Record{ Name = "Rob", City = "Kent", Country = "UK" }
            };
            Record[] expected = new Record[]
            {
                new Record{ Name = "Prakash", City = "Chennai", Country = "India" },
                new Record{ Name = "Rob", City = "Kent", Country = "UK" },
                new Record{ Name = "Jim", City = "Minneapolis", Country = "USA" }
            };

            Assert.Equal(expected, source.OrderBy((e) => e.Country).ThenBy((e) => e.Country, null));
        }
        public async Task AddTransaction_MultipleTransactionsError()
        {
            IList<Record> records1 = new Record[]
            {
                new Record(binaryData[0], binaryData[1], ByteString.Empty),
                new Record(binaryData[2], binaryData[3], ByteString.Empty),
            };

            ByteString mutation1 = new ByteString(MessageSerializer.SerializeMutation(new Mutation(ByteString.Empty, records1, ByteString.Empty)));

            IList<Record> records2 = new Record[]
            {
                new Record(binaryData[2], binaryData[5], ByteString.Empty),
                new Record(binaryData[6], binaryData[7], ByteString.Empty),
            };

            ByteString mutation2 = new ByteString(MessageSerializer.SerializeMutation(new Mutation(ByteString.Empty, records2, ByteString.Empty)));

            // Submit both transactions at once
            ConcurrentMutationException exception = await Assert.ThrowsAsync<ConcurrentMutationException>(() => this.Store.AddTransactions(new[]
            {
                new ByteString(MessageSerializer.SerializeTransaction(new Transaction(mutation1, new DateTime(), ByteString.Empty))),
                new ByteString(MessageSerializer.SerializeTransaction(new Transaction(mutation2, new DateTime(), ByteString.Empty)))
            }));

            IReadOnlyList<Record> result1 = await this.Store.GetRecords(new[] { binaryData[0] });
            IReadOnlyList<Record> result2 = await this.Store.GetRecords(new[] { binaryData[2] });
            IReadOnlyList<Record> result3 = await this.Store.GetRecords(new[] { binaryData[6] });

            AssertRecord(exception.FailedMutation, binaryData[2], binaryData[5], ByteString.Empty);
            AssertRecord(result1[0], binaryData[0], ByteString.Empty, ByteString.Empty);
            AssertRecord(result2[0], binaryData[2], ByteString.Empty, ByteString.Empty);
            AssertRecord(result3[0], binaryData[6], ByteString.Empty, ByteString.Empty);
        }
Пример #58
0
        public void SecondKeyRepeatAcrossDifferentPrimary()
        {
            Record[] source = new Record[]
            {
                new Record{ Name = "Jim", City = "Minneapolis", Country = "USA" },
                new Record{ Name = "Tim", City = "Seattle", Country = "USA" },
                new Record{ Name = "Philip", City = "Orlando", Country = "USA" },
                new Record{ Name = "Chris", City = "Minneapolis", Country = "USA" },
                new Record{ Name = "Rob", City = "Seattle", Country = "USA" }
            };
            Record[] expected = new Record[]
            {
                new Record{ Name = "Chris", City = "Minneapolis", Country = "USA" },
                new Record{ Name = "Jim", City = "Minneapolis", Country = "USA" },
                new Record{ Name = "Philip", City = "Orlando", Country = "USA" },
                new Record{ Name = "Rob", City = "Seattle", Country = "USA" },
                new Record{ Name = "Tim", City = "Seattle", Country = "USA" }
            };

            Assert.Equal(expected, source.OrderBy((e) => e.Name).ThenBy((e) => e.City, null));
        }
Пример #59
0
                public Record SampleRecord()
                {
                    var originator = new Mock<IBankAccount>();
                    var serializedOriginator = new Mock<ISerializedAccount>();

                    serializedOriginator.Setup(x => x.Line).Returns("ORIGINATOR");
                    originator.Setup(x => x.Serialize(It.IsAny<SerializeMethod>(),
                                It.IsAny<string[]>()))
                        .Returns(serializedOriginator.Object);

                    var destination = new Mock<IBankAccount>();
                    var serializedDestination = new Mock<ISerializedAccount>();

                    serializedDestination.Setup(x => x.Line).Returns("DESTINATION");
                    destination.Setup(x => x.Serialize(It.IsAny<SerializeMethod>(),
                                It.IsAny<string[]>()))
                        .Returns(serializedDestination.Object);

                    var record = new Record(originator.Object, destination.Object,
                            DirectDebitAlbany.TransCode.Payment, null, "abvc");

                    return record;
                }