Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit e5e2a9ba authored by cketti's avatar cketti
Browse files

Add `UriMatcher.isValidUri()`

parent 2985c670
Loading
Loading
Loading
Loading
+16 −0
Original line number Diff line number Diff line
@@ -31,4 +31,20 @@ object UriMatcher {
            parser.parseUri(text, startIndex)
        }.filterNotNull().toList()
    }

    @Suppress("ReturnCount")
    fun isValidUri(text: CharSequence): Boolean {
        val matchResult = URI_SCHEME.matchAt(text, 0) ?: return false

        val matchGroup = matchResult.groups[1]!!
        if (matchGroup.range.first != 0) {
            return false
        }

        val scheme = matchGroup.value.lowercase()
        val parser = SUPPORTED_URIS[scheme] ?: throw AssertionError("Scheme not found: $scheme")
        val uriMatch = parser.parseUri(text, startPos = 0) ?: return false

        return uriMatch.startIndex == 0 && uriMatch.endIndex == text.length
    }
}
+32 −0
Original line number Diff line number Diff line
package com.fsck.k9.message.html

import assertk.Assert
import assertk.assertThat
import assertk.assertions.hasSize
import assertk.assertions.isEmpty
import assertk.assertions.isEqualTo
import assertk.assertions.isFalse
import assertk.assertions.isNotEqualTo
import assertk.assertions.isTrue
import org.junit.Test

class UriMatcherTest {
@@ -82,6 +85,27 @@ class UriMatcherTest {
        )
    }

    @Test
    fun `valid URIs`() {
        assertThat("http://domain.example").isValidUri()
        assertThat("https://domain.example/").isValidUri()
        assertThat("mailto:user@domain.example").isValidUri()
    }

    @Test
    fun `not URIs`() {
        assertThat("some text here").isNotValidUri()
        assertThat("some text including the string http:").isNotValidUri()
        assertThat("some text including an email address without URI scheme: user@domain.example").isNotValidUri()
    }

    @Test
    fun `valid URIs surrounded by other characters`() {
        assertThat("text https://domain.example/").isNotValidUri()
        assertThat("https://domain.example/ text").isNotValidUri()
        assertThat("<https://domain.example/>").isNotValidUri()
    }

    private fun assertNoMatch(text: String) {
        val uriMatches = UriMatcher.findUris(text)
        assertThat(uriMatches).isEmpty()
@@ -104,3 +128,11 @@ class UriMatcherTest {
        }
    }
}

private fun Assert<String>.isValidUri() = given { actual ->
    assertThat(UriMatcher.isValidUri(actual)).isTrue()
}

private fun Assert<String>.isNotValidUri() = given { actual ->
    assertThat(UriMatcher.isValidUri(actual)).isFalse()
}