Skip to main content

waft_test/
opener.rs

1//! The system's opener in memory, as a host opens nothing: it keeps each link and file it was asked
2//! to open or reveal, and answers what the test gave.
3
4use std::cell::RefCell;
5use std::path::{Path, PathBuf};
6use std::rc::Rc;
7
8use waft_embedder::{OpenError, OpenFuture, Opener};
9
10/// An opener that keeps what it was asked and answers what the test gave: every link and file
11/// opens, until the test says otherwise. Every clone is the same opener.
12#[derive(Clone, Default)]
13pub struct MockOpener(Rc<OpenerState>);
14
15#[derive(Default)]
16struct OpenerState {
17    asked: RefCell<Vec<Opened>>,
18    answer: RefCell<Option<OpenError>>,
19    can_open: RefCell<Option<bool>>,
20}
21
22/// What the app asked the opener.
23#[derive(Clone, Debug, PartialEq, Eq)]
24pub enum Opened {
25    Link(String),
26    File(PathBuf),
27    Revealed(PathBuf),
28}
29
30impl MockOpener {
31    pub fn new() -> MockOpener {
32        MockOpener::default()
33    }
34
35    /// Fails every open and reveal with `error`.
36    pub fn failing(self, error: OpenError) -> MockOpener {
37        *self.0.answer.borrow_mut() = Some(error);
38        self
39    }
40
41    /// Answers `can` whether a link can be opened; `None`, the default, as a system that will not
42    /// say.
43    pub fn answering_can_open(self, can: Option<bool>) -> MockOpener {
44        *self.0.can_open.borrow_mut() = can;
45        self
46    }
47
48    /// What the app asked to open or reveal, in order.
49    pub fn asked(&self) -> Vec<Opened> {
50        self.0.asked.borrow().clone()
51    }
52
53    fn answer(&self, asked: Opened) -> OpenFuture {
54        self.0.asked.borrow_mut().push(asked);
55        let answer = match self.0.answer.borrow().clone() {
56            Some(error) => Err(error),
57            None => Ok(()),
58        };
59        Box::pin(std::future::ready(answer))
60    }
61}
62
63impl Opener for MockOpener {
64    fn open_link(&self, link: &str) -> OpenFuture {
65        self.answer(Opened::Link(link.to_owned()))
66    }
67
68    fn open_file(&self, path: &Path) -> OpenFuture {
69        self.answer(Opened::File(path.to_owned()))
70    }
71
72    fn reveal_file(&self, path: &Path) -> OpenFuture {
73        self.answer(Opened::Revealed(path.to_owned()))
74    }
75
76    fn can_open_link(&self, _link: &str) -> Option<bool> {
77        *self.0.can_open.borrow()
78    }
79}
80
81#[cfg(test)]
82mod tests {
83    use std::future::Future;
84    use std::task::{Context, Poll, Waker};
85
86    use super::*;
87
88    fn now<T>(future: impl Future<Output = T>) -> T {
89        let mut future = std::pin::pin!(future);
90        match future
91            .as_mut()
92            .poll(&mut Context::from_waker(Waker::noop()))
93        {
94            Poll::Ready(output) => output,
95            Poll::Pending => panic!("answers at once"),
96        }
97    }
98
99    #[test]
100    fn the_opener_keeps_what_it_was_asked_and_answers_as_told() {
101        let opener = MockOpener::new();
102        assert_eq!(now(opener.open_link("https://example.org")), Ok(()));
103        assert_eq!(now(opener.reveal_file(Path::new("/tmp/a"))), Ok(()));
104        assert_eq!(
105            opener.asked(),
106            [
107                Opened::Link("https://example.org".to_owned()),
108                Opened::Revealed(PathBuf::from("/tmp/a"))
109            ]
110        );
111        assert_eq!(opener.can_open_link("https://example.org"), None);
112        let failing = MockOpener::new()
113            .failing(OpenError::NoApp)
114            .answering_can_open(Some(false));
115        assert_eq!(
116            now(failing.open_file(Path::new("/tmp/b"))),
117            Err(OpenError::NoApp)
118        );
119        assert_eq!(failing.can_open_link("x-none:a"), Some(false));
120    }
121}