Skip to content

Instantly share code, notes, and snippets.

@Bombe
Last active August 5, 2019 20:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bombe/fb1ec487ea03614d96e9d152f21e64cc to your computer and use it in GitHub Desktop.
Save Bombe/fb1ec487ea03614d96e9d152f21e64cc to your computer and use it in GitHub Desktop.
class AsyncFreenetInterfaceTest {
@Test
fun `returned deferred is completed by success`() = runBlocking {
val result = FetchResult(ClientMetadata(), NullBucket())
val freenetClient = object : FreenetClient {
override fun fetch(freenetKey: FreenetURI) = result
}
val freenetInterface = AsyncFreenetInterface(freenetClient)
val fetched = async { freenetInterface.fetchUri(FreenetURI("KSK@GPL.txt")) }
withTimeout(1000) {
assertThat(fetched.await(), equalTo(Fetched(FreenetURI("KSK@GPL.txt"), result)))
}
}
@Test
fun `permanent redircts are being followed`() = runBlocking {
val result = FetchResult(ClientMetadata(), NullBucket())
val freenetClient = object : FreenetClient {
val redirected = AtomicBoolean(false)
override fun fetch(freenetKey: FreenetURI) =
if (redirected.compareAndSet(false, true))
throw FetchException(FetchException.FetchExceptionMode.PERMANENT_REDIRECT, FreenetURI("KSK@GPLv3.txt"))
else result
}
val freenetInterface = AsyncFreenetInterface(freenetClient)
val fetched = async { freenetInterface.fetchUri(FreenetURI("KSK@GPL.txt")) }
withTimeout(1000) {
assertThat(fetched.await(), equalTo(Fetched(FreenetURI("KSK@GPLv3.txt"), result)))
}
}
@Test
fun `fetch errors are being re-thrown`() = runBlocking<Unit> {
val freenetClient = object : FreenetClient {
override fun fetch(freenetKey: FreenetURI) =
throw FetchException(FetchException.FetchExceptionMode.ALL_DATA_NOT_FOUND)
}
val freenetInterface = AsyncFreenetInterface(freenetClient)
println("a")
val fetched = async { freenetInterface.fetchUri(FreenetURI("KSK@GPL.txt")) }
println("b")
withTimeout(1000) {
assertFailsWith(FetchException::class) {
println("d")
println("e: ${fetched.await()}")
println("c")
}
}
}
}
class AsyncFreenetInterface(private val freenetClient: FreenetClient) {
suspend fun fetchUri(freenetUri: FreenetURI): Fetched = coroutineScope {
var currentUri = freenetUri
var result: FetchResult? = null
while (result == null) {
try {
result = withContext(Dispatchers.Default) { freenetClient.fetch(currentUri) }
} catch (fetchException: FetchException) {
if (fetchException.mode == FetchException.FetchExceptionMode.PERMANENT_REDIRECT) {
currentUri = fetchException.newURI
continue
} else
throw fetchException
}
}
Fetched(currentUri, result)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment