Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

byte array support for .Net Driver #181

Merged
merged 3 commits into from
Jun 5, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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,6 +36,49 @@ public DriverIT(ITestOutputHelper output, StandAloneIntegrationTestFixture fixtu
{
}

[RequireServerVersionGreaterThanOrEqualToFact("3.2.0")]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can change all RequireXXServerFact to this format instead

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[]");
}
}

[Require31ServerFact]
public void ShouldConnectIPv6AddressIfEnabled()
{
Expand All @@ -51,7 +96,7 @@ 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 @@ -50,6 +50,60 @@ public Require31ServerFactAttribute()
}
}

/// <summary>
/// Use `Require32ServerFact` tag for the tests that require a server with version equals to or greater than 3.2
/// </summary>
public class Require32ServerFactAttribute : FactAttribute
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can be removed

{
public Require32ServerFactAttribute()
{
if (!IsBoltkitAvailable())
{
Skip = TestRequireBoltkit;
}
if (!(Version(ServerVersion()) >= V3_2_0))
{
Skip = $"Require server version >= 3.2, while current server version is {ServerVersion()}";
}
}
}

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

/// <summary>
/// Use `RequireServerVersionLessThanFactAttribute` tag for the tests that require a server with version less than the given version
/// </summary>
public class RequireServerVersionLessThanFactAttribute : FactAttribute
{
public RequireServerVersionLessThanFactAttribute(string version)
{
if (!IsBoltkitAvailable())
{
Skip = TestRequireBoltkit;
}
if (!(Version(version) >= Version(ServerVersion())))
{
Skip = $"Require server version < {version}, while current server version is {ServerVersion()}";
}
}
}

/// <summary>
/// Use `RequireServerFact` tag for the tests that require a single instance
/// </summary>
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();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,6 @@ internal interface ISocketClient : IDisposable
void Receive(IMessageResponseHandler responseHandler);
void ReceiveOne(IMessageResponseHandler responseHandler);
bool IsOpen { get; }
void UpdatePackStream(string serverVersion);
}
}
Loading