use icedwright_check::{MatchReport, Template};
use icedwright_locator::RoleKind;
use icedwright_semantics::yaml::{self, YamlOptions};
use icedwright_types::VirtualDuration;
use super::visual::STABLE_FRAMES;
use super::{SnapshotEnv, SnapshotError, themes};
use crate::error::Result;
use crate::harness::{Handle, TestProgram};
use crate::testing::matrix::Theme;
#[derive(Debug, Clone, Default)]
#[must_use]
pub struct SemanticOptions {
pub yaml: YamlOptions,
pub per_theme: bool,
pub timeout: Option<VirtualDuration>,
}
impl SemanticOptions {
pub fn new() -> Self {
Self::default()
}
pub fn yaml(mut self, yaml: YamlOptions) -> Self {
self.yaml = yaml;
self
}
pub fn per_theme(mut self, on: bool) -> Self {
self.per_theme = on;
self
}
pub fn timeout(mut self, timeout: impl Into<VirtualDuration>) -> Self {
self.timeout = Some(timeout.into());
self
}
}
impl<P: TestProgram, R: RoleKind> Handle<'_, P, R> {
pub fn semantic_yaml(&mut self, options: &YamlOptions) -> Result<String> {
let resolved = self.resolve()?;
Ok(yaml::write(&resolved.tree, resolved.id, options))
}
pub fn stable_semantic_yaml(&mut self, options: &YamlOptions) -> Result<String> {
let mut previous = self.semantic_yaml(options)?;
for _ in 0..STABLE_FRAMES {
self.harness.next_frame()?;
let next = self.semantic_yaml(options)?;
if next == previous {
return Ok(next);
}
previous = next;
}
Err(SnapshotError::NeverStableYaml {
subject: self.locator.to_string(),
frames: STABLE_FRAMES,
}
.into())
}
pub fn to_match_semantic(&mut self, template: &str) -> Result {
self.to_match_semantic_with(template, &SemanticOptions::default())
}
pub fn to_match_semantic_with(&mut self, template: &str, options: &SemanticOptions) -> Result {
let template = Template::parse(template).map_err(SnapshotError::from)?;
let locator = self.locator.clone();
let window = self.window;
let timeout = options
.timeout
.unwrap_or_else(|| self.harness.default_timeout());
let deadline = self.harness.now() + timeout;
let mut report: Option<MatchReport> = None;
let mut missing: Option<crate::Error> = None;
let _ = self.harness.advance_until(deadline, |harness| {
let tree = match window {
Some(window) => harness.tree_of(window),
None => harness.tree(),
};
let tree = match tree {
Ok(tree) => tree,
Err(error) => {
missing = Some(error);
return false;
}
};
match icedwright_locator::resolve(&tree, &locator) {
Ok(id) => {
let matched = template.matches(&tree, id);
let done = matched.is_match();
report = Some(matched);
missing = None;
done
}
Err(error) => {
missing = Some(error.into());
false
}
}
})?;
match (report, missing) {
(Some(report), None) if report.is_match() => Ok(()),
(_, Some(error)) => Err(error),
(Some(report), None) => Err(SnapshotError::Semantic {
subject: locator.to_string(),
report: Box::new(report),
}
.into()),
(None, None) => {
Err(SnapshotError::Location(format!("{locator} was never looked for")).into())
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Prepared {
pub yaml: String,
pub description: String,
pub suffix: String,
}
pub fn prepare<P: TestProgram, R: RoleKind>(
handle: &mut Handle<'_, P, R>,
name: Option<&str>,
options: &SemanticOptions,
) -> Result<Prepared> {
handle.harness.settle()?;
let yaml = handle.stable_semantic_yaml(&options.yaml)?;
let prepared = Prepared {
yaml,
description: handle.locator.to_string(),
suffix: handle.harness.variant().semantic_suffix(options.per_theme),
};
if let Some(theme) = handle.harness.variant().theme_axis()
&& !options.per_theme
{
check_themes(&prepared, name, theme)?;
}
Ok(prepared)
}
fn check_themes(prepared: &Prepared, name: Option<&str>, theme: Theme) -> Result {
let env = SnapshotEnv::current()?;
let Some(test) = env.test.as_deref() else {
return Ok(());
};
let name = name.unwrap_or(&prepared.description);
let key = themes::RecordKey::new(&env.crate_name, test, name, &prepared.suffix);
themes::record(&env.out_dir, &key, theme, &prepared.yaml)?;
themes::check_within_test(test, &key, name, theme, &prepared.yaml)?;
Ok(())
}
#[must_use]
pub fn settings(prepared: &Prepared) -> insta::Settings {
let mut settings = insta::Settings::clone_current();
settings.set_description(prepared.description.clone());
settings.set_omit_expression(true);
settings.set_snapshot_suffix(prepared.suffix.clone());
settings
}
#[macro_export]
macro_rules! assert_semantic_snapshot {
($name:literal, $handle:expr $(,)?) => {{
let __prepared = $crate::snapshot::__private::prepare(
&mut $handle,
::core::option::Option::Some($name),
&$crate::snapshot::SemanticOptions::default(),
)?;
$crate::snapshot::__private::settings(&__prepared).bind(|| {
$crate::snapshot::__private::insta::assert_snapshot!($name, __prepared.yaml.as_str());
});
}};
($handle:expr, @$snapshot:literal $(,)?) => {{
let __prepared = $crate::snapshot::__private::prepare(
&mut $handle,
::core::option::Option::None,
&$crate::snapshot::SemanticOptions::default(),
)?;
$crate::snapshot::__private::settings(&__prepared).bind(|| {
$crate::snapshot::__private::insta::assert_snapshot!(
__prepared.yaml.as_str(),
@$snapshot
);
});
}};
($handle:expr, $options:expr $(,)?) => {{
let __prepared = $crate::snapshot::__private::prepare(
&mut $handle,
::core::option::Option::None,
$options,
)?;
$crate::snapshot::__private::settings(&__prepared).bind(|| {
$crate::snapshot::__private::insta::assert_snapshot!(__prepared.yaml.as_str());
});
}};
($handle:expr $(,)?) => {{
let __prepared = $crate::snapshot::__private::prepare(
&mut $handle,
::core::option::Option::None,
&$crate::snapshot::SemanticOptions::default(),
)?;
$crate::snapshot::__private::settings(&__prepared).bind(|| {
$crate::snapshot::__private::insta::assert_snapshot!(__prepared.yaml.as_str());
});
}};
}