icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! `fake::Calls`: a recorder that makes the test side of an app's own trait a few lines long.

use std::fmt;
use std::sync::{Arc, Mutex};

use icedwright_probe::{NamedTask, TaskName};

use crate::error::HarnessError;
use crate::runtime::lock;

/// This file, which the controller compares task locations against: tasks named here come
/// from a fake and are exempt from `deny_unrouted`.
pub(crate) const FILE: &str = file!();

/// A fake was called with no `reply_with` closure to answer it.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("fake {fake} had no answer for {request}")]
pub struct Unanswered {
    /// The fake's name.
    pub fake: &'static str,
    /// The request, printed.
    pub request: String,
}

impl From<Unanswered> for HarnessError {
    fn from(unanswered: Unanswered) -> Self {
        HarnessError::Unanswered {
            fake: unanswered.fake,
            request: unanswered.request,
        }
    }
}

impl From<Unanswered> for crate::Error {
    fn from(unanswered: Unanswered) -> Self {
        HarnessError::from(unanswered).into()
    }
}

type Reply<Req, Resp> = Box<dyn FnMut(&Req) -> Resp + Send>;

struct Inner<Req, Resp> {
    name: &'static str,
    reply: Option<Reply<Req, Resp>>,
    calls: Vec<Req>,
}

/// Records the requests a fake receives and answers them from a closure. Cloning shares the
/// record, so the test keeps one copy and the app's fake the other.
pub struct Calls<Req, Resp> {
    inner: Arc<Mutex<Inner<Req, Resp>>>,
}

impl<Req, Resp> Clone for Calls<Req, Resp> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
        }
    }
}

impl<Req: fmt::Debug, Resp> fmt::Debug for Calls<Req, Resp> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let inner = lock(&self.inner);
        f.debug_struct("Calls")
            .field("name", &inner.name)
            .field("calls", &inner.calls)
            .finish_non_exhaustive()
    }
}

impl<Req, Resp> Calls<Req, Resp>
where
    Req: Clone + fmt::Debug + Send + 'static,
    Resp: Send + 'static,
{
    /// A recorder named `name`, with no answer yet.
    #[must_use]
    pub fn new(name: &'static str) -> Self {
        Self {
            inner: Arc::new(Mutex::new(Inner {
                name,
                reply: None,
                calls: Vec::new(),
            })),
        }
    }

    /// Answers every call with the closure's value.
    #[must_use]
    pub fn reply_with(self, reply: impl FnMut(&Req) -> Resp + Send + 'static) -> Self {
        lock(&self.inner).reply = Some(Box::new(reply));
        self
    }

    /// Records `request` and answers it.
    pub fn call(&self, request: Req) -> Result<Resp, Unanswered> {
        answer(&self.inner, request)
    }

    /// Records `request` and answers it as a task named `N`, so a test can hold, resolve or
    /// fail it like any named task. Unheld with no answer, the step fails with `Unanswered`.
    pub fn call_async<N>(
        &self,
        request: Req,
    ) -> impl NamedTask<Output = Resp> + Send + 'static + use<N, Req, Resp>
    where
        N: TaskName<Output = Resp>,
    {
        let inner = self.inner.clone();
        let detail = format!("{request:?}");
        N::task(async move {
            match answer(&inner, request) {
                Ok(response) => response,
                Err(unanswered) => {
                    crate::effects::report(unanswered.into());
                    std::future::pending().await
                }
            }
        })
        .detail(move || detail)
    }

    /// Every request so far, in order.
    #[must_use]
    pub fn calls(&self) -> Vec<Req> {
        lock(&self.inner).calls.clone()
    }
}

fn answer<Req: fmt::Debug + Clone, Resp>(
    inner: &Mutex<Inner<Req, Resp>>,
    request: Req,
) -> Result<Resp, Unanswered> {
    let mut inner = lock(inner);
    inner.calls.push(request.clone());
    let name = inner.name;
    match inner.reply.as_mut() {
        Some(reply) => Ok(reply(&request)),
        None => Err(Unanswered {
            fake: name,
            request: format!("{request:?}"),
        }),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn records_requests_in_order_and_answers_from_the_closure() {
        let calls: Calls<String, usize> =
            Calls::new("desktop.open_url").reply_with(|url: &String| url.len());
        let clone = calls.clone();
        assert_eq!(clone.call("ab".to_owned()), Ok(2));
        assert_eq!(calls.call("abc".to_owned()), Ok(3));
        assert_eq!(calls.calls(), vec!["ab".to_owned(), "abc".to_owned()]);
    }

    #[test]
    fn unset_answers_are_unanswered_with_the_name_and_request() {
        let calls: Calls<u32, ()> = Calls::new("store.save");
        assert_eq!(
            calls.call(7),
            Err(Unanswered {
                fake: "store.save",
                request: "7".to_owned()
            })
        );
        assert_eq!(calls.calls(), vec![7]);
        assert_eq!(
            Unanswered {
                fake: "store.save",
                request: "7".to_owned()
            }
            .to_string(),
            "fake store.save had no answer for 7"
        );
    }

    #[test]
    fn call_async_answers_from_reply_with_without_a_harness() {
        icedwright_probe::task_name!(Pick: Option<u32>);
        let calls: Calls<(), Option<u32>> = Calls::new("desktop.pick").reply_with(|()| Some(4));
        let runtime = tokio::runtime::Builder::new_current_thread()
            .build()
            .unwrap();
        assert_eq!(runtime.block_on(calls.call_async::<Pick>(())), Some(4));
    }
}