use std::collections::BTreeSet;
use std::fmt::{self, Debug};
use std::marker::PhantomData;
use std::panic::Location;
use iced_core::{theme, window};
use icedwright_check::assertion::{Evaluation, Outcome};
use icedwright_check::expectations::{self, Pattern, TaskView, WindowView};
use icedwright_check::retry_with;
use icedwright_locator::TextMatch;
use icedwright_probe::TaskName;
use icedwright_trace::StepKind;
use icedwright_types::VirtualDuration;
use super::{Settings, report, settle_soft};
use crate::effects::{Spawn, TaskState};
use crate::error::Result;
use crate::harness::{Harness, TestProgram};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Mark {
messages: usize,
}
#[must_use = "a message pattern does nothing until a matcher uses it"]
pub struct MessagePattern<M> {
matches: Box<dyn Fn(&M) -> bool>,
text: &'static str,
}
impl<M> MessagePattern<M> {
pub fn new(matches: impl Fn(&M) -> bool + 'static, text: &'static str) -> Self {
Self {
matches: Box::new(matches),
text,
}
}
}
impl<M> Pattern<M> for MessagePattern<M> {
fn matches(&self, message: &M) -> bool {
(self.matches)(message)
}
fn text(&self) -> &str {
self.text
}
}
impl<M> Debug for MessagePattern<M> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "message!({})", self.text)
}
}
#[macro_export]
macro_rules! message {
($($pattern:pat_param)|+ $(if $guard:expr)? $(,)?) => {
$crate::MessagePattern::new(
move |message| ::core::matches!(message, $($pattern)|+ $(if $guard)?),
::core::stringify!($($pattern)|+ $(if $guard)?),
)
};
}
impl<P: TestProgram> Harness<P> {
#[must_use]
pub fn mark(&self) -> Mark {
Mark {
messages: self.messages.len(),
}
}
pub fn expect_messages(&mut self) -> MessagesExpect<'_, P> {
MessagesExpect {
harness: self,
settings: Settings::default(),
since: 0,
}
}
pub fn expect_clipboard(&mut self) -> ClipboardExpect<'_, P> {
ClipboardExpect {
harness: self,
settings: Settings::default(),
}
}
pub fn expect_tasks(&mut self) -> TasksExpect<'_, P> {
TasksExpect {
harness: self,
settings: Settings::default(),
}
}
pub fn expect_windows(&mut self) -> WindowsExpect<'_, P> {
WindowsExpect {
harness: self,
settings: Settings::default(),
window: None,
}
}
pub fn expect_state<T, F>(&mut self, project: F) -> StateExpect<'_, P, T, F>
where
T: Debug,
F: for<'a> Fn(&'a P::State) -> T,
{
StateExpect {
harness: self,
settings: Settings::default(),
project,
value: PhantomData,
}
}
}
#[track_caller]
fn run<P: TestProgram>(
harness: &mut Harness<P>,
settings: &Settings,
subject: &str,
matcher: &str,
outcome: &mut dyn FnMut(&mut Harness<P>) -> Outcome,
) -> Result {
let location = Location::caller();
let negated = if settings.negated { "not()." } else { "" };
let kind = StepKind::Action {
action: format!("{subject}.{negated}{matcher}()"),
locator: None,
resolved: None,
point: None,
};
let result = harness.step(
|| kind,
|h| {
let policy = settings.policy(h.default_timeout());
let passed = retry_with(h, matcher, &policy, &mut |h: &mut Harness<P>| {
Ok(Evaluation::from(outcome(h)))
});
let Err(error) = passed else {
return Ok(());
};
let context = report::Context {
subject: subject.to_owned(),
location,
message: settings.message.as_deref(),
tree: None,
window: None,
soft: settings.soft,
};
Err(report::fail(h, error, &context))
},
);
settle_soft(harness, settings.soft, result)
}
macro_rules! negate {
($($ty:ty),+ $(,)?) => {
$(
impl<P: TestProgram> std::ops::Not for $ty {
type Output = Self;
fn not(mut self) -> Self {
self.settings.negated = !self.settings.negated;
self
}
}
)+
};
}
negate!(
MessagesExpect<'_, P>,
TasksExpect<'_, P>,
ClipboardExpect<'_, P>,
WindowsExpect<'_, P>
);
impl<P: TestProgram, T, F> std::ops::Not for StateExpect<'_, P, T, F> {
type Output = Self;
fn not(mut self) -> Self {
self.settings.negated = !self.settings.negated;
self
}
}
macro_rules! shared_options {
() => {
pub fn timeout(mut self, timeout: impl Into<VirtualDuration>) -> Self {
self.settings.timeout = Some(timeout.into());
self
}
pub fn message(mut self, context: impl Into<String>) -> Self {
self.settings.message = Some(context.into());
self
}
pub fn during(mut self, window: impl Into<VirtualDuration>) -> Self {
self.settings.during = Some(window.into());
self
}
};
}
#[must_use = "an expectation does nothing until a matcher is called and its result is used"]
pub struct MessagesExpect<'h, P: TestProgram> {
harness: &'h mut Harness<P>,
settings: Settings,
since: usize,
}
impl<P: TestProgram> Debug for MessagesExpect<'_, P> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MessagesExpect")
.field("settings", &self.settings)
.field("since", &self.since)
.finish_non_exhaustive()
}
}
impl<'h, P: TestProgram> MessagesExpect<'h, P> {
shared_options!();
pub fn since(mut self, mark: Mark) -> Self {
self.since = mark.messages;
self
}
pub fn soft(mut self) -> SoftMessages<'h, P> {
self.settings.soft = true;
SoftMessages(self)
}
#[track_caller]
fn check(self, matcher: &str, judge: &dyn Fn(&[&P::Message]) -> Outcome) -> Result {
let since = self.since;
run(
self.harness,
&self.settings,
"ui.expect_messages()",
matcher,
&mut |h: &mut Harness<P>| {
let log: Vec<&P::Message> = h
.messages
.get(since..)
.unwrap_or_default()
.iter()
.map(|record| &record.message)
.collect();
judge(&log)
},
)
}
#[track_caller]
pub fn to_contain(self, message: P::Message) -> Result
where
P::Message: PartialEq,
{
self.check("to_contain", &|log| {
expectations::contains(log.iter().copied(), &message)
})
}
#[track_caller]
pub fn to_match(self, pattern: MessagePattern<P::Message>) -> Result {
self.check("to_match", &|log| {
expectations::matching(log.iter().copied(), &pattern)
})
}
#[track_caller]
pub fn to_match_count(self, pattern: MessagePattern<P::Message>, count: usize) -> Result {
self.check("to_match_count", &|log| {
expectations::match_count(log.iter().copied(), &pattern, count)
})
}
#[track_caller]
pub fn to_match_in_order(
self,
patterns: impl IntoIterator<Item = MessagePattern<P::Message>>,
) -> Result {
let patterns: Vec<MessagePattern<P::Message>> = patterns.into_iter().collect();
self.check("to_match_in_order", &|log| {
let refs: Vec<&dyn Pattern<P::Message>> = patterns
.iter()
.map(|p| p as &dyn Pattern<P::Message>)
.collect();
expectations::in_order(log.iter().copied(), &refs)
})
}
#[track_caller]
pub fn to_be_empty(self) -> Result {
self.check("to_be_empty", &|log| {
expectations::no_messages(log.iter().copied())
})
}
}
#[must_use = "a soft expectation does nothing until a matcher is called"]
pub struct SoftMessages<'h, P: TestProgram>(MessagesExpect<'h, P>);
impl<P: TestProgram> Debug for SoftMessages<'_, P> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("SoftMessages").field(&self.0).finish()
}
}
impl<P: TestProgram> SoftMessages<'_, P> {
#[track_caller]
pub fn to_contain(self, message: P::Message) -> Result
where
P::Message: PartialEq,
{
self.0.to_contain(message)
}
#[track_caller]
pub fn to_match(self, pattern: MessagePattern<P::Message>) -> Result {
self.0.to_match(pattern)
}
#[track_caller]
pub fn to_match_count(self, pattern: MessagePattern<P::Message>, count: usize) -> Result {
self.0.to_match_count(pattern, count)
}
#[track_caller]
pub fn to_match_in_order(
self,
patterns: impl IntoIterator<Item = MessagePattern<P::Message>>,
) -> Result {
self.0.to_match_in_order(patterns)
}
#[track_caller]
pub fn to_be_empty(self) -> Result {
self.0.to_be_empty()
}
}
#[must_use = "an expectation does nothing until a matcher is called and its result is used"]
pub struct TasksExpect<'h, P: TestProgram> {
harness: &'h mut Harness<P>,
settings: Settings,
}
impl<P: TestProgram> Debug for TasksExpect<'_, P> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TasksExpect")
.field("settings", &self.settings)
.finish_non_exhaustive()
}
}
fn in_flight<P: TestProgram>(h: &Harness<P>) -> Vec<(String, bool)> {
let infos = h.task_infos();
let live = |state: TaskState| matches!(state, TaskState::Pending | TaskState::Held);
let carriers: BTreeSet<_> = infos
.iter()
.filter(|info| info.name().is_some() && live(info.state()))
.filter_map(crate::effects::TaskInfo::parent)
.collect();
infos
.iter()
.filter(|info| live(info.state()))
.filter(|info| *info.spawn() != Spawn::Subscription)
.filter(|info| info.name().is_some() || !carriers.contains(&info.id()))
.map(|info| {
let name = info
.name()
.map_or_else(|| format!("unnamed task {}", info.id()), str::to_owned);
(name, info.state() == TaskState::Held)
})
.collect()
}
impl<P: TestProgram> TasksExpect<'_, P> {
shared_options!();
#[track_caller]
fn check(self, matcher: &str, judge: &dyn Fn(&[TaskView<'_>]) -> Outcome) -> Result {
run(
self.harness,
&self.settings,
"ui.expect_tasks()",
matcher,
&mut |h: &mut Harness<P>| {
let tasks = in_flight(h);
let views: Vec<TaskView<'_>> = tasks
.iter()
.map(|(name, held)| TaskView { name, held: *held })
.collect();
judge(&views)
},
)
}
#[track_caller]
pub fn to_be_idle(self) -> Result {
self.check("to_be_idle", &expectations::tasks_idle)
}
#[track_caller]
pub fn to_have_pending<T: TaskName>(self) -> Result {
self.check("to_have_pending", &|tasks| {
expectations::task_pending(tasks, T::NAME)
})
}
#[track_caller]
pub fn to_have_held<T: TaskName>(self) -> Result {
self.check("to_have_held", &|tasks| {
expectations::task_held(tasks, T::NAME)
})
}
#[track_caller]
pub fn to_have_pending_count(self, count: usize) -> Result {
self.check("to_have_pending_count", &|tasks| {
expectations::task_count(tasks, count)
})
}
}
#[must_use = "an expectation does nothing until a matcher is called and its result is used"]
pub struct ClipboardExpect<'h, P: TestProgram> {
harness: &'h mut Harness<P>,
settings: Settings,
}
impl<P: TestProgram> Debug for ClipboardExpect<'_, P> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ClipboardExpect")
.field("settings", &self.settings)
.finish_non_exhaustive()
}
}
impl<P: TestProgram> ClipboardExpect<'_, P> {
shared_options!();
#[track_caller]
fn check(self, matcher: &str, judge: &dyn Fn(&crate::FakeClipboard) -> Outcome) -> Result {
run(
self.harness,
&self.settings,
"ui.expect_clipboard()",
matcher,
&mut |h: &mut Harness<P>| judge(&h.clipboard),
)
}
#[track_caller]
pub fn to_have_text(self, text: impl Into<TextMatch>) -> Result {
let text = text.into();
self.check("to_have_text", &|clipboard| {
expectations::clipboard_text(clipboard.text(), &text)
})
}
#[track_caller]
pub fn to_have_primary_text(self, text: impl Into<TextMatch>) -> Result {
let text = text.into();
self.check("to_have_primary_text", &|clipboard| {
expectations::clipboard_text(clipboard.primary(), &text)
})
}
#[track_caller]
pub fn to_be_empty(self) -> Result {
self.check("to_be_empty", &|clipboard| {
expectations::clipboard_empty(clipboard.text())
})
}
}
#[must_use = "an expectation does nothing until a matcher is called and its result is used"]
pub struct WindowsExpect<'h, P: TestProgram> {
harness: &'h mut Harness<P>,
settings: Settings,
window: Option<window::Id>,
}
impl<P: TestProgram> Debug for WindowsExpect<'_, P> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("WindowsExpect")
.field("settings", &self.settings)
.field("window", &self.window)
.finish_non_exhaustive()
}
}
impl<P: TestProgram> WindowsExpect<'_, P> {
shared_options!();
pub fn window(mut self, id: window::Id) -> Self {
self.window = Some(id);
self
}
#[track_caller]
fn check(
self,
matcher: &str,
judge: &dyn Fn(usize, Option<&WindowView<'_, theme::Mode>>) -> Outcome,
) -> Result {
let chosen = self.window;
run(
self.harness,
&self.settings,
"ui.expect_windows()",
matcher,
&mut |h: &mut Harness<P>| {
let id = chosen.or_else(|| h.focused());
let info = id.and_then(|id| h.window_info(id).ok());
let view = info.map(|info| WindowView {
title: &info.title,
theme_mode: info.theme_mode,
});
judge(h.windows().len(), view.as_ref())
},
)
}
#[track_caller]
pub fn to_have_count(self, count: usize) -> Result {
self.check("to_have_count", &|open, _| {
expectations::window_count(open, count)
})
}
#[track_caller]
pub fn to_have_title(self, title: impl Into<TextMatch>) -> Result {
let title = title.into();
self.check("to_have_title", &|_, window| {
expectations::window_title(window, &title)
})
}
#[track_caller]
pub fn to_have_theme_mode(self, mode: theme::Mode) -> Result {
self.check("to_have_theme_mode", &|_, window| {
expectations::window_theme(window, &mode)
})
}
}
#[must_use = "an expectation does nothing until a matcher is called and its result is used"]
pub struct StateExpect<'h, P: TestProgram, T, F> {
harness: &'h mut Harness<P>,
settings: Settings,
project: F,
value: PhantomData<fn() -> T>,
}
impl<P: TestProgram, T, F> Debug for StateExpect<'_, P, T, F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StateExpect")
.field("settings", &self.settings)
.finish_non_exhaustive()
}
}
impl<P: TestProgram, T: Debug, F: for<'a> Fn(&'a P::State) -> T> StateExpect<'_, P, T, F> {
shared_options!();
#[track_caller]
pub fn to_equal(self, expected: T) -> Result
where
T: PartialEq,
{
let project = &self.project;
run(
self.harness,
&self.settings,
"ui.expect_state(..)",
"to_equal",
&mut |h: &mut Harness<P>| expectations::state_equal(&project(&h.state), &expected),
)
}
#[track_caller]
pub fn to_satisfy<G>(self, check: G) -> Result
where
G: for<'a> Fn(&'a T) -> bool,
{
let project = &self.project;
run(
self.harness,
&self.settings,
"ui.expect_state(..)",
"to_satisfy",
&mut |h: &mut Harness<P>| {
let value = project(&h.state);
let holds = check(&value);
expectations::state_satisfies(&value, holds)
},
)
}
}