wabot_feature_socket_controller/testing.rs
1//! Drive socket events in a test, without a connection.
2//!
3//! ## What it runs, and what it can't
4//!
5//! It runs the **same dispatch closure** a live connection runs: the
6//! payload is deserialized and validated the same way, the controller
7//! is resolved from the same container, and the answer goes through
8//! the same [`ack_result`](crate::ack_result) — captured instead of
9//! sent. Nothing here reimplements the runtime, so what a test
10//! observes is what a client would have received.
11//!
12//! What it cannot do is *be* a connection. There is no
13//! `SocketRef`, so:
14//!
15//! * a handler that takes a `SocketRef` reports that it needs a live
16//! socket rather than running — [`EmittedEvent::needs_socket`] says
17//! so plainly;
18//! * a handshake middleware is *built* but not run, since running one
19//! means handing it a socket.
20//!
21//! For those, and for anything protocol-level, use a real client. The
22//! socket-rooms verification script did exactly that, and
23//! is what demonstrated the wire behaviour this harness stands on.
24//!
25//! ```ignore
26//! let harness = SocketHarness::new(RoomController::socket_registration(&container), container);
27//!
28//! let ack = harness.emit("join", json!({ "room": "general" })).await;
29//! assert_eq!(ack.value()["room"], "general");
30//!
31//! let bad = harness.emit("join", json!({ "room": "" })).await;
32//! assert_eq!(bad.error_code(), Some("INVALID_PAYLOAD"));
33//! ```
34
35use wabot_core::injection::Container;
36
37use crate::{AckSink, SocketControllerRegistration, SocketEventEntry};
38
39/// Runs a controller's events against a container, with no server.
40pub struct SocketHarness {
41 registration: SocketControllerRegistration,
42 container: Container,
43}
44
45impl SocketHarness {
46 pub fn new(registration: SocketControllerRegistration, container: Container) -> Self {
47 Self {
48 registration,
49 container,
50 }
51 }
52
53 pub fn namespace(&self) -> &str {
54 &self.registration.namespace
55 }
56
57 /// Event names, in registration order.
58 pub fn event_names(&self) -> Vec<&'static str> {
59 self.registration.event_names()
60 }
61
62 /// Handshake middleware names, in the order they would run.
63 pub fn handshake_names(&self) -> Vec<&'static str> {
64 self.registration.handshake_names()
65 }
66
67 /// The container a connection's events resolve from.
68 ///
69 /// A real connection gets a *child* of it, populated by the
70 /// handshake; register there what a middleware would have, and a
71 /// handler sees the same thing it would in production.
72 pub fn container(&self) -> &Container {
73 &self.container
74 }
75
76 fn entry(&self, event: &str) -> &SocketEventEntry {
77 self.registration
78 .events
79 .iter()
80 .find(|entry| entry.event == event)
81 .unwrap_or_else(|| {
82 panic!(
83 "no handler for the '{event}' event. This controller handles: {:?}",
84 self.registration.event_names()
85 )
86 })
87 }
88
89 /// Emit an event and capture what the client would have received.
90 ///
91 /// # Panics
92 ///
93 /// If no handler is registered for `event` — a test emitting an
94 /// event nothing handles is asserting nothing, and in production
95 /// that packet is silently dropped, which is worse to discover
96 /// later.
97 pub async fn emit(&self, event: &str, payload: serde_json::Value) -> EmittedEvent {
98 let entry = self.entry(event);
99 let (sink, captured) = AckSink::capture();
100 (entry.invoke)(self.container.clone(), None, payload, sink).await;
101 let ack = captured.lock().clone();
102 EmittedEvent {
103 event: event.to_string(),
104 ack,
105 }
106 }
107}
108
109/// What an emitted event produced.
110pub struct EmittedEvent {
111 pub event: String,
112 /// What went back through the ack, if anything. `None` means the
113 /// handler answered nothing — a `connection`-style handler.
114 pub ack: Option<serde_json::Value>,
115}
116
117impl EmittedEvent {
118 /// The acked value.
119 ///
120 /// # Panics
121 ///
122 /// If nothing was acked, naming the event — the usual cause is a
123 /// handler that needs a live socket.
124 pub fn value(&self) -> serde_json::Value {
125 self.ack.clone().unwrap_or_else(|| {
126 panic!(
127 "the '{}' event answered nothing. A handler that takes a SocketRef cannot be \
128 driven without a connection — check needs_socket().",
129 self.event
130 )
131 })
132 }
133
134 /// The `error.code` when the handler (or validation) refused.
135 pub fn error_code(&self) -> Option<&str> {
136 self.ack.as_ref()?.get("error")?.get("code")?.as_str()
137 }
138
139 pub fn error_message(&self) -> Option<&str> {
140 self.ack.as_ref()?.get("error")?.get("message")?.as_str()
141 }
142
143 pub fn is_error(&self) -> bool {
144 self.error_code().is_some()
145 }
146
147 /// True when the handler declined because it wants a real socket.
148 pub fn needs_socket(&self) -> bool {
149 self.error_message()
150 .is_some_and(|message| message.contains("needs a live socket"))
151 }
152
153 /// The acked value as `T`.
154 pub fn json<T: serde::de::DeserializeOwned>(&self) -> T {
155 serde_json::from_value(self.value()).unwrap_or_else(|error| {
156 panic!(
157 "the '{}' event answered {:?}, which is not a {} ({error})",
158 self.event,
159 self.ack,
160 std::any::type_name::<T>()
161 )
162 })
163 }
164}