use pagetop::prelude::*; // Rendering regions looks up localized labels, so the localization subsystem must be loaded. async fn setup() { Application::new().await; } fn request() -> HttpRequest { web::test::TestRequest::get().to_http_request() } /// Pushes a message while it renders, like a form that reports its own errors. #[derive(AutoDefault, Clone)] struct Pusher(&'static str); #[async_trait] impl Component for Pusher { fn new() -> Self { Self::default() } async fn prepare(&self, cx: &mut Context) -> Result { cx.push_message(MessageLevel::Error, Lc::n(self.0)); Ok(html! { p { "pusher-" (self.0) } }) } } /// Deferred component that shows how many messages the context holds when it renders. #[derive(Clone)] struct Counter; #[async_trait] impl Component for Counter { fn new() -> Self { Self } fn is_deferred(&self) -> bool { true } async fn prepare(&self, cx: &mut Context) -> Result { Ok(html! { span { "count-" (cx.messages().len()) } }) } } /// Deferred component that adds a stylesheet to the page while it renders. #[derive(Clone)] struct Styled; #[async_trait] impl Component for Styled { fn new() -> Self { Self } fn is_deferred(&self) -> bool { true } fn setup(&mut self, cx: &mut Context) { cx.alter_assets(StyleSheet::from("/deferred.css")); } } /// Renders a deferred component and throws its output away, so its mark never reaches the body. #[derive(Clone)] struct Discarder; #[async_trait] impl Component for Discarder { fn new() -> Self { Self } async fn prepare(&self, cx: &mut Context) -> Result { Counter.render(cx).await; Ok(html! { "discarded" }) } } async fn render(mut page: Page) -> String { page.render().await.expect("page renders").into_string() } #[pagetop::test] async fn messages_pushed_while_rendering_are_shown_first_in_the_content() { setup().await; let page = Page::new(request()) .with_child(Pusher("from-content")) .with_child_in(&CoreRegions::Footer, Pusher("from-footer")); let body = render(page).await; let messages = body.find(r#"class="messages""#).expect("messages"); assert!(body.find("region-content").unwrap() < messages); assert!(messages < body.find("pusher-from-content").unwrap()); assert!(messages < body.find("pusher-from-footer").unwrap()); assert_eq!(body.matches("message message-error").count(), 2); assert!(!body.contains("