mod others;
mod report;
#[cfg(test)]
mod tests;
use std::fmt;
use std::panic::Location;
use icedwright_check::assertion::{Assertion, Evaluation, NodeMatcher, evaluate_matcher};
use icedwright_check::{CheckError, RetryPolicy, ValueMatch, retry};
use icedwright_locator::{AnyRole, Locator, RoleKind, TextMatch};
use icedwright_semantics::SemanticTree;
use icedwright_trace::{CanonicalSelector, SelectorText, StepKind};
use icedwright_types::role::{
Checkable, Editable, Expandable, HasValue, Leveled, Pressable, SelectableItem,
};
use icedwright_types::{Checked, Ratio, Role, VirtualDuration};
pub use others::{
ClipboardExpect, Mark, MessagePattern, MessagesExpect, SoftMessages, StateExpect, TasksExpect,
WindowsExpect,
};
pub use report::ExpectError;
pub(crate) use report::ExpectState;
use crate::driver::Scoped;
use crate::error::Result;
use crate::harness::{Handle, Harness, TestProgram};
#[derive(Debug, Clone, Default)]
pub(crate) struct Settings {
pub(crate) timeout: Option<VirtualDuration>,
pub(crate) during: Option<VirtualDuration>,
pub(crate) negated: bool,
pub(crate) message: Option<String>,
pub(crate) soft: bool,
}
impl Settings {
pub(crate) fn policy<D>(&self, default: VirtualDuration) -> RetryPolicy<D>
where
D: icedwright_check::Driver<Duration = VirtualDuration>,
{
RetryPolicy {
timeout: self.timeout.unwrap_or(default),
during: self.during,
negated: self.negated,
}
}
}
struct Canonical(String);
impl CanonicalSelector for Canonical {
fn canonical(&self) -> String {
self.0.clone()
}
}
pub(crate) fn settle_soft<P: TestProgram>(
h: &mut Harness<P>,
soft: bool,
result: Result,
) -> Result {
match result {
Err(crate::Error::Expect(error)) if soft => {
h.expectations.record_soft(error);
Ok(())
}
other => other,
}
}
pub fn expect<'h, P: TestProgram, R: RoleKind>(subject: Handle<'h, P, R>) -> Expect<'h, P, R> {
Expect {
handle: subject,
settings: Settings::default(),
}
}
#[must_use = "an expectation does nothing until a matcher is called and its result is used"]
pub struct Expect<'h, P: TestProgram, R: RoleKind> {
handle: Handle<'h, P, R>,
settings: Settings,
}
impl<P: TestProgram, R: RoleKind> fmt::Debug for Expect<'_, P, R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Expect")
.field("locator", &self.handle.locator.to_string())
.field("settings", &self.settings)
.finish_non_exhaustive()
}
}
#[must_use = "a soft expectation does nothing until a matcher is called"]
pub struct Soft<'h, P: TestProgram, R: RoleKind>(Expect<'h, P, R>);
impl<P: TestProgram, R: RoleKind> fmt::Debug for Soft<'_, P, R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Soft").field(&self.0).finish()
}
}
impl<P: TestProgram, R: RoleKind> std::ops::Not for Expect<'_, P, R> {
type Output = Self;
fn not(mut self) -> Self {
self.settings.negated = !self.settings.negated;
self
}
}
type Evaluate<'a> =
dyn Fn(&SemanticTree, &Locator<AnyRole>) -> std::result::Result<Evaluation, CheckError> + 'a;
impl<'h, P: TestProgram, R: RoleKind> Expect<'h, P, R> {
pub fn timeout(mut self, timeout: impl Into<VirtualDuration>) -> Self {
self.settings.timeout = Some(timeout.into());
self
}
pub fn during(mut self, window: impl Into<VirtualDuration>) -> Self {
self.settings.during = Some(window.into());
self
}
pub fn message(mut self, context: impl Into<String>) -> Self {
self.settings.message = Some(context.into());
self
}
pub fn soft(mut self) -> Soft<'h, P, R> {
self.settings.soft = true;
Soft(self)
}
#[track_caller]
pub fn to_satisfy(self, matcher: impl NodeMatcher) -> Result {
let name = matcher.name().into_owned();
self.run(&name, &|tree, locator| {
evaluate_matcher(tree, locator, &matcher)
})
}
#[track_caller]
fn assert(self, assertion: Assertion) -> Result {
self.run(assertion.name(), &|tree, locator| {
assertion.evaluate(tree, locator)
})
}
#[track_caller]
fn run(self, matcher: &str, evaluate: &Evaluate<'_>) -> Result {
let location = Location::caller();
let Self { handle, settings } = self;
let Handle {
harness,
locator,
window,
} = handle;
let locator = locator.any_role();
let subject = icedwright_check::report::subject(&locator);
let kind = StepKind::Expect {
subject: SelectorText::of(&Canonical(locator.to_string())),
assertion: matcher.to_owned(),
negated: settings.negated,
};
let result = harness.step(
|| kind,
|h| {
let policy = settings.policy(h.default_timeout());
let mut driver = Scoped::new(h, window);
let passed = retry(
&mut driver,
matcher,
&|tree| evaluate(tree, &locator),
&policy,
);
let tree = driver.last_tree();
let Err(error) = passed else {
return Ok(());
};
let context = report::Context {
subject,
location,
message: settings.message.as_deref(),
tree: tree.as_deref(),
window,
soft: settings.soft,
};
Err(report::fail(h, error, &context))
},
);
settle_soft(harness, settings.soft, result)
}
}
macro_rules! matchers {
($(
$(#[doc = $doc:literal])+
fn $name:ident($($arg:ident: $ty:ty),*) $(where R: $bound:path)? => $assertion:expr;
)+) => {
impl<P: TestProgram, R: RoleKind> Expect<'_, P, R> {
$(
$(#[doc = $doc])+
#[track_caller]
pub fn $name(self, $($arg: $ty),*) -> Result $(where R: $bound)? {
self.assert($assertion)
}
)+
}
impl<P: TestProgram, R: RoleKind> Soft<'_, P, R> {
$(
$(#[doc = $doc])+
#[track_caller]
pub fn $name(self, $($arg: $ty),*) -> Result $(where R: $bound)? {
self.0.assert($assertion)
}
)+
}
};
}
matchers! {
fn to_be_attached() => Assertion::Attached;
fn to_be_visible() => Assertion::Visible;
fn to_be_hidden() => Assertion::Hidden;
fn to_be_enabled() => Assertion::Enabled;
fn to_be_disabled() => Assertion::Disabled;
fn to_be_focused() => Assertion::Focused;
fn to_be_in_viewport() => Assertion::InViewport(None);
fn to_be_in_viewport_ratio(ratio: Ratio) => Assertion::InViewport(Some(ratio));
fn to_have_text(text: impl Into<TextMatch>) => Assertion::Text(text.into());
fn to_have_texts(texts: impl IntoIterator<Item = impl Into<TextMatch>>) => Assertion::Texts(texts.into_iter().map(Into::into).collect());
fn to_contain_text(text: impl Into<TextMatch>) => Assertion::ContainText(text.into());
fn to_have_count(count: usize) => Assertion::Count(count);
fn to_have_role(role: Role) => Assertion::Role(role);
fn to_have_accessible_name(name: impl Into<TextMatch>) => Assertion::AccessibleName(name.into());
fn to_have_accessible_description(text: impl Into<TextMatch>) => Assertion::AccessibleDescription(text.into());
fn to_be_checked() where R: Checkable => Assertion::Checked(Checked::True);
fn to_be_checked_with(state: Checked) where R: Checkable => Assertion::Checked(state);
fn to_be_pressed() where R: Pressable => Assertion::Pressed;
fn to_be_expanded() where R: Expandable => Assertion::Expanded;
fn to_be_selected() where R: SelectableItem => Assertion::Selected;
fn to_have_value(value: impl Into<ValueMatch>) where R: HasValue => Assertion::Value(value.into());
fn to_have_level(level: u16) where R: Leveled => Assertion::Level(level);
fn to_be_editable() where R: Editable => Assertion::Editable;
}