🔀 Merge branch 'release/v82'
[Sone.git] / src / test / kotlin / net / pterodactylus / sone / utils / OptionalsTest.kt
1 package net.pterodactylus.sone.utils
2
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
9 import org.junit.Test
10 import java.util.concurrent.atomic.AtomicBoolean
11
12 /**
13  * Test for [Optional] utils.
14  */
15 class OptionalsTest {
16
17         @Test
18         fun `present optional can be transformed with let`() {
19                 val optional = Optional.of(1)
20                 assertThat(optional.let { it + 1 }, equalTo(2))
21         }
22
23         @Test
24         fun `empty optional is transform to null with let`() {
25                 val optional = Optional.absent<Int>()
26                 assertThat(optional.let { it + 1 }, nullValue())
27         }
28
29         @Test
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))
34         }
35
36         @Test
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))
41         }
42
43         @Test
44         fun `1 as optional is correct optional`() {
45                 val optional = 1.asOptional()
46                 assertThat(optional.get(), equalTo(1))
47         }
48
49         @Test
50         fun `null as optional is absent optional`() {
51                 val optional = null.asOptional()
52                 assertThat(optional.isPresent, equalTo(false))
53         }
54
55         @Test
56         fun testMapPresent() {
57                 val originalList = listOf(1, 2, null, 3, null)
58                 assertThat(originalList.mapPresent { fromNullable(it) }, contains(1, 2, 3))
59         }
60
61 }