icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
//! What `#[icedwright::test]` expands to calls, as `$crate::__private::testing`. Not a stable
//! API.

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;

/// Fails the build, at the parameter's span, when `T` is not a fixture.
pub const fn assert_fixture<T: Fixture>() {}

/// One combination, written as a `const` by the macro.
#[derive(Debug, Clone, Copy)]
pub struct EnvConst {
    /// The main window's size, or the program's own.
    pub size: Option<Size>,
    /// The system theme.
    pub theme: Theme,
    /// The system scale factor.
    pub scale_factor: ScaleFactor,
    /// The locale.
    pub locale: Locale,
    /// The axes the matrix varies, which name snapshots.
    pub varies: Varies,
}

/// Where the generated test is.
#[derive(Debug, Clone, Copy)]
pub struct TestInfo {
    /// `CARGO_PKG_NAME` of the crate the test is in.
    pub package: &'static str,
    /// `module_path!()` at the generated test.
    pub module: &'static str,
    /// The generated test's own name.
    pub name: &'static str,
}

impl TestInfo {
    /// The path libtest prints: the module path without the crate, then the name.
    #[must_use]
    pub fn path(&self) -> String {
        let mut parts: Vec<&str> = self.module.split("::").skip(1).collect();
        parts.push(self.name);
        parts.join("::")
    }
}

/// The body's result, or the payload it panicked with.
#[derive(Debug)]
pub struct Caught(Result<crate::Result, PanicPayload>);

/// A panic payload, kept to resume after teardown.
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),
        },
    }
}

/// The fixtures of one test, in setup order, and the runtime they use when there is no app.
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,
        }
    }

    /// The combination this test runs in.
    #[must_use]
    pub fn environment(&self) -> &Environment {
        &self.env
    }

    /// Builds `T` and its dependencies, once each.
    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(())
    }

    /// A fixture built by [`prepare`](Self::prepare).
    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
    }

    /// Takes the bare runtime out of `self`, building it first, so fixtures can borrow `self`
    /// while they use it.
    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)
    }

    /// Runs `started` on every fixture over a bare runtime, for a test with no app.
    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
    }

    /// Boots the harness with `config`, then runs `started` on every fixture.
    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)
    }

    /// Runs the body, catching a panic so teardown still runs.
    pub fn call(&self, body: impl FnOnce(&Context) -> crate::Result) -> Caught {
        Caught(catch_unwind(AssertUnwindSafe(|| body(self))).map_err(PanicPayload))
    }

    /// After a body with a harness: coverage, teardown in reverse order of setup, then
    /// [`Harness::finish`].
    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)
    }

    /// After a body with no harness: teardown in reverse order of setup.
    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))
        }
    }
}

/// A test named after a theme that rendered in the other one is reported, since its name
/// would otherwise mislead.
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
        )
    })
}

/// The test's result: the body's error first, then what failed after it, then notes. A
/// teardown error after a passing body fails the test; a panic resumes once teardown is done.
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,
    }))
}

/// A failure with more to say than one error: what went wrong after it, and 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 {}

/// Runs one generated test: builds its context, runs `body`, and tears down whatever was set
/// up when `body` stopped early.
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));
    }
    // Setup or launch stopped before the body ran.
    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)
}

/// Fails the build at the `app` key when the function cannot launch a program.
pub fn assert_app<Args, F: Launch<Args>>(app: F) {
    let _ = app;
}

/// Builds the program from an `app` function, injecting its fixtures.
pub fn launch<Args, F: Launch<Args>>(app: F, context: &mut Context) -> crate::Result<F::Program> {
    app.launch(context)
}

/// The configuration a test's harness starts from: the defaults with the environment applied.
pub fn config_for<P: TestProgram>(_: &P, context: &Context) -> HarnessConfig<P> {
    context.env.apply(HarnessConfig::default())
}

/// An `app` function: each parameter `&T` for a fixture `T`, returning a program.
#[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 {
    /// The program it returns.
    type Program: TestProgram;

    /// Builds its fixtures and calls it.
    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);

/// What a test body may return.
pub trait IntoResult {
    /// The body's result as an icedwright one.
    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)
    }
}

/// Message coverage when the program's message derives `Messages`, and nothing otherwise,
/// chosen by method resolution on `(&&MessageProbe(&harness)).known_messages()`.
#[derive(Debug)]
pub struct MessageProbe<'a, P: TestProgram>(pub &'a Harness<P>);

/// The arm taken when the message derives `Messages`.
pub trait KnownMessages {
    /// The message coverage.
    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()))
    }
}

/// The arm taken otherwise.
pub trait UnknownMessages {
    /// Nothing: the message's variants are not known.
    fn known_messages(&self) -> Option<MessageCoverageFile> {
        None
    }
}

impl<P: TestProgram> UnknownMessages for MessageProbe<'_, P> {}