🔀 Merge “release/v81” into “master”
[Sone.git] / src / test / kotlin / net / pterodactylus / sone / web / notification / NotificationHandlerTester.kt
1 /**
2  * Sone - NotificationHandlerTester.kt - Copyright © 2019–2020 David ‘Bombe’ Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sone.web.notification
19
20 import com.google.common.eventbus.*
21 import net.pterodactylus.util.notify.*
22
23 /**
24  * Helper for testing event handlers that deal with notifications. It contains
25  * a notification manager and an [event bus][EventBus] and automatically
26  * registers the created handler on the event bus.
27  *
28  * ```
29  * val notification = SomeNotification()
30  * val notificationTester = NotificationTester { SomeHandler(it, notification) }
31  *
32  * fun test() {
33  *     notificationTester.sendEvent(SomeEvent())
34  *     assertThat(notificationTester.elements, hasItem(notification))
35  * }
36  * ```
37  */
38 @Suppress("UnstableApiUsage")
39 class NotificationHandlerTester(createHandler: (NotificationManager) -> Any) {
40
41         private val eventBus = EventBus()
42         private val notificationManager = NotificationManager()
43
44         /** Returns all notifications of the notification manager. */
45         val notifications: Set<Notification>
46                 get() = notificationManager.notifications
47
48         init {
49                 eventBus.register(createHandler(notificationManager))
50         }
51
52         /** Sends an event to the event bus. */
53         fun sendEvent(event: Any) = eventBus.post(event)
54
55         /** Sets the first-start notification on the notification manager. */
56         fun firstStart() = notificationManager.firstStart()
57
58 }