Skip to content

Commit c2da8af

Browse files
committed
More reliable wait for the StubServer
Previously code had a `Thread.sleep(500)` which sometimes caused flaky tests. This commit makes it actually try to establish socket connections with 300ms delay.
1 parent 269b8b6 commit c2da8af

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

driver/src/main/java/org/neo4j/driver/internal/net/SocketClient.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ public void start()
130130
{
131131
throw new ServiceUnavailableException( format(
132132
"Unable to connect to %s, ensure the database is running and that there is a " +
133-
"working network connection to it.", address ) );
133+
"working network connection to it.", address ), e );
134134
}
135135
catch ( IOException e )
136136
{

driver/src/test/java/org/neo4j/driver/v1/util/StubServer.java

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@
2020

2121
import java.io.File;
2222
import java.io.IOException;
23+
import java.net.InetSocketAddress;
24+
import java.net.SocketAddress;
25+
import java.nio.channels.SocketChannel;
2326
import java.util.ArrayList;
2427
import java.util.List;
2528

@@ -33,6 +36,8 @@
3336

3437
public class StubServer
3538
{
39+
private static final int SOCKET_CONNECT_ATTEMPTS = 20;
40+
3641
public static final Config INSECURE_CONFIG = Config.build()
3742
.withEncryptionLevel( Config.EncryptionLevel.NONE ).toConfig();
3843

@@ -50,7 +55,7 @@ private StubServer( String script, int port ) throws IOException, InterruptedExc
5055
command.addAll( asList( Integer.toString( port ), script ) );
5156
ProcessBuilder server = new ProcessBuilder().inheritIO().command( command );
5257
process = server.start();
53-
sleep( 500 ); // might take a moment for the socket to start listening
58+
waitForSocket( port );
5459
}
5560

5661
public static StubServer start( String resource, int port ) throws IOException, InterruptedException
@@ -100,4 +105,22 @@ private static boolean boltKitAvailable()
100105
return false;
101106
}
102107
}
108+
109+
private static void waitForSocket( int port ) throws InterruptedException
110+
{
111+
SocketAddress address = new InetSocketAddress( "localhost", port );
112+
for ( int i = 0; i < SOCKET_CONNECT_ATTEMPTS; i++ )
113+
{
114+
try
115+
{
116+
SocketChannel.open( address );
117+
return;
118+
}
119+
catch ( Exception e )
120+
{
121+
sleep( 300 );
122+
}
123+
}
124+
throw new AssertionError( "Can't connect to " + address );
125+
}
103126
}

0 commit comments

Comments
 (0)