Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Test canceling a suspend invocation propagates to Call #3029

Merged
merged 1 commit into from
Feb 16, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions retrofit/src/test/java/retrofit2/KotlinSuspendTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,16 @@
*/
package retrofit2

import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import okhttp3.OkHttpClient
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import okhttp3.mockwebserver.SocketPolicy.DISCONNECT_AFTER_REQUEST
import okhttp3.mockwebserver.SocketPolicy.NO_RESPONSE
import org.assertj.core.api.Assertions.assertThat
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.Ignore
import org.junit.Rule
Expand Down Expand Up @@ -181,4 +186,31 @@ class KotlinSuspendTest {
val request = server.takeRequest()
assertThat(request.path).isEqualTo("/1/2/3")
}

@Test fun cancelationWorks() {
lateinit var call: okhttp3.Call

val okHttpClient = OkHttpClient()
val retrofit = Retrofit.Builder()
.baseUrl(server.url("/"))
.callFactory {
val newCall = okHttpClient.newCall(it)
call = newCall
newCall
}
.addConverterFactory(ToStringConverterFactory())
.build()
val example = retrofit.create(Service::class.java)

// This leaves the connection open indefinitely allowing us to cancel without racing a body.
server.enqueue(MockResponse().setSocketPolicy(NO_RESPONSE))

val deferred = GlobalScope.async { example.body() }

// This will block until the server has received the request ensuring it's in flight.
server.takeRequest()

deferred.cancel()
assertTrue(call.isCanceled)
}
}