Fixed ThunderbirdAutoconfigFetcher throwing on IOExceptions

If the requested url does not exist then the `fetchAutoconfigFile` would just crash instead of returning `null`. This would mean that the discovery code would also crash instead of trying other URLs.
This commit is contained in:
Jeroen1602 2023-03-13 15:27:44 +01:00
parent 6f428c1642
commit 6a89a03082
No known key found for this signature in database
GPG key ID: E5A3DE85D67A3FF9
3 changed files with 57 additions and 5 deletions

View file

@ -11,4 +11,5 @@ dependencies {
implementation(libs.okhttp)
testImplementation(libs.kxml2)
testImplementation(libs.okhttp.mockwebserver)
}

View file

@ -1,5 +1,7 @@
package com.fsck.k9.autodiscovery.thunderbird
import com.fsck.k9.logging.Timber
import java.io.IOException
import java.io.InputStream
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
@ -8,13 +10,18 @@ import okhttp3.Request
class ThunderbirdAutoconfigFetcher(private val okHttpClient: OkHttpClient) {
fun fetchAutoconfigFile(url: HttpUrl): InputStream? {
val request = Request.Builder().url(url).build()
return try {
val request = Request.Builder().url(url).build()
val response = okHttpClient.newCall(request).execute()
val response = okHttpClient.newCall(request).execute()
return if (response.isSuccessful) {
response.body?.byteStream()
} else {
if (response.isSuccessful) {
response.body?.byteStream()
} else {
null
}
} catch (e: IOException) {
Timber.d(e, "Error fetching URL: %s", url)
null
}
}

View file

@ -0,0 +1,44 @@
package com.fsck.k9.autodiscovery.thunderbird
import assertk.assertThat
import assertk.assertions.isEqualTo
import assertk.assertions.isNull
import kotlin.test.assertNotNull
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.OkHttpClient
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.junit.Test
class ThunderbirdAutoconfigFetcherTest {
private val fetcher = ThunderbirdAutoconfigFetcher(OkHttpClient.Builder().build())
@Test
fun shouldHandleNonexistentUrl() {
val nonExistentUrl =
"https://autoconfig.domain.invalid/mail/config-v1.1.xml?emailaddress=test%40domain.example".toHttpUrl()
val inputStream = fetcher.fetchAutoconfigFile(nonExistentUrl)
assertThat(inputStream).isNull()
}
@Test
fun shouldHandleEmptyResponse() {
val server = MockWebServer().apply {
this.enqueue(
MockResponse()
.setBody("")
.setResponseCode(204),
)
start()
}
val url = server.url("/empty/")
val inputStream = fetcher.fetchAutoconfigFile(url)
assertNotNull(inputStream) { inputStream ->
assertThat(inputStream.available()).isEqualTo(0)
}
}
}