private ExecutionPlanDescription getMockDescription( String name ) { ExecutionPlanDescription plan = mock( ExecutionPlanDescription.class ); when( plan.getName() ).thenReturn( name ); when( plan.getArguments() ).thenReturn( MapUtil.map( "argumentKey", "argumentValue" ) ); return plan; }
private static SegmentCommitInfo getSegmentCommitInfo() { SegmentInfo segmentInfo = new SegmentInfo( mock( Directory.class ), Version.LATEST, "test", Integer.MAX_VALUE, true, mock( Codec.class ), MapUtil.stringMap(), RandomUtils.nextBytes( 16 ), MapUtil.stringMap() ); return new SegmentCommitInfo( segmentInfo, 1, 1L, 1L, 1L ); }
/** * A short-hand method for creating a {@link Map} of key/value pairs where * both keys and values are {@link String}s. * * @param strings alternating key and value. * @return a Map with the entries supplied by {@code strings}. */ public static Map<String, String> stringMap( String... strings ) { return genericMap( (Object[]) strings ); }
/** * Loads a {@link Map} from a {@link File} assuming strings as keys * and values. * * @param file the {@link File} containing a {@link Properties}-like * layout of keys and values. * @return the read data as a {@link Map}. * @throws IOException if the file reader throws {@link IOException}. */ public static Map<String, String> load( File file ) throws IOException { FileInputStream stream = null; try { stream = new FileInputStream( file ); return load( stream ); } finally { closeIfNotNull( stream ); } }
/** * Stores the data in {@code config} into {@code file} in a standard java * {@link Properties} format. * @param config the data to store in the properties file. * @param file the file to store the properties in. * @throws IOException IO error. */ public static void store( Map<String, String> config, File file ) throws IOException { OutputStream stream = null; try { stream = new BufferedOutputStream( new FileOutputStream( file ) ); store( config, stream ); } finally { closeIfNotNull( stream ); } }
@Test public void shouldInterruptTransaction() { // given TransitionalPeriodTransactionMessContainer kernel = mockKernel(); TransitionalTxManagementKernelTransaction tx = mock( TransitionalTxManagementKernelTransaction.class ); when( kernel.newTransaction( any( Type.class ), any( LoginContext.class ), anyLong() ) ).thenReturn( tx ); TransactionRegistry registry = mock( TransactionRegistry.class ); when( registry.begin( any( TransactionHandle.class ) ) ).thenReturn( 1337L ); QueryExecutionEngine executionEngine = mock( QueryExecutionEngine.class ); TransactionHandle handle = getTransactionHandle( kernel, executionEngine, registry ); ExecutionResultSerializer output = mock( ExecutionResultSerializer.class ); Statement statement = new Statement( "MATCH (n) RETURN n", map(), false, (ResultDataContent[]) null ); handle.execute( statements( statement ), output, mock( HttpServletRequest.class ) ); // when handle.terminate(); // then verify( tx, times( 1 ) ).terminate(); }
@Test @SuppressWarnings( "unchecked" ) public void deadlockExceptionHasCorrectStatus() throws Exception { // given QueryExecutionEngine executionEngine = mock( QueryExecutionEngine.class ); when( executionEngine.executeQuery( anyString(), any( MapValue.class ), isNull() ) ) .thenThrow( new DeadlockDetectedException( "deadlock" ) ); GraphDatabaseQueryService queryService = mock( GraphDatabaseQueryService.class ); TransactionHandle handle = new TransactionHandle( mockKernel(), executionEngine, queryService, mock( TransactionRegistry.class ), uriScheme, true, AUTH_DISABLED, anyLong(), NullLogProvider.getInstance() ); ExecutionResultSerializer output = mock( ExecutionResultSerializer.class ); // when handle.execute( statements( new Statement( "query", map(), false, (ResultDataContent[]) null ) ), output, mock( HttpServletRequest.class ) ); // then verify( output ).errors( argThat( hasErrors( Status.Transaction.DeadlockDetected ) ) ); }
@Test void nonUniqueSamplingCancel() throws IOException { Terms terms = getTerms( "test", 1 ); Map<String,Terms> fieldTermsMap = MapUtil.genericMap( "0string", terms, "id", terms, "0string", terms ); IndexReaderStub indexReader = new IndexReaderStub( new SamplingFields( fieldTermsMap ) ); when( indexSearcher.getIndexReader() ).thenReturn( indexReader ); NonUniqueLuceneIndexSampler luceneIndexSampler = createSampler(); taskControl.cancel(); IndexNotFoundKernelException notFoundKernelException = assertThrows( IndexNotFoundKernelException.class, luceneIndexSampler::sampleIndex ); assertEquals( notFoundKernelException.getMessage(), "Index dropped while sampling." ); }
@Test public void shouldAccessExampleMetaData() { EmbeddedProxySPI spi = mock( EmbeddedProxySPI.class ); final KernelTransactionImplementation transaction = mock( KernelTransactionImplementation.class ); when( transaction.getMetaData() ).thenReturn( genericMap( "username", "Igor" ) ); TxStateTransactionDataSnapshot transactionDataSnapshot = new TxStateTransactionDataSnapshot( state, spi, ops, transaction ); assertEquals( 1, transactionDataSnapshot.metaData().size() ); assertThat( "Expected metadata map to contain defined username", transactionDataSnapshot.metaData(), equalTo( genericMap( "username", "Igor" ) ) ); }
@Test public void nextShouldNotEqualNotNext() { // Given Result result = mock( Result.class ); when( result.columns() ).thenReturn( Collections.singletonList( "name" ) ); when( result.hasNext() ).thenReturn( true, true, false ); //noinspection unchecked when( result.next() ).thenReturn( MapUtil.map( "name", "bob" ), MapUtil.map( "name", "Steve Brook" ), null ); // When CypherAdapterStream cursor = new CypherAdapterStream( result ); // Then assertThat( cursor, equalsStream( new String[]{"name"}, eqRecord( equalTo( "bob" ) ), eqRecord( equalTo( "Steve Brook" ) ) ) ); } }
@Test public void shouldAdvertiseServicesWhenAsked() throws Exception { UriInfo uriInfo = mock( UriInfo.class ); URI uri = new URI( "http://example.org:7474/" ); when( uriInfo.getBaseUri() ).thenReturn( uri ); RootService svc = new RootService( new CommunityNeoServer( Config.defaults( stringMap( new HttpConnector( "http", Encryption.NONE ).type.name(), "HTTP", new HttpConnector( "http", Encryption.NONE ).enabled.name(), "true" ) ), GraphDatabaseDependencies.newDependencies().userLogProvider( NullLogProvider.getInstance() ) .monitors( new Monitors() ) ) ); EntityOutputFormat output = new EntityOutputFormat( new JsonFormat(), null, null ); Response serviceDefinition = svc.getServiceDefinition( uriInfo, output ); assertEquals( 200, serviceDefinition.getStatus() ); Map<String, Object> result = (Map<String, Object>) output.getResultAsMap().get( "services" ); assertThat( result.get( "console" ) .toString(), containsString( String.format( "%sserver/console", uri.toString() ) ) ); assertThat( result.get( "jmx" ) .toString(), containsString( String.format( "%sserver/jmx", uri.toString() ) ) ); } }
@Test public void shouldDispatchRun() throws Exception { BoltStateMachine stateMachine = mock( BoltStateMachine.class ); SynchronousBoltConnection connection = new SynchronousBoltConnection( stateMachine ); channel = new EmbeddedChannel( newDecoder( connection ) ); String statement = "RETURN 1"; MapValue parameters = ValueUtils.asMapValue( MapUtil.map( "param1", 1, "param2", "2", "param3", true, "param4", 5.0 ) ); channel.writeInbound( Unpooled.wrappedBuffer( serialize( packerUnderTest, new RunMessage( statement, parameters ) ) ) ); channel.finishAndReleaseAll(); verify( stateMachine ).process( eq( new RunMessage( statement, parameters ) ), any() ); }
@Test public void shouldHandleBasicMBean() throws Throwable { // given when( jmxServer.getAttribute( beanName, "name" ) ).thenReturn( "Hello, world!" ); JmxQueryProcedure procedure = new JmxQueryProcedure( ProcedureSignature.procedureName( "bob" ), jmxServer ); // when RawIterator<Object[],ProcedureException> result = procedure.apply( null, new Object[]{"*:*"}, resourceTracker ); // then assertThat( asList( result ), contains( equalTo( new Object[]{ "org.neo4j:chevyMakesTheTruck=bobMcCoshMakesTheDifference", "This is a description", map( attributeName, map( "description", "This is the attribute desc.", "value", "Hello, world!" ) ) } ) ) ); }
@Test public void shouldTransitionToFailedStateIfPopulationJobCrashes() throws Exception { // GIVEN IndexPopulator failingPopulator = mock( IndexPopulator.class ); doThrow( new RuntimeException( "BORK BORK" ) ).when( failingPopulator ).add( any(Collection.class) ); FlippableIndexProxy index = new FlippableIndexProxy(); createNode( map( name, "Taylor" ), FIRST ); IndexPopulationJob job = newIndexPopulationJob( failingPopulator, index, EntityType.NODE, indexDescriptor( FIRST, name, false ) ); // WHEN job.run(); // THEN assertThat( index.getState(), equalTo( InternalIndexState.FAILED ) ); }
@Test public void shouldHandleMBeanThatThrowsOnGetAttribute() throws Throwable { // given some JVM MBeans do not allow accessing their attributes, despite marking // then as readable when( jmxServer.getAttribute( beanName, "name" ) ) // We throw the exact combo thrown by JVM MBeans here, so that any other exception will bubble up, // and we can make an informed decision about swallowing more exception on an as-needed basis. .thenThrow( new RuntimeMBeanException( new UnsupportedOperationException( "Haha, screw discoverable services!" ) ) ); JmxQueryProcedure procedure = new JmxQueryProcedure( ProcedureSignature.procedureName( "bob" ), jmxServer ); // when RawIterator<Object[],ProcedureException> result = procedure.apply( null, new Object[]{"*:*"}, resourceTracker ); // then assertThat( asList( result ), contains( equalTo( new Object[]{ "org.neo4j:chevyMakesTheTruck=bobMcCoshMakesTheDifference", "This is a description", map( attributeName, map( "description", "This is the attribute desc.", "value", null ) ) } ) ) ); }
@Test public void nonStrictRetainsSettings() { IndividualSettingsValidator iv = new IndividualSettingsValidator( singletonList( strict_config_validation ), true ); final Map<String,String> rawConfig = stringMap( strict_config_validation.name(), FALSE, "dbms.jibber.jabber", "bla", "external_plugin.foo", "bar" ); Config config = mockConfig( rawConfig ); iv.validate( config, log ); verify( log ).warn( "Unknown config option: %s", "dbms.jibber.jabber" ); verifyNoMoreInteractions( log ); }
@Test void testDefault() { Setting<Integer> setting = setting( "foo", INTEGER, "3" ); // Ok assertThat( setting.apply( map( stringMap() ) ), equalTo( 3 ) ); }
@Test public void warnsWhenNameIsNotBolt() { String randomEnabled = "dbms.connector.bla.enabled"; String randomType = "dbms.connector.bla.type"; cv.validate( stringMap( randomEnabled, "true", randomType, "BOLT" ), warningConsumer ); verify( warningConsumer ).accept( format( DEPRECATED_CONNECTOR_MSG, format( "> %s%n> %s%n", randomEnabled, randomType ) ) ); }
@Test void shouldBeginTransactionWithMultipleBookmarks() throws Exception { Map<String,Object> params = map( "bookmarks", asList( "neo4j:bookmark:v1:tx7", "neo4j:bookmark:v1:tx1", "neo4j:bookmark:v1:tx92", "neo4j:bookmark:v1:tx39" ) ); BoltStateMachineState newState = state.process( new RunMessage( "BEGIN", asMapValue( params ) ), context ); assertEquals( streamingState, newState ); verify( statementProcessor ).beginTransaction( new Bookmark( 92 ) ); }
@Test public void shouldMakeCustomAuthTokenAndCustomcSchemeWithParameters() { Map<String, Object> token = AuthToken.newCustomAuthToken( "me", "my secret", "my realm", "my scheme", map("a", "A", "b", "B") ); assertThat("Should have correct username", token.get(AuthToken.PRINCIPAL), equalTo("me")); assertThat( "Should have correct password", token.get( AuthToken.CREDENTIALS ), equalTo( UTF8.encode( "my secret" ) ) ); assertThat("Should have correct scheme", token.get(AuthToken.SCHEME_KEY), equalTo("my scheme")); assertThat("Should have correct realm", token.get(AuthToken.REALM_KEY), equalTo( "my realm" )); assertThat("Should have correct parameters", token.get(AuthToken.PARAMETERS), equalTo( map("a", "A", "b", "B") )); } }