コード例 #1
0
        public void ShouldSerialize()
        {
            var writerMachine = CreateWriterMachine();
            var writer        = writerMachine.Writer();

            writer.Write(new BeginMessage(null, Bookmark.From(SessionTests.FakeABookmark(123)), TimeSpan.FromMinutes(1),
                                          new Dictionary <string, object>
            {
                { "username", "MollyMostlyWhite" }
            }, AccessMode.Write));

            var readerMachine = CreateReaderMachine(writerMachine.GetOutput());
            var reader        = readerMachine.Reader();

            reader.PeekNextType().Should().Be(PackStream.PackType.Struct);
            reader.ReadStructHeader().Should().Be(1);
            reader.ReadStructSignature().Should().Be(BoltProtocolV3MessageFormat.MsgBegin);

            var metadata = reader.ReadMap();

            metadata.Should().HaveCount(3).And.ContainKeys("bookmarks", "tx_timeout", "tx_metadata");

            metadata["bookmarks"].CastOrThrow <List <object> >().Should().HaveCount(1).And
            .Contain("bookmark-123");
            metadata["tx_timeout"].Should().Be(60000L);

            metadata["tx_metadata"].CastOrThrow <Dictionary <string, object> >().Should().HaveCount(1).And.Contain(
                new[]
            {
                new KeyValuePair <string, object>("username", "MollyMostlyWhite"),
            });
        }
コード例 #2
0
            public async Task ShouldPassBookmarkDownToDiscovery()
            {
                var bookmark = Bookmark.From("bookmark-1", "bookmark-2");
                var rt       = new RoutingTable("foo", new[] { server01 }, new[] { server02 }, new[] { server03 }, 10);

                var discovery = new Mock <IDiscovery>();

                discovery.Setup(x => x.DiscoverAsync(It.IsAny <IConnection>(), "foo", null, bookmark))
                .ReturnsAsync(rt);

                var poolManager = new Mock <IClusterConnectionPoolManager>();

                poolManager.Setup(x => x.CreateClusterConnectionAsync(It.IsAny <Uri>()))
                .ReturnsAsync(Mock.Of <IConnection>());

                var initialAddressProvider = new Mock <IInitialServerAddressProvider>();

                initialAddressProvider.Setup(x => x.Get()).Returns(new HashSet <Uri> {
                    server01
                });

                var manager = new RoutingTableManager(initialAddressProvider.Object, discovery.Object,
                                                      poolManager.Object, Mock.Of <ILogger>(), TimeSpan.MaxValue);

                var routingTable = await manager.EnsureRoutingTableForModeAsync(AccessMode.Write, "foo", null, bookmark);

                routingTable.Should().Be(rt);
                discovery.Verify(x => x.DiscoverAsync(It.IsAny <IConnection>(), "foo", null, bookmark), Times.Once);
            }
コード例 #3
0
            public async Task ShouldCarryOutRediscoveryWith43Server(int routerCount, int writerCount, int readerCount,
                                                                    string database, params string[] bookmarks)
            {
                // Given
                var routingContext = new Dictionary <string, string>
                {
                    { "address", "127.0.0.1:9001" },
                    { "region", "china" },
                    { "policy", "myp_policy" }
                };
                var recordFields = CreateGetServersDictionary(routerCount, writerCount, readerCount);
                var mockConn     = Setup43SocketConnection(routingContext, database, Bookmark.From(bookmarks), recordFields);

                mockConn.Setup(m => m.RoutingContext).Returns(routingContext);
                var manager = new ClusterDiscovery(routingContext, null);

                // When
                var table = await manager.DiscoverAsync(mockConn.Object, database, Bookmark.From(bookmarks));

                // Then
                table.Database.Should().Be(database ?? "");
                table.Readers.Count().Should().Be(readerCount);
                table.Writers.Count().Should().Be(writerCount);
                table.Routers.Count().Should().Be(routerCount);
                table.ExpireAfterSeconds.Should().Be(15000L);
                mockConn.Verify(x => x.CloseAsync(), Times.Once);
            }
コード例 #4
0
            public async Task ShouldCarryOutRediscoveryWith40Server(int routerCount, int writerCount, int readerCount,
                                                                    string database, params string[] bookmarks)
            {
                // Given
                var routingContext = new Dictionary <string, string>
                {
                    { "name", "molly" },
                    { "age", "1" },
                    { "color", "white" }
                };
                var recordFields = CreateGetServersResponseRecordFields(routerCount, writerCount, readerCount);
                var mockConn     =
                    Setup40SocketConnection(routingContext, database, Bookmark.From(bookmarks), recordFields);
                var manager = new ClusterDiscovery(routingContext, null);

                // When
                var table = await manager.DiscoverAsync(mockConn.Object, database, Bookmark.From(bookmarks));

                // Then
                table.Database.Should().Be(database ?? "");
                table.Readers.Count().Should().Be(readerCount);
                table.Writers.Count().Should().Be(writerCount);
                table.Routers.Count().Should().Be(routerCount);
                table.ExpireAfterSeconds.Should().Be(15000L);
                mockConn.Verify(x => x.CloseAsync(), Times.Once);
            }
コード例 #5
0
        public async Task ShouldDiscoverEndpointsForADatabaseWithBookmarks()
        {
            using (BoltStubServer.Start("V4/acquire_endpoints_aDatabase_with_bookmark", 9001))
            {
                using (BoltStubServer.Start("V4/read_from_aDatabase_with_bookmark", 9005))
                {
                    var bookmark1 = Bookmark.From("system:1111");
                    var bookmark2 = Bookmark.From("aDatabase:5555");

                    using (var driver =
                               GraphDatabase.Driver("neo4j://127.0.0.1:9001", AuthTokens.None, _setupConfig))
                    {
                        var session = driver.AsyncSession(o =>
                                                          o.WithDatabase("aDatabase").WithDefaultAccessMode(AccessMode.Read)
                                                          .WithBookmarks(bookmark1, bookmark2));
                        try
                        {
                            var cursor =
                                await session.RunAsync("MATCH (n) RETURN n.name");

                            var result = await cursor.ToListAsync(r => r[0].As <string>());

                            result.Should().BeEquivalentTo("Bob", "Alice", "Tina");
                        }
                        finally
                        {
                            await session.CloseAsync();
                        }
                    }
                }
            }
        }
コード例 #6
0
                public void ShouldBeEqual(string[] values1, string[] values2)
                {
                    var bookmark1 = Bookmark.From(values1);
                    var bookmark2 = Bookmark.From(values2);

                    bookmark1.Should().Be(bookmark2);
                }
コード例 #7
0
            public async Task ArgsContainBookmarkUsed()
            {
                // Arrange
                var bookmark  = Bookmark.From("Bookmark1");
                var bookmarks = new List <Bookmark> {
                    bookmark
                };

                const string queryText = "RETURN [] AS data";

                var queryParams = new Dictionary <string, object>();

                var cypherQuery = new CypherQuery(queryText, queryParams, CypherResultMode.Set, CypherResultFormat.Transactional, "neo4j")
                {
                    Bookmarks = bookmarks
                };

                using (var testHarness = new BoltTestHarness())
                {
                    var recordMock = new Mock <IRecord>();
                    recordMock.Setup(r => r["data"]).Returns(new List <INode>());
                    recordMock.Setup(r => r.Keys).Returns(new[] { "data" });

                    var testStatementResult = new TestStatementResult(new[] { "data" }, recordMock.Object);
                    testHarness.SetupCypherRequestResponse(cypherQuery.QueryText, cypherQuery.QueryParameters, testStatementResult);

                    var graphClient = await testHarness.CreateAndConnectBoltGraphClient();

                    graphClient.OperationCompleted += (s, e) => { e.BookmarksUsed.Should().Contain(bookmarks[0]); };

                    await graphClient.ExecuteGetCypherResultsAsync <IEnumerable <ObjectWithIds> >(cypherQuery);
                }
            }
コード例 #8
0
        public async Task ShouldThrowForUnreachableBookmark()
        {
            Bookmark bookmark;
            var      session = Driver.AsyncSession();

            try
            {
                await CreateNodeInTx(session, 1);

                bookmark = session.LastBookmark;
            }
            finally
            {
                await session.CloseAsync();
            }

            // Config the default server bookmark_ready_timeout to be something smaller than 30s to speed up this test
            session = Driver.AsyncSession(o => o.WithBookmarks(Bookmark.From(BookmarkValue(bookmark) + "0")));
            try
            {
                var exc = await Record.ExceptionAsync(() => session.BeginTransactionAsync());

                exc.Should().BeOfType <TransientException>().Which
                .Message.Should().Contain("not up to the requested version:");
            }
            finally
            {
                await session.CloseAsync();
            }
        }
コード例 #9
0
            public async Task SessionIsCalledWithBookmarks()
            {
                // Arrange
                var bookmarks = new List <Bookmark> {
                    Bookmark.From("Bookmark1"), Bookmark.From("Bookmark2")
                };

                var cypherQuery = new CypherQuery("RETURN 1", new Dictionary <string, object>(), CypherResultMode.Projection, CypherResultFormat.Transactional, "neo4j")
                {
                    Bookmarks = bookmarks
                };

                using (var testHarness = new BoltTestHarness())
                {
                    try
                    {
                        (await(await testHarness.CreateAndConnectBoltGraphClient()).ExecuteGetCypherResultsAsync <object>(cypherQuery)).ToArray();
                    }
                    catch
                    {
                        /*Not interested in actually getting results*/
                    }

                    //Assert
                    // testHarness.MockDriver.Verify(d => d.Session(It.IsAny<AccessMode>(), It.Is<IEnumerable<string>>(s => s.Contains(bookmarks[0]) && s.Contains(bookmarks[1]))), Times.Once);
                    testHarness.MockDriver.Verify(d => d.AsyncSession(It.IsAny <Action <SessionConfigBuilder> >()), Times.Once);

                    throw new NotImplementedException();
                }
            }
コード例 #10
0
        private static Bookmark BookmarkNumOverride(Bookmark bookmark, long newSeq)
        {
            var(value, seq) = LastBookmarkValue(bookmark);
            var prefix = value.Substring(0, value.Length - seq.ToString().Length);

            return(Bookmark.From(prefix + newSeq));
        }
コード例 #11
0
        public void ShouldSerialize()
        {
            var writerMachine = CreateWriterMachine();
            var writer        = writerMachine.Writer();

            var query = new Query("RETURN $x", new Dictionary <string, object>
            {
                { "x", 1L }
            });

            writer.Write(new RunWithMetadataMessage(query, "my-database",
                                                    Bookmark.From(SessionTests.FakeABookmark(123)), TimeSpan.FromMinutes(1),
                                                    new Dictionary <string, object>
            {
                { "username", "MollyMostlyWhite" }
            }, AccessMode.Write));

            var readerMachine = CreateReaderMachine(writerMachine.GetOutput());
            var reader        = readerMachine.Reader();

            reader.PeekNextType().Should().Be(PackStream.PackType.Struct);
            reader.ReadStructHeader().Should().Be(3);
            reader.ReadStructSignature().Should().Be(BoltProtocolV3MessageFormat.MsgRun);
            reader.ReadString().Should().Be("RETURN $x");
            reader.ReadMap().Should().HaveCount(1).And.Contain(new KeyValuePair <string, object>("x", 1L));

            var metadata = reader.ReadMap();

            metadata.Should().BeEquivalentTo(
                new Dictionary <string, object>
            {
                { "bookmarks", new[] { "bookmark-123" } },
コード例 #12
0
            public void ShouldSaveBookmark()
            {
                var mockConn = new Mock <IConnection>();
                var bookmark = Bookmark.From(FakeABookmark(123));
                var tx       = new Transaction(mockConn.Object, null, null, bookmark);

                tx.Bookmark.Should().Be(bookmark);
            }
コード例 #13
0
 public void ShouldThrowWhenADatabaseIsGiven(string database)
 {
     BoltV3.Awaiting(p => p.RunInAutoCommitTransactionAsync(Mock.Of <IConnection>(), new Query("text"),
                                                            false, Mock.Of <IBookmarkTracker>(), Mock.Of <IResultResourceHandler>(), database,
                                                            Bookmark.From("123"),
                                                            TransactionConfig.Default))
     .Should().Throw <ClientException>().WithMessage("*that does not support multiple databases*");
 }
コード例 #14
0
            public void ShouldNotKeepInitialBookmark()
            {
                var mockConn = new Mock <IConnection>();
                var bookmark = Bookmark.From(FakeABookmark(234));
                var tx       = new Transaction(mockConn.Object, null, null, bookmark);

                tx.Bookmark.Should().BeNull();
            }
コード例 #15
0
                public void ShouldUnionValues(string[] values1, string[] values2, string[] values3)
                {
                    var bookmark1 = Bookmark.From(values1);
                    var bookmark2 = Bookmark.From(values2);
                    var bookmark3 = Bookmark.From(values3);

                    Bookmark.From(new[] { bookmark1, bookmark2 }).Should().Be(bookmark3);
                }
コード例 #16
0
            public void ShouldRunWithoutBookmarkIfInvalidBookmarkGiven()
            {
                var mockConn = new Mock <IConnection>();
                var bookmark = Bookmark.From((string)null);
                var tx       = new Transaction(mockConn.Object, null, null, bookmark);

                mockConn.Verify(RunBegin(), Times.Once);
                mockConn.Verify(x => x.Sync(), Times.Never);
            }
コード例 #17
0
            public async Task ShouldSyncIfValidBookmarkGiven()
            {
                var mockConn = new Mock <IConnection>();
                var bookmark = Bookmark.From(FakeABookmark(234));
                await BoltV1.BeginTransactionAsync(mockConn.Object, bookmark);

                mockConn.Verify(x => x.Enqueue(It.IsAny <RunMessage>(), It.IsAny <IMessageResponseCollector>(), PullAll), Times.Once);
                mockConn.Verify(x => x.SyncAsync(), Times.Once);
            }
コード例 #18
0
            public void ShouldThrowWhenADatabaseIsGiven(string database)
            {
                var V3       = new BoltProtocolV3();
                var mockConn = NewConnectionWithMode(AccessMode.Read);

                V3.Awaiting(p => p.BeginTransactionAsync(mockConn.Object, database, Bookmark.From("123"),
                                                         TransactionConfig.Default, null))
                .Should().Throw <ClientException>().WithMessage("*that does not support multiple databases*");
            }
コード例 #19
0
            public async Task ShouldNotSyncIfInvalidBookmarkGiven()
            {
                var mockConn = new Mock <IConnection>();
                var bookmark = Bookmark.From((string)null);
                await BoltV3.BeginTransactionAsync(mockConn.Object, bookmark, null);

                mockConn.Verify(x => x.Enqueue(It.IsAny <BeginMessage>(), It.IsAny <IMessageResponseCollector>(), null), Times.Once);
                mockConn.Verify(x => x.SyncAsync(), Times.Never);
            }
コード例 #20
0
            public void ShouldSyncIfValidBookmarkGiven()
            {
                var mockConn = new Mock <IConnection>();
                var bookmark = Bookmark.From(FakeABookmark(234));

                BoltV3.BeginTransaction(mockConn.Object, bookmark, null);

                mockConn.Verify(x => x.Enqueue(It.IsAny <BeginMessage>(), It.IsAny <IMessageResponseCollector>(), null), Times.Once);
                mockConn.Verify(x => x.Sync(), Times.Once);
            }
コード例 #21
0
            public void ShouldNotSyncIfInvalidBookmarkGiven()
            {
                var mockConn = new Mock <IConnection>();
                var bookmark = Bookmark.From((string)null);

                BoltV1.BeginTransaction(mockConn.Object, bookmark);

                mockConn.Verify(x => x.Enqueue(It.IsAny <RunMessage>(), It.IsAny <IMessageResponseCollector>(), PullAll), Times.Once);
                mockConn.Verify(x => x.Sync(), Times.Never);
            }
コード例 #22
0
        /// <inheritdoc />
        public ICypherFluentQuery WithBookmark(string bookmark)
        {
            if (string.IsNullOrWhiteSpace(bookmark))
            {
                return(this);
            }

            QueryWriter.Bookmarks.Add(Bookmark.From(bookmark));
            return(this);
        }
コード例 #23
0
            public async Task TestMocking()
            {
                Mock <IAsyncSession> sessionMock = new Mock <IAsyncSession>();
                Mock <IDriver>       driverMock  = new Mock <IDriver>();

                driverMock.Setup(d => d.AsyncSession()).Returns(sessionMock.Object);
                driverMock.Setup(d => d.AsyncSession(It.IsAny <Action <SessionConfigBuilder> >())).Returns(sessionMock.Object);

                driverMock.Object.AsyncSession(x => x.WithBookmarks(Bookmark.From("x"))).Should().NotBeNull();
            }
コード例 #24
0
 public IAsyncSession Session(IEnumerable <string> bookmarks)
 {
     return(driver.AsyncSession(x =>
     {
         if (bookmarks != null)
         {
             x.WithBookmarks(Bookmark.From(bookmarks.ToArray()));
         }
     }));
 }
コード例 #25
0
 internal static AsyncSession NewSession(IBoltProtocol protocol, IDriverLogger logger = null,
     IAsyncRetryLogic retryLogic = null, AccessMode mode = AccessMode.Write, string bookmark = null,
     bool reactive = false)
 {
     var mockConn = new Mock<IConnection>();
     mockConn.Setup(x => x.IsOpen).Returns(true);
     mockConn.Setup(x => x.BoltProtocol).Returns(protocol);
     return new AsyncSession(new TestConnectionProvider(mockConn.Object), logger, retryLogic, mode,
         Bookmark.From(bookmark), reactive);
 }
コード例 #26
0
            public void ShouldRunWithBookmarkIfValidBookmarkGiven()
            {
                var mockConn = new Mock <IConnection>();
                var bookmark = Bookmark.From(FakeABookmark(234));
                var tx       = new Transaction(mockConn.Object, null, null, bookmark);

                IDictionary <string, object> paramters = bookmark.AsBeginTransactionParameters();

                mockConn.Verify(RunBegin(paramters), Times.Once);
                mockConn.Verify(x => x.Sync(), Times.Never);
            }
コード例 #27
0
 public IAsyncSession Session(AccessMode defaultMode, IEnumerable <string> bookmarks)
 {
     return(driver.AsyncSession(x =>
     {
         x.WithDefaultAccessMode(defaultMode);
         if (bookmarks != null)
         {
             x.WithBookmarks(Bookmark.From(bookmarks.ToArray()));
         }
     }));
 }
コード例 #28
0
 public void ShouldFailToBeginTxcWithInvalidBookmark()
 {
     Server.Driver
     .RxSession(
         o => o.WithDefaultAccessMode(AccessMode.Read).WithBookmarks(Bookmark.From("InvalidBookmark")))
     .BeginTransaction()
     .WaitForCompletion()
     .AssertEqual(
         OnError <IRxTransaction>(0,
                                  Matches <Exception>(exc => exc.Message.Should().Contain("InvalidBookmark"))));
 }
コード例 #29
0
        public static IAsyncSession AsyncSession(this IDriver driver, Version databaseVersion, string database, bool isWrite, IEnumerable <string> bookmarks)
        {
            IEnumerable <Bookmark> properBookmarks = null;

            if (bookmarks != null)
            {
                properBookmarks = bookmarks.Select(b => Bookmark.From(b));
            }

            return(driver.AsyncSession(databaseVersion, database, isWrite, properBookmarks));
        }
コード例 #30
0
            public void ShouldSyncIfBookmarkPresents()
            {
                var mockConn = new Mock <IConnection>();
                var bookmark = Bookmark.From(FakeABookmark(234));
                var tx       = new Transaction(mockConn.Object, null, null, bookmark);

                IDictionary <string, object> paramters = bookmark.AsBeginTransactionParameters();

                mockConn.Verify(x => x.Run("BEGIN", paramters, null, true), Times.Once);
                mockConn.Verify(x => x.Sync(), Times.Once);
            }