Skip to main content

TestApp

Struct TestApp 

Source
pub struct TestApp { /* private fields */ }
Expand description

A headless app for tests.

TestApp runs a real App on a deterministic scheduler. Its platform keeps the clipboard, opened URLs and prompts in memory, so you can assert on them instead of seeing them on screen. Each TestApp is independent: state set in one doesn’t appear in another.

See the testing guide.

Implementations§

Source§

impl TestApp

Source

pub fn new() -> Self

Creates a test app with scheduler seed 0.

Text is shaped by the test text system, not by real fonts. Use TestApp::with_text_system when a test measures real glyphs.

Source

pub fn with_seed(seed: u64) -> Self

Creates a test app whose scheduler orders ready tasks by seed.

The seed decides which ready task runs first. The same seed gives the same order every time, so a failing seed can be replayed.

Source

pub fn with_text_system(text_system: Arc<dyn PlatformTextSystem>) -> Self

Creates a test app that shapes text with text_system. Uses seed 0.

Pass a real text system to measure glyphs as the app would on a platform.

Source

pub fn with_text_system_and_assets( text_system: Arc<dyn PlatformTextSystem>, asset_source: Arc<dyn AssetSource>, ) -> Self

Creates a test app with the given text system and asset source.

This is TestApp::with_text_system plus an AssetSource, so views can load icons and other assets. Uses seed 0.

Source

pub fn update<R>(&mut self, f: impl FnOnce(&mut App) -> R) -> R

Runs f with mutable access to the App, then runs pending tasks until none can make progress.

Effects such as observers and subscriptions run when f returns, before the pending tasks run. Timers that haven’t expired stay pending; use TestApp::advance_clock to fire them.

§Example
let mut app = TestApp::new();
let finished = Rc::new(Cell::new(false));

let flag = finished.clone();
app.spawn(|_| async move { flag.set(true) }).detach();

// Any update runs the task that was spawned above.
app.update(|_| ());
assert!(finished.get());
Source

pub fn read<R>(&self, f: impl FnOnce(&App) -> R) -> R

Runs f with read-only access to the App.

This doesn’t run pending tasks. A task that is still waiting to run doesn’t run before f is called.

Source

pub fn new_entity<T: 'static>( &mut self, build: impl FnOnce(&mut Context<'_, T>) -> T, ) -> Entity<T>

Creates an entity from build and runs pending tasks until parked.

This is cx.new(build) inside TestApp::update.

Source

pub fn update_entity<T: 'static, R>( &mut self, entity: &Entity<T>, f: impl FnOnce(&mut T, &mut Context<'_, T>) -> R, ) -> R

Updates an entity and runs pending tasks until parked.

Source

pub fn read_entity<T: 'static, R>( &self, entity: &Entity<T>, f: impl FnOnce(&T, &App) -> R, ) -> R

Reads an entity without running pending tasks.

Source

pub fn open_window<V: Render + 'static>( &mut self, build_view: impl FnOnce(&mut Window, &mut Context<'_, V>) -> V, ) -> TestAppWindow<V>

Opens a window sized to the test display and returns a TestAppWindow for its root view.

The window’s bounds are the maximized bounds of the test display. Use TestApp::open_window_with_options to choose other bounds.

§Panics

Panics if the window can’t be opened.

Source

pub fn open_window_with_options<V: Render + 'static>( &mut self, options: WindowOptions, build_view: impl FnOnce(&mut Window, &mut Context<'_, V>) -> V, ) -> TestAppWindow<V>

Opens a window with options and returns a TestAppWindow for its root view.

§Panics

Panics if the window can’t be opened.

Source

pub fn run_until_parked(&self)

Runs tasks until none can make progress.

This doesn’t move the simulated clock. A timer that hasn’t expired stays pending until TestApp::advance_clock moves time past it.

§Example
let mut app = TestApp::new();
let fired = Rc::new(Cell::new(false));

let flag = fired.clone();
app.spawn(|cx| async move {
    cx.background_executor().timer(Duration::from_secs(1)).await;
    flag.set(true);
})
.detach();

app.run_until_parked();
assert!(!fired.get(), "the timer hasn't expired yet");

app.advance_clock(Duration::from_secs(1));
app.run_until_parked();
assert!(fired.get());
Source

pub fn advance_clock(&self, duration: Duration)

Moves the simulated clock forward by duration.

Tasks that become ready run during the call, including timers that expire within the window. Use this to test timeouts and delays, as in the example for TestApp::run_until_parked.

Source

pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncApp) -> Fut) -> Task<R> ⓘ
where Fut: Future<Output = R> + 'static, R: 'static,

Spawns a future on the foreground executor, given an AsyncApp for this app.

The future runs when the app runs tasks: during TestApp::run_until_parked, TestApp::advance_clock or the next update. Await, store or detach the returned Task, as in a real app. See async work.

Source

pub fn background_spawn<R>( &self, future: impl Future<Output = R> + Send + 'static, ) -> Task<R> ⓘ
where R: Send + 'static,

Spawns a Send future on the background executor.

Like TestApp::spawn, the future runs when the app runs tasks.

Source

pub fn to_async(&self) -> AsyncApp

Returns an AsyncApp for this app.

The handle holds a weak reference, so it can’t keep the app alive.

Source

pub fn background_executor(&self) -> &BackgroundExecutor

Returns the test background executor.

Source

pub fn foreground_executor(&self) -> &ForegroundExecutor

Returns the test foreground executor.

Source

pub fn text_system(&self) -> &Arc<TextSystem> ⓘ

Returns the text system the app uses to shape and measure text.

Source

pub fn has_global<G: Global>(&self) -> bool

Returns whether a global of type G is set.

Source

pub fn set_global<G: Global>(&mut self, global: G)

Sets the global of type G, replacing any previous value, then runs pending tasks.

Source

pub fn read_global<G: Global, R>(&self, f: impl FnOnce(&G, &App) -> R) -> R

Runs f with the global of type G.

§Panics

Panics if no global of type G is set. Check with TestApp::has_global first.

Source

pub fn update_global<G: Global, R>( &mut self, f: impl FnOnce(&mut G, &mut App) -> R, ) -> R

Runs f with mutable access to the global of type G, then runs pending tasks.

§Panics

Panics if no global of type G is set.

Source

pub fn write_to_clipboard(&self, item: ClipboardItem)

Writes item to the test clipboard.

TestApp::read_from_clipboard returns the item until something else is written.

Source

pub fn read_from_clipboard(&self) -> Option<ClipboardItem>

Returns the item most recently written to the test clipboard, or None if nothing was written.

Source

pub fn opened_url(&self) -> Option<String>

Returns the URL most recently passed to App::open_url, or None.

Nothing is launched. Only the last URL is kept, so open a second URL and the first is no longer reported.

§Example
let mut app = TestApp::new();
app.update(|cx| cx.open_url("https://example.com"));
assert_eq!(app.opened_url().as_deref(), Some("https://example.com"));
Source

pub fn did_prompt_for_new_path(&self) -> bool

Returns whether a App::prompt_for_new_path request is waiting for an answer.

Answer it with TestApp::simulate_new_path_selection.

Source

pub fn simulate_new_path_selection( &self, select: impl FnOnce(&Path) -> Option<PathBuf>, )

Answers the oldest pending App::prompt_for_new_path request.

select receives the directory the app asked about and returns the chosen path, or None to cancel the request.

§Panics

Panics if no new-path request is pending.

Source

pub fn has_pending_prompt(&self) -> bool

Returns whether a prompt from Window::prompt is waiting for an answer.

Source

pub fn simulate_prompt_answer(&self, button: &str)

Answers the oldest pending prompt by pressing the button labelled button.

The prompt is removed before the label is checked, so a wrong label still consumes it.

§Panics

Panics if no prompt is pending, or if no button has the label button.

Source

pub fn windows(&self) -> Vec<AnyWindowHandle>

Returns the handles of all open windows.

Trait Implementations§

Source§

impl Default for TestApp

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<S, D, Swp, Dwp, T> AdaptInto<D, Swp, Dwp, T> for S
where T: Real + Zero + Arithmetics + Clone, Swp: WhitePoint<T>, Dwp: WhitePoint<T>, D: AdaptFrom<S, Swp, Dwp, T>,

Source§

fn adapt_into_using<M>(self, method: M) -> D
where M: TransformMatrix<T>,

👎Deprecated since 0.7.7:

replaced by palette::chromatic_adaptation::AdaptIntoUnclamped

Convert the source color to the destination color using the specified method.
Source§

fn adapt_into(self) -> D

👎Deprecated since 0.7.7:

replaced by palette::chromatic_adaptation::AdaptIntoUnclamped

Convert the source color to the destination color using the bradford method by default.
Source§

impl<T, C> AdaptIntoUnclamped<T> for C
where T: AdaptFromUnclamped<C>,

Source§

type Scalar = <T as AdaptFromUnclamped<C>>::Scalar

The number type that’s used as the color’s components.
Source§

fn adapt_into_unclamped_with<M>(self) -> T

Adapt a color of type Self into a color of type T, using the custom matrix M. Read more
Source§

fn adapt_into_unclamped(self) -> T
where Bradford: LmsToXyz<Self::Scalar> + XyzToLms<Self::Scalar>,

Adapt a color of type Self into a color of type T, using the Bradford matrix. Read more
Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T, C> ArraysFrom<C> for T
where C: IntoArrays<T>,

Source§

fn arrays_from(colors: C) -> T

Cast a collection of colors into a collection of arrays.
Source§

impl<T, C> ArraysInto<C> for T
where C: FromArrays<T>,

Source§

fn arrays_into(self) -> C

Cast this collection of arrays into a collection of colors.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<WpParam, T, U> Cam16IntoUnclamped<WpParam, T> for U
where T: FromCam16Unclamped<WpParam, U>,

Source§

type Scalar = <T as FromCam16Unclamped<WpParam, U>>::Scalar

The number type that’s used in parameters when converting.
Source§

fn cam16_into_unclamped( self, parameters: BakedParameters<WpParam, <U as Cam16IntoUnclamped<WpParam, T>>::Scalar>, ) -> T

Converts self into C, using the provided parameters.
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T, C> ComponentsFrom<C> for T
where C: IntoComponents<T>,

Source§

fn components_from(colors: C) -> T

Cast a collection of colors into a collection of color components.
Source§

impl<T, C> ComponentsInto<C> for T

Source§

fn components_into(self) -> C

Cast this collection of color components into a collection of colors. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromAngle<T> for T

Source§

fn from_angle(angle: T) -> T

Performs a conversion from angle.
Source§

impl<T, U> FromStimulus<U> for T
where U: IntoStimulus<T>,

Source§

fn from_stimulus(other: U) -> T

Converts other into Self, while performing the appropriate scaling, rounding and clamping.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> IntoAngle<U> for T
where U: FromAngle<T>,

Source§

fn into_angle(self) -> U

Performs a conversion into T.
Source§

impl<WpParam, T, U> IntoCam16Unclamped<WpParam, T> for U
where T: Cam16FromUnclamped<WpParam, U>,

Source§

type Scalar = <T as Cam16FromUnclamped<WpParam, U>>::Scalar

The number type that’s used in parameters when converting.
Source§

fn into_cam16_unclamped( self, parameters: BakedParameters<WpParam, <U as IntoCam16Unclamped<WpParam, T>>::Scalar>, ) -> T

Converts self into C, using the provided parameters.
Source§

impl<T, U> IntoColor<U> for T
where U: FromColor<T>,

Source§

fn into_color(self) -> U

Convert into T with values clamped to the color defined bounds Read more
Source§

impl<T, U> IntoColorUnclamped<U> for T
where U: FromColorUnclamped<T>,

Source§

fn into_color_unclamped(self) -> U

Convert into T. The resulting color might be invalid in its color space Read more
Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoStimulus<T> for T

Source§

fn into_stimulus(self) -> T

Converts self into T, while performing the appropriate scaling, rounding and clamping.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<R, P> ReadPrimitive<R> for P
where R: Read + ReadEndian<P>, P: Default,

Source§

fn read_from_little_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_little_endian().
Source§

fn read_from_big_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_big_endian().
Source§

fn read_from_native_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_native_endian().
Source§

impl<T, C> TryComponentsInto<C> for T
where C: TryFromComponents<T>,

Source§

type Error = <C as TryFromComponents<T>>::Error

The error for when try_into_colors fails to cast.
Source§

fn try_components_into(self) -> Result<C, <T as TryComponentsInto<C>>::Error>

Try to cast this collection of color components into a collection of colors. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T, U> TryIntoColor<U> for T
where U: TryFromColor<T>,

Source§

fn try_into_color(self) -> Result<U, OutOfBounds<U>>

Convert into T, returning ok if the color is inside of its defined range, otherwise an OutOfBounds error is returned which contains the unclamped color. Read more
Source§

impl<C, U> UintsFrom<C> for U
where C: IntoUints<U>,

Source§

fn uints_from(colors: C) -> U

Cast a collection of colors into a collection of unsigned integers.
Source§

impl<C, U> UintsInto<C> for U
where C: FromUints<U>,

Source§

fn uints_into(self) -> C

Cast this collection of unsigned integers into a collection of colors.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more