日本語

Testing handlers

Tests that call a page's, an action's, and a stream's handler as functions and read the signals by their types, and tests that send a request through the router to check what the router adds.

Calling a handler

A handler is an async fn that takes the router's state and the arguments, so a test calls it as a function and reads what it returned. The tests below need two crates the server does not, added to Cargo.toml:

Cargo.toml
[dev-dependencies]
http-body-util = "0.1"
tower = { version = "0.5", features = ["util"] }

The program below is a page with a like button and an action that adds to a shared count. Its first three tests call index and like directly, and the last three send requests to the router. cargo test runs all of them.

src/main.rs
use std::sync::Arc;
use std::sync::atomic::{AtomicI32, Ordering};

use axum::Router;
use axum::http::StatusCode;
use hypersig::html::{button, p, span};
use hypersig::{Action, Page, Patches, Route, RouterExt, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Votes {
    likes: i32,
    error: String,
}

hypersig::routes! {
    fn pages(Router<Likes>);
    const INDEX: Route = "/" => index;
    action LIKE: Action<Votes, i32> = post "/like" => like;
}

#[derive(Clone, Default)]
struct Likes(Arc<AtomicI32>);

async fn index(likes: Likes, (): ()) -> Page<Votes> {
    let initial = Votes {
        likes: likes.0.load(Ordering::Relaxed),
        error: String::new(),
    };
    Page::new("Votes", initial)
        .child(
            button()
                .on_click(LIKE.call_with(1).error(Votes::error()))
                .text("Like ")
                .child(span().bind_text(Votes::likes().to_text())),
        )
        .child(p().bind_text(Votes::error()))
}

async fn like(likes: Likes, by: i32) -> Result<Patches<Votes>, (StatusCode, &'static str)> {
    if !(1..=5).contains(&by) {
        return Err((StatusCode::UNPROCESSABLE_ENTITY, "Like 1 to 5 times."));
    }
    let total = likes.0.fetch_add(by, Ordering::Relaxed) + by;
    Ok(Votes::likes().patch(total).into())
}

fn app(likes: Likes) -> Router {
    pages(Router::new()).hypersig_runtime().with_state(likes)
}

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await?;
    axum::serve(listener, app(Likes::default())).await
}

#[cfg(test)]
mod tests {
    use axum::body::Body;
    use axum::http::{HeaderValue, Request};
    use http_body_util::BodyExt as _;
    use tower::ServiceExt as _;

    use super::*;

    #[tokio::test]
    async fn the_page_starts_at_the_stored_count() {
        let likes = Likes::default();
        likes.0.store(7, Ordering::Relaxed);
        let page = index(likes, ()).await;
        assert_eq!(page.value_of(Votes::likes()), 7);
        assert!(page.render().contains(">7</span>"));
    }

    #[tokio::test]
    async fn a_like_adds_to_the_count() {
        let patches = like(Likes::default(), 2).await.unwrap();
        assert_eq!(patches.value_of(Votes::likes()), Some(2));
    }

    #[tokio::test]
    async fn more_than_five_likes_are_refused() {
        let refused = like(Likes::default(), 6).await;
        assert_eq!(
            refused.err(),
            Some((StatusCode::UNPROCESSABLE_ENTITY, "Like 1 to 5 times."))
        );
    }

    #[tokio::test]
    async fn the_router_answers_the_action_with_its_patches() {
        let response = app(Likes::default())
            .oneshot(LIKE.request(&3))
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let body = response.into_body().collect().await.unwrap().to_bytes();
        let expected = Patches::from(Votes::likes().patch(3)).to_event_stream();
        assert_eq!(body, expected.as_bytes());
    }

    #[tokio::test]
    async fn a_call_from_another_site_is_refused() {
        let mut request = LIKE.request(&3);
        request
            .headers_mut()
            .insert("sec-fetch-site", HeaderValue::from_static("cross-site"));
        let response = app(Likes::default()).oneshot(request).await.unwrap();
        assert_eq!(response.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn the_router_serves_the_page() {
        let request = Request::get(INDEX.url(()).as_str())
            .body(Body::empty())
            .unwrap();
        let response = app(Likes::default()).oneshot(request).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
    }
}

Reading a page's initial values

pub fn value_of<T: DeserializeOwned, M: FromPage>(&self, signal: Sig<S, T, M>) -> T
pub fn render(&self) -> String

Page::value_of returns the value a signal starts at in the browser: the value the page was built with, or for a computed signal, the value computed from the others. It takes the Sig the derive generated, so a test names a signal as the page does, and a misspelled field fails to compile.

Page::render returns the document the server sends, with each bound text and attribute written from the initial values, so a test can look for a text in it, as the_page_starts_at_the_stored_count looks for >7</span>. It panics where two elements share an id or a NodeRef name, so a test that renders each page finds those before a visitor does. Debugging a running page lists the other panics. To read one element in place of searching the whole document, use Simulation::element from Testing a page without a browser.

Reading an action's patches

pub fn value_of<T: DeserializeOwned>(&self, signal: Sig<S, T>) -> Option<T>
pub fn navigates_to(&self) -> Option<&Url>
pub fn replaces<F: Fragment<Signals = S>>(&self) -> bool
Method of Patches<S>What it returns
value_ofThe value the batch sets the signal to, or None where the batch leaves it alone
navigates_toThe URL of the first navigate in the batch, where the browser goes. A later one is never followed.
replacesWhether the batch re-renders the fragment F

A handler that refuses returns its error, which a test compares as a value, as more_than_five_likes_are_refused compares the status and the sentence. Patches<S> and the Sig share the signal struct S, so a test cannot read a batch with the field of another page's struct:

use hypersig::{Patches, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Votes {
    likes: i32,
}

#[derive(Signals, Serialize, Deserialize)]
struct Poll {
    likes: i32,
}

let patches: Patches<Votes> = Votes::likes().patch(3).into();
// error[E0308]: mismatched types: expected `Sig<Votes, _>`, found `Sig<Poll, i32>`
let likes = patches.value_of(Poll::likes());

Reading a list patch

pub fn items_of<T: DeserializeOwned>(&self, list: Sig<S, Vec<T>>) -> Vec<T>
pub fn removed_keys_of<T: Serialize, K: DeserializeOwned, E: IntoExpr<S, K>>(
    &self,
    list: Sig<S, Vec<T>>,
    key: impl FnOnce(Item<S, T>) -> E,
) -> Vec<K>

A handler that answers with a list patch sends only the items that change, so value_of does not see them. Patches::items_of returns the items a batch appends, prepends, or upserts into a list, in the order the batch sends them, which for a prepend is not the order the browser shows. Patches::removed_keys_of returns the keys it removes. The second takes the key closure the handler passed to patch_remove, and leaves out a removal by another key, so the test also checks the key the browser compares.

use hypersig::{Item, Patches, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize, Debug, PartialEq)]
struct Card {
    id: i32,
    title: String,
}

#[derive(Signals, Serialize, Deserialize)]
struct Board {
    cards: Vec<Card>,
}

let by_id = |card: Item<Board, Card>| card.at(Card::id());

// What a handler that renames card 3 and deletes card 7 returns.
let renamed = Card { id: 3, title: "Ship it".to_owned() };
let patches: Patches<Board> = Board::cards()
    .patch_upsert(&[renamed], by_id)
    .and(Board::cards().patch_remove(&[7], by_id))
    .into();

assert_eq!(
    patches.items_of(Board::cards()),
    [Card { id: 3, title: "Ship it".to_owned() }],
);
assert_eq!(patches.removed_keys_of(Board::cards(), by_id), [7]);

Reading a stream's batches

A stream's handler returns a Stream of Patches, so a test collects it with StreamExt::collect from the futures crate and reads each batch with the methods above. A stream that never ends, such as a clock, is read with StreamExt::take(n) before collect.

use futures::{Stream, StreamExt as _, stream};
use hypersig::{Patches, Signals, StreamAction};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Launch {
    left: i32,
}

hypersig::routes! {
    fn streams(Router<()>);
    stream COUNTDOWN: StreamAction<Launch, i32> = "/countdown" => countdown;
}

fn countdown((): (), from: i32) -> impl Stream<Item = Patches<Launch>> {
    stream::iter((0..from).rev()).map(|left| Launch::left().patch(left).into())
}

// The body of a `#[tokio::test] async fn`.
let batches: Vec<Patches<Launch>> = countdown((), 3).collect().await;
let left: Vec<Option<i32>> = batches.iter().map(|batch| batch.value_of(Launch::left())).collect();
assert_eq!(left, [Some(2), Some(1), Some(0)]);

Sending a request to the router

The last three tests of the program send a request to the Router with oneshot from tower::ServiceExt, which runs it in the process without opening a port. Write a test at this level for what the router adds to the handler: an extractor that refuses a visitor, the status of a refusal, the page for a URL no route matches, and the 400 for arguments that do not deserialize. The action's request comes from LIKE.request(&3), and a page's URL from Route::url, so a renamed action or route moves the test with it.

// impl<S, A: Serialize> Action<S, A>
pub fn request(&self, args: &A) -> axum::http::Request<axum::body::Body>
// impl<S, A> StreamAction<S, A>
pub fn request(&self, args: &A) -> axum::http::Request<axum::body::Body>
where
    A: serde::Serialize

Action::request builds the request the runtime sends, and StreamAction::request the GET that opens a stream, so a test names the action, not its path or its headers. args has the action's argument type, so a test cannot send arguments the handler does not take. The request carries these:

Part of the requestValue
Accepttext/event-stream, which RequestKind::of reads to tell a call (RequestKind::Runtime) from a page load (RequestKind::Navigation)
hypersig-callThe header the runtime adds to every call
A POST's bodyThe arguments as JSON, with Content-Type: application/json
A GET's URLThe arguments as JSON in the args query parameter, left out for ()
Sec-Fetch-SiteNot set. The router passes a request without it.

The router refuses a POST without that Content-Type, a GET without hypersig-call, and a Sec-Fetch-Site other than same-origin, as a_call_from_another_site_is_refused shows with cross-site and a 403. Security lists every refusal with its status. The body of an answered action is the batch as Server-Sent Events, which Patches::to_event_stream writes in the same form. A test compares the body with the batch it expects, as the_router_answers_the_action_with_its_patches does, in place of a text written by hand.

A handler that takes an extractor

A handler that takes an extractor, such as the Session of Signing in, is called with a value the test builds, as the tests below do for that page's sign_in. Session::new(None, Arc::new(MemoryStore::default()), None) makes an empty session with a store of its own, and the test reads what the handler wrote with Session::get. What the layer adds, the cookie in the answer, shows only through the router, so a second test sends the action through oneshot on the router with its SessionManagerLayer.

use std::sync::Arc;

use tower::ServiceExt as _;
use tower_sessions::{MemoryStore, Session};

// The body of a `#[tokio::test] async fn`. The test builds the `Session` the
// layer would hand the handler, with a store of its own.
let session = Session::new(None, Arc::new(MemoryStore::default()), None);
let credentials = Credentials { name: "ada".to_owned(), password: "secret".to_owned() };
let patches = sign_in(AppState, session.clone(), credentials).await.unwrap();
assert_eq!(patches.navigates_to(), Some(&HOME.url(())));
let member = session.get::<String>(MEMBER).await.unwrap();
assert_eq!(member.as_deref(), Some("ada"));

// A second test sends the action through the router, where the layer reads
// and writes the cookie as it does for a visitor.
let credentials = Credentials { name: "ada".to_owned(), password: "secret".to_owned() };
let response = app().oneshot(SIGN_IN.request(&credentials)).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let cookie = response.headers().get(header::SET_COOKIE).unwrap();
assert!(cookie.to_str().unwrap().starts_with("session="));

What these tests leave out

  • A handler called as a function skips the router: its extractors, the refusals of a request from another site, and the reading of the arguments from JSON. Test those through oneshot.
  • A routes! block whose generated function the application never calls compiles, and its pages and actions answer 404. A router test that expects a 200 from LIKE.request(&3) fails in that case.
  • Page::value_of and Patches::value_of panic where the value does not deserialize into the signal's type, which happens where a Serialize impl skips the field or disagrees with its Deserialize impl.
  • What the page does with the answer: the runtime applying the batch, and the statements that run when a signal changes. Testing a page without a browser covers the events, and a browser test the rest.

Next