Skip to content

Commit

Permalink
KTOR-2914 Change exception type and clarify message (#3201)
Browse files Browse the repository at this point in the history
* KTOR-2914 Change exception type and clarify message
  • Loading branch information
e5l authored Oct 24, 2022
1 parent 298e0ad commit 34e9d51
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

package io.ktor.network.selector

import io.ktor.utils.io.errors.*
import kotlinx.coroutines.*
import java.nio.channels.*
import java.nio.channels.spi.*
Expand Down Expand Up @@ -33,15 +34,9 @@ public abstract class SelectorManagerSupport internal constructor() : SelectorMa
public final override suspend fun select(selectable: Selectable, interest: SelectInterest) {
val interestedOps = selectable.interestedOps
val flag = interest.flag
if (interestedOps and flag == 0) {
val message = if (selectable.isClosed) {
"Selectable is closed"
} else {
"Selectable is invalid state: $interestedOps, $flag"
}

throw IllegalArgumentException(message)
}
if (selectable.isClosed) selectableIsClosed()
if (interestedOps and flag == 0) selectableIsInvalid(interestedOps, flag)

suspendCancellableCoroutine<Unit> { continuation ->
continuation.invokeOnCancellation {
Expand Down Expand Up @@ -179,3 +174,11 @@ public abstract class SelectorManagerSupport internal constructor() : SelectorMa

public class ClosedSelectorCancellationException : CancellationException("Closed selector")
}

private fun selectableIsClosed(): Nothing {
throw IOException("Selectable is already closed")
}

private fun selectableIsInvalid(interestedOps: Int, flag: Int): Nothing {
error("Selectable is invalid state: $interestedOps, $flag")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/

package io.ktor.network.selector

import io.mockk.*
import kotlinx.coroutines.*
import org.junit.*
import org.junit.Test
import java.io.*
import kotlin.test.*

class ActorSelectorManagerTest {
val manager = ActorSelectorManager(Dispatchers.Default)

@After
fun tearDown() {
manager.close()
}

@Test
fun testSelectableIsClosed(): Unit = runBlocking {
val selectable: Selectable = mockk()
every { selectable.interestedOps } returns SelectInterest.READ.flag
every { selectable.isClosed } returns true

assertFailsWith<IOException> {
manager.select(selectable, SelectInterest.READ)
}
}

@Test
fun testSelectOnWrongInterest(): Unit = runBlocking {
val selectable: Selectable = mockk()
every { selectable.interestedOps } returns SelectInterest.READ.flag
every { selectable.isClosed } returns false

assertFailsWith<IllegalStateException> {
manager.select(selectable, SelectInterest.WRITE)
}
}
}

0 comments on commit 34e9d51

Please sign in to comment.