use std::collections::BTreeSet;
use std::process::Command;
use iced::theme::Mode;
use iced::widget::{column, text};
use iced::{Element, Task};
use icedwright::matrix::{Locale, Size, Theme};
use icedwright::prelude::*;
use icedwright::units::ScaleFactor;
task_name! {
pub LoadCount: u32;
}
#[derive(Debug, Clone, PartialEq)]
enum Message {
Loaded(u32),
}
#[derive(Debug)]
struct Shelf {
count: Option<u32>,
greeting: String,
}
impl Shelf {
fn update(&mut self, message: Message) {
match message {
Message::Loaded(count) => self.count = Some(count),
}
}
fn view(&self) -> Element<'_, Message> {
let count = match self.count {
Some(count) => format!("{count} books"),
None => "Loading".to_owned(),
};
column![text(self.greeting.clone()), text(count)].into()
}
}
#[derive(Debug)]
struct Store {
books: u32,
}
impl Fixture for Store {
type Deps = (TempDir,);
fn setup((dir,): (&TempDir,), _: &Environment) -> Result<Self, FixtureError> {
std::fs::write(dir.path().join("books"), "3")?;
let books = std::fs::read_to_string(dir.path().join("books"))?;
let books = books.trim().parse().map_err(FixtureError::other)?;
Ok(Store { books })
}
}
fn launch(
store: &Store,
env: &Environment,
) -> iced::Application<
impl iced::Program<State = Shelf, Message = Message, Theme = iced::Theme> + use<>,
> {
let books = store.books;
let greeting = format!("Hello in {}", env.locale);
iced::application(
move || {
let shelf = Shelf {
count: None,
greeting: greeting.clone(),
};
let load = Task::perform(LoadCount::task(async move { books }), Message::Loaded);
(shelf, load)
},
Shelf::update,
Shelf::view,
)
}
fn hold_loads<P: TestProgram>(config: HarnessConfig<P>) -> HarnessConfig<P> {
config.tasks(|rules| {
rules.hold::<LoadCount>();
})
}
fn shows<P: TestProgram>(ui: &mut Harness<P>, wanted: &str) -> icedwright::Result<bool> {
Ok(ui.get_by_text(wanted).count()? > 0)
}
#[icedwright::test(app = launch, config = hold_loads, matrix(
sizes(Size::Phone, Size::Custom(1024, 700)),
themes(Theme::Light, Theme::Dark),
))]
fn the_window_follows_the_combination(
ui: &mut Harness<impl TestProgram<State = Shelf, Message = Message>>,
env: &Environment,
) -> icedwright::Result {
let window = ui.main_window()?.id();
let info = ui.window_info(window)?;
let (width, height) = env.size.map(Size::dimensions).unwrap_or_default();
assert_eq!(info.logical_size.get().width, f32::from(width));
assert_eq!(info.logical_size.get().height, f32::from(height));
assert_eq!(info.theme_mode, Mode::from(env.theme));
let size = if width == 360 { "phone" } else { "w1024h700" };
let theme = if env.theme == Theme::Dark {
"dark"
} else {
"light"
};
assert_eq!(ui.variant().to_string(), format!("{theme}-{size}"));
assert_eq!(ui.tasks().held().filter(|t| t.is::<LoadCount>()).count(), 1);
assert_eq!(ui.state().count, None);
ui.tasks().resolve::<LoadCount>(7)?;
assert!(shows(ui, "7 books")?);
Ok(())
}
icedwright::matrix! {
pub scales_and_locales = scales(ScaleFactor::ONE, ScaleFactor::TWO), locales(Locale::EN_GB, "ar")
}
#[icedwright::test(app = launch, matrix = scales_and_locales)]
fn the_app_is_given_the_locale(
ui: &mut Harness<impl TestProgram<State = Shelf, Message = Message>>,
locale: Locale,
env: &Environment,
) -> icedwright::Result {
assert_eq!(locale, env.locale);
assert!(shows(ui, &format!("Hello in {locale}"))?);
let window = ui.main_window()?.id();
assert_eq!(ui.window_info(window)?.scale_factor, env.scale_factor);
assert_eq!(
ui.variant().to_string(),
format!("{}x", env.scale_factor.get())
);
assert!(shows(ui, "3 books")?);
Ok(())
}
#[icedwright::suite(app = launch, matrix(themes(Theme::Light, Theme::Dark)))]
mod suite {
use super::*;
#[icedwright::test]
fn inherits_the_suite(
ui: &mut Harness<impl TestProgram<State = Shelf, Message = Message>>,
env: &Environment,
) -> icedwright::Result {
let window = ui.main_window()?.id();
assert_eq!(ui.window_info(window)?.theme_mode, Mode::from(env.theme));
Ok(())
}
#[icedwright::test(config = hold_loads, matrix(sizes(Size::Tablet)))]
fn overrides_the_matrix(
ui: &mut Harness<impl TestProgram<State = Shelf, Message = Message>>,
env: &Environment,
) -> icedwright::Result {
assert_eq!(env.size, Some(Size::Tablet));
assert_eq!(env.theme, Theme::Light);
ui.tasks().resolve::<LoadCount>(1)?;
Ok(())
}
}
#[icedwright::test(app = launch, matrix(
sizes(Size::Phone, Size::Tablet, Size::Desktop),
themes(Theme::Light, Theme::Dark),
scales(ScaleFactor::ONE, ScaleFactor::TWO),
pairwise,
))]
fn pairwise_runs_fewer(
ui: &mut Harness<impl TestProgram<State = Shelf, Message = Message>>,
) -> icedwright::Result {
assert!(shows(ui, "3 books")?);
Ok(())
}
#[icedwright::test(matrix(
sizes(Size::Phone, Size::Desktop),
scales(ScaleFactor::ONE, ScaleFactor::X1_25),
exclude(Size::Phone, ScaleFactor::X1_25),
))]
fn excluded_combinations_are_not_generated(env: &Environment) {
assert!(!(env.size == Some(Size::Phone) && env.scale_factor == ScaleFactor::X1_25));
}
#[icedwright::test]
fn fixtures_without_an_app(seed: Seed, dir: &TempDir, env: &Environment) -> icedwright::Result {
assert_eq!(env.test(), "fixtures_without_an_app");
assert_eq!(seed, Seed::from_env_or(env.test())?);
assert!(dir.path().is_dir());
assert!(dir.path().ends_with("icedwright/fixtures_without_an_app"));
Ok(())
}
#[icedwright::test]
#[should_panic(expected = "the body panicked")]
fn a_panic_reaches_libtest(env: &Environment) {
panic!("the body panicked in {}", env.test());
}
fn listed() -> icedwright::Result<BTreeSet<String>> {
let output = Command::new(std::env::current_exe()?)
.args(["--list", "--format", "terse"])
.output()?;
Ok(String::from_utf8_lossy(&output.stdout)
.lines()
.filter_map(|line| line.strip_suffix(": test"))
.map(str::to_owned)
.collect())
}
#[test]
fn each_combination_is_a_test_named_after_its_values() -> icedwright::Result {
let listed = listed()?;
let expected = [
"the_window_follows_the_combination::phone_light",
"the_window_follows_the_combination::phone_dark",
"the_window_follows_the_combination::w1024h700_light",
"the_window_follows_the_combination::w1024h700_dark",
"the_app_is_given_the_locale::x1_en_gb",
"the_app_is_given_the_locale::x1_ar",
"the_app_is_given_the_locale::x2_en_gb",
"the_app_is_given_the_locale::x2_ar",
"suite::inherits_the_suite::light",
"suite::inherits_the_suite::dark",
"suite::overrides_the_matrix::tablet",
"excluded_combinations_are_not_generated::phone_x1",
"excluded_combinations_are_not_generated::desktop_x1",
"excluded_combinations_are_not_generated::desktop_x1_25",
"fixtures_without_an_app",
"a_panic_reaches_libtest",
];
for name in expected {
assert!(listed.contains(name), "{name} is missing from {listed:#?}");
}
assert!(!listed.contains("excluded_combinations_are_not_generated::phone_x1_25"));
let pairwise: Vec<&String> = listed
.iter()
.filter(|name| name.starts_with("pairwise_runs_fewer::"))
.collect();
assert!(
(6..12).contains(&pairwise.len()),
"pairwise chose {pairwise:?}"
);
Ok(())
}