Skip to content

Commit

Permalink
Merge pull request #181 from neo4j/1.4-byte-array-dot-net
Browse files Browse the repository at this point in the history
byte array support for .Net Driver
  • Loading branch information
zhenlineo authored Jun 5, 2017
2 parents 740c8a4 + 82722aa commit 47d05ce
Show file tree
Hide file tree
Showing 14 changed files with 304 additions and 73 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public BookmarkIT(ITestOutputHelper output, StandAloneIntegrationTestFixture fix
{
}

[Require31ServerFact]
[RequireServerVersionGreaterThanOrEqualToFact("3.1.0")]
public void ShouldContainLastBookmarkAfterTx()
{
using (var session = Driver.Session())
Expand All @@ -48,7 +48,7 @@ public void ShouldContainLastBookmarkAfterTx()
}
}

[Require31ServerFact]
[RequireServerVersionGreaterThanOrEqualToFact("3.1.0")]
public void BookmarkUnchangedAfterRolledBackTx()
{
using (var session = Driver.Session())
Expand All @@ -66,7 +66,7 @@ public void BookmarkUnchangedAfterRolledBackTx()
}
}

[Require31ServerFact]
[RequireServerVersionGreaterThanOrEqualToFact("3.1.0")]
public void BookmarkUnchangedAfterTxFailure()
{
using (var session = Driver.Session())
Expand All @@ -84,7 +84,7 @@ public void BookmarkUnchangedAfterTxFailure()
}
}

[Require31ServerFact]
[RequireServerVersionGreaterThanOrEqualToFact("3.1.0")]
public void ShouldThrowForInvalidBookmark()
{
var invalidBookmark = "invalid bookmark format";
Expand All @@ -96,7 +96,7 @@ public void ShouldThrowForInvalidBookmark()
}
}

[Require31ServerFact]
[RequireServerVersionGreaterThanOrEqualToFact("3.1.0")]
public void ShouldThrowForUnreachableBookmark()
{
using (var session = (Session)Driver.Session())
Expand All @@ -111,7 +111,7 @@ public void ShouldThrowForUnreachableBookmark()
}


[Require31ServerFact]
[RequireServerVersionGreaterThanOrEqualToFact("3.1.0")]
public void ShouldWaitOnBookmark()
{
using (var session = Driver.Session())
Expand Down
73 changes: 62 additions & 11 deletions Neo4j.Driver/Neo4j.Driver.IntegrationTests/DirectDriver/DriverIT.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,14 @@
// limitations under the License.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Neo4j.Driver.Internal;
using Neo4j.Driver.Internal.Packstream;
using Neo4j.Driver.V1;
using Xunit;
using Xunit.Abstractions;
Expand All @@ -34,7 +36,50 @@ public DriverIT(ITestOutputHelper output, StandAloneIntegrationTestFixture fixtu
{
}

[Require31ServerFact]
[RequireServerVersionGreaterThanOrEqualToFact("3.2.0")]
public void ShouldPackAndUnpackBytes()
{
// Given
var converter = new BigEndianTargetBitConverter();
byte[] byteArray = converter.GetBytes("hello, world");

// When
using (var driver = GraphDatabase.Driver("bolt://127.0.0.1:7687", AuthToken))
using (var session = driver.Session())
{
var result = session.Run(
"CREATE (a {value:{value}}) RETURN a.value", new Dictionary<string, object> {{"value", byteArray}});
// Then
foreach (var record in result)
{
var value = record["a.value"].ValueAs<byte[]>();
value.Should().BeEquivalentTo(byteArray);
}
}
}

[RequireServerVersionLessThanFact("3.2.0")]
public void ShouldNotPackBytes()
{
// Given
var converter = new BigEndianTargetBitConverter();
byte[] byteArray = converter.GetBytes("hello, world");

// When
using (var driver = GraphDatabase.Driver("bolt://127.0.0.1:7687", AuthToken))
using (var session = driver.Session())
{
var exception = Record.Exception(() =>
session.Run("CREATE (a {value:{value}})",
new Dictionary<string, object> {{"value", byteArray}}));

// Then
exception.Should().BeOfType<ProtocolException>();
exception.Message.Should().Be("Cannot understand value with type System.Byte[]");
}
}

[RequireServerVersionGreaterThanOrEqualToFact("3.1.0")]
public void ShouldConnectIPv6AddressIfEnabled()
{
using (var driver = GraphDatabase.Driver("bolt://[::1]:7687", AuthToken, new Config {Ipv6Enabled = true}))
Expand All @@ -45,13 +90,13 @@ public void ShouldConnectIPv6AddressIfEnabled()
}
}

[Require31ServerFact]
[RequireServerVersionGreaterThanOrEqualToFact("3.1.0")]
public void ShouldNotConnectIPv6AddressIfDisabled()
{
using (var driver = GraphDatabase.Driver("bolt://[::1]:7687", AuthToken))
using (var session = driver.Session())
{
var exception = Record.Exception(()=> session.Run("RETURN 1"));
var exception = Record.Exception(() => session.Run("RETURN 1"));
exception.GetBaseException().Should().BeOfType<NotSupportedException>();
exception.GetBaseException().Message.Should().Contain("This protocol version is not supported");
}
Expand All @@ -71,7 +116,8 @@ public void ShouldConnectIPv4AddressIfIpv6Disabled()
[RequireServerFact]
public void ShouldConnectIPv4AddressIfIpv6Enabled()
{
using (var driver = GraphDatabase.Driver("bolt://127.0.0.1:7687", AuthToken, new Config {Ipv6Enabled = true}))
using (
var driver = GraphDatabase.Driver("bolt://127.0.0.1:7687", AuthToken, new Config {Ipv6Enabled = true}))
using (var session = driver.Session())
{
var ret = session.Run("RETURN 1").Single();
Expand Down Expand Up @@ -119,11 +165,11 @@ public void SoakRun(int threadCount)
{
var statisticsCollector = new StatisticsCollector();
var driver = GraphDatabase.Driver(ServerEndPoint, AuthToken, new Config
{
DriverStatisticsCollector = statisticsCollector,
ConnectionTimeout = Config.Infinite,
EncryptionLevel = EncryptionLevel.Encrypted
});
{
DriverStatisticsCollector = statisticsCollector,
ConnectionTimeout = Config.Infinite,
EncryptionLevel = EncryptionLevel.Encrypted
});

Output.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss.ffffff")}] Started");

Expand All @@ -134,7 +180,11 @@ public void SoakRun(int threadCount)
Output.WriteLine(statisticsCollector.CollectStatistics().ToContentString());
}

string[] queries = { "RETURN 1295 + 42", "UNWIND range(1,10000) AS x CREATE (n {prop:x}) DELETE n RETURN sum(x)" };
string[] queries =
{
"RETURN 1295 + 42",
"UNWIND range(1,10000) AS x CREATE (n {prop:x}) DELETE n RETURN sum(x)"
};
try
{
using (var session = driver.Session())
Expand All @@ -144,7 +194,8 @@ public void SoakRun(int threadCount)
}
catch (Exception e)
{
Output.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss.ffffff")}] Thread {i} failed to run query {queries[i%2]} due to {e.Message}");
Output.WriteLine(
$"[{DateTime.Now.ToString("HH:mm:ss.ffffff")}] Thread {i} failed to run query {queries[i % 2]} due to {e.Message}");
}
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,19 +33,37 @@ public RequireBoltStubServerFactAttribute()
}

/// <summary>
/// Use `Require31ServerFact` tag for the tests that require a server with version equals to or greater than 3.1
/// Use `RequireServerVersionGreaterThanOrEqualToFact` tag for the tests that require a server with version equals to or greater than given version
/// </summary>
public class Require31ServerFactAttribute : FactAttribute
public class RequireServerVersionGreaterThanOrEqualToFact : FactAttribute
{
public Require31ServerFactAttribute()
public RequireServerVersionGreaterThanOrEqualToFact(string version)
{
if (!IsBoltkitAvailable())
{
Skip = TestRequireBoltkit;
}
if (!(Version(ServerVersion()) >= V3_1_0))
if (!(Version(ServerVersion()) >= Version(version)))
{
Skip = $"Require server version >= {version}, while current server version is {ServerVersion()}";
}
}
}

/// <summary>
/// Use `RequireServerVersionLessThanFact` tag for the tests that require a server with version less than the given version
/// </summary>
public class RequireServerVersionLessThanFact : FactAttribute
{
public RequireServerVersionLessThanFact(string version)
{
if (!IsBoltkitAvailable())
{
Skip = TestRequireBoltkit;
}
if (!(Version(version) >= Version(ServerVersion())))
{
Skip = $"Require server version >= 3.1, while current server version is {ServerVersion()}";
Skip = $"Require server version < {version}, while current server version is {ServerVersion()}";
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,27 @@ namespace Neo4j.Driver.Tests
{
public class PackStreamMessageFormatV1Tests
{
public class WriterV1
public class WriterV1Tests
{
public class PackValueMethod
{
[Fact]
public void ShouldPackBytes()
{
var outputStreamMock = new Mock<IChunkedOutputStream>();

var writer = new PackStreamMessageFormatV1.WriterV1(outputStreamMock.Object);
var converter = new BigEndianTargetBitConverter();
var value = new byte[0];

outputStreamMock.Setup(x => x.Write(It.IsAny<byte[]>())).Callback((byte[] data)=>value = data);

var byteArray = converter.GetBytes("hello, world");
writer.PackValue(byteArray);
converter.ToString(value).Should().Be("hello, world");
}
}

private class Mocks
{
public Mock<Stream> MockStream { get; }
Expand Down Expand Up @@ -278,10 +297,48 @@ public void PackRunMessageWithDictionaryMixedTypesParamCorrectly()
}
}

public class ReaderBytesIncompatibleV1Tests
{
public class UnpackValueMethod
{
[Fact]
public void ShouldThrowExceptionForUnpackingBytes()
{
var reader = new PackStreamMessageFormatV1.ReaderBytesIncompatibleV1(null);
var ex = Record.Exception(()=> reader.UnpackValue(PackStream.PackType.Bytes));
ex.Should().BeOfType<ProtocolException>();
}
}
}

public class WriterBytesIncompatibleV2Tests
{
public class PackValueMethod
{
[Fact]
public void ShouldThrowExceptionForPackingBytes()
{
var writer = new PackStreamMessageFormatV1.WriterBytesIncompatibleV1(null);
var ex = Record.Exception(() => writer.PackValue(new byte[] {0xCB}));
ex.Should().BeOfType<ProtocolException>();
}
}
}

public class ReaderV1Tests
{
public class UnpackValueMethod
{
public void ShouldPackBytes()
{
var inputStreamMock = new Mock<IChunkedInputStream>();
inputStreamMock.SetupSequence(x => x.ReadByte()).Returns(PackStream.BYTES_8).Returns((byte)0x00);
var reader = new PackStreamMessageFormatV1.ReaderV1(inputStreamMock.Object);

var unpackValue = reader.UnpackValue(PackStream.PackType.Bytes).ValueAs<byte[]>();
unpackValue.Length.Should().Be(0);
}

[Theory]
[InlineData(2147483648, new byte[] {0xCB, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00})]
[InlineData(9223372036854775807, new byte[] {0xCB, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF})]
Expand Down
14 changes: 0 additions & 14 deletions Neo4j.Driver/Neo4j.Driver.Tests/PackStream/PackerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,20 +85,6 @@ public void ShouldPackNullSuccessfully()

}

// public class PackRawMethod
// {
// [Fact]
// public void ShouldUnpacPawBytesSuccessfully()
// {
// var mocks = new Mocks();
// var u = new PackStream.Packer(mocks.OutputStream);
//
// var bytes = new byte[] { 1, 2, 3 };
// u.PackRaw(bytes);
// mocks.VerifyWrite(bytes);
// }
// }

public class PackLongMethod
{
[Theory]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

namespace Neo4j.Driver.Internal.Connector
{
internal class ChunkedInputStream : IInputStream
internal class ChunkedInputStream : IChunkedInputStream
{
private const int ChunkSize = 1024*8;
public static readonly byte[] Tail = {0x00, 0x00};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

namespace Neo4j.Driver.Internal.Connector
{
internal class ChunkedOutputStream : IOutputStream
internal class ChunkedOutputStream : IChunkedOutputStream
{
internal const int BufferSize = 1024*8;
private const int ChunkHeaderBufferSize = 2;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Copyright (c) 2002-2017 "Neo Technology,"
// Network Engine for Objects in Lund AB [http://neotechnology.com]
//
// This file is part of Neo4j.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Neo4j.Driver.Internal.Connector
{
internal interface IChunkedInputStream : IInputStream
{
void ReadMessageTail();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Copyright (c) 2002-2017 "Neo Technology,"
// Network Engine for Objects in Lund AB [http://neotechnology.com]
//
// This file is part of Neo4j.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Neo4j.Driver.Internal.Connector
{
internal interface IChunkedOutputStream : IOutputStream
{
IOutputStream WriteMessageTail();
}
}
Loading

0 comments on commit 47d05ce

Please sign in to comment.