Skip to content

Commit

Permalink
Ensure close is called in all use cases (#1190)
Browse files Browse the repository at this point in the history
  • Loading branch information
yschimke committed Jan 5, 2023
1 parent f8434f5 commit bc7e735
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 7 deletions.
14 changes: 7 additions & 7 deletions okio/src/commonMain/kotlin/okio/Okio.kt
Expand Up @@ -56,13 +56,13 @@ inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {
result = block(this)
} catch (t: Throwable) {
thrown = t
}

try {
this?.close()
} catch (t: Throwable) {
if (thrown == null) thrown = t
else thrown.addSuppressed(t)
} finally {
try {
this?.close()
} catch (t: Throwable) {
if (thrown == null) thrown = t
else thrown.addSuppressed(t)
}
}

if (thrown != null) throw thrown
Expand Down
28 changes: 28 additions & 0 deletions okio/src/commonTest/kotlin/okio/UseTest.kt
@@ -0,0 +1,28 @@
package okio

import okio.Path.Companion.toPath
import okio.fakefilesystem.FakeFileSystem
import kotlin.test.Test

class UseTest {
val fakeFileSystem = FakeFileSystem(clock = FakeClock()).also { it.emulateUnix() }

val base = "/cache".toPath().also {
fakeFileSystem.createDirectories(it)
}

@Test
fun closesWithUseBlock() {
fun testMethodWithUse() {
val sink = fakeFileSystem.sink(base / "all-files-includes-file")

sink.use {
return@testMethodWithUse
}
}

testMethodWithUse()

fakeFileSystem.checkNoOpenFiles()
}
}

0 comments on commit bc7e735

Please sign in to comment.