use std::fmt;
use std::sync::{Arc, Mutex};
use icedwright_probe::{NamedTask, TaskName};
use crate::error::HarnessError;
use crate::runtime::lock;
pub(crate) const FILE: &str = file!();
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("fake {fake} had no answer for {request}")]
pub struct Unanswered {
pub fake: &'static str,
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>,
}
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,
{
#[must_use]
pub fn new(name: &'static str) -> Self {
Self {
inner: Arc::new(Mutex::new(Inner {
name,
reply: None,
calls: Vec::new(),
})),
}
}
#[must_use]
pub fn reply_with(self, reply: impl FnMut(&Req) -> Resp + Send + 'static) -> Self {
lock(&self.inner).reply = Some(Box::new(reply));
self
}
pub fn call(&self, request: Req) -> Result<Resp, Unanswered> {
answer(&self.inner, request)
}
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)
}
#[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));
}
}