From c3a5dfacd98ca8190b266ac0652cbba93423a7c7 Mon Sep 17 00:00:00 2001 From: =?utf8?q?David=20=E2=80=98Bombe=E2=80=99=20Roden?= Date: Sun, 4 Jun 2017 19:11:04 +0200 Subject: [PATCH] Add utilities for Freenet buckets --- .../kotlin/net/pterodactylus/sone/utils/Buckets.kt | 9 ++++++ .../net/pterodactylus/sone/utils/BucketsTest.kt | 34 ++++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 src/main/kotlin/net/pterodactylus/sone/utils/Buckets.kt create mode 100644 src/test/kotlin/net/pterodactylus/sone/utils/BucketsTest.kt diff --git a/src/main/kotlin/net/pterodactylus/sone/utils/Buckets.kt b/src/main/kotlin/net/pterodactylus/sone/utils/Buckets.kt new file mode 100644 index 0000000..99924ad --- /dev/null +++ b/src/main/kotlin/net/pterodactylus/sone/utils/Buckets.kt @@ -0,0 +1,9 @@ +package net.pterodactylus.sone.utils + +import freenet.support.api.Bucket + +fun Bucket.use(block: (Bucket) -> R): R = try { + block(this) +} finally { + free() +} diff --git a/src/test/kotlin/net/pterodactylus/sone/utils/BucketsTest.kt b/src/test/kotlin/net/pterodactylus/sone/utils/BucketsTest.kt new file mode 100644 index 0000000..a17bdd2 --- /dev/null +++ b/src/test/kotlin/net/pterodactylus/sone/utils/BucketsTest.kt @@ -0,0 +1,34 @@ +package net.pterodactylus.sone.utils + +import freenet.support.api.Bucket +import net.pterodactylus.sone.test.mock +import org.junit.Test +import org.mockito.Mockito.verify +import kotlin.test.fail + +/** + * Unit test for [freenet.support.api.Bucket]-related utilities. + */ +class BucketsTest { + + private val bucket = mock() + + @Test + fun `bucket is freed after use without exception`() { + bucket.use { } + verify(bucket).free() + } + + @Test + fun `bucket is freed after use with exceptions`() { + try { + bucket.use { throw Exception() } + @Suppress("UNREACHABLE_CODE") + fail() + } catch (e: Exception) { + } finally { + verify(bucket).free() + } + } + +} -- 2.7.4