Skip to content

Commit

Permalink
Fix SelectorHelpers.computeAbsoluteUrl
Browse files Browse the repository at this point in the history
part of #1117
  • Loading branch information
Him188 committed Nov 15, 2024
1 parent 60b68b2 commit a306b65
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
package me.him188.ani.app.domain.mediasource.web.format

import androidx.compose.runtime.Immutable
import io.ktor.http.URLBuilder
import io.ktor.http.appendPathSegments
import kotlinx.serialization.Serializable
import kotlin.jvm.JvmInline

Expand Down Expand Up @@ -48,15 +50,8 @@ fun Regex.Companion.parseOrNull(regex: String): Regex? {

object SelectorHelpers {
fun computeAbsoluteUrl(baseUrl: String, relativeUrl: String): String {
@Suppress("NAME_SHADOWING")
var baseUrl = baseUrl
if (baseUrl.endsWith('/')) {
baseUrl = baseUrl.dropLast(1)
}
return when {
relativeUrl.startsWith("http") -> relativeUrl
relativeUrl.startsWith('/') -> baseUrl + relativeUrl
else -> "$baseUrl/$relativeUrl"
}
return URLBuilder(baseUrl)
.appendPathSegments(relativeUrl, encodeSlash = false)
.buildString()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/*
* Copyright (C) 2024 OpenAni and contributors.
*
* 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
* Use of this source code is governed by the GNU AGPLv3 license, which can be found at the following link.
*
* https://github.com/open-ani/ani/blob/main/LICENSE
*/

package me.him188.ani.app.domain.mediasource.web.format

import me.him188.ani.test.TestContainer
import me.him188.ani.test.TestFactory
import me.him188.ani.test.runDynamicTests
import kotlin.test.assertEquals

/**
* @see SelectorHelpers.computeAbsoluteUrl
*/
@TestContainer
class ComputeAbsoluteUrlTest {
@TestFactory
fun computeAbsoluteUrlTest() = runDynamicTests {
fun case(
expected: String,
baseUrl: String,
relativeUrl: String,
) = add("$baseUrl + $relativeUrl = $expected") {
assertEquals(
expected,
SelectorHelpers.computeAbsoluteUrl(baseUrl, relativeUrl),
)
}

case(
"https://example.com/relative",
"https://example.com", "relative",
)

case(
"https://example.com/relative",
"https://example.com", "/relative",
)

case(
"https://example.com/relative",
"https://example.com/", "/relative",
)

case(
"https://example.com/relative/",
"https://example.com/", "/relative/",
)

case(
"https://example.com/relative/foo",
"https://example.com/", "/relative/foo",
)

case(
"https://example.com/relative/foo/../bar",
"https://example.com/", "/relative/foo/../bar",
)

case(
"https://example.com/",
"https://example.com/", "",
)

case(
"http://localhost/",
"", "",
)

case(
"http://localhost/test",
"", "/test",
)

case(
"http://localhost/test",
"", "test",
)
}
}

0 comments on commit a306b65

Please sign in to comment.