use std::cell::RefCell;
use super::fixture::{Fixture, FixtureError, RuntimeRef, TestOutcome};
use super::matrix::{Locale, Size, Theme};
use super::support::{Context, EnvConst, IntoResult, TestInfo, run};
use super::{Environment, Seed, TempDir, Varies};
use crate::units::ScaleFactor;
thread_local! {
static LOG: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
}
fn log(entry: impl Into<String>) {
LOG.with(|log| log.borrow_mut().push(entry.into()));
}
fn take_log() -> Vec<String> {
LOG.with(|log| std::mem::take(&mut *log.borrow_mut()))
}
#[derive(Debug)]
struct Store;
impl Fixture for Store {
type Deps = ();
fn setup(_: (), _: &Environment) -> Result<Self, FixtureError> {
log("setup Store");
Ok(Store)
}
fn started(&mut self, runtime: &mut RuntimeRef<'_>) -> Result<(), FixtureError> {
let now = runtime.block_on(async { tokio::time::Instant::now() })?;
let later = runtime.block_on(async { tokio::time::Instant::now() })?;
log(format!("started Store, clock still: {}", now == later));
Ok(())
}
fn teardown(self, outcome: &TestOutcome, _: &mut RuntimeRef<'_>) -> Result<(), FixtureError> {
log(format!("teardown Store passed={}", outcome.passed()));
Ok(())
}
}
#[derive(Debug)]
struct Api(String);
impl Fixture for Api {
type Deps = (Store, Environment);
fn setup((_, env): (&Store, &Environment), _: &Environment) -> Result<Self, FixtureError> {
log("setup Api");
Ok(Api(env.locale.tag().to_owned()))
}
fn started(&mut self, _: &mut RuntimeRef<'_>) -> Result<(), FixtureError> {
log("started Api");
Ok(())
}
fn teardown(self, outcome: &TestOutcome, _: &mut RuntimeRef<'_>) -> Result<(), FixtureError> {
log(format!("teardown Api passed={}", outcome.passed()));
Ok(())
}
}
#[derive(Debug)]
struct Chicken;
#[derive(Debug)]
struct Egg;
impl Fixture for Chicken {
type Deps = (Egg,);
fn setup(_: (&Egg,), _: &Environment) -> Result<Self, FixtureError> {
Ok(Chicken)
}
}
impl Fixture for Egg {
type Deps = (Chicken,);
fn setup(_: (&Chicken,), _: &Environment) -> Result<Self, FixtureError> {
Ok(Egg)
}
}
#[derive(Debug)]
struct Broken;
impl Fixture for Broken {
type Deps = (Store,);
fn setup(_: (&Store,), _: &Environment) -> Result<Self, FixtureError> {
Err(FixtureError::other(std::io::Error::other("no disk")))
}
}
#[derive(Debug)]
struct FailsTeardown;
impl Fixture for FailsTeardown {
type Deps = ();
fn setup(_: (), _: &Environment) -> Result<Self, FixtureError> {
Ok(FailsTeardown)
}
fn teardown(self, _: &TestOutcome, _: &mut RuntimeRef<'_>) -> Result<(), FixtureError> {
Err(FixtureError::other(std::io::Error::other(
"left a lock behind",
)))
}
}
const INFO: TestInfo = TestInfo {
package: "icedwright",
module: "icedwright::testing::tests",
name: "case",
};
const ENV: EnvConst = EnvConst {
size: Some(Size::Phone),
theme: Theme::Dark,
scale_factor: ScaleFactor::TWO,
locale: Locale::AR,
varies: Varies {
size: true,
theme: true,
scale: false,
},
};
#[test]
fn the_variant_names_only_the_axes_the_matrix_varies() {
let result = run(INFO, ENV, |ctx| {
assert_eq!(ctx.environment().variant().to_string(), "dark-phone");
Ok(())
});
assert!(result.is_ok(), "{result:?}");
let all = Environment::new("t")
.with_theme(Theme::Dark)
.with_size(Size::Phone)
.with_scale_factor(ScaleFactor::TWO);
assert_eq!(all.variant().file_stem("board"), "board@dark-phone-2x");
assert!(Environment::new("t").variant().is_empty());
}
#[test]
fn apply_writes_the_axes_and_the_variant_into_the_config() {
let env = Environment::new("t")
.with_theme(Theme::Dark)
.with_size(Size::Tablet)
.with_scale_factor(ScaleFactor::X1_25);
let config: crate::HarnessConfig<crate::MountProgram<u32, ()>> =
env.apply(crate::HarnessConfig::default());
assert_eq!(config.system_theme, iced_core::theme::Mode::Dark);
assert_eq!(config.scale_factor, ScaleFactor::X1_25);
assert_eq!(config.size, Some(Size::Tablet.into()));
assert_eq!(config.variant, env.variant());
}
fn bare_test(body: impl FnOnce(&Api) -> crate::Result) -> crate::Result {
run(INFO, ENV, |ctx| {
ctx.prepare::<Api>()?;
ctx.start_bare()?;
let caught = ctx.call(|ctx| IntoResult::into_result(body(ctx.get::<Api>()?)));
ctx.finish_bare(caught)
})
}
#[test]
fn dependencies_set_up_first_start_in_order_and_tear_down_in_reverse() {
let result = bare_test(|api| {
log(format!("body {}", api.0));
Ok(())
});
assert!(result.is_ok(), "{result:?}");
assert_eq!(
take_log(),
vec![
"setup Store",
"setup Api",
"started Store, clock still: true",
"started Api",
"body ar",
"teardown Api passed=true",
"teardown Store passed=true",
]
);
}
#[test]
fn teardown_sees_a_failed_body() {
let result = bare_test(|_| Err(crate::Error::other(std::io::Error::other("nope"))));
assert!(format!("{result:?}").contains("nope"));
let log = take_log();
assert!(
log.contains(&"teardown Api passed=false".to_owned()),
"{log:?}"
);
assert!(
log.contains(&"teardown Store passed=false".to_owned()),
"{log:?}"
);
}
#[test]
fn teardown_runs_after_a_panic_and_the_panic_goes_on() {
let unwound = std::panic::catch_unwind(|| {
let _ = bare_test(|_| panic!("the body broke"));
});
assert!(unwound.is_err());
let log = take_log();
assert_eq!(
log[log.len() - 2..],
["teardown Api passed=false", "teardown Store passed=false"]
);
}
#[test]
fn a_cycle_names_both_fixtures() {
let mut ctx = Context::new(INFO, Environment::new("case"));
let error = ctx.prepare::<Chicken>().unwrap_err();
let FixtureError::Cycle { a, b } = error else {
panic!("{error:?}")
};
assert!(a.ends_with("Chicken") && b.ends_with("Egg"), "{a} {b}");
assert!(matches!(
ctx.prepare::<Egg>(),
Err(FixtureError::Cycle { .. })
));
}
#[test]
fn a_failed_setup_names_the_fixture_and_tears_down_what_was_built() {
let result = run(INFO, ENV, |ctx| {
ctx.prepare::<Broken>()?;
Ok(())
});
let text = format!("{result:?}");
assert!(text.contains("Broken failed in setup: no disk"), "{text}");
assert_eq!(
take_log(),
vec!["setup Store", "teardown Store passed=false"]
);
}
#[test]
fn a_teardown_error_fails_a_passing_test_and_is_appended_to_a_failing_one() {
let passing = run(INFO, ENV, |ctx| {
ctx.prepare::<FailsTeardown>()?;
ctx.start_bare()?;
let caught = ctx.call(|_| Ok(()));
ctx.finish_bare(caught)
});
let text = format!("{passing:?}");
assert!(
text.contains("FailsTeardown failed in teardown: left a lock behind"),
"{text}"
);
let failing = run(INFO, ENV, |ctx| {
ctx.prepare::<FailsTeardown>()?;
ctx.start_bare()?;
let caught = ctx.call(|_| Err(crate::Error::other(std::io::Error::other("first"))));
ctx.finish_bare(caught)
});
let text = format!("{failing:?}");
let first = text.find("first").unwrap();
let then = text.find("and then: ").unwrap();
assert!(first < then, "{text}");
}
#[test]
fn a_fixture_read_before_it_is_built_is_an_error() {
let ctx = Context::new(INFO, Environment::new("case"));
assert!(matches!(ctx.get::<Store>(), Err(FixtureError::NotBuilt(_))));
}
#[test]
fn the_environment_carries_the_combination_and_the_test_path() {
let result = run(INFO, ENV, |ctx| {
let env = ctx.environment();
assert_eq!(env.size, Some(Size::Phone));
assert_eq!(env.theme, Theme::Dark);
assert_eq!(env.scale_factor, ScaleFactor::TWO);
assert_eq!(env.locale, Locale::AR);
assert_eq!(env.test(), "testing::tests::case");
assert_eq!(env.package(), "icedwright");
ctx.prepare::<Seed>()?;
assert_eq!(*ctx.get::<Seed>()?, Seed::for_test("testing::tests::case"));
Ok(())
});
assert!(result.is_ok(), "{result:?}");
}
#[test]
fn a_temp_dir_is_kept_when_the_test_fails_and_removed_when_it_passes() {
let mut kept = None;
let result = run(
TestInfo {
name: "temp_dir_kept",
..INFO
},
ENV,
|ctx| {
ctx.prepare::<TempDir>()?;
ctx.start_bare()?;
let caught = ctx.call(|ctx| {
kept = Some(ctx.get::<TempDir>()?.path().to_owned());
Err(crate::Error::other(std::io::Error::other("failed")))
});
ctx.finish_bare(caught)
},
);
assert!(result.is_err());
let kept = kept.unwrap();
assert!(kept.is_dir(), "{}", kept.display());
assert!(kept.ends_with("icedwright/testing/tests/temp_dir_kept"));
std::fs::remove_dir_all(&kept).unwrap();
let mut removed = None;
let result = run(
TestInfo {
name: "temp_dir_removed",
..INFO
},
ENV,
|ctx| {
ctx.prepare::<TempDir>()?;
ctx.start_bare()?;
let caught = ctx.call(|ctx| {
removed = Some(ctx.get::<TempDir>()?.path().to_owned());
Ok(())
});
ctx.finish_bare(caught)
},
);
assert!(result.is_ok());
assert!(!removed.unwrap().exists());
}