Add utilities for Freenet buckets
authorDavid ‘Bombe’ Roden <bombe@pterodactylus.net>
Sun, 4 Jun 2017 17:11:04 +0000 (19:11 +0200)
committerDavid ‘Bombe’ Roden <bombe@pterodactylus.net>
Sun, 4 Jun 2017 17:11:04 +0000 (19:11 +0200)
src/main/kotlin/net/pterodactylus/sone/utils/Buckets.kt [new file with mode: 0644]
src/test/kotlin/net/pterodactylus/sone/utils/BucketsTest.kt [new file with mode: 0644]

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 (file)
index 0000000..99924ad
--- /dev/null
@@ -0,0 +1,9 @@
+package net.pterodactylus.sone.utils
+
+import freenet.support.api.Bucket
+
+fun <R> 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 (file)
index 0000000..a17bdd2
--- /dev/null
@@ -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<Bucket>()
+
+       @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()
+               }
+       }
+
+}