Smeltery
Get started

Anvil (broadcasting)

v0.1

Testing broadcasts

rust
use serde_json::json;
use smeltery::anvil::testing::{AnvilSpy, TestSocket, auth_of, authorize};
use smeltery::anvil::{Anvil, AnvilExt as _, Channel, ChannelCtx};
use smeltery::testing::TestApp;

let app = TestApp::new(|b| {
    b.anvil(|c| {
        c.public("news");
        // In this test, user n owns order n.
        c.private("orders.{order}", |ctx: ChannelCtx| async move {
            Ok(ctx.user_id() == Some(ctx.param::<i64>("order")?))
        });
    })
});
let spy = AnvilSpy::of(app.app());
let mut socket = TestSocket::connect(app.app());

// A private subscription with the auth endpoint's answer.
app.acting_as(7);
let auth = auth_of(&authorize(&app, socket.socket_id(), "private-orders.7", None)).unwrap();
assert_eq!(
    socket.subscribe("private-orders.7", Some(&auth))["event"],
    "pusher_internal:subscription_succeeded"
);

let anvil = Anvil::of(app.app()).unwrap();
app.block_on(async {
    anvil.to(Channel::private("orders.7")).event("shipped").with(&json!({ "id": 7 })).await
})?;
assert!(spy.sent_on("private-orders.7", "shipped"));
assert_eq!(socket.events()[0]["data"], r#"{"id":7}"#);

AnvilSpy records every send, the last 10,000 (sent(), sent_on(channel, name), nothing_sent()); TestSocket connects to the hub without a network (subscribe, subscribe_presence, whisper, unsubscribe, send, events, closed; dropping it leaves its presence channels); authorize posts to the auth endpoint as the TestApp's browser (with TestApp::with_csrf, pass the CSRF token), and presence_of reads a presence answer's auth and channel_data. TestSocket keeps presence members in the process's memory (the TestApp's local PubSub driver).

↑↓ moveEnter openEsc close