Skip to content

Commit

Permalink
Simplifies DatabaseRule settings
Browse files Browse the repository at this point in the history
Previously DatabaseRule had these ways of specifying settings:
- withSetting
- withConfiguration
- setConfig
- ensureStarted(String... additionalConfig)
- restartDatabase(String... additionalConfig)
- configure (override method)

each doing its own thing with settings and where they were applied
especially withSetting/withConfiguration/setConfig were sensitive
to where they were called. If a specific test would call withSetting
instead of setConfig it would have had no effect and vice versa.

This has been simplified to:
- withSetting/withSettings
- restartDatabase(String... additionalConfig)

withSetting/withSettings can now be called either at rule construction,
where those settings will be considered global to all tests in the class
or be called in test before db is started, where the setting(s) will
be considered local to the test.
restartDatabase is a convenience for shutdown,withSetting...,start so
it's still a nice way to add settings during a restart.
  • Loading branch information
tinwelint committed Aug 30, 2018
1 parent 05e491d commit ae42d85
Show file tree
Hide file tree
Showing 13 changed files with 85 additions and 95 deletions.
Expand Up @@ -30,8 +30,8 @@
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;


import org.neo4j.graphdb.factory.GraphDatabaseBuilder;
import org.neo4j.graphdb.factory.GraphDatabaseSettings; import org.neo4j.graphdb.factory.GraphDatabaseSettings;
import org.neo4j.test.rule.DatabaseRule;
import org.neo4j.test.rule.ImpermanentDatabaseRule; import org.neo4j.test.rule.ImpermanentDatabaseRule;


import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
Expand All @@ -42,14 +42,8 @@ public class CreateIndexStressIT
private final AtomicBoolean hasFailed = new AtomicBoolean( false ); private final AtomicBoolean hasFailed = new AtomicBoolean( false );


@Rule @Rule
public ImpermanentDatabaseRule db = new ImpermanentDatabaseRule() public DatabaseRule db = new ImpermanentDatabaseRule()
{ .withSetting( GraphDatabaseSettings.query_cache_size, "0" );
@Override
protected void configure( GraphDatabaseBuilder builder )
{
builder.setConfig( GraphDatabaseSettings.query_cache_size, "0" );
}
};


private final ExecutorService executorService = Executors.newFixedThreadPool( 10 ); private final ExecutorService executorService = Executors.newFixedThreadPool( 10 );


Expand Down
Expand Up @@ -83,7 +83,7 @@ public void shouldListAndReadExplicitIndexesForReadOnlyDb() throws Exception
public void shouldNotCreateIndexesForReadOnlyDb() public void shouldNotCreateIndexesForReadOnlyDb()
{ {
// given // given
db.ensureStarted( GraphDatabaseSettings.read_only.name(), TRUE.toString() ); db.withSetting( GraphDatabaseSettings.read_only, TRUE.toString() );


// when // when
try ( Transaction tx = db.beginTx() ) try ( Transaction tx = db.beginTx() )
Expand Down
Expand Up @@ -112,7 +112,7 @@ public void shouldNotBeAbleToViolateConstraintWhenBackingIndexFailsToOpen() thro
public void shouldArchiveFailedIndex() throws Exception public void shouldArchiveFailedIndex() throws Exception
{ {
// given // given
db.setConfig( GraphDatabaseSettings.archive_failed_index, "true" ); db.withSetting( GraphDatabaseSettings.archive_failed_index, "true" );
try ( Transaction tx = db.beginTx() ) try ( Transaction tx = db.beginTx() )
{ {
Node node = db.createNode( PERSON ); Node node = db.createNode( PERSON );
Expand Down
Expand Up @@ -70,12 +70,12 @@ public abstract class DatabaseRule extends ExternalResource implements GraphData
private DatabaseLayout databaseLayout; private DatabaseLayout databaseLayout;
private Supplier<Statement> statementSupplier; private Supplier<Statement> statementSupplier;
private boolean startEagerly = true; private boolean startEagerly = true;
private Map<Setting<?>, String> config; private final Map<Setting<?>, String> globalConfig = new HashMap<>();
private final Monitors monitors = new Monitors(); private final Monitors monitors = new Monitors();


/** /**
* Means the database will be started on first {@link #getGraphDatabaseAPI()}} * Means the database will be started on first {@link #getGraphDatabaseAPI()}}
* or {@link #ensureStarted(String...)} call. * or {@link #ensureStarted()} call.
*/ */
public DatabaseRule startLazily() public DatabaseRule startLazily()
{ {
Expand Down Expand Up @@ -274,7 +274,7 @@ private void create()
factory.setMonitors( monitors ); factory.setMonitors( monitors );
configure( factory ); configure( factory );
databaseBuilder = newBuilder( factory ); databaseBuilder = newBuilder( factory );
configure( databaseBuilder ); globalConfig.forEach( databaseBuilder::setConfig );
} }
catch ( RuntimeException e ) catch ( RuntimeException e )
{ {
Expand Down Expand Up @@ -308,57 +308,66 @@ protected void configure( GraphDatabaseFactory databaseFactory )
// Override to configure the database factory // Override to configure the database factory
} }


protected void configure( GraphDatabaseBuilder builder )
{
// Override to configure the database

// Adjusted defaults for testing
applyConfigChanges( builder );
}

public GraphDatabaseBuilder setConfig( Setting<?> setting, String value )
{
return databaseBuilder.setConfig( setting, value );
}

/** /**
* {@link DatabaseRule} now implements {@link GraphDatabaseAPI} directly, so no need. Also for ensuring * {@link DatabaseRule} now implements {@link GraphDatabaseAPI} directly, so no need. Also for ensuring
* a lazily started database is created, use {@link #ensureStarted( String... )} instead. * a lazily started database is created, use {@link #ensureStarted()} instead.
*/ */
public GraphDatabaseAPI getGraphDatabaseAPI() public GraphDatabaseAPI getGraphDatabaseAPI()
{ {
ensureStarted(); ensureStarted();
return database; return database;
} }


public synchronized void ensureStarted( String... additionalConfig ) public synchronized void ensureStarted()
{ {
if ( database == null ) if ( database == null )
{ {
applyConfigChanges( databaseBuilder, additionalConfig );
database = (GraphDatabaseAPI) databaseBuilder.newGraphDatabase(); database = (GraphDatabaseAPI) databaseBuilder.newGraphDatabase();
databaseLayout = database.databaseLayout(); databaseLayout = database.databaseLayout();
statementSupplier = resolveDependency( ThreadToStatementContextBridge.class ); statementSupplier = resolveDependency( ThreadToStatementContextBridge.class );
} }
} }


/**
* Adds or replaces a setting for the database managed by this database rule.
* <p>
* If this method is called when constructing the rule, the setting is considered a global setting applied to all tests.
* <p>
* If this method is called inside a specific test, i.e. after {@link #before()}, but before started (a call to {@link #startLazily()} have been made),
* then this setting will be considered a test-specific setting, adding to or overriding the global settings for this test only.
* Test-specific settings will be remembered throughout a test, even between restarts.
* <p>
* If this method is called when a database is already started an {@link IllegalStateException} will be thrown since the setting
* will have no effect, instead letting the developer notice that and change the test code.
*/
public DatabaseRule withSetting( Setting<?> key, String value ) public DatabaseRule withSetting( Setting<?> key, String value )
{ {
if ( this.config == null ) if ( database != null )
{ {
this.config = new HashMap<>(); // Database already started
throw new IllegalStateException( "Wanted to set " + key + "=" + value + ", but database has already been started" );
}
if ( databaseBuilder != null )
{
// Test already started, but db not yet started
databaseBuilder.setConfig( key, value );
}
else
{
// Test haven't started, we're still in phase of constructing this rule
globalConfig.put( key, value );
} }
this.config.put( key, value );
return this; return this;
} }


public DatabaseRule withConfiguration( Map<Setting<?>,String> configuration ) /**
* Applies all settings in the settings map.
*
* @see #withSetting(Setting, String)
*/
public DatabaseRule withSettings( Map<Setting<?>,String> configuration )
{ {
if ( this.config == null ) configuration.forEach( this::withSetting );
{
this.config = new HashMap<>();
}
this.config.putAll( configuration );
return this; return this;
} }


Expand All @@ -383,19 +392,12 @@ public GraphDatabaseAPI restartDatabase( RestartAction action, String... configC
database.shutdown(); database.shutdown();
action.run( fs, databaseLayout ); action.run( fs, databaseLayout );
database = null; database = null;
applyConfigChanges( databaseBuilder, configChanges ); // This DatabaseBuilder has already been configured with the global settings as well as any test-specific settings,
// so just apply these additional settings.
databaseBuilder.setConfig( stringMap( configChanges ) );
return getGraphDatabaseAPI(); return getGraphDatabaseAPI();
} }


private void applyConfigChanges( GraphDatabaseBuilder builder, String... configChanges )
{
if ( config != null )
{
config.forEach( builder::setConfig );
}
builder.setConfig( stringMap( configChanges ) );
}

@Override @Override
public void shutdown() public void shutdown()
{ {
Expand Down
Expand Up @@ -236,7 +236,7 @@ public void shouldPrintThatIncrementalBackupIsPerformedAndFallingBackToFull() th
{ {
defaultBackupPortHostParams(); defaultBackupPortHostParams();
Config defaultConfig = Config.defaults(); Config defaultConfig = Config.defaults();
dbRule.setConfig( GraphDatabaseSettings.keep_logical_logs, "false" ); dbRule.withSetting( GraphDatabaseSettings.keep_logical_logs, "false" );
// have logs rotated on every transaction // have logs rotated on every transaction
GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI(); GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI();
createSchemaIndex( db ); createSchemaIndex( db );
Expand Down Expand Up @@ -676,7 +676,7 @@ public void shouldGiveHelpfulErrorMessageIfLogsPrunedPastThePointOfNoReturn() th
// Given // Given
defaultBackupPortHostParams(); defaultBackupPortHostParams();
Config defaultConfig = Config.defaults(); Config defaultConfig = Config.defaults();
dbRule.setConfig( GraphDatabaseSettings.keep_logical_logs, "false" ); dbRule.withSetting( GraphDatabaseSettings.keep_logical_logs, "false" );
// have logs rotated on every transaction // have logs rotated on every transaction
GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI(); GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI();
createSchemaIndex( db ); createSchemaIndex( db );
Expand Down Expand Up @@ -719,7 +719,7 @@ public void shouldFallbackToFullBackupIfIncrementalFailsAndExplicitlyAskedToDoTh
// Given // Given
defaultBackupPortHostParams(); defaultBackupPortHostParams();
Config defaultConfig = Config.defaults(); Config defaultConfig = Config.defaults();
dbRule.setConfig( GraphDatabaseSettings.keep_logical_logs, "false" ); dbRule.withSetting( GraphDatabaseSettings.keep_logical_logs, "false" );
// have logs rotated on every transaction // have logs rotated on every transaction
GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI(); GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI();
createSchemaIndex( db ); createSchemaIndex( db );
Expand Down Expand Up @@ -763,7 +763,7 @@ public void shouldHandleBackupWhenLogFilesHaveBeenDeleted() throws Exception
// Given // Given
defaultBackupPortHostParams(); defaultBackupPortHostParams();
Config defaultConfig = Config.defaults(); Config defaultConfig = Config.defaults();
dbRule.setConfig( GraphDatabaseSettings.keep_logical_logs, "false" ); dbRule.withSetting( GraphDatabaseSettings.keep_logical_logs, "false" );
GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI(); GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI();
createSchemaIndex( db ); createSchemaIndex( db );
BackupProtocolService backupProtocolService = backupService(); BackupProtocolService backupProtocolService = backupService();
Expand Down Expand Up @@ -841,7 +841,7 @@ public void shouldDoFullBackupOnIncrementalFallbackToFullIfNoBackupFolderExists(
// Given // Given
defaultBackupPortHostParams(); defaultBackupPortHostParams();
Config defaultConfig = Config.defaults(); Config defaultConfig = Config.defaults();
dbRule.setConfig( GraphDatabaseSettings.keep_logical_logs, "false" ); dbRule.withSetting( GraphDatabaseSettings.keep_logical_logs, "false" );
GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI(); GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI();
createSchemaIndex( db ); createSchemaIndex( db );
BackupProtocolService backupProtocolService = backupService(); BackupProtocolService backupProtocolService = backupService();
Expand All @@ -865,7 +865,7 @@ public void shouldContainTransactionsThatHappenDuringBackupProcess() throws Thro
defaultBackupPortHostParams(); defaultBackupPortHostParams();
Config defaultConfig = Config.defaults(); Config defaultConfig = Config.defaults();
defaultConfig.augment( OnlineBackupSettings.online_backup_server, BACKUP_HOST + ":" + backupPort ); defaultConfig.augment( OnlineBackupSettings.online_backup_server, BACKUP_HOST + ":" + backupPort );
dbRule.setConfig( OnlineBackupSettings.online_backup_enabled, "false" ); dbRule.withSetting( OnlineBackupSettings.online_backup_enabled, "false" );
Config withOnlineBackupDisabled = Config.defaults(); Config withOnlineBackupDisabled = Config.defaults();


final Barrier.Control barrier = new Barrier.Control(); final Barrier.Control barrier = new Barrier.Control();
Expand Down Expand Up @@ -925,7 +925,7 @@ public void backupsShouldBeMentionedInServerConsoleLog() throws Throwable
defaultBackupPortHostParams(); defaultBackupPortHostParams();
Config config = Config.defaults(); Config config = Config.defaults();
config.augment( OnlineBackupSettings.online_backup_server, BACKUP_HOST + ":" + backupPort ); config.augment( OnlineBackupSettings.online_backup_server, BACKUP_HOST + ":" + backupPort );
dbRule.setConfig( OnlineBackupSettings.online_backup_enabled, "false" ); dbRule.withSetting( OnlineBackupSettings.online_backup_enabled, "false" );
Config withOnlineBackupDisabled = Config.defaults(); Config withOnlineBackupDisabled = Config.defaults();
createAndIndexNode( dbRule, 1 ); createAndIndexNode( dbRule, 1 );


Expand Down Expand Up @@ -1025,7 +1025,7 @@ public void incrementalBackupShouldFailWhenTargetDirContainsDifferentStore() thr


private void defaultBackupPortHostParams() private void defaultBackupPortHostParams()
{ {
dbRule.setConfig( OnlineBackupSettings.online_backup_server, BACKUP_HOST + ":" + backupPort ); dbRule.withSetting( OnlineBackupSettings.online_backup_server, BACKUP_HOST + ":" + backupPort );
} }


private static void createSchemaIndex( GraphDatabaseService db ) private static void createSchemaIndex( GraphDatabaseService db )
Expand Down
Expand Up @@ -452,9 +452,9 @@ private void startDb( Integer backupPort )


private void startDb( EmbeddedDatabaseRule db, Integer backupPort ) private void startDb( EmbeddedDatabaseRule db, Integer backupPort )
{ {
db.setConfig( GraphDatabaseSettings.record_format, recordFormat ); db.withSetting( GraphDatabaseSettings.record_format, recordFormat );
db.setConfig( OnlineBackupSettings.online_backup_enabled, Settings.TRUE ); db.withSetting( OnlineBackupSettings.online_backup_enabled, Settings.TRUE );
db.setConfig( OnlineBackupSettings.online_backup_server, "127.0.0.1" + ":" + backupPort ); db.withSetting( OnlineBackupSettings.online_backup_server, "127.0.0.1" + ":" + backupPort );
db.ensureStarted(); db.ensureStarted();
createSomeData( db ); createSomeData( db );
} }
Expand Down
Expand Up @@ -71,7 +71,7 @@ public class DeferringLocksIT
@Before @Before
public void initDb() public void initDb()
{ {
dbRule.setConfig( DeferringStatementLocksFactory.deferred_locks_enabled, Settings.TRUE ); dbRule.withSetting( DeferringStatementLocksFactory.deferred_locks_enabled, Settings.TRUE );
db = dbRule.getGraphDatabaseAPI(); db = dbRule.getGraphDatabaseAPI();
} }


Expand Down
Expand Up @@ -415,7 +415,7 @@ public void shouldDisableCpuTimeTracking() throws Exception
{ {
// given // given
String query = "MATCH (n) SET n.v = n.v + 1"; String query = "MATCH (n) SET n.v = n.v + 1";
db.setConfig( track_query_cpu_time, FALSE ); db.withSetting( track_query_cpu_time, FALSE );
Map<String,Object> data; Map<String,Object> data;


// when // when
Expand Down Expand Up @@ -467,7 +467,7 @@ public void shouldDisableHeapAllocationTracking() throws Exception
{ {
// given // given
String query = "MATCH (n) SET n.v = n.v + 1"; String query = "MATCH (n) SET n.v = n.v + 1";
db.setConfig( track_query_allocation, FALSE ); db.withSetting( track_query_allocation, FALSE );
Map<String,Object> data; Map<String,Object> data;


// when // when
Expand Down
Expand Up @@ -53,7 +53,7 @@ public void shouldUseForsetiAsDefaultLockManager()
public void shouldAllowUsingCommunityLockManager() public void shouldAllowUsingCommunityLockManager()
{ {
// When // When
dbRule.setConfig( GraphDatabaseSettings.lock_manager, "community" ); dbRule.withSetting( GraphDatabaseSettings.lock_manager, "community" );
GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI(); GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI();


// Then // Then
Expand Down
Expand Up @@ -67,7 +67,7 @@ public static Iterable<Object[]> configurations()


public MergeLockConcurrencyTest( ConfigBuilder config ) public MergeLockConcurrencyTest( ConfigBuilder config )
{ {
db.withConfiguration( config.configuration() ); db.withSettings( config.configuration() );
} }


@Test @Test
Expand Down
Expand Up @@ -77,7 +77,7 @@ public static List<String> recordFormats()
@Before @Before
public void configureRecordFormat() public void configureRecordFormat()
{ {
db.setConfig( GraphDatabaseSettings.record_format, recordFormat ); db.withSetting( GraphDatabaseSettings.record_format, recordFormat );
} }


@Test @Test
Expand Down
Expand Up @@ -38,7 +38,6 @@


import org.neo4j.graphdb.Result; import org.neo4j.graphdb.Result;
import org.neo4j.graphdb.Transaction; import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseBuilder;
import org.neo4j.graphdb.factory.GraphDatabaseFactory; import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.graphdb.factory.GraphDatabaseSettings; import org.neo4j.graphdb.factory.GraphDatabaseSettings;
import org.neo4j.kernel.configuration.Settings; import org.neo4j.kernel.configuration.Settings;
Expand Down Expand Up @@ -71,14 +70,8 @@ protected void configure( GraphDatabaseFactory factory )
{ {
((TestGraphDatabaseFactory) factory).setFileSystem( fs.get() ); ((TestGraphDatabaseFactory) factory).setFileSystem( fs.get() );
} }
}.withSetting( GraphDatabaseSettings.log_queries, Settings.TRUE ).startLazily();


@Override
protected void configure( GraphDatabaseBuilder builder )
{
builder.setConfig( GraphDatabaseSettings.log_queries, Settings.TRUE );
builder.setConfig( GraphDatabaseSettings.logs_directory, logsDirectory().getPath() );
}
};
@Rule @Rule
public final TestRule order = outerRule( dir ).around( fs ).around( db ) public final TestRule order = outerRule( dir ).around( fs ).around( db )
.around( ( base, description ) -> new Statement() .around( ( base, description ) -> new Statement()
Expand Down Expand Up @@ -106,6 +99,8 @@ public void evaluate() throws Throwable
@Before @Before
public void setup() throws Exception public void setup() throws Exception
{ {
// Set this config a bit later since it's dependent on directory of the dbRule, which is assigned in its creation phase.
db.withSetting( GraphDatabaseSettings.logs_directory, logsDirectory().getPath() );
server = new GraphDatabaseShellServer( db.getGraphDatabaseAPI() ); server = new GraphDatabaseShellServer( db.getGraphDatabaseAPI() );
SystemOutput output = new SystemOutput( new PrintWriter( out ) ); SystemOutput output = new SystemOutput( new PrintWriter( out ) );
client = ShellLobby.newClient( server, new HashMap<>(), output, action -> () -> client = ShellLobby.newClient( server, new HashMap<>(), output, action -> () ->
Expand Down

0 comments on commit ae42d85

Please sign in to comment.