Skip to content

Add example code for 1.5 driver documentation #248

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

Merged
merged 4 commits into from
Oct 5, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
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
64 changes: 64 additions & 0 deletions Neo4j.Driver/Neo4j.Driver.IntegrationTests/Examples.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,70 @@ public void TestBasicAuthExample()
}
}

public class ConfigConnectionPoolExample : BaseExample
{
public ConfigConnectionPoolExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture)
: base(output, fixture)
{
}

// tag::config-connection-pool[]
public IDriver CreateDriverWithCustomizedConnectionPool(string uri, string user, string password)
{
return GraphDatabase.Driver(uri, AuthTokens.Basic(user, password),
new Config
{
MaxConnectionLifetime = TimeSpan.FromMinutes(30),
MaxConnectionPoolSize = 50,
ConnectionAcquisitionTimeout = TimeSpan.FromMinutes(2)
});
}
// end::config-connection-pool[]

[RequireServerFact]
public void TestConfigConnectionPoolExample()
{
// Given
using (var driver = CreateDriverWithCustomizedConnectionPool(Uri, User, Password))
using (var session = driver.Session())
{
// When & Then
session.Run("RETURN 1").Single()[0].As<int>().Should().Be(1);
}
}
}

public class ConfigLoadBalancingStrategyExample : BaseExample
{
public ConfigLoadBalancingStrategyExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture)
: base(output, fixture)
{
}

// tag::config-load-balancing-strategy[]
public IDriver CreateDriverWithCustomizedLoadBalancingStrategy(string uri, string user, string password)
{
return GraphDatabase.Driver(uri, AuthTokens.Basic(user, password),
new Config
{
LoadBalancingStrategy = LoadBalancingStrategy.LeastConnected
});
}
// end::config-load-balancing-strategy[]

[RequireServerFact]
public void TestConfigLoadBalancingStrategyExample()
{
// Given
using (var driver = CreateDriverWithCustomizedLoadBalancingStrategy(Uri, User, Password))
using (var session = driver.Session())
{
// When & Then
session.Run("RETURN 1").Single()[0].As<int>().Should().Be(1);
}
}
}

public class ConfigConnectionTimeoutExample : BaseExample
{
public ConfigConnectionTimeoutExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture)
Expand Down
46 changes: 39 additions & 7 deletions Neo4j.Driver/Neo4j.Driver.Tests/ConfigTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,25 @@ public void DefaultConfigShouldGiveCorrectValueBack()
config.EncryptionLevel.Should().Be(EncryptionLevel.Encrypted);
config.TrustStrategy.Should().Be(TrustStrategy.TrustAllCertificates);
config.Logger.Should().BeOfType<DebugLogger>();
config.MaxIdleConnectionPoolSize.Should().Be(10);
config.MaxIdleConnectionPoolSize.Should().Be(500);
config.LoadBalancingStrategy.Should().Be(LoadBalancingStrategy.LeastConnected);
}

[Fact]
public void ShouldUseMaxConnectionValueIfMaxIdleValueIsNotSpecified()
{
var config = new Config {MaxConnectionPoolSize = 50};
config.MaxConnectionPoolSize.Should().Be(50);
config.MaxIdleConnectionPoolSize.Should().Be(50);
}

[Fact]
public void ShouldSetMaxIdleValueWhenSetSeperately()
{
var config = new Config {MaxIdleConnectionPoolSize = 20, MaxConnectionPoolSize = 50};
config.MaxConnectionPoolSize.Should().Be(50);
config.MaxIdleConnectionPoolSize.Should().Be(20);
}
}

public class ConfigBuilderTests
Expand All @@ -47,7 +63,23 @@ public void ShouldUseDefaultValueIfNotSpecified()
config.EncryptionLevel.Should().Be(EncryptionLevel.Encrypted);
config.TrustStrategy.Should().Be(TrustStrategy.TrustAllCertificates);
config.Logger.Should().BeOfType<DebugLogger>();
config.MaxIdleConnectionPoolSize.Should().Be(10);
config.MaxIdleConnectionPoolSize.Should().Be(500);
}

[Fact]
public void ShouldUseMaxConnectionValueIfMaxIdleValueIsNotSpecified()
{
var config = Config.Builder.WithMaxConnectionPoolSize(50).ToConfig();
config.MaxConnectionPoolSize.Should().Be(50);
config.MaxIdleConnectionPoolSize.Should().Be(50);
}

[Fact]
public void ShouldSetMaxIdleValueWhenSetSeperately()
{
var config = Config.Builder.WithMaxConnectionPoolSize(50).WithMaxIdleConnectionPoolSize(20).ToConfig();
config.MaxConnectionPoolSize.Should().Be(50);
config.MaxIdleConnectionPoolSize.Should().Be(20);
}

[Fact]
Expand All @@ -57,7 +89,7 @@ public void WithLoggingShouldModifyTheSingleValue()
config.EncryptionLevel.Should().Be(EncryptionLevel.Encrypted);
config.TrustStrategy.Should().Be(TrustStrategy.TrustAllCertificates);
config.Logger.Should().BeNull();
config.MaxIdleConnectionPoolSize.Should().Be(10);
config.MaxIdleConnectionPoolSize.Should().Be(500);
}

[Fact]
Expand All @@ -77,7 +109,7 @@ public void WithEncryptionLevelShouldModifyTheSingleValue()
config.EncryptionLevel.Should().Be(EncryptionLevel.None);
config.TrustStrategy.Should().Be(TrustStrategy.TrustAllCertificates);
config.Logger.Should().BeOfType<DebugLogger>();
config.MaxIdleConnectionPoolSize.Should().Be(10);
config.MaxIdleConnectionPoolSize.Should().Be(500);
}

[Fact]
Expand All @@ -87,7 +119,7 @@ public void WithTrustStrategyShouldModifyTheSingleValue()
config.EncryptionLevel.Should().Be(EncryptionLevel.Encrypted);
config.TrustStrategy.Should().Be(TrustStrategy.TrustSystemCaSignedCertificates);
config.Logger.Should().BeOfType<DebugLogger>();
config.MaxIdleConnectionPoolSize.Should().Be(10);
config.MaxIdleConnectionPoolSize.Should().Be(500);
}

[Fact]
Expand All @@ -99,15 +131,15 @@ public void ChangingNewConfigShouldNotAffectOtherConfig()


config2.Logger.Should().BeNull();
config2.MaxIdleConnectionPoolSize.Should().Be(10);
config2.MaxIdleConnectionPoolSize.Should().Be(500);

config1.MaxIdleConnectionPoolSize.Should().Be(3);
config1.Logger.Should().BeOfType<DebugLogger>();

config.EncryptionLevel.Should().Be(EncryptionLevel.Encrypted);
config.TrustStrategy.Should().Be(TrustStrategy.TrustAllCertificates);
config.Logger.Should().BeOfType<DebugLogger>();
config.MaxIdleConnectionPoolSize.Should().Be(10);
config.MaxIdleConnectionPoolSize.Should().Be(500);
}
}
}
Expand Down
60 changes: 47 additions & 13 deletions Neo4j.Driver/Neo4j.Driver.Tests/ConnectionPoolTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,19 @@ namespace Neo4j.Driver.Tests
{
public class ConnectionPoolTests
{
internal static ConnectionPool NewConnectionPoolWithNoConnectionTimeoutValidation(
IConnection connection,
BlockingCollection<IPooledConnection> availableConnections = null,
ConcurrentSet<IPooledConnection> inUseConnections = null)
{
var testConfigWithIdleTimeoutAndLifetimeCheckDisabled = new Config
{
MaxConnectionLifetime = Config.InfiniteInterval,
ConnectionIdleTimeout = Config.InfiniteInterval
};
return new ConnectionPool(connection, availableConnections, inUseConnections,
poolSettings: new ConnectionPoolSettings(testConfigWithIdleTimeoutAndLifetimeCheckDisabled));
}
public class AcquireMethod
{
private readonly ITestOutputHelper _output;
Expand All @@ -45,6 +58,17 @@ private IConnection MockedConnection
{
var mock = new Mock<IPooledConnection>();
mock.Setup(x => x.IsOpen).Returns(true);
mock.Setup(x => x.IdleTimer).Returns(MockedTimer);
mock.Setup(x => x.LifetimeTimer).Returns(MockedTimer);
return mock.Object;
}
}

private ITimer MockedTimer
{
get {
var mock = new Mock<ITimer>();
mock.Setup(t => t.ElapsedMilliseconds).Returns(0);
return mock.Object;
}
}
Expand Down Expand Up @@ -72,7 +96,7 @@ public void ShouldCallConnInit()
public void ShouldBlockWhenMaxPoolSizeReached()
{
var connectionPoolSettings = new ConnectionPoolSettings(new Config {MaxConnectionPoolSize = 2});
var pool = new ConnectionPool(MockedConnection, settings: connectionPoolSettings);
var pool = new ConnectionPool(MockedConnection, poolSettings: connectionPoolSettings);
var conn = pool.Acquire();
pool.Acquire();
pool.NumberOfAvailableConnections.Should().Be(0);
Expand Down Expand Up @@ -105,7 +129,7 @@ public void ShouldThrowClientExceptionWhenFailedToAcquireWithinTimeout()
MaxConnectionPoolSize = 2,
ConnectionAcquisitionTimeout = TimeSpan.FromMilliseconds(0)
});
var pool = new ConnectionPool(MockedConnection, settings: connectionPoolSettings);
var pool = new ConnectionPool(MockedConnection, poolSettings: connectionPoolSettings);
var conn = pool.Acquire();
pool.Acquire();
pool.NumberOfAvailableConnections.Should().Be(0);
Expand All @@ -120,7 +144,7 @@ public void ShouldThrowClientExceptionWhenFailedToAcquireWithinTimeout()
public void ShouldNotExceedIdleLimit()
{
var connectionPoolSettings = new ConnectionPoolSettings(new Config {MaxIdleConnectionPoolSize = 2});
var pool = new ConnectionPool(MockedConnection, settings: connectionPoolSettings);
var pool = new ConnectionPool(MockedConnection, poolSettings: connectionPoolSettings);

var conns = new List<IConnection>();
for (var i = 0; i < 4; i++)
Expand All @@ -142,7 +166,7 @@ public void ShouldNotExceedIdleLimit()
public void ShouldAcquireFromPoolIfAvailable()
{
var connectionPoolSettings = new ConnectionPoolSettings(new Config {MaxIdleConnectionPoolSize = 2});
var pool = new ConnectionPool(MockedConnection, settings: connectionPoolSettings);
var pool = new ConnectionPool(MockedConnection, poolSettings: connectionPoolSettings);

for (var i = 0; i < 4; i++)
{
Expand Down Expand Up @@ -211,6 +235,8 @@ public void ShouldReuseWhenOpenConnectionInQueue()
var conns = new BlockingCollection<IPooledConnection>();
var mock = new Mock<IPooledConnection>();
mock.Setup(x => x.IsOpen).Returns(true);
mock.Setup(x => x.IdleTimer).Returns(MockedTimer);
mock.Setup(x => x.LifetimeTimer).Returns(MockedTimer);

conns.Add(mock.Object);
var pool = new ConnectionPool(MockedConnection, conns);
Expand All @@ -237,7 +263,7 @@ public void ShouldReuseOpenConnectionWhenOpenAndClosedConnectionsInQueue()

conns.Add(unhealthyMock.Object);
conns.Add(healthyMock.Object);
var pool = new ConnectionPool(MockedConnection, conns);
var pool = NewConnectionPoolWithNoConnectionTimeoutValidation(MockedConnection, conns);

pool.NumberOfAvailableConnections.Should().Be(2);
pool.NumberOfInUseConnections.Should().Be(0);
Expand Down Expand Up @@ -268,7 +294,7 @@ public void ShouldCloseIdleTooLongConn()
var enableIdleTooLongTest = TimeSpan.FromMilliseconds(100);
var poolSettings = new ConnectionPoolSettings(
new Config {MaxIdleConnectionPoolSize = 2, ConnectionIdleTimeout = enableIdleTooLongTest});
var pool = new ConnectionPool(MockedConnection, conns, settings: poolSettings);
var pool = new ConnectionPool(MockedConnection, conns, poolSettings: poolSettings);

pool.NumberOfAvailableConnections.Should().Be(1);
pool.NumberOfInUseConnections.Should().Be(0);
Expand Down Expand Up @@ -301,8 +327,12 @@ public void ShouldReuseIdleNotTooLongConn()
conns.Add(mock.Object);
var enableIdleTooLongTest = TimeSpan.FromMilliseconds(100);
var poolSettings = new ConnectionPoolSettings(
new Config {MaxIdleConnectionPoolSize = 2, ConnectionIdleTimeout = enableIdleTooLongTest});
var pool = new ConnectionPool(MockedConnection, conns, settings: poolSettings);
new Config {
MaxIdleConnectionPoolSize = 2,
ConnectionIdleTimeout = enableIdleTooLongTest,
MaxConnectionLifetime = Config.InfiniteInterval, // disable life time check
});
var pool = new ConnectionPool(MockedConnection, conns, poolSettings: poolSettings);

pool.NumberOfAvailableConnections.Should().Be(1);
pool.NumberOfInUseConnections.Should().Be(0);
Expand Down Expand Up @@ -343,7 +373,7 @@ public void ShouldAcquireNewWhenBeingUsedConcurrentlyBy(int numberOfThreads)
mockConns.Enqueue(mock);
}

var pool = new ConnectionPool(MockedConnection, conns);
var pool = NewConnectionPoolWithNoConnectionTimeoutValidation(MockedConnection, conns);

pool.NumberOfAvailableConnections.Should().Be(numberOfThreads);
pool.NumberOfInUseConnections.Should().Be(0);
Expand Down Expand Up @@ -407,7 +437,7 @@ public void ShouldCloseAcquiredConnectionIfPoolDisposeStarted()
// Given
var conns = new BlockingCollection<IPooledConnection>();
var healthyMock = new Mock<IPooledConnection>();
var pool = new ConnectionPool(MockedConnection, conns);
var pool = NewConnectionPoolWithNoConnectionTimeoutValidation(MockedConnection, conns);

pool.NumberOfAvailableConnections.Should().Be(0);
pool.NumberOfInUseConnections.Should().Be(0);
Expand Down Expand Up @@ -453,6 +483,7 @@ public void ShouldTimeoutAfterAcquireTimeoutIfPoolIsFull()
public void ShouldTimeoutAfterAcquireTimeoutWhenConnectionIsNotValidated()
{
Config config = Config.Builder.WithConnectionAcquisitionTimeout(TimeSpan.FromSeconds(5))
.WithConnectionTimeout(Config.InfiniteInterval)
.ToConfig();

var notValidConnection = new Mock<IPooledConnection>();
Expand Down Expand Up @@ -577,12 +608,15 @@ public void ShouldCloseTheConnectionWhenConnectionIsReusableButThePoolIsFull()

var availableConns = new BlockingCollection<IPooledConnection>();
var pooledConnMock = new Mock<IPooledConnection>();
for (int i = 0; i < Config.DefaultConfig.MaxIdleConnectionPoolSize; i++)
var poolSettings = new ConnectionPoolSettings(
new Config {MaxConnectionPoolSize = 10});

for (int i = 0; i < poolSettings.MaxIdleConnectionPoolSize; i++)
{
availableConns.Add(pooledConnMock.Object);
}

var pool = new ConnectionPool(null, availableConns, inUseConns);
var pool = new ConnectionPool(null, availableConns, inUseConns, poolSettings: poolSettings);

pool.NumberOfAvailableConnections.Should().Be(10);
pool.NumberOfInUseConnections.Should().Be(1);
Expand All @@ -609,7 +643,7 @@ public void ShouldStartTimerBeforeReturnToPoolWhenIdleDetectionEnabled()
var poolSettings = new ConnectionPoolSettings(
new Config {MaxIdleConnectionPoolSize = 2, ConnectionIdleTimeout = enableIdleTooLongTest});
;
var pool = new ConnectionPool(null, null, inUseConns, settings: poolSettings);
var pool = new ConnectionPool(null, null, inUseConns, poolSettings: poolSettings);

pool.NumberOfAvailableConnections.Should().Be(0);
pool.NumberOfInUseConnections.Should().Be(1);
Expand Down
4 changes: 2 additions & 2 deletions Neo4j.Driver/Neo4j.Driver/Internal/ConnectionPool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,9 @@ internal ConnectionPool(
BlockingCollection<IPooledConnection> availableConnections = null,
ConcurrentSet<IPooledConnection> inUseConnections = null,
ILogger logger = null,
ConnectionPoolSettings settings = null,
ConnectionPoolSettings poolSettings = null,
BufferSettings bufferSettings = null)
: this(null, null, settings ?? new ConnectionPoolSettings(Config.DefaultConfig),
: this(null, null, poolSettings ?? new ConnectionPoolSettings(Config.DefaultConfig),
bufferSettings ?? new BufferSettings(Config.DefaultConfig), logger)
{
_fakeConnection = connection;
Expand Down
Loading