1 package net.pterodactylus.sone.utils
3 import com.google.common.base.Optional
4 import com.google.common.base.Optional.fromNullable
5 import org.hamcrest.MatcherAssert.assertThat
6 import org.hamcrest.Matchers.contains
7 import org.hamcrest.Matchers.equalTo
8 import org.hamcrest.Matchers.nullValue
10 import java.util.concurrent.atomic.AtomicBoolean
13 * Test for [Optional] utils.
18 fun `present optional can be transformed with let`() {
19 val optional = Optional.of(1)
20 assertThat(optional.let { it + 1 }, equalTo(2))
24 fun `empty optional is transform to null with let`() {
25 val optional = Optional.absent<Int>()
26 assertThat(optional.let { it + 1 }, nullValue())
30 fun `present optional can be processed with also`() {
31 val called = AtomicBoolean(false)
32 Optional.of(1).also { if (it == 1) called.set(true) }
33 assertThat(called.get(), equalTo(true))
37 fun `absent optional is not processed with also`() {
38 val called = AtomicBoolean(false)
39 Optional.absent<Int>().also { called.set(true) }
40 assertThat(called.get(), equalTo(false))
44 fun `1 as optional is correct optional`() {
45 val optional = 1.asOptional()
46 assertThat(optional.get(), equalTo(1))
50 fun `null as optional is asent optional`() {
51 val optional = null.asOptional()
52 assertThat(optional.isPresent, equalTo(false))
56 fun testMapPresent() {
57 val originalList = listOf(1, 2, null, 3, null)
58 assertThat(originalList.mapPresent { fromNullable(it) }, contains(1, 2, 3))