Make ensureProtocol case-insensitive

This commit is contained in:
Jenna Vassar
2026-08-18 17:03:40 -07:00
parent 1b2d5b9c92
commit 2e2bf71ad5
2 changed files with 38 additions and 2 deletions
@@ -20,12 +20,13 @@ fun String.isValidUrl(): Boolean {
}
/**
* Ensure string starts with "http". If it is not the case, "https://" is added, only if the String is not empty
* Ensure string starts with "http" (case-insensitively, so "HTTP://" / "HTTPS://" are respected). If it is
* not the case, "https://" is added, only if the String is not empty.
*/
fun String.ensureProtocol(): String {
return when {
isEmpty() -> this
!startsWith("http") -> "https://$this"
!startsWith("http", ignoreCase = true) -> "https://$this"
else -> this
}
}
@@ -0,0 +1,35 @@
/*
* Copyright (c) 2026 Element Creations Ltd.
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
* Please see LICENSE files in the repository root for full details.
*/
package io.element.android.libraries.core.uri
import com.google.common.truth.Truth.assertThat
import org.junit.Test
class UrlUtilsTest {
@Test
fun `ensureProtocol keeps an empty string unchanged`() {
assertThat("".ensureProtocol()).isEqualTo("")
}
@Test
fun `ensureProtocol prepends https when there is no scheme`() {
assertThat("matrix.org".ensureProtocol()).isEqualTo("https://matrix.org")
}
@Test
fun `ensureProtocol keeps an existing http or https scheme`() {
assertThat("https://matrix.org".ensureProtocol()).isEqualTo("https://matrix.org")
assertThat("http://matrix.org".ensureProtocol()).isEqualTo("http://matrix.org")
}
@Test
fun `ensureProtocol keeps an uppercase scheme rather than double-prepending`() {
assertThat("HTTPS://matrix.org".ensureProtocol()).isEqualTo("HTTPS://matrix.org")
assertThat("Http://matrix.org".ensureProtocol()).isEqualTo("Http://matrix.org")
}
}