From daec76db2073ffc4459a4994fa69341322f486d9 Mon Sep 17 00:00:00 2001 From: MishaDemianenko Date: Wed, 18 Jul 2018 20:24:56 +0200 Subject: [PATCH] Migrate dbms module tests to junit 5. Tests cleanup. Put annoying import report into correct test directory. Allow junit extensions to instantiate and store a value in the context without test defined fields. For example, suppress output rule can be transparent and catch/print output without any field in a particular test. --- .../extension/StatefullFieldExtension.java | 7 +- .../neo4j/dbms/archive/IncorrectFormat.java | 2 +- .../commandline/dbms/CsvImporterTest.java | 21 ++- .../dbms/DiagnosticsReportCommandTest.java | 89 ++++----- .../commandline/dbms/DumpCommandTest.java | 175 ++++++------------ .../commandline/dbms/ImportCommandTest.java | 89 ++++----- .../commandline/dbms/LoadCommandTest.java | 156 ++++++---------- .../org/neo4j/commandline/dbms/UtilTest.java | 38 ++-- ...mporterConfigurationForNeo4jAdminTest.java | 27 ++- ...svInputConfigurationForNeo4jAdminTest.java | 22 +-- .../DatabaseManagementSystemSettingsTest.java | 8 +- .../org/neo4j/dbms/archive/ArchiveTest.java | 35 ++-- .../org/neo4j/dbms/archive/DumperTest.java | 91 ++++----- .../org/neo4j/dbms/archive/LoaderTest.java | 166 ++++++----------- 14 files changed, 361 insertions(+), 565 deletions(-) diff --git a/community/common/src/test/java/org/neo4j/test/extension/StatefullFieldExtension.java b/community/common/src/test/java/org/neo4j/test/extension/StatefullFieldExtension.java index 1edbf6235a09f..5cb61b573db72 100644 --- a/community/common/src/test/java/org/neo4j/test/extension/StatefullFieldExtension.java +++ b/community/common/src/test/java/org/neo4j/test/extension/StatefullFieldExtension.java @@ -52,6 +52,7 @@ public void afterAll( ExtensionContext context ) public void postProcessTestInstance( Object testInstance, ExtensionContext context ) throws Exception { Class clazz = testInstance.getClass(); + Object instance = createInstance( context ); List declaredFields = getAllFields( clazz ); for ( Field declaredField : declaredFields ) { @@ -59,7 +60,7 @@ public void postProcessTestInstance( Object testInstance, ExtensionContext conte getFieldType().equals( declaredField.getType() ) ) { declaredField.setAccessible( true ); - declaredField.set( testInstance, createFieldInstance( context ) ); + declaredField.set( testInstance, instance ); } } } @@ -74,7 +75,7 @@ void removeStoredValue( ExtensionContext context ) getLocalStore( context ).remove( getFieldKey(), getFieldType() ); } - Store getStore( ExtensionContext extensionContext, Namespace namespace ) + static Store getStore( ExtensionContext extensionContext, Namespace namespace ) { return extensionContext.getRoot().getStore( namespace ); } @@ -84,7 +85,7 @@ private Store getLocalStore( ExtensionContext extensionContext ) return getStore( extensionContext, getNameSpace() ); } - private Object createFieldInstance( ExtensionContext extensionContext ) + private Object createInstance( ExtensionContext extensionContext ) { Store store = getLocalStore( extensionContext ); return store.getOrComputeIfAbsent( getFieldKey(), (Function) s -> createField( extensionContext ) ); diff --git a/community/dbms/src/main/java/org/neo4j/dbms/archive/IncorrectFormat.java b/community/dbms/src/main/java/org/neo4j/dbms/archive/IncorrectFormat.java index 131cb237c89cf..c09abf67dbe46 100644 --- a/community/dbms/src/main/java/org/neo4j/dbms/archive/IncorrectFormat.java +++ b/community/dbms/src/main/java/org/neo4j/dbms/archive/IncorrectFormat.java @@ -24,7 +24,7 @@ public class IncorrectFormat extends Exception { - public IncorrectFormat( Path archive, IOException cause ) + IncorrectFormat( Path archive, IOException cause ) { super( archive.toString(), cause ); } diff --git a/community/dbms/src/test/java/org/neo4j/commandline/dbms/CsvImporterTest.java b/community/dbms/src/test/java/org/neo4j/commandline/dbms/CsvImporterTest.java index be6e1ea534236..a40d601189155 100644 --- a/community/dbms/src/test/java/org/neo4j/commandline/dbms/CsvImporterTest.java +++ b/community/dbms/src/test/java/org/neo4j/commandline/dbms/CsvImporterTest.java @@ -19,8 +19,8 @@ */ package org.neo4j.commandline.dbms; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import java.io.ByteArrayInputStream; import java.io.File; @@ -34,21 +34,22 @@ import org.neo4j.graphdb.factory.GraphDatabaseSettings; import org.neo4j.helpers.Args; import org.neo4j.kernel.configuration.Config; -import org.neo4j.test.rule.SuppressOutput; +import org.neo4j.test.extension.Inject; +import org.neo4j.test.extension.SuppressOutputExtension; +import org.neo4j.test.extension.TestDirectoryExtension; import org.neo4j.test.rule.TestDirectory; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.neo4j.helpers.collection.MapUtil.stringMap; -public class CsvImporterTest +@ExtendWith( {TestDirectoryExtension.class, SuppressOutputExtension.class} ) +class CsvImporterTest { - @Rule - public final TestDirectory testDir = TestDirectory.testDirectory(); - @Rule - public final SuppressOutput suppressOutput = SuppressOutput.suppressAll(); + @Inject + private TestDirectory testDir; @Test - public void writesReportToSpecifiedReportFile() throws Exception + void writesReportToSpecifiedReportFile() throws Exception { File dbDir = testDir.directory( "db" ); File logDir = testDir.directory( "logs" ); diff --git a/community/dbms/src/test/java/org/neo4j/commandline/dbms/DiagnosticsReportCommandTest.java b/community/dbms/src/test/java/org/neo4j/commandline/dbms/DiagnosticsReportCommandTest.java index 91e263b9ae635..46b2fbc052603 100644 --- a/community/dbms/src/test/java/org/neo4j/commandline/dbms/DiagnosticsReportCommandTest.java +++ b/community/dbms/src/test/java/org/neo4j/commandline/dbms/DiagnosticsReportCommandTest.java @@ -19,12 +19,11 @@ */ package org.neo4j.commandline.dbms; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.JRE; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.extension.ExtendWith; import java.io.ByteArrayOutputStream; import java.io.File; @@ -43,30 +42,32 @@ import org.neo4j.commandline.admin.RealOutsideWorld; import org.neo4j.diagnostics.DiagnosticsOfflineReportProvider; import org.neo4j.diagnostics.DiagnosticsReportSource; +import org.neo4j.io.fs.DefaultFileSystemAbstraction; import org.neo4j.io.fs.FileSystemAbstraction; import org.neo4j.kernel.configuration.Config; -import org.neo4j.test.rule.SuppressOutput; +import org.neo4j.test.extension.DefaultFileSystemExtension; +import org.neo4j.test.extension.Inject; +import org.neo4j.test.extension.SuppressOutputExtension; +import org.neo4j.test.extension.TestDirectoryExtension; import org.neo4j.test.rule.TestDirectory; -import org.neo4j.test.rule.fs.DefaultFileSystemRule; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.neo4j.commandline.dbms.DiagnosticsReportCommand.DEFAULT_CLASSIFIERS; import static org.neo4j.commandline.dbms.DiagnosticsReportCommand.describeClassifier; +@ExtendWith( {TestDirectoryExtension.class, DefaultFileSystemExtension.class, SuppressOutputExtension.class} ) public class DiagnosticsReportCommandTest { - @Rule - public SuppressOutput suppressOutput = SuppressOutput.suppressAll(); - @Rule - public TestDirectory testDirectory = TestDirectory.testDirectory(); - @Rule - public ExpectedException expected = ExpectedException.none(); - @Rule - public DefaultFileSystemRule fsRule = new DefaultFileSystemRule(); + @Inject + private TestDirectory testDirectory; + @Inject + private DefaultFileSystemAbstraction fs; private Path homeDir; private Path configDir; @@ -93,8 +94,8 @@ protected List provideSources( Set classifiers } } - @Before - public void setUp() throws Exception + @BeforeEach + void setUp() throws Exception { homeDir = testDirectory.directory( "home-dir" ).toPath(); configDir = testDirectory.directory( "config-dir" ).toPath(); @@ -107,47 +108,42 @@ public void setUp() throws Exception originalUserDir = System.setProperty( "user.dir", testDirectory.absolutePath().getAbsolutePath() ); } - @After - public void tearDown() + @AfterEach + void tearDown() { // Restore directory System.setProperty( "user.dir", originalUserDir ); } @Test - public void exitIfConfigFileIsMissing() throws IOException, CommandFailed, IncorrectUsage + void exitIfConfigFileIsMissing() throws IOException { Files.delete( configFile ); String[] args = {"--list"}; try ( RealOutsideWorld outsideWorld = new RealOutsideWorld() ) { - DiagnosticsReportCommand - diagnosticsReportCommand = new DiagnosticsReportCommand( homeDir, configDir, outsideWorld ); + DiagnosticsReportCommand diagnosticsReportCommand = new DiagnosticsReportCommand( homeDir, configDir, outsideWorld ); - expected.expect( CommandFailed.class ); - expected.expectMessage( containsString( "Unable to find config file, tried: " ) ); - diagnosticsReportCommand.execute( args ); + CommandFailed commandFailed = assertThrows( CommandFailed.class, () -> diagnosticsReportCommand.execute( args ) ); + assertThat( commandFailed.getMessage(), containsString( "Unable to find config file, tried: " ) ); } } @Test - public void allHasToBeOnlyClassifier() throws Exception + void allHasToBeOnlyClassifier() throws Exception { String[] args = {"all", "logs", "tx"}; try ( RealOutsideWorld outsideWorld = new RealOutsideWorld() ) { - DiagnosticsReportCommand - diagnosticsReportCommand = new DiagnosticsReportCommand( homeDir, configDir, outsideWorld ); + DiagnosticsReportCommand diagnosticsReportCommand = new DiagnosticsReportCommand( homeDir, configDir, outsideWorld ); - expected.expect( IncorrectUsage.class ); - expected.expectMessage( - "If you specify 'all' this has to be the only classifier. Found ['logs','tx'] as well." ); - diagnosticsReportCommand.execute( args ); + IncorrectUsage incorrectUsage = assertThrows( IncorrectUsage.class, () -> diagnosticsReportCommand.execute( args ) ); + assertEquals( "If you specify 'all' this has to be the only classifier. Found ['logs','tx'] as well.", incorrectUsage.getMessage() ); } } @Test - public void printUnrecognizedClassifiers() throws Exception + void printUnrecognizedClassifiers() throws Exception { String[] args = {"logs", "tx", "invalid"}; try ( RealOutsideWorld outsideWorld = new RealOutsideWorld() ) @@ -155,15 +151,14 @@ public void printUnrecognizedClassifiers() throws Exception DiagnosticsReportCommand diagnosticsReportCommand = new DiagnosticsReportCommand( homeDir, configDir, outsideWorld ); - expected.expect( IncorrectUsage.class ); - expected.expectMessage( "Unknown classifier: invalid" ); - diagnosticsReportCommand.execute( args ); + IncorrectUsage incorrectUsage = assertThrows( IncorrectUsage.class, () -> diagnosticsReportCommand.execute( args ) ); + assertEquals( "Unknown classifier: invalid", incorrectUsage.getMessage() ); } } @SuppressWarnings( "ResultOfMethodCallIgnored" ) @Test - public void defaultValuesShouldBeValidClassifiers() + void defaultValuesShouldBeValidClassifiers() { for ( String classifier : DEFAULT_CLASSIFIERS ) { @@ -171,20 +166,19 @@ public void defaultValuesShouldBeValidClassifiers() } // Make sure the above actually catches bad classifiers - expected.expect( IllegalArgumentException.class ); - expected.expectMessage( "Unknown classifier: invalid" ); - describeClassifier( "invalid" ); + IllegalArgumentException exception = assertThrows( IllegalArgumentException.class, () -> describeClassifier( "invalid" ) ); + assertEquals( "Unknown classifier: invalid", exception.getMessage() ); } @Test - public void listShouldDisplayAllClassifiers() throws Exception + void listShouldDisplayAllClassifiers() throws Exception { try ( ByteArrayOutputStream baos = new ByteArrayOutputStream() ) { PrintStream ps = new PrintStream( baos ); String[] args = {"--list"}; OutsideWorld outsideWorld = mock( OutsideWorld.class ); - when( outsideWorld.fileSystem() ).thenReturn( fsRule.get() ); + when( outsideWorld.fileSystem() ).thenReturn( fs ); when( outsideWorld.outStream() ).thenReturn( ps ); DiagnosticsReportCommand @@ -206,7 +200,7 @@ public void listShouldDisplayAllClassifiers() throws Exception } @Test - public void overrideDestination() throws Exception + void overrideDestination() throws Exception { // because of https://bugs.openjdk.java.net/browse/JDK-8202127 and current surefire behaviour we need to have custom value for JRE >= 11 String toArgument = JRE.JAVA_11.isCurrentVersion() ? "--to=" + System.getProperty( "user.dir" ) + "/other/" : "--to=other/"; @@ -229,16 +223,15 @@ public void overrideDestination() throws Exception } @Test - public void errorOnInvalidPid() throws Exception + void errorOnInvalidPid() throws Exception { - expected.expect( CommandFailed.class ); - expected.expectMessage( "Unable to parse --pid" ); String[] args = {"--pid=a", "all"}; try ( RealOutsideWorld outsideWorld = new RealOutsideWorld() ) { DiagnosticsReportCommand diagnosticsReportCommand = new DiagnosticsReportCommand( homeDir, configDir, outsideWorld ); - diagnosticsReportCommand.execute( args ); + CommandFailed commandFailed = assertThrows( CommandFailed.class, () -> diagnosticsReportCommand.execute( args ) ); + assertEquals( "Unable to parse --pid", commandFailed.getMessage() ); } } } diff --git a/community/dbms/src/test/java/org/neo4j/commandline/dbms/DumpCommandTest.java b/community/dbms/src/test/java/org/neo4j/commandline/dbms/DumpCommandTest.java index 428b785a1efca..ae95d1c9f2dac 100644 --- a/community/dbms/src/test/java/org/neo4j/commandline/dbms/DumpCommandTest.java +++ b/community/dbms/src/test/java/org/neo4j/commandline/dbms/DumpCommandTest.java @@ -19,18 +19,17 @@ */ package org.neo4j.commandline.dbms; -import org.apache.commons.lang3.SystemUtils; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnOs; +import org.junit.jupiter.api.condition.OS; +import org.junit.jupiter.api.extension.ExtendWith; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.PrintStream; -import java.nio.file.AccessDeniedException; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.NoSuchFileException; @@ -50,17 +49,19 @@ import org.neo4j.kernel.impl.store.MetaDataStore; import org.neo4j.kernel.impl.storemigration.StoreFileType; import org.neo4j.kernel.internal.locker.StoreLocker; +import org.neo4j.test.extension.Inject; +import org.neo4j.test.extension.TestDirectoryExtension; import org.neo4j.test.rule.TestDirectory; import static java.lang.String.format; import static java.util.Arrays.asList; import static java.util.Collections.emptySet; +import static java.util.Collections.singletonList; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; @@ -71,12 +72,11 @@ import static org.neo4j.graphdb.factory.GraphDatabaseSettings.data_directory; import static org.neo4j.graphdb.factory.GraphDatabaseSettings.logical_logs_location; -public class DumpCommandTest +@ExtendWith( TestDirectoryExtension.class ) +class DumpCommandTest { - @Rule - public TestDirectory testDirectory = TestDirectory.testDirectory(); - @Rule - public ExpectedException expected = ExpectedException.none(); + @Inject + private TestDirectory testDirectory; private Path homeDir; private Path configDir; @@ -84,8 +84,8 @@ public class DumpCommandTest private Dumper dumper; private Path databaseDirectory; - @Before - public void setUp() throws Exception + @BeforeEach + void setUp() throws Exception { homeDir = testDirectory.directory( "home-dir" ).toPath(); configDir = testDirectory.directory( "config-dir" ).toPath(); @@ -96,7 +96,7 @@ public void setUp() throws Exception } @Test - public void shouldDumpTheDatabaseToTheArchive() throws Exception + void shouldDumpTheDatabaseToTheArchive() throws Exception { execute( "foo.db" ); verify( dumper ).dump( eq( homeDir.resolve( "data/databases/foo.db" ) ), @@ -104,20 +104,19 @@ public void shouldDumpTheDatabaseToTheArchive() throws Exception } @Test - public void shouldCalculateTheDatabaseDirectoryFromConfig() throws Exception + void shouldCalculateTheDatabaseDirectoryFromConfig() throws Exception { Path dataDir = testDirectory.directory( "some-other-path" ).toPath(); Path databaseDir = dataDir.resolve( "databases/foo.db" ); putStoreInDirectory( databaseDir ); - Files.write( configDir.resolve( Config.DEFAULT_CONFIG_FILE_NAME ), - asList( formatProperty( data_directory, dataDir ) ) ); + Files.write( configDir.resolve( Config.DEFAULT_CONFIG_FILE_NAME ), singletonList( formatProperty( data_directory, dataDir ) ) ); execute( "foo.db" ); verify( dumper ).dump( eq( databaseDir ), eq( databaseDir ), any(), any() ); } @Test - public void shouldCalculateTheTxLogDirectoryFromConfig() throws Exception + void shouldCalculateTheTxLogDirectoryFromConfig() throws Exception { Path dataDir = testDirectory.directory( "some-other-path" ).toPath(); Path txLogsDir = testDirectory.directory( "txLogsPath" ).toPath(); @@ -132,10 +131,9 @@ public void shouldCalculateTheTxLogDirectoryFromConfig() throws Exception } @Test - public void shouldHandleDatabaseSymlink() throws Exception + @DisabledOnOs( OS.WINDOWS ) + void shouldHandleDatabaseSymlink() throws Exception { - assumeFalse( "Can't reliably create symlinks on windows", SystemUtils.IS_OS_WINDOWS ); - Path symDir = testDirectory.directory( "path-to-links" ).toPath(); Path realDatabaseDir = symDir.resolve( "foo.db" ); @@ -147,15 +145,14 @@ public void shouldHandleDatabaseSymlink() throws Exception Files.createSymbolicLink( databaseDir, realDatabaseDir ); Files.write( configDir.resolve( Config.DEFAULT_CONFIG_FILE_NAME ), - asList( format( "%s=%s", data_directory.name(), dataDir.toString().replace( '\\', '/' ) ) ) ); + singletonList( format( "%s=%s", data_directory.name(), dataDir.toString().replace( '\\', '/' ) ) ) ); execute( "foo.db" ); verify( dumper ).dump( eq( realDatabaseDir ), eq( realDatabaseDir ), any(), any() ); } @Test - public void shouldCalculateTheArchiveNameIfPassedAnExistingDirectory() - throws Exception + void shouldCalculateTheArchiveNameIfPassedAnExistingDirectory() throws Exception { File to = testDirectory.directory( "some-dir" ); new DumpCommand( homeDir, configDir, dumper ).execute( new String[]{"--database=" + "foo.db", "--to=" + to} ); @@ -163,7 +160,7 @@ public void shouldCalculateTheArchiveNameIfPassedAnExistingDirectory() } @Test - public void shouldConvertToCanonicalPath() throws Exception + void shouldConvertToCanonicalPath() throws Exception { new DumpCommand( homeDir, configDir, dumper ) .execute( new String[]{"--database=" + "foo.db", "--to=foo.dump"} ); @@ -172,7 +169,7 @@ public void shouldConvertToCanonicalPath() throws Exception } @Test - public void shouldNotCalculateTheArchiveNameIfPassedAnExistingFile() + void shouldNotCalculateTheArchiveNameIfPassedAnExistingFile() throws Exception { Files.createFile( archive ); @@ -181,7 +178,7 @@ public void shouldNotCalculateTheArchiveNameIfPassedAnExistingFile() } @Test - public void shouldRespectTheStoreLock() throws Exception + void shouldRespectTheStoreLock() throws Exception { Path databaseDirectory = homeDir.resolve( "data/databases/foo.db" ); @@ -190,40 +187,28 @@ public void shouldRespectTheStoreLock() throws Exception { storeLocker.checkLock(); - execute( "foo.db" ); - fail( "expected exception" ); - } - catch ( CommandFailed e ) - { - assertThat( e.getMessage(), equalTo( "the database is in use -- stop Neo4j and try again" ) ); + CommandFailed commandFailed = assertThrows( CommandFailed.class, () -> execute( "foo.db" ) ); + assertEquals( "the database is in use -- stop Neo4j and try again", commandFailed.getMessage() ); } } @Test - public void shouldReleaseTheStoreLockAfterDumping() throws Exception + void shouldReleaseTheStoreLockAfterDumping() throws Exception { execute( "foo.db" ); assertCanLockStore( databaseDirectory ); } @Test - public void shouldReleaseTheStoreLockEvenIfThereIsAnError() throws Exception + void shouldReleaseTheStoreLockEvenIfThereIsAnError() throws Exception { doThrow( IOException.class ).when( dumper ).dump( any(), any(), any(), any() ); - - try - { - execute( "foo.db" ); - } - catch ( CommandFailed ignored ) - { - } - + assertThrows( CommandFailed.class, () -> execute( "foo.db" ) ); assertCanLockStore( databaseDirectory ); } @Test - public void shouldNotAccidentallyCreateTheDatabaseDirectoryAsASideEffectOfStoreLocking() + void shouldNotAccidentallyCreateTheDatabaseDirectoryAsASideEffectOfStoreLocking() throws Exception { Path databaseDirectory = homeDir.resolve( "data/databases/accident.db" ); @@ -238,10 +223,9 @@ public void shouldNotAccidentallyCreateTheDatabaseDirectoryAsASideEffectOfStoreL } @Test - public void shouldReportAHelpfulErrorIfWeDontHaveWritePermissionsForLock() throws Exception + @DisabledOnOs( OS.WINDOWS ) + void shouldReportAHelpfulErrorIfWeDontHaveWritePermissionsForLock() throws Exception { - assumeFalse( "We haven't found a way to reliably tests permissions on Windows", SystemUtils.IS_OS_WINDOWS ); - try ( FileSystemAbstraction fileSystem = new DefaultFileSystemAbstraction(); StoreLocker storeLocker = new StoreLocker( fileSystem, databaseDirectory.toFile() ) ) { @@ -250,24 +234,18 @@ public void shouldReportAHelpfulErrorIfWeDontHaveWritePermissionsForLock() throw try ( Closeable ignored = withPermissions( databaseDirectory.resolve( StoreLocker.STORE_LOCK_FILENAME ), emptySet() ) ) { - execute( "foo.db" ); - fail( "expected exception" ); - } - catch ( CommandFailed e ) - { - assertThat( e.getMessage(), equalTo( "you do not have permission to dump the database -- is Neo4j " + - "running as a different user?" ) ); + CommandFailed commandFailed = assertThrows( CommandFailed.class, () -> execute( "foo.db" ) ); + assertEquals( commandFailed.getMessage(), "you do not have permission to dump the database -- is Neo4j running as a different user?" ); } } } @Test - public void shouldExcludeTheStoreLockFromTheArchiveToAvoidProblemsWithReadingLockedFilesOnWindows() + void shouldExcludeTheStoreLockFromTheArchiveToAvoidProblemsWithReadingLockedFilesOnWindows() throws Exception { doAnswer( invocation -> { - //noinspection unchecked Predicate exclude = invocation.getArgument( 3 ); assertThat( exclude.test( Paths.get( StoreLocker.STORE_LOCK_FILENAME ) ), is( true ) ); assertThat( exclude.test( Paths.get( "some-other-file" ) ), is( false ) ); @@ -278,95 +256,60 @@ public void shouldExcludeTheStoreLockFromTheArchiveToAvoidProblemsWithReadingLoc } @Test - public void shouldDefaultToGraphDB() throws Exception + void shouldDefaultToGraphDB() throws Exception { Path dataDir = testDirectory.directory( "some-other-path" ).toPath(); Path databaseDir = dataDir.resolve( "databases/graph.db" ); putStoreInDirectory( databaseDir ); - Files.write( configDir.resolve( Config.DEFAULT_CONFIG_FILE_NAME ), - asList( formatProperty( data_directory, dataDir ) ) ); + Files.write( configDir.resolve( Config.DEFAULT_CONFIG_FILE_NAME ), singletonList( formatProperty( data_directory, dataDir ) ) ); new DumpCommand( homeDir, configDir, dumper ).execute( new String[]{"--to=" + archive} ); verify( dumper ).dump( eq( databaseDir ), eq( databaseDir ), any(), any() ); } @Test - public void shouldObjectIfTheArchiveArgumentIsMissing() throws Exception + void shouldObjectIfTheArchiveArgumentIsMissing() { - try - { - new DumpCommand( homeDir, configDir, null ).execute( new String[]{"--database=something"} ); - fail( "expected exception" ); - } - catch ( IllegalArgumentException e ) - { - assertThat( e.getMessage(), equalTo( "Missing argument 'to'" ) ); - } + + IllegalArgumentException exception = assertThrows( IllegalArgumentException.class, + () -> new DumpCommand( homeDir, configDir, null ).execute( new String[]{"--database=something"} ) ); + assertEquals( "Missing argument 'to'", exception.getMessage() ); } @Test - public void shouldGiveAClearErrorIfTheArchiveAlreadyExists() throws Exception + void shouldGiveAClearErrorIfTheArchiveAlreadyExists() throws Exception { doThrow( new FileAlreadyExistsException( "the-archive-path" ) ).when( dumper ).dump( any(), any(), any(), any() ); - try - { - execute( "foo.db" ); - fail( "expected exception" ); - } - catch ( CommandFailed e ) - { - assertThat( e.getMessage(), equalTo( "archive already exists: the-archive-path" ) ); - } + CommandFailed commandFailed = assertThrows( CommandFailed.class, () -> execute( "foo.db" ) ); + assertEquals( "archive already exists: the-archive-path", commandFailed.getMessage() ); } @Test - public void shouldGiveAClearMessageIfTheDatabaseDoesntExist() throws Exception + void shouldGiveAClearMessageIfTheDatabaseDoesntExist() { - try - { - execute( "bobo.db" ); - fail( "expected exception" ); - } - catch ( CommandFailed e ) - { - assertThat( e.getMessage(), equalTo( "database does not exist: bobo.db" ) ); - } + CommandFailed commandFailed = assertThrows( CommandFailed.class, () -> execute( "bobo.db" ) ); + assertEquals( "database does not exist: bobo.db", commandFailed.getMessage() ); } @Test - public void shouldGiveAClearMessageIfTheArchivesParentDoesntExist() throws Exception + void shouldGiveAClearMessageIfTheArchivesParentDoesntExist() throws Exception { doThrow( new NoSuchFileException( archive.getParent().toString() ) ).when( dumper ).dump(any(), any(), any(), any() ); - try - { - execute( "foo.db" ); - fail( "expected exception" ); - } - catch ( CommandFailed e ) - { - assertThat( e.getMessage(), - equalTo( "unable to dump database: NoSuchFileException: " + archive.getParent() ) ); - } + CommandFailed commandFailed = assertThrows( CommandFailed.class, () -> execute( "foo.db" ) ); + assertEquals( "unable to dump database: NoSuchFileException: " + archive.getParent(), commandFailed.getMessage() ); } @Test - public void shouldWrapIOExceptionsCarefullyBecauseCriticalInformationIsOftenEncodedInTheirNameButMissingFromTheirMessage() + void shouldWrapIOExceptionsCarefullyBecauseCriticalInformationIsOftenEncodedInTheirNameButMissingFromTheirMessage() throws Exception { doThrow( new IOException( "the-message" ) ).when( dumper ).dump(any(), any(), any(), any() ); - try - { - execute( "foo.db" ); - fail( "expected exception" ); - } - catch ( CommandFailed e ) - { - assertThat( e.getMessage(), equalTo( "unable to dump database: IOException: the-message" ) ); - } + CommandFailed commandFailed = assertThrows( CommandFailed.class, () -> execute( "foo.db" ) ); + assertEquals( "unable to dump database: IOException: the-message", commandFailed.getMessage() ); } @Test - public void shouldPrintNiceHelp() throws Exception + void shouldPrintNiceHelp() throws Exception { try ( ByteArrayOutputStream baos = new ByteArrayOutputStream() ) { diff --git a/community/dbms/src/test/java/org/neo4j/commandline/dbms/ImportCommandTest.java b/community/dbms/src/test/java/org/neo4j/commandline/dbms/ImportCommandTest.java index 62e408ec3cdd2..e73c4f6515570 100644 --- a/community/dbms/src/test/java/org/neo4j/commandline/dbms/ImportCommandTest.java +++ b/community/dbms/src/test/java/org/neo4j/commandline/dbms/ImportCommandTest.java @@ -19,8 +19,8 @@ */ package org.neo4j.commandline.dbms; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -42,29 +42,33 @@ import org.neo4j.kernel.configuration.Config; import org.neo4j.kernel.impl.store.MetaDataStore; import org.neo4j.kernel.impl.storemigration.StoreFileType; +import org.neo4j.test.extension.Inject; +import org.neo4j.test.extension.SuppressOutputExtension; +import org.neo4j.test.extension.TestDirectoryExtension; import org.neo4j.test.rule.SuppressOutput; import org.neo4j.test.rule.TestDirectory; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class ImportCommandTest +@ExtendWith( {TestDirectoryExtension.class, SuppressOutputExtension.class} ) +class ImportCommandTest { - @Rule - public final TestDirectory testDir = TestDirectory.testDirectory(); - @Rule - public final SuppressOutput suppressOutput = SuppressOutput.suppressAll(); + @Inject + private TestDirectory testDir; + @Inject + private SuppressOutput suppressOutput; @Test - public void defaultsToCsvWhenModeNotSpecified() throws Exception + void defaultsToCsvWhenModeNotSpecified() throws Exception { File homeDir = testDir.directory( "home" ); ImporterFactory mockImporterFactory = mock( ImporterFactory.class ); @@ -89,7 +93,7 @@ public void defaultsToCsvWhenModeNotSpecified() throws Exception } @Test - public void acceptsNodeMetadata() throws Exception + void acceptsNodeMetadata() throws Exception { File homeDir = testDir.directory( "home" ); ImporterFactory mockImporterFactory = mock( ImporterFactory.class ); @@ -111,7 +115,7 @@ public void acceptsNodeMetadata() throws Exception } @Test - public void acceptsRelationshipsMetadata() throws Exception + void acceptsRelationshipsMetadata() throws Exception { File homeDir = testDir.directory( "home" ); ImporterFactory mockImporterFactory = mock( ImporterFactory.class ); @@ -133,7 +137,7 @@ public void acceptsRelationshipsMetadata() throws Exception } @Test - public void requiresDatabaseArgument() throws Exception + void requiresDatabaseArgument() { try ( NullOutsideWorld outsideWorld = new NullOutsideWorld() ) { @@ -142,20 +146,13 @@ public void requiresDatabaseArgument() throws Exception outsideWorld ); String[] arguments = {"--mode=database", "--from=bar"}; - try - { - importCommand.execute( arguments ); - fail( "Should have thrown an exception." ); - } - catch ( IncorrectUsage e ) - { - assertThat( e.getMessage(), containsString( "database" ) ); - } + IncorrectUsage incorrectUsage = assertThrows( IncorrectUsage.class, () -> importCommand.execute( arguments ) ); + assertThat( incorrectUsage.getMessage(), containsString( "database" ) ); } } @Test - public void failIfInvalidModeSpecified() throws Exception + void failIfInvalidModeSpecified() { try ( NullOutsideWorld outsideWorld = new NullOutsideWorld() ) { @@ -164,20 +161,13 @@ public void failIfInvalidModeSpecified() throws Exception outsideWorld ); String[] arguments = {"--mode=foo", "--database=bar", "--from=baz"}; - try - { - importCommand.execute( arguments ); - fail( "Should have thrown an exception." ); - } - catch ( IncorrectUsage e ) - { - assertThat( e.getMessage(), containsString( "foo" ) ); - } + IncorrectUsage incorrectUsage = assertThrows( IncorrectUsage.class, () -> importCommand.execute( arguments ) ); + assertThat( incorrectUsage.getMessage(), containsString( "foo" ) ); } } @Test - public void failIfDestinationDatabaseAlreadyExists() throws Exception + void failIfDestinationDatabaseAlreadyExists() throws Exception { try ( NullOutsideWorld outsideWorld = new NullOutsideWorld() ) { @@ -186,29 +176,23 @@ public void failIfDestinationDatabaseAlreadyExists() throws Exception putStoreInDirectory( homeDir.resolve( "data" ).resolve( "databases" ).resolve( "existing.db" ) ); String[] arguments = {"--mode=csv", "--database=existing.db"}; - try - { - importCommand.execute( arguments ); - fail( "Should have thrown an exception." ); - } - catch ( Exception e ) - { - assertThat( e.getMessage(), containsString( "already contains a database" ) ); - } + Exception exception = assertThrows( Exception.class, () -> importCommand.execute( arguments ) ); + assertThat( exception.getMessage(), containsString( "already contains a database" ) ); } } @Test - public void shouldUseArgumentsFoundInside_f_Argument() throws FileNotFoundException, CommandFailed, IncorrectUsage + void shouldUseArgumentsFoundInside_f_Argument() throws FileNotFoundException, CommandFailed, IncorrectUsage { // given + File report = testDir.file( "report" ); ImportCommand importCommand = new ImportCommand( testDir.directory( "home" ).toPath(), testDir.directory( "conf" ).toPath(), new RealOutsideWorld( System.out, System.err, new ByteArrayInputStream( new byte[0] ) ) ); File nodesFile = createTextFile( "nodes.csv", ":ID", "1", "2" ); - String pathForFile = nodesFile.getAbsolutePath(); - String pathWithEscapedSpaces = pathForFile.replaceAll( " ", "\\\\ " ); - File argFile = createTextFile( "args.txt", "--database=foo", "--nodes=" + pathWithEscapedSpaces ); + String pathWithEscapedSpaces = escapeSpaces( nodesFile.getAbsolutePath() ); + String reportEscapedPath = escapeSpaces( report.getAbsolutePath() ); + File argFile = createTextFile( "args.txt", "--database=foo", "--nodes=" + pathWithEscapedSpaces, "--report-file=" + reportEscapedPath ); String[] arguments = {"-f", argFile.getAbsolutePath()}; // when @@ -221,7 +205,7 @@ public void shouldUseArgumentsFoundInside_f_Argument() throws FileNotFoundExcept } @Test - public void shouldPrintNiceHelp() throws Throwable + void shouldPrintNiceHelp() throws Throwable { try ( ByteArrayOutputStream baos = new ByteArrayOutputStream() ) { @@ -334,7 +318,7 @@ public void shouldPrintNiceHelp() throws Throwable } } - private void putStoreInDirectory( Path storeDir ) throws IOException + private static void putStoreInDirectory( Path storeDir ) throws IOException { Files.createDirectories( storeDir ); Path storeFile = storeDir.resolve( StoreFileType.STORE.augment( MetaDataStore.DEFAULT_NAME ) ); @@ -353,4 +337,9 @@ private File createTextFile( String name, String... lines ) throws FileNotFoundE } return file; } + + private static String escapeSpaces( String pathForFile ) + { + return pathForFile.replaceAll( " ", "\\\\ " ); + } } diff --git a/community/dbms/src/test/java/org/neo4j/commandline/dbms/LoadCommandTest.java b/community/dbms/src/test/java/org/neo4j/commandline/dbms/LoadCommandTest.java index 33204c5ce0cff..80d97b2be8b83 100644 --- a/community/dbms/src/test/java/org/neo4j/commandline/dbms/LoadCommandTest.java +++ b/community/dbms/src/test/java/org/neo4j/commandline/dbms/LoadCommandTest.java @@ -19,10 +19,11 @@ */ package org.neo4j.commandline.dbms; -import org.apache.commons.lang3.SystemUtils; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnOs; +import org.junit.jupiter.api.condition.OS; +import org.junit.jupiter.api.extension.ExtendWith; import java.io.ByteArrayOutputStream; import java.io.File; @@ -48,16 +49,18 @@ import org.neo4j.io.fs.FileSystemAbstraction; import org.neo4j.kernel.configuration.Config; import org.neo4j.kernel.internal.locker.StoreLocker; +import org.neo4j.test.extension.Inject; +import org.neo4j.test.extension.TestDirectoryExtension; import org.neo4j.test.rule.TestDirectory; import static java.lang.String.format; import static java.util.Arrays.asList; +import static java.util.Collections.singletonList; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; @@ -67,17 +70,18 @@ import static org.neo4j.graphdb.factory.GraphDatabaseSettings.data_directory; import static org.neo4j.graphdb.factory.GraphDatabaseSettings.logical_logs_location; -public class LoadCommandTest +@ExtendWith( TestDirectoryExtension.class ) +class LoadCommandTest { - @Rule - public TestDirectory testDirectory = TestDirectory.testDirectory(); + @Inject + private TestDirectory testDirectory; private Path homeDir; private Path configDir; private Path archive; private Loader loader; - @Before - public void setUp() + @BeforeEach + void setUp() { homeDir = testDirectory.directory( "home-dir" ).toPath(); configDir = testDirectory.directory( "config-dir" ).toPath(); @@ -86,28 +90,27 @@ public void setUp() } @Test - public void shouldLoadTheDatabaseFromTheArchive() throws CommandFailed, IncorrectUsage, IOException, IncorrectFormat + void shouldLoadTheDatabaseFromTheArchive() throws CommandFailed, IncorrectUsage, IOException, IncorrectFormat { execute( "foo.db" ); verify( loader ).load( archive, homeDir.resolve( "data/databases/foo.db" ), homeDir.resolve( "data/databases/foo.db" ) ); } @Test - public void shouldCalculateTheDatabaseDirectoryFromConfig() + void shouldCalculateTheDatabaseDirectoryFromConfig() throws IOException, CommandFailed, IncorrectUsage, IncorrectFormat { Path dataDir = testDirectory.directory( "some-other-path" ).toPath(); Path databaseDir = dataDir.resolve( "databases/foo.db" ); Files.createDirectories( databaseDir ); - Files.write( configDir.resolve( Config.DEFAULT_CONFIG_FILE_NAME ), - asList( formatProperty( data_directory, dataDir ) ) ); + Files.write( configDir.resolve( Config.DEFAULT_CONFIG_FILE_NAME ), singletonList( formatProperty( data_directory, dataDir ) ) ); execute( "foo.db" ); verify( loader ).load( any(), eq( databaseDir ), eq( databaseDir ) ); } @Test - public void shouldCalculateTheTxLogDirectoryFromConfig() throws Exception + void shouldCalculateTheTxLogDirectoryFromConfig() throws Exception { Path dataDir = testDirectory.directory( "some-other-path" ).toPath(); Path txLogsDir = testDirectory.directory( "txLogsPath" ).toPath(); @@ -121,10 +124,9 @@ public void shouldCalculateTheTxLogDirectoryFromConfig() throws Exception } @Test - public void shouldHandleSymlinkToDatabaseDir() throws IOException, CommandFailed, IncorrectUsage, IncorrectFormat + @DisabledOnOs( OS.WINDOWS ) + void shouldHandleSymlinkToDatabaseDir() throws IOException, CommandFailed, IncorrectUsage, IncorrectFormat { - assumeFalse( "Can't reliably create symlinks on windows", SystemUtils.IS_OS_WINDOWS ); - Path symDir = testDirectory.directory( "path-to-links" ).toPath(); Path realDatabaseDir = symDir.resolve( "foo.db" ); @@ -136,21 +138,19 @@ public void shouldHandleSymlinkToDatabaseDir() throws IOException, CommandFailed Files.createSymbolicLink( databaseDir, realDatabaseDir ); - Files.write( configDir.resolve( Config.DEFAULT_CONFIG_FILE_NAME ), - asList( formatProperty( data_directory, dataDir ) ) ); + Files.write( configDir.resolve( Config.DEFAULT_CONFIG_FILE_NAME ), singletonList( formatProperty( data_directory, dataDir ) ) ); execute( "foo.db" ); verify( loader ).load( any(), eq( realDatabaseDir ), eq( realDatabaseDir ) ); } @Test - public void shouldMakeFromCanonical() throws IOException, CommandFailed, IncorrectUsage, IncorrectFormat + void shouldMakeFromCanonical() throws IOException, CommandFailed, IncorrectUsage, IncorrectFormat { Path dataDir = testDirectory.directory( "some-other-path" ).toPath(); Path databaseDir = dataDir.resolve( "databases/foo.db" ); Files.createDirectories( databaseDir ); - Files.write( configDir.resolve( Config.DEFAULT_CONFIG_FILE_NAME ), - asList( formatProperty( data_directory, dataDir ) ) ); + Files.write( configDir.resolve( Config.DEFAULT_CONFIG_FILE_NAME ), singletonList( formatProperty( data_directory, dataDir ) ) ); new LoadCommand( homeDir, configDir, loader ) .execute( ArrayUtil.concat( new String[]{"--database=foo.db", "--from=foo.dump"} ) ); @@ -159,7 +159,7 @@ public void shouldMakeFromCanonical() throws IOException, CommandFailed, Incorre } @Test - public void shouldDeleteTheOldDatabaseIfForceArgumentIsProvided() + void shouldDeleteTheOldDatabaseIfForceArgumentIsProvided() throws CommandFailed, IncorrectUsage, IOException, IncorrectFormat { Path databaseDirectory = homeDir.resolve( "data/databases/foo.db" ); @@ -175,7 +175,7 @@ public void shouldDeleteTheOldDatabaseIfForceArgumentIsProvided() } @Test - public void shouldNotDeleteTheOldDatabaseIfForceArgumentIsNotProvided() + void shouldNotDeleteTheOldDatabaseIfForceArgumentIsNotProvided() throws CommandFailed, IncorrectUsage, IOException, IncorrectFormat { Path databaseDirectory = homeDir.resolve( "data/databases/foo.db" ); @@ -191,7 +191,7 @@ public void shouldNotDeleteTheOldDatabaseIfForceArgumentIsNotProvided() } @Test - public void shouldRespectTheStoreLock() throws IOException, IncorrectUsage + void shouldRespectTheStoreLock() throws IOException { Path databaseDirectory = homeDir.resolve( "data/databases/foo.db" ); Files.createDirectories( databaseDirectory ); @@ -200,17 +200,13 @@ public void shouldRespectTheStoreLock() throws IOException, IncorrectUsage StoreLocker locker = new StoreLocker( fileSystem, databaseDirectory.toFile() ) ) { locker.checkLock(); - execute( "foo.db", "--force" ); - fail( "expected exception" ); - } - catch ( CommandFailed e ) - { - assertThat( e.getMessage(), equalTo( "the database is in use -- stop Neo4j and try again" ) ); + CommandFailed commandFailed = assertThrows( CommandFailed.class, () -> execute( "foo.db", "--force" ) ); + assertEquals( "the database is in use -- stop Neo4j and try again", commandFailed.getMessage() ); } } @Test - public void shouldDefaultToGraphDb() throws Exception + void shouldDefaultToGraphDb() throws Exception { Path databaseDir = homeDir.resolve( "data/databases/graph.db" ); Files.createDirectories( databaseDir ); @@ -220,100 +216,58 @@ public void shouldDefaultToGraphDb() throws Exception } @Test - public void shouldObjectIfTheArchiveArgumentIsMissing() throws Exception + void shouldObjectIfTheArchiveArgumentIsMissing() { - try - { - new LoadCommand( homeDir, configDir, loader ).execute( new String[]{"--database=something"} ); - fail( "expected exception" ); - } - catch ( IllegalArgumentException e ) - { - assertThat( e.getMessage(), equalTo( "Missing argument 'from'" ) ); - } + IllegalArgumentException exception = assertThrows( IllegalArgumentException.class, + () -> new LoadCommand( homeDir, configDir, loader ).execute( new String[]{"--database=something"} ) ); + assertEquals( "Missing argument 'from'", exception.getMessage() ); } @Test - public void shouldGiveAClearMessageIfTheArchiveDoesntExist() throws IOException, IncorrectFormat, IncorrectUsage + void shouldGiveAClearMessageIfTheArchiveDoesntExist() throws IOException, IncorrectFormat { doThrow( new NoSuchFileException( archive.toString() ) ).when( loader ).load( any(), any(), any() ); - try - { - execute( null ); - fail( "expected exception" ); - } - catch ( CommandFailed e ) - { - assertThat( e.getMessage(), equalTo( "archive does not exist: " + archive ) ); - } + CommandFailed commandFailed = assertThrows( CommandFailed.class, () -> execute( null ) ); + assertEquals( "archive does not exist: " + archive, commandFailed.getMessage() ); } @Test - public void shouldGiveAClearMessageIfTheDatabaseAlreadyExists() throws IOException, IncorrectFormat, IncorrectUsage + void shouldGiveAClearMessageIfTheDatabaseAlreadyExists() throws IOException, IncorrectFormat, IncorrectUsage { doThrow( FileAlreadyExistsException.class ).when( loader ).load( any(), any(), any() ); - try - { - execute( "foo.db" ); - fail( "expected exception" ); - } - catch ( CommandFailed e ) - { - assertThat( e.getMessage(), equalTo( "database already exists: foo.db" ) ); - } + CommandFailed commandFailed = assertThrows( CommandFailed.class, () -> execute( "foo.db" ) ); + assertEquals( "database already exists: foo.db", commandFailed.getMessage() ); } @Test - public void shouldGiveAClearMessageIfTheDatabasesDirectoryIsNotWritable() - throws IOException, IncorrectFormat, IncorrectUsage + void shouldGiveAClearMessageIfTheDatabasesDirectoryIsNotWritable() + throws IOException, IncorrectFormat { doThrow( AccessDeniedException.class ).when( loader ).load( any(), any(), any() ); - try - { - execute( null ); - fail( "expected exception" ); - } - catch ( CommandFailed e ) - { - assertThat( e.getMessage(), equalTo( - "you do not have permission to load a database -- is Neo4j running " + "as a different user?" ) ); - } + CommandFailed commandFailed = assertThrows( CommandFailed.class, () -> execute( null ) ); + assertEquals( "you do not have permission to load a database -- is Neo4j running as a different user?", commandFailed.getMessage() ); } @Test - public void shouldWrapIOExceptionsCarefullyBecauseCriticalInformationIsOftenEncodedInTheirNameButMissingFromTheirMessage() - throws IOException, IncorrectUsage, IncorrectFormat + void shouldWrapIOExceptionsCarefullyBecauseCriticalInformationIsOftenEncodedInTheirNameButMissingFromTheirMessage() + throws IOException, IncorrectFormat { doThrow( new FileSystemException( "the-message" ) ).when( loader ).load( any(), any(), any() ); - try - { - execute( null ); - fail( "expected exception" ); - } - catch ( CommandFailed e ) - { - assertThat( e.getMessage(), equalTo( "unable to load database: FileSystemException: the-message" ) ); - } + CommandFailed commandFailed = assertThrows( CommandFailed.class, () -> execute( null ) ); + assertEquals( "unable to load database: FileSystemException: the-message", commandFailed.getMessage() ); } @Test - public void shouldThrowIfTheArchiveFormatIsInvalid() throws IOException, IncorrectUsage, IncorrectFormat + void shouldThrowIfTheArchiveFormatIsInvalid() throws IOException, IncorrectFormat { doThrow( IncorrectFormat.class ).when( loader ).load( any(), any(), any() ); - try - { - execute( null ); - fail( "expected exception" ); - } - catch ( CommandFailed e ) - { - assertThat( e.getMessage(), containsString( archive.toString() ) ); - assertThat( e.getMessage(), containsString( "valid Neo4j archive" ) ); - } + CommandFailed commandFailed = assertThrows( CommandFailed.class, () -> execute( null ) ); + assertThat( commandFailed.getMessage(), containsString( archive.toString() ) ); + assertThat( commandFailed.getMessage(), containsString( "valid Neo4j archive" ) ); } @Test - public void shouldPrintNiceHelp() throws Throwable + void shouldPrintNiceHelp() throws Throwable { try ( ByteArrayOutputStream baos = new ByteArrayOutputStream() ) { diff --git a/community/dbms/src/test/java/org/neo4j/commandline/dbms/UtilTest.java b/community/dbms/src/test/java/org/neo4j/commandline/dbms/UtilTest.java index a1e7f0c552253..fd0d115288ce7 100644 --- a/community/dbms/src/test/java/org/neo4j/commandline/dbms/UtilTest.java +++ b/community/dbms/src/test/java/org/neo4j/commandline/dbms/UtilTest.java @@ -19,38 +19,41 @@ */ package org.neo4j.commandline.dbms; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.neo4j.commandline.Util; +import org.neo4j.test.extension.Inject; +import org.neo4j.test.extension.TestDirectoryExtension; import org.neo4j.test.rule.TestDirectory; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.neo4j.commandline.Util.isSameOrChildFile; import static org.neo4j.commandline.Util.isSameOrChildPath; import static org.neo4j.commandline.Util.neo4jVersion; -public class UtilTest +@ExtendWith( TestDirectoryExtension.class ) +class UtilTest { - @Rule - public final TestDirectory directory = TestDirectory.testDirectory(); + @Inject + private TestDirectory directory; @Test - public void canonicalPath() + void canonicalPath() { assertNotNull( Util.canonicalPath( "foo" ).getParent() ); } @Test - public void returnsAVersion() + void returnsAVersion() { - assertNotNull( "A version should be returned", neo4jVersion() ); + assertNotNull( neo4jVersion(), "A version should be returned" ); } @Test - public void correctlyIdentifySameOrChildFile() + void correctlyIdentifySameOrChildFile() { assertTrue( isSameOrChildFile( directory.directory(), directory.directory( "a" ) ) ); assertTrue( isSameOrChildFile( directory.directory(), directory.directory() ) ); @@ -61,16 +64,13 @@ public void correctlyIdentifySameOrChildFile() } @Test - public void correctlyIdentifySameOrChildPath() + void correctlyIdentifySameOrChildPath() { assertTrue( isSameOrChildPath( directory.directory().toPath(), directory.directory( "a" ).toPath() ) ); assertTrue( isSameOrChildPath( directory.directory().toPath(), directory.directory().toPath() ) ); - assertTrue( isSameOrChildPath( directory.directory( "/a/./b" ).toPath(), - directory.directory( "a/b" ).toPath() ) ); - assertTrue( isSameOrChildPath( directory.directory( "a/b" ).toPath(), - directory.directory( "/a/./b" ).toPath() ) ); + assertTrue( isSameOrChildPath( directory.directory( "/a/./b" ).toPath(), directory.directory( "a/b" ).toPath() ) ); + assertTrue( isSameOrChildPath( directory.directory( "a/b" ).toPath(), directory.directory( "/a/./b" ).toPath() ) ); - assertFalse( isSameOrChildPath( directory.directory( "a" ).toPath(), - directory.directory( "b" ).toPath() ) ); + assertFalse( isSameOrChildPath( directory.directory( "a" ).toPath(), directory.directory( "b" ).toPath() ) ); } } diff --git a/community/dbms/src/test/java/org/neo4j/commandline/dbms/config/WrappedBatchImporterConfigurationForNeo4jAdminTest.java b/community/dbms/src/test/java/org/neo4j/commandline/dbms/config/WrappedBatchImporterConfigurationForNeo4jAdminTest.java index 22cae3e376eb1..ca2ffbbdcc88f 100644 --- a/community/dbms/src/test/java/org/neo4j/commandline/dbms/config/WrappedBatchImporterConfigurationForNeo4jAdminTest.java +++ b/community/dbms/src/test/java/org/neo4j/commandline/dbms/config/WrappedBatchImporterConfigurationForNeo4jAdminTest.java @@ -19,21 +19,20 @@ */ package org.neo4j.commandline.dbms.config; -import org.junit.Test; -import org.omg.CORBA.COMM_FAILURE; +import org.junit.jupiter.api.Test; import java.util.function.Function; import org.neo4j.unsafe.impl.batchimport.Configuration; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.neo4j.io.ByteUnit.kibiBytes; import static org.neo4j.unsafe.impl.batchimport.Configuration.DEFAULT; -public class WrappedBatchImporterConfigurationForNeo4jAdminTest +class WrappedBatchImporterConfigurationForNeo4jAdminTest { @Test - public void shouldDelegateDenseNodeThreshold() + void shouldDelegateDenseNodeThreshold() { shouldDelegate( expected -> new Configuration() { @@ -46,7 +45,7 @@ public int denseNodeThreshold() } @Test - public void shouldDelegateMovingAverageSize() + void shouldDelegateMovingAverageSize() { shouldDelegate( expected -> new Configuration() { @@ -59,7 +58,7 @@ public int movingAverageSize() } @Test - public void shouldDelegateSequentialBackgroundFlushing() + void shouldDelegateSequentialBackgroundFlushing() { shouldDelegate( expected -> new Configuration() { @@ -72,7 +71,7 @@ public boolean sequentialBackgroundFlushing() } @Test - public void shouldDelegateBatchSize() + void shouldDelegateBatchSize() { shouldDelegate( expected -> new Configuration() { @@ -85,7 +84,7 @@ public int batchSize() } @Test - public void shouldOverrideMaxNumberOfProcessors() + void shouldOverrideMaxNumberOfProcessors() { shouldOverride( expected -> new Configuration() { @@ -98,7 +97,7 @@ public int batchSize() } @Test - public void shouldDelegateParallelRecordWrites() + void shouldDelegateParallelRecordWrites() { shouldDelegate( expected -> new Configuration() { @@ -111,7 +110,7 @@ public boolean parallelRecordWrites() } @Test - public void shouldDelegateParallelRecordReads() + void shouldDelegateParallelRecordReads() { shouldDelegate( expected -> new Configuration() { @@ -124,7 +123,7 @@ public boolean parallelRecordReads() } @Test - public void shouldDelegateHighIO() + void shouldDelegateHighIO() { shouldDelegate( expected -> new Configuration() { @@ -137,7 +136,7 @@ public boolean highIO() } @Test - public void shouldDelegateMaxMemoryUsage() + void shouldDelegateMaxMemoryUsage() { shouldDelegate( expected -> new Configuration() { @@ -150,7 +149,7 @@ public long maxMemoryUsage() } @Test - public void shouldDelegateAllowCacheAllocationOnHeap() + void shouldDelegateAllowCacheAllocationOnHeap() { shouldDelegate( expected -> new Configuration() { diff --git a/community/dbms/src/test/java/org/neo4j/commandline/dbms/config/WrappedCsvInputConfigurationForNeo4jAdminTest.java b/community/dbms/src/test/java/org/neo4j/commandline/dbms/config/WrappedCsvInputConfigurationForNeo4jAdminTest.java index c5e5b3e1908af..2d0f289b5290a 100644 --- a/community/dbms/src/test/java/org/neo4j/commandline/dbms/config/WrappedCsvInputConfigurationForNeo4jAdminTest.java +++ b/community/dbms/src/test/java/org/neo4j/commandline/dbms/config/WrappedCsvInputConfigurationForNeo4jAdminTest.java @@ -19,19 +19,19 @@ */ package org.neo4j.commandline.dbms.config; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.function.Function; import org.neo4j.unsafe.impl.batchimport.input.csv.Configuration; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.neo4j.unsafe.impl.batchimport.input.csv.Configuration.COMMAS; -public class WrappedCsvInputConfigurationForNeo4jAdminTest +class WrappedCsvInputConfigurationForNeo4jAdminTest { @Test - public void shouldDelegateArrayDelimiter() + void shouldDelegateArrayDelimiter() { shouldDelegate( expected -> new Configuration.Overridden( COMMAS ) { @@ -44,7 +44,7 @@ public char arrayDelimiter() } @Test - public void shouldDelegateDelimiter() + void shouldDelegateDelimiter() { shouldDelegate( expected -> new Configuration.Overridden( COMMAS ) { @@ -57,7 +57,7 @@ public char delimiter() } @Test - public void shouldDelegateQuoteCharacter() + void shouldDelegateQuoteCharacter() { shouldDelegate( expected -> new Configuration.Overridden( COMMAS ) { @@ -70,7 +70,7 @@ public char quotationCharacter() } @Test - public void shouldOverrideTrimStrings() + void shouldOverrideTrimStrings() { shouldOverride( expected -> new Configuration.Overridden( COMMAS ) { @@ -83,7 +83,7 @@ public boolean trimStrings() } @Test - public void shouldOverrideBufferSize() + void shouldOverrideBufferSize() { shouldOverride( expected -> new Configuration.Overridden( COMMAS ) { @@ -96,7 +96,7 @@ public int bufferSize() } @Test - public void shouldDelegateMultiLineFields() + void shouldDelegateMultiLineFields() { shouldDelegate( expected -> new Configuration.Overridden( COMMAS ) { @@ -109,7 +109,7 @@ public boolean multilineFields() } @Test - public void shouldOverrideEmptyQuotedStringsAsNull() + void shouldOverrideEmptyQuotedStringsAsNull() { shouldOverride( expected -> new Configuration.Overridden( COMMAS ) { @@ -122,7 +122,7 @@ public boolean emptyQuotedStringsAsNull() } @Test - public void shouldOverrideLegacyStyleQuoting() + void shouldOverrideLegacyStyleQuoting() { shouldOverride( expected -> new Configuration.Overridden( COMMAS ) { diff --git a/community/dbms/src/test/java/org/neo4j/dbms/DatabaseManagementSystemSettingsTest.java b/community/dbms/src/test/java/org/neo4j/dbms/DatabaseManagementSystemSettingsTest.java index 66c7afed3fb69..6157b214b4b8f 100644 --- a/community/dbms/src/test/java/org/neo4j/dbms/DatabaseManagementSystemSettingsTest.java +++ b/community/dbms/src/test/java/org/neo4j/dbms/DatabaseManagementSystemSettingsTest.java @@ -19,20 +19,20 @@ */ package org.neo4j.dbms; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import org.neo4j.graphdb.factory.GraphDatabaseSettings; import org.neo4j.kernel.configuration.Config; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.Assert.assertThat; -public class DatabaseManagementSystemSettingsTest +class DatabaseManagementSystemSettingsTest { @Test - public void shouldPutDatabaseDirectoriesIntoDataDatabases() + void shouldPutDatabaseDirectoriesIntoDataDatabases() { Config config = Config.defaults( GraphDatabaseSettings.data_directory, "the-data-directory" ); assertThat( config.get( GraphDatabaseSettings.database_path ), diff --git a/community/dbms/src/test/java/org/neo4j/dbms/archive/ArchiveTest.java b/community/dbms/src/test/java/org/neo4j/dbms/archive/ArchiveTest.java index d4ad8f27f007f..67a6deed4c2fb 100644 --- a/community/dbms/src/test/java/org/neo4j/dbms/archive/ArchiveTest.java +++ b/community/dbms/src/test/java/org/neo4j/dbms/archive/ArchiveTest.java @@ -19,8 +19,8 @@ */ package org.neo4j.dbms.archive; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import java.io.IOException; import java.nio.file.Files; @@ -31,19 +31,22 @@ import org.neo4j.function.Predicates; import org.neo4j.kernel.impl.transaction.log.files.TransactionLogFiles; +import org.neo4j.test.extension.Inject; +import org.neo4j.test.extension.TestDirectoryExtension; import org.neo4j.test.rule.TestDirectory; import static java.nio.file.Files.isDirectory; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.neo4j.helpers.collection.Pair.pair; -public class ArchiveTest +@ExtendWith( TestDirectoryExtension.class ) +class ArchiveTest { - @Rule - public TestDirectory testDirectory = TestDirectory.testDirectory(); + @Inject + private TestDirectory testDirectory; @Test - public void shouldRoundTripAnEmptyDirectory() throws IOException, IncorrectFormat + void shouldRoundTripAnEmptyDirectory() throws IOException, IncorrectFormat { Path directory = testDirectory.directory( "a-directory" ).toPath(); Files.createDirectories( directory ); @@ -52,7 +55,7 @@ public void shouldRoundTripAnEmptyDirectory() throws IOException, IncorrectForma } @Test - public void shouldRoundTripASingleFile() throws IOException, IncorrectFormat + void shouldRoundTripASingleFile() throws IOException, IncorrectFormat { Path directory = testDirectory.directory( "a-directory" ).toPath(); Files.createDirectories( directory ); @@ -62,7 +65,7 @@ public void shouldRoundTripASingleFile() throws IOException, IncorrectFormat } @Test - public void shouldRoundTripAnEmptyFile() throws IOException, IncorrectFormat + void shouldRoundTripAnEmptyFile() throws IOException, IncorrectFormat { Path directory = testDirectory.directory( "a-directory" ).toPath(); Files.createDirectories( directory ); @@ -72,7 +75,7 @@ public void shouldRoundTripAnEmptyFile() throws IOException, IncorrectFormat } @Test - public void shouldRoundTripFilesWithDifferentContent() throws IOException, IncorrectFormat + void shouldRoundTripFilesWithDifferentContent() throws IOException, IncorrectFormat { Path directory = testDirectory.directory( "a-directory" ).toPath(); Files.createDirectories( directory ); @@ -83,7 +86,7 @@ public void shouldRoundTripFilesWithDifferentContent() throws IOException, Incor } @Test - public void shouldRoundTripEmptyDirectories() throws IOException, IncorrectFormat + void shouldRoundTripEmptyDirectories() throws IOException, IncorrectFormat { Path directory = testDirectory.directory( "a-directory" ).toPath(); Path subdir = directory.resolve( "a-subdirectory" ); @@ -92,7 +95,7 @@ public void shouldRoundTripEmptyDirectories() throws IOException, IncorrectForma } @Test - public void shouldRoundTripFilesInDirectories() throws IOException, IncorrectFormat + void shouldRoundTripFilesInDirectories() throws IOException, IncorrectFormat { Path directory = testDirectory.directory( "a-directory" ).toPath(); Path subdir = directory.resolve( "a-subdirectory" ); @@ -102,7 +105,7 @@ public void shouldRoundTripFilesInDirectories() throws IOException, IncorrectFor } @Test - public void shouldCopeWithLongPaths() throws IOException, IncorrectFormat + void shouldCopeWithLongPaths() throws IOException, IncorrectFormat { Path directory = testDirectory.directory( "a-directory" ).toPath(); Path subdir = directory.resolve( "a/very/long/path/which/is/not/realistic/for/a/database/today/but/which" + @@ -114,7 +117,7 @@ public void shouldCopeWithLongPaths() throws IOException, IncorrectFormat } @Test - public void shouldExcludeFilesMatchedByTheExclusionPredicate() throws IOException, IncorrectFormat + void shouldExcludeFilesMatchedByTheExclusionPredicate() throws IOException, IncorrectFormat { Path directory = testDirectory.directory( "a-directory" ).toPath(); Files.createDirectories( directory ); @@ -134,7 +137,7 @@ public void shouldExcludeFilesMatchedByTheExclusionPredicate() throws IOExceptio } @Test - public void shouldExcludeWholeDirectoriesMatchedByTheExclusionPredicate() throws IOException, IncorrectFormat + void shouldExcludeWholeDirectoriesMatchedByTheExclusionPredicate() throws IOException, IncorrectFormat { Path directory = testDirectory.directory( "a-directory" ).toPath(); Path subdir = directory.resolve( "subdir" ); @@ -153,7 +156,7 @@ public void shouldExcludeWholeDirectoriesMatchedByTheExclusionPredicate() throws } @Test - public void dumpAndLoadTransactionLogsFromCustomLocations() throws IOException, IncorrectFormat + void dumpAndLoadTransactionLogsFromCustomLocations() throws IOException, IncorrectFormat { Path directory = testDirectory.directory( "dbDirectory" ).toPath(); Path txLogsDirectory = testDirectory.directory( "txLogsDirectory" ).toPath(); diff --git a/community/dbms/src/test/java/org/neo4j/dbms/archive/DumperTest.java b/community/dbms/src/test/java/org/neo4j/dbms/archive/DumperTest.java index 77724a5ec69ee..d1f5001fd7bc9 100644 --- a/community/dbms/src/test/java/org/neo4j/dbms/archive/DumperTest.java +++ b/community/dbms/src/test/java/org/neo4j/dbms/archive/DumperTest.java @@ -19,9 +19,10 @@ */ package org.neo4j.dbms.archive; -import org.apache.commons.lang3.SystemUtils; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnOs; +import org.junit.jupiter.api.condition.OS; +import org.junit.jupiter.api.extension.ExtendWith; import java.io.Closeable; import java.io.IOException; @@ -33,100 +34,74 @@ import java.nio.file.Path; import org.neo4j.function.Predicates; +import org.neo4j.test.extension.Inject; +import org.neo4j.test.extension.TestDirectoryExtension; import org.neo4j.test.rule.TestDirectory; import static java.util.Collections.emptySet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; -public class DumperTest +@ExtendWith( TestDirectoryExtension.class ) +class DumperTest { - @Rule - public TestDirectory testDirectory = TestDirectory.testDirectory(); + @Inject + private TestDirectory testDirectory; @Test - public void shouldGiveAClearErrorIfTheArchiveAlreadyExists() throws IOException + void shouldGiveAClearErrorIfTheArchiveAlreadyExists() throws IOException { Path directory = testDirectory.directory( "a-directory" ).toPath(); Path archive = testDirectory.file( "the-archive.dump" ).toPath(); Files.write( archive, new byte[0] ); - try - { - new Dumper().dump( directory, directory, archive, Predicates.alwaysFalse() ); - fail( "Expected an exception" ); - } - catch ( FileAlreadyExistsException e ) - { - assertEquals( archive.toString(), e.getMessage() ); - } + FileAlreadyExistsException exception = + assertThrows( FileAlreadyExistsException.class, () -> new Dumper().dump( directory, directory, archive, Predicates.alwaysFalse() ) ); + assertEquals( archive.toString(), exception.getMessage() ); } @Test - public void shouldGiveAClearErrorMessageIfTheDirectoryDoesntExist() throws IOException + void shouldGiveAClearErrorMessageIfTheDirectoryDoesntExist() { Path directory = testDirectory.file( "a-directory" ).toPath(); Path archive = testDirectory.file( "the-archive.dump" ).toPath(); - try - { - new Dumper().dump( directory, directory, archive, Predicates.alwaysFalse() ); - fail( "Expected an exception" ); - } - catch ( NoSuchFileException e ) - { - assertEquals( directory.toString(), e.getMessage() ); - } + NoSuchFileException exception = + assertThrows( NoSuchFileException.class, () -> new Dumper().dump( directory, directory, archive, Predicates.alwaysFalse() ) ); + assertEquals( directory.toString(), exception.getMessage() ); } @Test - public void shouldGiveAClearErrorMessageIfTheArchivesParentDirectoryDoesntExist() throws IOException + void shouldGiveAClearErrorMessageIfTheArchivesParentDirectoryDoesntExist() { Path directory = testDirectory.directory( "a-directory" ).toPath(); Path archive = testDirectory.file( "subdir/the-archive.dump" ).toPath(); - try - { - new Dumper().dump( directory, directory, archive, Predicates.alwaysFalse() ); - fail( "Expected an exception" ); - } - catch ( NoSuchFileException e ) - { - assertEquals( archive.getParent().toString(), e.getMessage() ); - } + NoSuchFileException exception = + assertThrows( NoSuchFileException.class, () -> new Dumper().dump( directory, directory, archive, Predicates.alwaysFalse() ) ); + assertEquals( archive.getParent().toString(), exception.getMessage() ); } @Test - public void shouldGiveAClearErrorMessageIfTheArchivesParentDirectoryIsAFile() throws IOException + void shouldGiveAClearErrorMessageIfTheArchivesParentDirectoryIsAFile() throws IOException { Path directory = testDirectory.directory( "a-directory" ).toPath(); Path archive = testDirectory.file( "subdir/the-archive.dump" ).toPath(); Files.write( archive.getParent(), new byte[0] ); - try - { - new Dumper().dump( directory, directory, archive, Predicates.alwaysFalse() ); - fail( "Expected an exception" ); - } - catch ( FileSystemException e ) - { - assertEquals( archive.getParent().toString() + ": Not a directory", e.getMessage() ); - } + FileSystemException exception = + assertThrows( FileSystemException.class, () -> new Dumper().dump( directory, directory, archive, Predicates.alwaysFalse() ) ); + assertEquals( archive.getParent().toString() + ": Not a directory", exception.getMessage() ); } @Test - public void shouldGiveAClearErrorMessageIfTheArchivesParentDirectoryIsNotWritable() throws IOException + @DisabledOnOs( OS.WINDOWS ) + void shouldGiveAClearErrorMessageIfTheArchivesParentDirectoryIsNotWritable() throws IOException { - assumeFalse( "We haven't found a way to reliably tests permissions on Windows", SystemUtils.IS_OS_WINDOWS ); - Path directory = testDirectory.directory( "a-directory" ).toPath(); Path archive = testDirectory.file( "subdir/the-archive.dump" ).toPath(); Files.createDirectories( archive.getParent() ); try ( Closeable ignored = TestUtils.withPermissions( archive.getParent(), emptySet() ) ) { - new Dumper().dump( directory, directory, archive, Predicates.alwaysFalse() ); - fail( "Expected an exception" ); - } - catch ( AccessDeniedException e ) - { - assertEquals( archive.getParent().toString(), e.getMessage() ); + AccessDeniedException exception = + assertThrows( AccessDeniedException.class, () -> new Dumper().dump( directory, directory, archive, Predicates.alwaysFalse() ) ); + assertEquals( archive.getParent().toString(), exception.getMessage() ); } } } diff --git a/community/dbms/src/test/java/org/neo4j/dbms/archive/LoaderTest.java b/community/dbms/src/test/java/org/neo4j/dbms/archive/LoaderTest.java index 9e16f07802817..06727560db3a4 100644 --- a/community/dbms/src/test/java/org/neo4j/dbms/archive/LoaderTest.java +++ b/community/dbms/src/test/java/org/neo4j/dbms/archive/LoaderTest.java @@ -20,9 +20,10 @@ package org.neo4j.dbms.archive; import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream; -import org.apache.commons.lang3.SystemUtils; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnOs; +import org.junit.jupiter.api.condition.OS; +import org.junit.jupiter.api.extension.ExtendWith; import java.io.Closeable; import java.io.IOException; @@ -34,55 +35,43 @@ import java.nio.file.Path; import java.util.Random; +import org.neo4j.test.extension.Inject; +import org.neo4j.test.extension.TestDirectoryExtension; import org.neo4j.test.rule.TestDirectory; -import static java.util.Arrays.asList; import static java.util.Collections.emptySet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeFalse; +import static java.util.Collections.singletonList; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.neo4j.dbms.archive.TestUtils.withPermissions; -public class LoaderTest +@ExtendWith( TestDirectoryExtension.class ) +class LoaderTest { - @Rule - public TestDirectory testDirectory = TestDirectory.testDirectory(); + @Inject + private TestDirectory testDirectory; @Test - public void shouldGiveAClearErrorMessageIfTheArchiveDoesntExist() throws IOException, IncorrectFormat + void shouldGiveAClearErrorMessageIfTheArchiveDoesntExist() { Path archive = testDirectory.file( "the-archive.dump" ).toPath(); Path destination = testDirectory.file( "the-destination" ).toPath(); - try - { - new Loader().load( archive, destination, destination ); - fail( "Expected an exception" ); - } - catch ( NoSuchFileException e ) - { - assertEquals( archive.toString(), e.getMessage() ); - } + NoSuchFileException exception = assertThrows( NoSuchFileException.class, () -> new Loader().load( archive, destination, destination ) ); + assertEquals( archive.toString(), exception.getMessage() ); } @Test - public void shouldGiveAClearErrorMessageIfTheArchiveIsNotInGzipFormat() throws IOException + void shouldGiveAClearErrorMessageIfTheArchiveIsNotInGzipFormat() throws IOException { Path archive = testDirectory.file( "the-archive.dump" ).toPath(); - Files.write( archive, asList( "some incorrectly formatted data" ) ); + Files.write( archive, singletonList( "some incorrectly formatted data" ) ); Path destination = testDirectory.file( "the-destination" ).toPath(); - try - { - new Loader().load( archive, destination, destination ); - fail( "Expected an exception" ); - } - catch ( IncorrectFormat e ) - { - assertEquals( archive.toString(), e.getMessage() ); - } + IncorrectFormat incorrectFormat = assertThrows( IncorrectFormat.class, () -> new Loader().load( archive, destination, destination ) ); + assertEquals( archive.toString(), incorrectFormat.getMessage() ); } @Test - public void shouldGiveAClearErrorMessageIfTheArchiveIsNotInTarFormat() throws IOException + void shouldGiveAClearErrorMessageIfTheArchiveIsNotInTarFormat() throws IOException { Path archive = testDirectory.file( "the-archive.dump" ).toPath(); try ( GzipCompressorOutputStream compressor = @@ -94,141 +83,90 @@ public void shouldGiveAClearErrorMessageIfTheArchiveIsNotInTarFormat() throws IO } Path destination = testDirectory.file( "the-destination" ).toPath(); - try - { - new Loader().load( archive, destination, destination ); - fail( "Expected an exception" ); - } - catch ( IncorrectFormat e ) - { - assertEquals( archive.toString(), e.getMessage() ); - } + + IncorrectFormat incorrectFormat = assertThrows( IncorrectFormat.class, () -> new Loader().load( archive, destination, destination ) ); + assertEquals( archive.toString(), incorrectFormat.getMessage() ); } @Test - public void shouldGiveAClearErrorIfTheDestinationAlreadyExists() throws IOException, IncorrectFormat + void shouldGiveAClearErrorIfTheDestinationAlreadyExists() { Path archive = testDirectory.file( "the-archive.dump" ).toPath(); Path destination = testDirectory.directory( "the-destination" ).toPath(); - try - { - new Loader().load( archive, destination, destination ); - fail( "Expected an exception" ); - } - catch ( FileAlreadyExistsException e ) - { - assertEquals( destination.toString(), e.getMessage() ); - } + FileAlreadyExistsException exception = assertThrows( FileAlreadyExistsException.class, () -> new Loader().load( archive, destination, destination ) ); + assertEquals( destination.toString(), exception.getMessage() ); } @Test - public void shouldGiveAClearErrorIfTheDestinationTxLogAlreadyExists() throws IOException, IncorrectFormat + void shouldGiveAClearErrorIfTheDestinationTxLogAlreadyExists() { Path archive = testDirectory.file( "the-archive.dump" ).toPath(); Path destination = testDirectory.file( "the-destination" ).toPath(); Path txLogsDestination = testDirectory.directory( "txLogsDestination" ).toPath(); - try - { - new Loader().load( archive, destination, txLogsDestination ); - fail( "Expected an exception" ); - } - catch ( FileAlreadyExistsException e ) - { - assertEquals( txLogsDestination.toString(), e.getMessage() ); - } + + FileAlreadyExistsException exception = + assertThrows( FileAlreadyExistsException.class, () -> new Loader().load( archive, destination, txLogsDestination ) ); + assertEquals( txLogsDestination.toString(), exception.getMessage() ); } @Test - public void shouldGiveAClearErrorMessageIfTheDestinationsParentDirectoryDoesntExist() - throws IOException, IncorrectFormat + void shouldGiveAClearErrorMessageIfTheDestinationsParentDirectoryDoesntExist() { Path archive = testDirectory.file( "the-archive.dump" ).toPath(); Path destination = testDirectory.directory( "subdir/the-destination" ).toPath(); - try - { - new Loader().load( archive, destination, destination ); - fail( "Expected an exception" ); - } - catch ( NoSuchFileException e ) - { - assertEquals( destination.getParent().toString(), e.getMessage() ); - } + NoSuchFileException noSuchFileException = assertThrows( NoSuchFileException.class, () -> new Loader().load( archive, destination, destination ) ); + assertEquals( destination.getParent().toString(), noSuchFileException.getMessage() ); } @Test - public void shouldGiveAClearErrorMessageIfTheTxLogsParentDirectoryDoesntExist() - throws IOException, IncorrectFormat + void shouldGiveAClearErrorMessageIfTheTxLogsParentDirectoryDoesntExist() { Path archive = testDirectory.file( "the-archive.dump" ).toPath(); Path destination = testDirectory.file( "destination" ).toPath(); Path txLogsDestination = testDirectory.directory( "subdir/txLogs" ).toPath(); - try - { - new Loader().load( archive, destination, txLogsDestination ); - fail( "Expected an exception" ); - } - catch ( NoSuchFileException e ) - { - assertEquals( txLogsDestination.getParent().toString(), e.getMessage() ); - } + NoSuchFileException noSuchFileException = assertThrows( NoSuchFileException.class, () -> new Loader().load( archive, destination, txLogsDestination ) ); + assertEquals( txLogsDestination.getParent().toString(), noSuchFileException.getMessage() ); } @Test - public void shouldGiveAClearErrorMessageIfTheDestinationsParentDirectoryIsAFile() - throws IOException, IncorrectFormat + void shouldGiveAClearErrorMessageIfTheDestinationsParentDirectoryIsAFile() + throws IOException { Path archive = testDirectory.file( "the-archive.dump" ).toPath(); Path destination = testDirectory.directory( "subdir/the-destination" ).toPath(); Files.write( destination.getParent(), new byte[0] ); - try - { - new Loader().load( archive, destination, destination ); - fail( "Expected an exception" ); - } - catch ( FileSystemException e ) - { - assertEquals( destination.getParent().toString() + ": Not a directory", e.getMessage() ); - } + FileSystemException exception = assertThrows( FileSystemException.class, () -> new Loader().load( archive, destination, destination ) ); + assertEquals( destination.getParent().toString() + ": Not a directory", exception.getMessage() ); } @Test - public void shouldGiveAClearErrorMessageIfTheDestinationsParentDirectoryIsNotWritable() - throws IOException, IncorrectFormat + @DisabledOnOs( OS.WINDOWS ) + void shouldGiveAClearErrorMessageIfTheDestinationsParentDirectoryIsNotWritable() + throws IOException { - assumeFalse( "We haven't found a way to reliably tests permissions on Windows", SystemUtils.IS_OS_WINDOWS ); - Path archive = testDirectory.file( "the-archive.dump" ).toPath(); Path destination = testDirectory.directory( "subdir/the-destination" ).toPath(); Files.createDirectories( destination.getParent() ); try ( Closeable ignored = withPermissions( destination.getParent(), emptySet() ) ) { - new Loader().load( archive, destination, destination ); - fail( "Expected an exception" ); - } - catch ( AccessDeniedException e ) - { - assertEquals( destination.getParent().toString(), e.getMessage() ); + AccessDeniedException exception = assertThrows( AccessDeniedException.class, () -> new Loader().load( archive, destination, destination ) ); + assertEquals( destination.getParent().toString(), exception.getMessage() ); } } @Test - public void shouldGiveAClearErrorMessageIfTheTxLogsParentDirectoryIsNotWritable() - throws IOException, IncorrectFormat + @DisabledOnOs( OS.WINDOWS ) + void shouldGiveAClearErrorMessageIfTheTxLogsParentDirectoryIsNotWritable() + throws IOException { - assumeFalse( "We haven't found a way to reliably tests permissions on Windows", SystemUtils.IS_OS_WINDOWS ); - Path archive = testDirectory.file( "the-archive.dump" ).toPath(); Path destination = testDirectory.file( "destination" ).toPath(); Path txLogsDirectory = testDirectory.directory( "subdir/txLogs" ).toPath(); Files.createDirectories( txLogsDirectory.getParent() ); try ( Closeable ignored = withPermissions( txLogsDirectory.getParent(), emptySet() ) ) { - new Loader().load( archive, destination, txLogsDirectory ); - fail( "Expected an exception" ); - } - catch ( AccessDeniedException e ) - { - assertEquals( txLogsDirectory.getParent().toString(), e.getMessage() ); + AccessDeniedException exception = assertThrows( AccessDeniedException.class, () -> new Loader().load( archive, destination, txLogsDirectory ) ); + assertEquals( txLogsDirectory.getParent().toString(), exception.getMessage() ); } } }