Fix flaky GarminSimulatorClientTest.receiveMessage

This commit is contained in:
Robert Buessow 2023-12-07 22:18:47 +01:00
parent 6e4c7d9376
commit ec596c51df
2 changed files with 8 additions and 8 deletions

View file

@ -13,6 +13,7 @@ import java.net.ServerSocket
import java.net.Socket
import java.net.SocketException
import java.time.Duration
import java.time.Instant
import java.util.Collections
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
@ -142,10 +143,10 @@ class GarminSimulatorClient(
/** Wait for the server to start listing to requests. */
fun awaitReady(wait: Duration): Boolean {
var waitNanos = wait.toNanos()
val waitUntil = Instant.now() + wait
readyLock.withLock {
while (!serverSocket.isBound && waitNanos > 0L) {
waitNanos = readyCond.awaitNanos(waitNanos)
while (!serverSocket.isBound && Instant.now() < waitUntil) {
readyCond.await(20, TimeUnit.MILLISECONDS)
}
}
return serverSocket.isBound

View file

@ -5,6 +5,7 @@ import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.eq
import org.mockito.kotlin.isNull
import org.mockito.kotlin.mock
@ -28,18 +29,16 @@ class GarminSimulatorClientTest: TestBase() {
fun receiveMessage() {
val payload = "foo".toByteArray()
assertTrue(client.awaitReady(Duration.ofSeconds(10)))
verify(receiver, timeout(100)).onConnect(client)
val port = client.port
val ip = Inet4Address.getByAddress(byteArrayOf(127, 0, 0, 1))
Socket(ip, port).use { socket ->
assertTrue(socket.isConnected)
socket.getOutputStream().write(payload)
socket.getOutputStream().flush()
verify(receiver).onConnect(client)
verify(receiver, timeout(1_000))
.onReceiveMessage(eq(client), any(), eq("SIMAPP"), eq(payload))
}
assertEquals(1, client.connectedDevices.size)
val device: GarminDevice = client.connectedDevices.first()
verify(receiver, timeout(1_000))
.onReceiveMessage(eq(client), eq(device.id), eq("SIMAPP"), eq(payload))
}
@Test