use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::fmt;
use std::panic::{AssertUnwindSafe, catch_unwind, resume_unwind};
use std::sync::Arc;
use icedwright_types::Messages;
use icedwright_types::units::ScaleFactor;
use crate::config::HarnessConfig;
use crate::harness::{Harness, TestProgram};
use crate::runtime::{self, Blocking, Signal};
use crate::time::EPOCH_OFFSET;
use super::coverage::{self, MessageCoverageFile};
pub use super::environment::Varies;
use super::environment::Environment;
use super::fixture::{Fixture, FixtureError, FixtureSet, RuntimeRef, Stage, TestOutcome};
use super::matrix::{Locale, Size, Theme};
pub use icedwright_macros::test_with_matrix;
pub const fn assert_fixture<T: Fixture>() {}
#[derive(Debug, Clone, Copy)]
pub struct EnvConst {
pub size: Option<Size>,
pub theme: Theme,
pub scale_factor: ScaleFactor,
pub locale: Locale,
pub varies: Varies,
}
#[derive(Debug, Clone, Copy)]
pub struct TestInfo {
pub package: &'static str,
pub module: &'static str,
pub name: &'static str,
}
impl TestInfo {
#[must_use]
pub fn path(&self) -> String {
let mut parts: Vec<&str> = self.module.split("::").skip(1).collect();
parts.push(self.name);
parts.join("::")
}
}
#[derive(Debug)]
pub struct Caught(Result<crate::Result, PanicPayload>);
pub struct PanicPayload(Box<dyn Any + Send>);
impl fmt::Debug for PanicPayload {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&panic_message(&self.0))
}
}
fn panic_message(payload: &(dyn Any + Send)) -> String {
if let Some(text) = payload.downcast_ref::<&str>() {
return format!("panicked: {text}");
}
if let Some(text) = payload.downcast_ref::<String>() {
return format!("panicked: {text}");
}
"panicked".to_owned()
}
trait Slot {
fn value(&self) -> &dyn Any;
fn name(&self) -> &'static str;
fn started(&mut self, runtime: &mut RuntimeRef<'_>) -> Result<(), FixtureError>;
fn teardown(
self: Box<Self>,
outcome: &TestOutcome,
runtime: &mut RuntimeRef<'_>,
) -> Result<(), FixtureError>;
}
struct Held<T>(T);
impl<T: Fixture> Slot for Held<T> {
fn value(&self) -> &dyn Any {
&self.0
}
fn name(&self) -> &'static str {
std::any::type_name::<T>()
}
fn started(&mut self, runtime: &mut RuntimeRef<'_>) -> Result<(), FixtureError> {
self.0.started(runtime)
}
fn teardown(
self: Box<Self>,
outcome: &TestOutcome,
runtime: &mut RuntimeRef<'_>,
) -> Result<(), FixtureError> {
self.0.teardown(outcome, runtime)
}
}
fn failed(fixture: &'static str, stage: Stage, error: FixtureError) -> FixtureError {
match error {
FixtureError::Cycle { .. } | FixtureError::Failed { .. } => error,
other => FixtureError::Failed {
fixture,
stage,
source: Box::new(other),
},
}
}
pub struct Context {
info: TestInfo,
env: Environment,
slots: Vec<Box<dyn Slot>>,
index: HashMap<TypeId, usize>,
building: Vec<(TypeId, &'static str)>,
bare: Option<tokio::runtime::Runtime>,
}
impl fmt::Debug for Context {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let names: Vec<&str> = self.slots.iter().map(|slot| slot.name()).collect();
f.debug_struct("Context")
.field("test", &self.env.test())
.field("fixtures", &names)
.finish_non_exhaustive()
}
}
impl Context {
pub(crate) fn new(info: TestInfo, env: Environment) -> Self {
Self {
info,
env,
slots: Vec::new(),
index: HashMap::new(),
building: Vec::new(),
bare: None,
}
}
#[must_use]
pub fn environment(&self) -> &Environment {
&self.env
}
pub fn prepare<T: Fixture>(&mut self) -> Result<(), FixtureError> {
let id = TypeId::of::<T>();
if self.index.contains_key(&id) {
return Ok(());
}
let name = std::any::type_name::<T>();
if self.building.iter().any(|(building, _)| *building == id) {
let asked_by = self.building.last().map_or(name, |(_, by)| *by);
return Err(FixtureError::Cycle {
a: name,
b: asked_by,
});
}
self.building.push((id, name));
let built = T::Deps::prepare(self).and_then(|()| {
let deps = T::Deps::refs(self)?;
T::setup(deps, &self.env).map_err(|error| failed(name, Stage::Setup, error))
});
self.building.pop();
let value = built?;
self.index.insert(id, self.slots.len());
self.slots.push(Box::new(Held(value)));
Ok(())
}
pub fn get<T: Fixture>(&self) -> Result<&T, FixtureError> {
self.index
.get(&TypeId::of::<T>())
.and_then(|slot| self.slots.get(*slot))
.and_then(|slot| slot.value().downcast_ref::<T>())
.ok_or(FixtureError::NotBuilt(std::any::type_name::<T>()))
}
fn started(&mut self, runtime: &mut RuntimeRef<'_>) -> Result<(), FixtureError> {
for slot in &mut self.slots {
let name = slot.name();
slot.started(runtime)
.map_err(|error| failed(name, Stage::Started, error))?;
}
Ok(())
}
fn teardown(
&mut self,
outcome: &TestOutcome,
runtime: &mut RuntimeRef<'_>,
) -> Vec<FixtureError> {
self.index.clear();
let mut errors = Vec::new();
while let Some(slot) = self.slots.pop() {
let name = slot.name();
if let Err(error) = slot.teardown(outcome, runtime) {
errors.push(failed(name, Stage::Teardown, error));
}
}
errors
}
fn take_bare(&mut self) -> Result<tokio::runtime::Runtime, FixtureError> {
if let Some(runtime) = self.bare.take() {
return Ok(runtime);
}
let runtime = runtime::build(&Blocking::new(Arc::new(Signal::default())))?;
runtime.block_on(tokio::time::advance(EPOCH_OFFSET));
Ok(runtime)
}
pub fn start_bare(&mut self) -> Result<(), FixtureError> {
let runtime = self.take_bare()?;
let result = self.started(&mut RuntimeRef::new(Some(&runtime)));
self.bare = Some(runtime);
result
}
pub fn boot<P: TestProgram>(
&mut self,
program: P,
config: HarnessConfig<P>,
) -> crate::Result<Harness<P>> {
let mut harness = Harness::with_config(program, config)?;
self.started(&mut harness.runtime())?;
Ok(harness)
}
pub fn call(&self, body: impl FnOnce(&Context) -> crate::Result) -> Caught {
Caught(catch_unwind(AssertUnwindSafe(|| body(self))).map_err(PanicPayload))
}
pub fn finish<P: TestProgram>(
&mut self,
mut harness: Harness<P>,
messages: Option<MessageCoverageFile>,
caught: Caught,
) -> crate::Result {
let (outcome, result, panic) = split(caught);
let mut notes = Vec::new();
if !outcome.passed() {
notes.extend(theme_note(&harness, self.env.theme));
}
let mut problems: Vec<crate::Error> = Vec::new();
if let Err(error) = coverage::write_if_enabled(&self.info, &mut harness, messages) {
problems.push(error);
}
let errors = self.teardown(&outcome, &mut harness.runtime());
problems.extend(errors.into_iter().map(crate::Error::from));
if let Err(error) = harness.finish() {
problems.push(error);
}
conclude(result, problems, notes, panic)
}
pub fn finish_bare(&mut self, caught: Caught) -> crate::Result {
let (outcome, result, panic) = split(caught);
let runtime = self.bare.take();
let errors = self.teardown(&outcome, &mut RuntimeRef::new(runtime.as_ref()));
self.bare = runtime;
let problems = errors.into_iter().map(crate::Error::from).collect();
conclude(result, problems, Vec::new(), panic)
}
}
fn split(caught: Caught) -> (TestOutcome, crate::Result, Option<PanicPayload>) {
match caught.0 {
Ok(Ok(())) => (TestOutcome::Passed, Ok(()), None),
Ok(Err(error)) => (TestOutcome::Failed(format!("{error:?}")), Err(error), None),
Err(payload) => {
let message = panic_message(&payload.0);
(TestOutcome::Failed(message), Ok(()), Some(payload))
}
}
}
fn theme_note<P: TestProgram>(harness: &Harness<P>, theme: Theme) -> Option<String> {
let window = harness.windows().into_iter().next()?;
let info = harness.window_info(window).ok()?;
let wanted: iced_core::theme::Mode = theme.into();
(info.theme_mode != wanted).then(|| {
format!(
"the combination asked for the {wanted:?} system theme, but the app rendered \
{:?}; its theme() does not follow the system",
info.theme_mode
)
})
}
fn conclude(
result: crate::Result,
mut problems: Vec<crate::Error>,
notes: Vec<String>,
panic: Option<PanicPayload>,
) -> crate::Result {
if let Some(payload) = panic {
for problem in &problems {
eprintln!("icedwright: after the panic, {problem:?}");
}
resume_unwind(payload.0);
}
let error = match result {
Ok(()) if problems.len() <= 1 => return problems.pop().map_or(Ok(()), Err),
Ok(()) => None,
Err(error) if problems.is_empty() && notes.is_empty() => return Err(error),
Err(error) => Some(error),
};
Err(crate::Error::other(TestFailure {
error,
problems,
notes,
}))
}
#[derive(Debug)]
struct TestFailure {
error: Option<crate::Error>,
problems: Vec<crate::Error>,
notes: Vec<String>,
}
impl fmt::Display for TestFailure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut lines = Vec::new();
if let Some(error) = &self.error {
lines.push(format!("{error:?}"));
}
for problem in &self.problems {
lines.push(format!("and then: {problem:?}"));
}
for note in &self.notes {
lines.push(format!("note: {note}"));
}
f.write_str(&lines.join("\n"))
}
}
impl std::error::Error for TestFailure {}
pub fn run(
info: TestInfo,
env: EnvConst,
body: impl FnOnce(&mut Context) -> crate::Result,
) -> crate::Result {
let mut environment = Environment::new(info.path())
.with_locale(env.locale)
.with_package(info.package);
environment.size = env.size;
environment.theme = env.theme;
environment.scale_factor = env.scale_factor;
environment.varies = env.varies;
let mut context = Context::new(info, environment);
let caught = catch_unwind(AssertUnwindSafe(|| body(&mut context)));
if context.slots.is_empty() {
return caught.unwrap_or_else(|payload| resume_unwind(payload));
}
let (outcome, result, panic) = match caught {
Ok(Ok(())) => (TestOutcome::Passed, Ok(()), None),
Ok(Err(error)) => (TestOutcome::Failed(format!("{error:?}")), Err(error), None),
Err(payload) => (
TestOutcome::Failed(panic_message(&payload)),
Ok(()),
Some(PanicPayload(payload)),
),
};
let bare = context.take_bare().ok();
let errors = context.teardown(&outcome, &mut RuntimeRef::new(bare.as_ref()));
let problems = errors.into_iter().map(crate::Error::from).collect();
conclude(result, problems, Vec::new(), panic)
}
pub fn assert_app<Args, F: Launch<Args>>(app: F) {
let _ = app;
}
pub fn launch<Args, F: Launch<Args>>(app: F, context: &mut Context) -> crate::Result<F::Program> {
app.launch(context)
}
pub fn config_for<P: TestProgram>(_: &P, context: &Context) -> HarnessConfig<P> {
context.env.apply(HarnessConfig::default())
}
#[diagnostic::on_unimplemented(
message = "`{Self}` cannot be an icedwright `app` function",
label = "each parameter must be `&T` for a fixture `T`, and it must return `impl TestProgram`",
note = "built-in fixtures: `TempDir`, `Environment`, `Locale`, `Seed`, `fake::Calls<Req, Resp>`",
note = "a returned `impl Trait` borrows every reference parameter unless it says `+ use<>`; \
write `impl iced::Program<..> + use<>` so the program owns what it keeps"
)]
pub trait Launch<Args>: Sized {
type Program: TestProgram;
fn launch(self, context: &mut Context) -> crate::Result<Self::Program>;
}
impl<F, P> Launch<()> for F
where
F: FnOnce() -> P,
P: TestProgram,
{
type Program = P;
fn launch(self, _: &mut Context) -> crate::Result<P> {
Ok(self())
}
}
macro_rules! launches {
($($name:ident $binding:ident),+) => {
impl<Func, P, $($name: Fixture),+> Launch<($($name,)+)> for Func
where
Func: FnOnce($(&$name),+) -> P,
P: TestProgram,
{
type Program = P;
fn launch(self, context: &mut Context) -> crate::Result<P> {
<($($name,)+) as FixtureSet>::prepare(context)?;
let ($($binding,)+) = <($($name,)+) as FixtureSet>::refs(context)?;
Ok(self($($binding),+))
}
}
};
}
launches!(A a);
launches!(A a, B b);
launches!(A a, B b, C c);
launches!(A a, B b, C c, D d);
launches!(A a, B b, C c, D d, E e);
launches!(A a, B b, C c, D d, E e, F f);
launches!(A a, B b, C c, D d, E e, F f, G g);
launches!(A a, B b, C c, D d, E e, F f, G g, H h);
pub trait IntoResult {
fn into_result(self) -> crate::Result;
}
impl IntoResult for () {
fn into_result(self) -> crate::Result {
Ok(())
}
}
impl<E: Into<crate::Error>> IntoResult for Result<(), E> {
fn into_result(self) -> crate::Result {
self.map_err(Into::into)
}
}
#[derive(Debug)]
pub struct MessageProbe<'a, P: TestProgram>(pub &'a Harness<P>);
pub trait KnownMessages {
fn known_messages(&self) -> Option<MessageCoverageFile>;
}
impl<P: TestProgram> KnownMessages for &MessageProbe<'_, P>
where
P::Message: Messages,
{
fn known_messages(&self) -> Option<MessageCoverageFile> {
Some(MessageCoverageFile::of(&self.0.coverage()))
}
}
pub trait UnknownMessages {
fn known_messages(&self) -> Option<MessageCoverageFile> {
None
}
}
impl<P: TestProgram> UnknownMessages for MessageProbe<'_, P> {}