waft_test/
notifications.rs1use std::cell::RefCell;
5use std::rc::Rc;
6use std::time::SystemTime;
7
8use waft_embedder::{
9 Notification, NotificationError, NotificationPermission, NotificationReplies,
10 NotificationScheduling, Notifications, PermissionFuture, PermissionState, PostFuture,
11};
12
13#[derive(Clone)]
17pub struct MockNotifications(Rc<NotificationsState>);
18
19struct NotificationsState {
20 shown: RefCell<Vec<Notification>>,
21 scheduled: RefCell<Vec<(Notification, SystemTime)>>,
22 permission: Option<MockPermission>,
24 replies: bool,
25 scheduling: bool,
26}
27
28impl Default for MockNotifications {
29 fn default() -> MockNotifications {
30 MockNotifications(Rc::new(NotificationsState {
31 shown: RefCell::default(),
32 scheduled: RefCell::default(),
33 permission: None,
34 replies: true,
35 scheduling: true,
36 }))
37 }
38}
39
40struct MockPermission {
42 state: RefCell<PermissionState>,
43 answer: PermissionState,
44 asked: RefCell<u32>,
45}
46
47impl MockNotifications {
48 pub fn new() -> MockNotifications {
49 MockNotifications::default()
50 }
51
52 pub fn asking(self, state: PermissionState, answer: PermissionState) -> MockNotifications {
56 self.rebuilt(|notifications| {
57 notifications.permission = Some(MockPermission {
58 state: RefCell::new(state),
59 answer,
60 asked: RefCell::new(0),
61 });
62 })
63 }
64
65 pub fn without_replies(self) -> MockNotifications {
67 self.rebuilt(|notifications| notifications.replies = false)
68 }
69
70 pub fn without_scheduling(self) -> MockNotifications {
72 self.rebuilt(|notifications| notifications.scheduling = false)
73 }
74
75 pub fn shown(&self) -> Vec<Notification> {
77 self.0.shown.borrow().clone()
78 }
79
80 pub fn scheduled(&self) -> Vec<(Notification, SystemTime)> {
82 self.0.scheduled.borrow().clone()
83 }
84
85 pub fn times_asked(&self) -> u32 {
87 self.0
88 .permission
89 .as_ref()
90 .map_or(0, |permission| *permission.asked.borrow())
91 }
92
93 fn rebuilt(self, change: impl FnOnce(&mut NotificationsState)) -> MockNotifications {
94 let mut state = Rc::try_unwrap(self.0)
95 .unwrap_or_else(|_| panic!("configure MockNotifications before cloning it"));
96 change(&mut state);
97 MockNotifications(Rc::new(state))
98 }
99
100 fn allowed(&self) -> Result<(), NotificationError> {
103 let state = self
104 .0
105 .permission
106 .as_ref()
107 .map(|permission| *permission.state.borrow());
108 match state {
109 None | Some(PermissionState::Granted) => Ok(()),
110 Some(_) => Err(NotificationError::Denied),
111 }
112 }
113}
114
115impl MockPermission {
116 fn ask(&self) -> PermissionState {
117 let mut state = self.state.borrow_mut();
118 if *state == PermissionState::NotAsked {
119 *self.asked.borrow_mut() += 1;
120 *state = self.answer;
121 }
122 *state
123 }
124}
125
126fn replace(list: &mut Vec<Notification>, notification: &Notification) {
128 match list.iter_mut().find(|shown| shown.id == notification.id) {
129 Some(shown) => *shown = notification.clone(),
130 None => list.push(notification.clone()),
131 }
132}
133
134impl Notifications for MockNotifications {
135 fn post(&self, notification: &Notification) -> PostFuture {
136 let posted = self.allowed().map(|()| {
137 self.0
138 .scheduled
139 .borrow_mut()
140 .retain(|(scheduled, _)| scheduled.id != notification.id);
141 replace(&mut self.0.shown.borrow_mut(), notification);
142 });
143 Box::pin(std::future::ready(posted))
144 }
145
146 fn remove(&self, id: &str) {
147 self.0.shown.borrow_mut().retain(|shown| shown.id != id);
148 self.0
149 .scheduled
150 .borrow_mut()
151 .retain(|(scheduled, _)| scheduled.id != id);
152 }
153
154 fn permission(&self) -> Option<&dyn NotificationPermission> {
155 self.0.permission.is_some().then_some(self)
156 }
157
158 fn replies(&self) -> Option<&dyn NotificationReplies> {
159 self.0.replies.then_some(self)
160 }
161
162 fn scheduling(&self) -> Option<&dyn NotificationScheduling> {
163 self.0.scheduling.then_some(self)
164 }
165}
166
167impl NotificationPermission for MockNotifications {
168 fn state(&self) -> PermissionFuture {
169 let state = self
170 .0
171 .permission
172 .as_ref()
173 .map_or(PermissionState::Granted, |permission| {
174 *permission.state.borrow()
175 });
176 Box::pin(std::future::ready(state))
177 }
178
179 fn request(&self) -> PermissionFuture {
180 let state = self
181 .0
182 .permission
183 .as_ref()
184 .map_or(PermissionState::Granted, MockPermission::ask);
185 Box::pin(std::future::ready(state))
186 }
187}
188
189impl NotificationReplies for MockNotifications {}
190
191impl NotificationScheduling for MockNotifications {
192 fn schedule(&self, notification: &Notification, at: SystemTime) -> PostFuture {
193 let scheduled = self.allowed().map(|()| {
194 let mut scheduled = self.0.scheduled.borrow_mut();
195 scheduled.retain(|(waiting, _)| waiting.id != notification.id);
196 scheduled.push((notification.clone(), at));
197 });
198 Box::pin(std::future::ready(scheduled))
199 }
200}
201
202#[cfg(test)]
203mod tests {
204 use std::task::{Context, Poll, Waker};
205 use std::time::Duration;
206
207 use super::*;
208
209 fn now<T>(future: std::pin::Pin<Box<dyn std::future::Future<Output = T>>>) -> T {
210 let mut future = future;
211 match future
212 .as_mut()
213 .poll(&mut Context::from_waker(Waker::noop()))
214 {
215 Poll::Ready(value) => value,
216 Poll::Pending => panic!("the mock answers at once"),
217 }
218 }
219
220 #[test]
221 fn a_post_under_an_id_replaces_and_remove_takes_it_away() {
222 let notifications = MockNotifications::new();
223 let mut first = Notification::new("download", "Downloading");
224 assert_eq!(now(notifications.post(&first)), Ok(()));
225 first.title = "Downloaded".to_owned();
226 assert_eq!(now(notifications.post(&first)), Ok(()));
227 assert_eq!(notifications.shown(), [first]);
228 notifications.remove("download");
229 assert!(notifications.shown().is_empty());
230 }
231
232 #[test]
233 fn a_post_never_asks_and_is_denied_until_the_user_allows() {
234 let notifications =
235 MockNotifications::new().asking(PermissionState::NotAsked, PermissionState::Granted);
236 let reminder = Notification::new("reminder", "Stand up");
237 assert_eq!(
238 now(notifications.post(&reminder)),
239 Err(NotificationError::Denied)
240 );
241 let at = SystemTime::UNIX_EPOCH + Duration::from_secs(60);
242 let scheduling = notifications.scheduling().expect("scheduling");
243 assert_eq!(
244 now(scheduling.schedule(&reminder, at)),
245 Err(NotificationError::Denied)
246 );
247 assert_eq!(notifications.times_asked(), 0, "no post asked");
248 let permission = notifications.permission().expect("the system asks");
249 assert_eq!(now(permission.request()), PermissionState::Granted);
250 assert_eq!(now(notifications.post(&reminder)), Ok(()));
251 assert_eq!(notifications.times_asked(), 1);
252 }
253
254 #[test]
255 fn a_refusal_is_asked_once() {
256 let notifications =
257 MockNotifications::new().asking(PermissionState::NotAsked, PermissionState::Denied);
258 let permission = notifications.permission().expect("the system asks");
259 assert_eq!(now(permission.request()), PermissionState::Denied);
260 assert_eq!(now(permission.request()), PermissionState::Denied);
261 assert_eq!(notifications.times_asked(), 1);
262 assert_eq!(
263 now(notifications.post(&Notification::new("reminder", "Stand up"))),
264 Err(NotificationError::Denied)
265 );
266 }
267
268 #[test]
269 fn a_schedule_waits_until_a_post_or_a_remove() {
270 let notifications = MockNotifications::new();
271 let at = SystemTime::UNIX_EPOCH + Duration::from_secs(60);
272 let reminder = Notification::new("reminder", "Stand up");
273 let scheduling = notifications.scheduling().expect("scheduling");
274 assert_eq!(now(scheduling.schedule(&reminder, at)), Ok(()));
275 assert_eq!(notifications.scheduled(), [(reminder.clone(), at)]);
276 notifications.remove("reminder");
277 assert!(notifications.scheduled().is_empty());
278 assert!(
279 MockNotifications::new()
280 .without_scheduling()
281 .scheduling()
282 .is_none()
283 );
284 }
285}