Skip to main content

tilo_notify/
conformance.rs

1//! The contract every [`Notifier`] keeps, as checks a backend's tests run, plus a
2//! [`Recording`] notifier.
3//!
4//! The checks send only requests the contract says must fail before the platform
5//! sees them, so they run headless against the real backends; a violation panics
6//! with the rule.
7#![allow(
8    clippy::panic,
9    clippy::missing_panics_doc,
10    reason = "a conformance check fails by panicking with the violated rule"
11)]
12
13use std::sync::Mutex;
14
15use crate::{Feature, Notification, Notifier, NotifyError, Scheduled, SystemTime, availability};
16
17pub fn check_contract(notifier: &dyn Notifier) {
18    for (label, malformed) in [
19        ("an empty tag", Notification::new("", "Title", "Body")),
20        ("an empty title", Notification::new("tag", " ", "Body")),
21        (
22            "a control character",
23            Notification::new("t\nag", "Title", ""),
24        ),
25    ] {
26        assert!(
27            matches!(
28                notifier.show(&malformed),
29                Err(NotifyError::Invalid(_) | NotifyError::Unavailable)
30            ),
31            "{label} must be refused before the platform"
32        );
33    }
34    assert!(
35        matches!(
36            notifier.withdraw(""),
37            Err(NotifyError::Invalid(_) | NotifyError::Unavailable)
38        ),
39        "withdrawing an empty tag must be refused"
40    );
41    assert!(
42        notifier
43            .schedule(&Notification::new("", "Title", ""), SystemTime::UNIX_EPOCH)
44            .is_err(),
45        "a malformed schedule must be refused"
46    );
47}
48
49/// [`check_contract`] for this target's [`system`](crate::system) backend, which
50/// also answers `Unsupported` for scheduling where the target's column says so.
51pub fn check_system(notifier: &dyn Notifier) {
52    check_contract(notifier);
53    let unsupported = matches!(
54        availability(Feature::Schedule),
55        crate::Availability::Unsupported(_)
56    );
57    match notifier.schedule(&Notification::new("", "Title", ""), SystemTime::UNIX_EPOCH) {
58        Err(NotifyError::Unsupported(_)) => {}
59        Err(NotifyError::Invalid(_) | NotifyError::Unavailable) => assert!(
60            !unsupported,
61            "this target cannot schedule, so it must say Unsupported"
62        ),
63        other => panic!("a malformed schedule must be refused, got {other:?}"),
64    }
65}
66
67#[derive(Default)]
68pub struct Recording {
69    log: Mutex<RecordingLog>,
70}
71
72#[derive(Default)]
73struct RecordingLog {
74    shown: Vec<Notification>,
75    withdrawn: Vec<String>,
76    scheduled: Vec<(Notification, SystemTime)>,
77}
78
79impl Recording {
80    pub fn shown(&self) -> Vec<Notification> {
81        self.log
82            .lock()
83            .map(|log| log.shown.clone())
84            .unwrap_or_default()
85    }
86
87    pub fn withdrawn(&self) -> Vec<String> {
88        self.log
89            .lock()
90            .map(|log| log.withdrawn.clone())
91            .unwrap_or_default()
92    }
93}
94
95impl Notifier for Recording {
96    fn show(&self, notification: &Notification) -> Result<(), NotifyError> {
97        crate::validate(notification)?;
98        if let Ok(mut log) = self.log.lock() {
99            log.shown.push(notification.clone());
100        }
101        Ok(())
102    }
103
104    fn withdraw(&self, tag: &str) -> Result<(), NotifyError> {
105        crate::validate_tag(tag)?;
106        if let Ok(mut log) = self.log.lock() {
107            log.withdrawn.push(tag.to_owned());
108        }
109        Ok(())
110    }
111
112    fn schedule(&self, notification: &Notification, at: SystemTime) -> Result<(), NotifyError> {
113        crate::validate(notification)?;
114        if let Ok(mut log) = self.log.lock() {
115            log.scheduled
116                .retain(|(held, _)| held.tag != notification.tag);
117            log.scheduled.push((notification.clone(), at));
118        }
119        Ok(())
120    }
121
122    fn scheduled(&self) -> Result<Vec<Scheduled>, NotifyError> {
123        Ok(self
124            .log
125            .lock()
126            .map(|log| {
127                log.scheduled
128                    .iter()
129                    .map(|(notification, at)| Scheduled {
130                        tag: notification.tag.clone(),
131                        at: *at,
132                    })
133                    .collect()
134            })
135            .unwrap_or_default())
136    }
137
138    fn cancel_scheduled(&self, tag: &str) -> Result<(), NotifyError> {
139        if let Ok(mut log) = self.log.lock() {
140            log.scheduled.retain(|(held, _)| held.tag != tag);
141        }
142        Ok(())
143    }
144}