ronantakizawa/codereview-bench huggingface dataset:
Repository: ktorio/ktor
File: ktor-client/ktor-client-core/jvm/test/FileStorageTest.kt (Kotlin)

Code before:
 * Copyright 2014-2025 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
 */

import io.ktor.client.plugins.cache.storage.*
import io.ktor.http.*
import io.ktor.util.date.*
import kotlinx.coroutines.*
import kotlin.io.path.*
import kotlin.test.*
import java.io.*

class FileStorageTest {
    private lateinit var tempDirectory: File

    @BeforeTest
    fun setUp() {
        tempDirectory = createTempDirectory().toFile()
    }

    @AfterTest
    fun tearDown() {
        tempDirectory.deleteRecursively()
    }

    @Test
    fun testFindAll(): Unit = runBlocking {
        val storage = FileStorage(tempDirectory)

        storage.store(Url("http://example.com"), data())
        storage.store(Url("http://example.com"), data(mapOf("key" to "value")))

        assertEquals(2, storage.findAll(Url("http://example.com")).size)
    }

    @Test
    fun testFind(): Unit = runBlocking {
        val storage = FileStorage(tempDirectory)

        storage.store(Url("http://example.com"), data())
        storage.store(Url("http://example.com"), data(mapOf("key" to "value")))

        assertNotNull(storage.find(Url("http://example.com"), mapOf("key" to "value")))
    }

    @Test
    fun testStore(): Unit = runBlocking {
        val storage = FileStorage(tempDirectory)
        storage.store(Url("http://example.com"), data())

        assertEquals(1, storage.findAll(Url("http://example.com")).size)


Review comment (suggestion):
Minor. Let's use `runTest` and explicit `Unit` can be removed then
```suggestion
    fun testFindAll() = runTest {
```

Code after:
 * Copyright 2014-2025 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
 */

import io.ktor.client.plugins.cache.storage.*
import io.ktor.http.*
import io.ktor.util.date.*
import kotlinx.coroutines.test.*
import java.io.*
import kotlin.io.path.*
import kotlin.test.*

class FileStorageTest {
    private lateinit var tempDirectory: File

    @BeforeTest
    fun setUp() {
        tempDirectory = createTempDirectory().toFile()
    }

    @AfterTest
    fun tearDown() {
        tempDirectory.deleteRecursively()
    }

    @Test
    fun testFindAll() = runTest {
        val storage = FileStorage(tempDirectory)

        storage.store(Url("http://example.com"), data())
        storage.store(Url("http://example.com"), data(mapOf("key" to "value")))

        assertEquals(2, storage.findAll(Url("http://example.com")).size)
    }

    @Test
    fun testFind() = runTest {
        val storage = FileStorage(tempDirectory)

        storage.store(Url("http://example.com"), data())
        storage.store(Url("http://example.com"), data(mapOf("key" to "value")))

        assertNotNull(storage.find(Url("http://example.com"), mapOf("key" to "value")))
    }

    @Test
    fun testStore() = runTest {
        val storage = FileStorage(tempDirectory)
        storage.store(Url("http://example.com"), data())

        assertEquals(1, storage.findAll(Url("http://example.com")).size)
Repository: ktorio/ktor
File: ktor-network/common/test/io/ktor/network/sockets/tests/InetSocketAddressTest.kt (Kotlin)

Code before:
 * Copyright 2014-2025 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
 */

package io.ktor.network.sockets.tests

import io.ktor.network.sockets.*
import io.ktor.util.*
import kotlin.test.Test
import kotlin.test.assertContentEquals

class InetSocketAddressTest {
    @Test
    fun testResolveAddress() {
        // Address resolving is not supported on JS and WASM platforms
        if (PlatformUtils.IS_JS || PlatformUtils.IS_WASM_JS) return

        val testCases = listOf(
            "127.0.0.1" to byteArrayOf(127, 0, 0, 1),
            "::1" to byteArrayOf(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1),
        )

        for ((hostname, expectedBytes) in testCases) {
            val address = InetSocketAddress(hostname, 8080)
            val resolved = address.resolveAddress()
            assertContentEquals(expectedBytes, resolved, "Unexpected bytes for $hostname")
        }
    }
}


Review comment (bug):
Test failed on macOS:
> kotlin.AssertionError: Unexpected bytes for address '::1'. Array elements differ at index 0. Expected element <0>, actual element <7>.
Expected <[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]>, actual <[7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]>.

I can reproduce this problem locally and the resolved address is always consists one or two random bytes followed by zeroes. `ipString` returns `700::`, and Linux tests pass, so the problem is unlikely in the way I'm getting bytes.
@e5l, @bjhham, do you have any idea why `::1` is resolved to a random address on macOS?

Code after:
 * Copyright 2014-2025 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
 */

package io.ktor.network.sockets.tests

import io.ktor.network.sockets.*
import io.ktor.util.*
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertContentEquals

class InetSocketAddressTest {

    @BeforeTest
    fun setUp() {
        initSocketsIfNeeded()
    }

    @Test
    fun testResolveAddress() {
        // Address resolving is not supported on JS and WASM platforms
        if (PlatformUtils.IS_JS || PlatformUtils.IS_WASM_JS) return

        val testCases = listOf(
            "127.0.0.1" to byteArrayOf(127, 0, 0, 1),
            "::1" to byteArrayOf(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1),
        )

        for ((hostname, expectedBytes) in testCases) {
            val address = InetSocketAddress(hostname, 8080)
            val resolved = address.resolveAddress()
            assertContentEquals(expectedBytes, resolved, "Unexpected bytes for the address '$hostname'")
        }
    }
}
Repository: ktorio/ktor
File: ktor-server/ktor-server-plugins/ktor-server-cors/common/src/io/ktor/server/plugins/cors/routing/CORS.kt (Kotlin)

Code before:
 */

package io.ktor.server.plugins.cors.routing

import io.ktor.server.application.*
import io.ktor.server.plugins.cors.*

/**
 * A plugin that allows you to configure handling cross-origin requests.
 * This plugin allows you to configure allowed hosts, HTTP methods, headers set by the client, and so on.
 *
 * The configuration below allows requests from the specified address and allows sending the `Content-Type` header:
 * ```kotlin
 * install(CORS) {
 *     host("0.0.0.0:8081")
 *     header(HttpHeaders.ContentType)
 * }
 * ```
 *
 * You can learn more from [CORS](https://ktor.io/docs/cors.html).
 *
 * [Report a problem](https://ktor.io/feedback/?fqname=io.ktor.server.plugins.cors.routing.CORS)
 */

@Deprecated(
    message = "The plugin installation has been moved to the Route.cors method",
    level = DeprecationLevel.WARNING,
)
public val CORS: RouteScopedPlugin<CORSConfig> = createRouteScopedPlugin("CORS", ::CORSConfig) {
    buildPlugin()
}

internal val commonCORS: RouteScopedPlugin<CORSConfig> = createRouteScopedPlugin("CORS", ::CORSConfig) {
    buildPlugin()
}


Review comment (suggestion):
let's explain the difference between `install(CORS)` and `cors {}` in the API docs for the both symbols

Code after:
 */

package io.ktor.server.plugins.cors.routing

import io.ktor.server.application.*
import io.ktor.server.plugins.cors.*
import io.ktor.server.routing.options

/**
 * A plugin that allows you to configure handling cross-origin requests.
 * This plugin allows you to configure allowed hosts, HTTP methods, headers set by the client, and so on.
 *
 * The configuration below allows requests from the specified address and allows sending the `Content-Type` header:
 * ```kotlin
 * install(CORS) {
 *     host("0.0.0.0:8081")
 *     header(HttpHeaders.ContentType)
 * }
 * ```
 *
 * You can learn more from [CORS](https://ktor.io/docs/cors.html).
 *
 * [Report a problem](https://ktor.io/feedback/?fqname=io.ktor.server.plugins.cors.routing.CORS)
 */
public val CORS: RouteScopedPlugin<CORSConfig> = createRouteScopedPlugin("CORS", ::CORSConfig) {
    route?.options("{cors-options-wildcard...}") {
        // Handled by an interceptor of the Call phase added in the plugin
    }

    buildPlugin()
}
Repository: ktorio/ktor
File: ktor-client/ktor-client-cio/jvm/src/io/ktor/client/engine/cio/Proxy.jvm.kt (Kotlin)

Code before:
/*
 * Copyright 2014-2025 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
 */

package io.ktor.client.engine.cio

import io.ktor.client.engine.ProxyConfig
import java.net.InetSocketAddress
import java.net.Proxy

internal actual fun discoverHttpProxy(): ProxyConfig? {
    var proxy: Proxy? = null

    try {
        // For Android
        val host = System.getProperty("http.proxyHost")
        val port = System.getProperty("http.proxyPort")?.toIntOrNull() ?: 0

        if (host != null && host.isNotEmpty()) {
            proxy = Proxy(Proxy.Type.HTTP, InetSocketAddress(host, port))
        }
    } catch (_: SecurityException) {
    }

    return proxy
}


Review comment (suggestion):
I guess we should rely on `ProxySelector.getDefault()` instead. There is more sophisticated logic to determine proxy host and port (see `sun.net.spi.DefaultProxySelector`).
This would require requesting a new proxy for each URL, but it doesn't seem a problem here.

Code after:
/*
 * Copyright 2014-2025 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
 */

package io.ktor.client.engine.cio

import io.ktor.client.engine.ProxyConfig
import io.ktor.http.Url
import io.ktor.http.toURI
import java.net.Proxy
import java.net.ProxySelector
import java.net.URISyntaxException

internal actual fun lookupGlobalProxy(url: Url): ProxyConfig? {
    val url = try {
        url.toURI()
    } catch (_: URISyntaxException) {
        null
    }

    if (url == null) {
        return null
    }

    val proxies = ProxySelector.getDefault().select(url)

    return if (proxies.isNotEmpty()) {
        val proxy = proxies.first()

        // When no proxy is available, the list will contain one element with type DIRECT
        if (proxies.size == 1 && proxy.type() == Proxy.Type.DIRECT) {
            null
        } else {
            proxy
        }
    } else {
        null
    }
}
Repository: ktorio/ktor
File: ktor-client/ktor-client-cio/jvm/src/io/ktor/client/engine/cio/Proxy.jvm.kt (Kotlin)

Code before:
/*
 * Copyright 2014-2025 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
 */

package io.ktor.client.engine.cio

import io.ktor.client.engine.ProxyConfig
import io.ktor.http.Url
import io.ktor.http.toURI
import java.net.Proxy
import java.net.ProxySelector

internal actual fun lookupGlobalProxy(url: Url): ProxyConfig? {
    val proxies = ProxySelector.getDefault().select(url.toURI())

    return if (proxies.isNotEmpty()) {
        val proxy = proxies.first()

        if (proxies.size == 1 && proxy.type() == Proxy.Type.DIRECT) {
            null
        } else {
            proxies.first()
        }
    } else {
        null
    }
}


Review comment (suggestion):
A comment clarifying the purpose of this `if` would be helpful. As now it is not clear without reading `ProxySelector.select(...)` documentation

Code after:

import io.ktor.client.engine.ProxyConfig
import io.ktor.http.Url
import io.ktor.http.toURI
import java.net.Proxy
import java.net.ProxySelector
import java.net.URISyntaxException

internal actual fun lookupGlobalProxy(url: Url): ProxyConfig? {
    val url = try {
        url.toURI()
    } catch (_: URISyntaxException) {
        null
    }

    if (url == null) {
        return null
    }

    val proxies = ProxySelector.getDefault().select(url)

    return if (proxies.isNotEmpty()) {
        val proxy = proxies.first()

        // When no proxy is available, the list will contain one element with type DIRECT
        if (proxies.size == 1 && proxy.type() == Proxy.Type.DIRECT) {
            null
        } else {
            proxy
        }
    } else {
        null
    }
}
Repository: ktorio/ktor
File: ktor-server/ktor-server-tests/common/test/io/ktor/tests/server/plugins/ConditionalHeadersTests.kt (Kotlin)

Code before:
    }

    @Test
    fun testIfMatchListConditionAccepted() = withConditionalApplication {
        val result = client.get {
            header(HttpHeaders.IfMatch, "tag0,tag1,tag3")
        }
        assertEquals(HttpStatusCode.OK, result.status)
        assertEquals("response", result.bodyAsText())
        assertEquals("\"tag1\"", result.headers[HttpHeaders.ETag])
    }

    @Test
    fun testIfMatchListConditionFailed() = withConditionalApplication {
        val result = client.get {
            header(HttpHeaders.IfMatch, "tag0,tag2,tag3")
        }
        assertEquals(HttpStatusCode.PreconditionFailed, result.status)
    }

    @Test
    fun testInvalidWeakStarETag() = withConditionalApplication {
        assertFailsWith<IllegalArgumentException> {
            EntityTagVersion(EntityTagVersion.STAR.etag, weak = true)
        }
    }
}


Review comment (bug):
Minor. Probably `withConditionalApplication` can be removed
```suggestion
    fun testInvalidWeakStarETag() {
        assertFailsWith<IllegalArgumentException> {
            EntityTagVersion(EntityTagVersion.STAR.etag, weak = true)
        }
    }
```

Code after:
    }

    @Test
    fun testIfMatchListConditionAccepted() = withConditionalApplication {
        val result = client.get {
            header(HttpHeaders.IfMatch, "tag0,tag1,tag3")
        }
        assertEquals(HttpStatusCode.OK, result.status)
        assertEquals("response", result.bodyAsText())
        assertEquals("\"tag1\"", result.headers[HttpHeaders.ETag])
    }

    @Test
    fun testIfMatchListConditionFailed() = withConditionalApplication {
        val result = client.get {
            header(HttpHeaders.IfMatch, "tag0,tag2,tag3")
        }
        assertEquals(HttpStatusCode.PreconditionFailed, result.status)
    }

    @Test
    fun testInvalidWeakStarETag() {
        assertFailsWith<IllegalArgumentException> {
            EntityTagVersion(EntityTagVersion.STAR.etag, weak = true)
        }
    }
}
Repository: ktorio/ktor
File: ktor-client/ktor-client-darwin/darwin/src/io/ktor/client/engine/darwin/ProxySupportCommon.kt (Kotlin)

Code before:
private const val HTTP_PORT_KEY = "HTTPPort"
private const val SOCKS_ENABLE_KEY = "SOCKSEnable"
private const val SOCKS_PROXY_KEY = "SOCKSProxy"
private const val SOCKS_PORT_KEY = "SOCKSPort"

internal fun NSURLSessionConfiguration.setupProxy(config: DarwinClientEngineConfig) {
    val proxy = config.proxy ?: return
    val url = proxy.url

    when (url.protocol) {
        URLProtocol.HTTP -> setupHttpProxy(url)
        URLProtocol.HTTPS -> setupHttpProxy(url)
        URLProtocol.SOCKS -> setupSocksProxy(url)
        else -> error("Proxy type ${url.protocol.name} is unsupported by Darwin client engine.")
    }
}

internal fun NSURLSessionConfiguration.setupHttpProxy(url: Url) {
    connectionProxyDictionary = mapOf<Any?, Any?>(
        HTTP_ENABLE_KEY to 1,
        HTTP_PROXY_KEY to url.host,
        HTTP_PORT_KEY to url.port
    )
}

internal fun NSURLSessionConfiguration.setupSocksProxy(url: Url) {
    connectionProxyDictionary = mapOf<Any?, Any?>(
        SOCKS_ENABLE_KEY to 1,
        SOCKS_PROXY_KEY to url.host,
        SOCKS_PORT_KEY to url.port
    )
}


Review comment (suggestion):
Can be `private`? And could you also change the visibility of `setupHttpProxy`?
```suggestion
private fun NSURLSessionConfiguration.setupSocksProxy(url: Url) {
```

Code after:
private const val HTTP_PORT_KEY = "HTTPPort"
private const val SOCKS_ENABLE_KEY = "SOCKSEnable"
private const val SOCKS_PROXY_KEY = "SOCKSProxy"
private const val SOCKS_PORT_KEY = "SOCKSPort"

internal fun NSURLSessionConfiguration.setupProxy(config: DarwinClientEngineConfig) {
    val proxy = config.proxy ?: return
    val url = proxy.url

    when (url.protocol) {
        URLProtocol.HTTP -> setupHttpProxy(url)
        URLProtocol.HTTPS -> setupHttpProxy(url)
        URLProtocol.SOCKS -> setupSocksProxy(url)
        else -> error("Proxy type ${url.protocol.name} is unsupported by Darwin client engine.")
    }
}

private fun NSURLSessionConfiguration.setupHttpProxy(url: Url) {
    connectionProxyDictionary = mapOf<Any?, Any?>(
        HTTP_ENABLE_KEY to 1,
        HTTP_PROXY_KEY to url.host,
        HTTP_PORT_KEY to url.port
    )
}

private fun NSURLSessionConfiguration.setupSocksProxy(url: Url) {
    connectionProxyDictionary = mapOf<Any?, Any?>(
        SOCKS_ENABLE_KEY to 1,
        SOCKS_PROXY_KEY to url.host,
        SOCKS_PORT_KEY to url.port
    )
}
Repository: ktorio/ktor
File: ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/ProxyTest.kt (Kotlin)

Code before:
        test { client ->
            val response = client.get("http://google.com").body<String>()
            assertEquals("proxy", response)
        }
    }

    @Test
    fun testProxyWithSerialization() = clientTests(except("Js", "web:CIO")) {
        config {
            engine {
                proxy = ProxyBuilder.http(TCP_SERVER)
            }

            install(ContentNegotiation) { json() }
        }

        test { client ->
            val response = client.get("http://google.com/json").body<ProxyResponse>()
            val expected = ProxyResponse("ok")

            assertEquals(expected, response)
        }
    }

    @Test
    fun testSocksProxy() = clientTests(except("Js", "Darwin", "DarwinLegacy", "CIO", "Apache", "Apache5", "Java")) {
        config {
            engine {
                proxy = ProxyBuilder.socks("127.0.0.1", 8083)
            }
        }

        test { client ->
            val response = client.get("http://google.com").body<String>()
            assertEquals("proxy", response)
        }
    }
}


Review comment (suggestion):
@wodoro, you will need to remove `"Darwin"` from the list to enable this test.

Code after:
        test { client ->
            val response = client.get("http://google.com").body<String>()
            assertEquals("proxy", response)
        }
    }

    @Test
    fun testProxyWithSerialization() = clientTests(except("Js", "web:CIO")) {
        config {
            engine {
                proxy = ProxyBuilder.http(TCP_SERVER)
            }

            install(ContentNegotiation) { json() }
        }

        test { client ->
            val response = client.get("http://google.com/json").body<ProxyResponse>()
            val expected = ProxyResponse("ok")

            assertEquals(expected, response)
        }
    }

    @Test
    fun testSocksProxy() = clientTests(
        except("Js", "Darwin", "DarwinLegacy", "WinHttp", "CIO", "Apache", "Apache5", "Java")
    ) {
        config {
            engine {
                proxy = ProxyBuilder.socks("127.0.0.1", 8083)
            }
        }

        test { client ->
            val response = client.get("http://google.com").body<String>()
            assertEquals("proxy", response)
        }
    }
}
Repository: ktorio/ktor
File: build-logic/src/main/kotlin/ktorbuild.optional.cocoapods.gradle.kts (Kotlin)

Code before:
        apply(plugin = COCOAPODS_PLUGIN_ID)
    } else @Suppress("UnstableApiUsage") {
        // Disable Darwin targets if CocoaPods is not available
        ktorBuild.targets["darwin"] = false

        val problemReporter = project.serviceOf<Problems>().reporter
        problemReporter.reportVisible(
            KtorBuildProblems.missingCocoaPods,
            details = "CocoaPods not found.",
            contextualLabel = "Apple targets won't be added in the project.",
        ) {
            solution("Install CocoaPods")
            solution("Ensure 'pod' command is available in PATH")
            buildFileLocation()
            documentedAt("https://github.com/ktorio/ktor/blob/main/CONTRIBUTING.md#building-the-project")
        }
    }
}

internal abstract class CocoaPodsAvailableValueSource @Inject constructor(
    val execOperations: ExecOperations,
) : ValueSource<Boolean, ValueSourceParameters.None> {

    override fun obtain(): Boolean {
        val result = execOperations.exec {
            commandLine("which", "pod")
            isIgnoreExitValue = true
        }

        return result.exitValue == 0
    }
}


Review comment (suggestion):
By default, gradle prints the output of the command to stdin, so the output is just location.
I'd suggest printing it like this:
```
val outputBuffer = ByteArrayOutputStream()
val result = execOperations.exec {
     commandLine("which", "pod")
     standardOutput = outputBuffer
     isIgnoreExitValue = true
}
println("Resolved CocoaPods location: ${outputBuffer.toString().trim()}")
```
Or disable output with `standardOutput = OutputStream.nullOutputStream()`




Code after:
    if (!HostManager.hostIsMac || cocoaPodsAvailable.get()) {
        apply(plugin = COCOAPODS_PLUGIN_ID)
    } else @Suppress("UnstableApiUsage") {
        // Disable Darwin targets if CocoaPods is not available
        ktorBuild.targets["darwin"] = false

        val problemReporter = project.serviceOf<Problems>().reporter
        problemReporter.reportVisible(
            KtorBuildProblems.missingCocoaPods,
            details = "CocoaPods not found.",
            contextualLabel = "Apple targets won't be added in the project.",
        ) {
            solution("Install CocoaPods")
            solution("Ensure 'pod' command is available in PATH")
            buildFileLocation()
            documentedAt("https://github.com/ktorio/ktor/blob/main/CONTRIBUTING.md#building-the-project")
        }
    }
}

internal abstract class CocoaPodsAvailableValueSource @Inject constructor(
    val execOperations: ExecOperations,
) : ValueSource<Boolean, ValueSourceParameters.None> {

    override fun obtain(): Boolean {
        val result = execOperations.exec {
            commandLine("which", "pod")
            isIgnoreExitValue = true
            standardOutput = OutputStream.nullOutputStream()
            errorOutput = OutputStream.nullOutputStream()
        }

        return result.exitValue == 0
    }
}