sergeych 16b2d1780b added reconnection/connection waiting logic
added way to close cannection from the adapter if the protocol implementation allows it (adapter.onCancel/adapter.cancel())
2022-12-18 03:30:11 +01:00

112 lines
3.1 KiB
Kotlin

package net.sergeych.parsec3
import assertThrows
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import kotlinx.coroutines.runBlocking
import net.sergeych.mp_logger.Log
import kotlin.test.Test
import kotlin.test.assertEquals
internal class WsServerKtTest {
data class TestSession(var buzz: String = "BuZZ"): WithAdapter()
object TestApiServer: CommandHost<TestSession>() {
val foo by command<String,String>()
val ping by command<Unit,String>()
}
object TestApiClient: CommandHost<WithAdapter>() {
val bar by command<String,String>()
}
@Test
fun testWsServer() {
embeddedServer(Netty, port = 8081) {
parsec3TransportServer(
TestApiServer,
) {
newSession { TestSession() }
on(api.foo) {
it + buzz + "-foo"
}
}
}.start(wait = false)
val client = Parsec3WSClient("ws://localhost:8081/api/p3", TestApiClient) {
on(api.bar) {
"bar:$it"
}
}
runBlocking {
val x = TestApiServer.foo.invoke(client.adapter(), "*great*")
assertEquals("*great*BuZZ-foo", x)
client.close()
}
}
@Test
fun testWsServerReconnect() {
embeddedServer(Netty, port = 8080) {
parsec3TransportServer(
TestApiServer,
) {
newSession { TestSession() }
var count = 0
on(api.foo) {
adapter.cancel()
"cancelled:${count++}"
}
on(api.ping) { "pong!"}
}
}.start(wait = false)
Log.connectConsole(Log.Level.DEBUG)
val client = Parsec3WSClient("ws://localhost:8080/api/p3", TestApiClient) {
on(api.bar) {
"bar:$it"
}
}
runBlocking {
assertEquals("pong!", TestApiServer.ping.invoke(client.adapter()))
assertThrows<Adapter.CloseError> { TestApiServer.foo.invoke(client.adapter(), "*great*") }
assertEquals("pong!", TestApiServer.ping.invoke(client.adapter()))
assertThrows<Adapter.CloseError> { TestApiServer.foo.invoke(client.adapter(), "*great*") }
}
}
@Test
fun testWsServerWaitForConnect() {
val client = Parsec3WSClient("ws://localhost:8084/api/p3", TestApiClient) {
on(api.bar) {
"bar:$it"
}
}
println("---1")
embeddedServer(Netty, port = 8084) {
parsec3TransportServer(
TestApiServer,
) {
newSession { TestSession() }
on(api.foo) {
it + buzz + "-foo"
}
}
}.start(wait = false)
runBlocking {
println("----2")
val x = TestApiServer.foo.invoke(client.adapter(), "*great*")
println(">> $x")
assertEquals("*great*BuZZ-foo", x)
client.close()
}
}
}