Skip to main content

astrs_node_api/testing/
mod.rs

1//! The testing harness (blueprint §9.1's `init_testing`).
2//!
3//! ```
4//! use astrs_node_api::prelude::*;
5//! use astrs_wire::StopCause;
6//!
7//! # fn main() -> Result<(), NodeError> {
8//! let mut harness = Node::init_testing()?;
9//! let id = harness.node.id().clone();
10//!
11//! harness.daemon.stop(&id, StopCause::Requested)?;
12//! let event = harness.events.recv().expect("the stop");
13//! assert!(event.is_stop());
14//! # Ok(())
15//! # }
16//! ```
17//!
18//! # What makes this worth having
19//!
20//! A node's logic is `event in → output out`, and everything between is the
21//! session. A harness that stubbed the session would test the stub. This one
22//! runs the *real* session — the real greeting, the real frame codec, the real
23//! dispatcher, the real queues — against a [`MockDaemon`] that speaks the real
24//! protocol on the other end of a `tokio::io::duplex` pair. The only thing
25//! that is not real is the socket.
26//!
27//! That buys three things a stub cannot:
28//!
29//! * **Two-node tests.** [`TestHarness::pair`] connects a producer and a
30//!   consumer wired to each other, so a service round trip or an action FSM is
31//!   an ordinary `#[test]`.
32//! * **Protocol regressions.** A change that breaks the wire breaks these
33//!   tests, because they *are* on the wire.
34//! * **Route-upgrade tests.** [`MockDaemon::upgrade_route`] drives the §6.3
35//!   handshake, including the ack the node sends back.
36
37pub mod daemon;
38
39use std::time::Duration;
40
41use astrs_wire::{
42    DataId, InputSpec, NodeId, NodeSource, NodeSpawnSpec, OutputSpec, PortRef, StopCause,
43};
44
45use crate::error::{NodeError, Result};
46use crate::events::EventStream;
47use crate::node::Node;
48
49#[cfg(unix)]
50pub use daemon::UnixEndpoint;
51pub use daemon::{DUPLEX_BUFFER, HANDSHAKE_TIMEOUT, MockDaemon, RecordedRequest, RecordedSend};
52
53/// How long the harness's convenience waits allow.
54pub const DEFAULT_WAIT: Duration = Duration::from_secs(5);
55
56/// A node, its event stream, and the daemon it is talking to.
57#[derive(Debug)]
58pub struct TestHarness {
59    /// The node under test.
60    pub node: Node,
61    /// Its event stream.
62    pub events: EventStream,
63    /// The daemon on the other end.
64    pub daemon: MockDaemon,
65}
66
67impl TestHarness {
68    /// The node id [`TestHarness::start`] uses.
69    pub const DEFAULT_NODE: &'static str = "node-under-test";
70
71    /// The input [`TestHarness::start`] declares.
72    pub const DEFAULT_INPUT: &'static str = "in";
73
74    /// The output [`TestHarness::start`] declares.
75    pub const DEFAULT_OUTPUT: &'static str = "out";
76
77    /// Starts a daemon and one node with a single input and output.
78    ///
79    /// # Errors
80    ///
81    /// [`NodeError::Testing`] when the harness cannot be started.
82    pub fn start() -> Result<Self> {
83        let daemon = MockDaemon::start()?;
84        let spec = Self::default_spec(&daemon)?;
85        let (node, events) = daemon.connect_node(spec)?;
86        Ok(Self {
87            node,
88            events,
89            daemon,
90        })
91    }
92
93    /// Starts a daemon and one node with an explicit specification.
94    ///
95    /// # Errors
96    ///
97    /// As [`TestHarness::start`].
98    pub fn with_spec(spec: NodeSpawnSpec) -> Result<Self> {
99        let daemon = MockDaemon::start()?;
100        let (node, events) = daemon.connect_node(spec)?;
101        Ok(Self {
102            node,
103            events,
104            daemon,
105        })
106    }
107
108    /// Starts a daemon with a producer and a consumer wired to each other.
109    ///
110    /// `producer` publishes on `output`; `consumer` reads it as `input`. The
111    /// returned pair is `(producer, consumer)`.
112    ///
113    /// # Errors
114    ///
115    /// As [`TestHarness::start`].
116    pub fn pair(producer: &str, output: &str, consumer: &str, input: &str) -> Result<(Self, Self)> {
117        let daemon = MockDaemon::start()?;
118        let producer_spec = NodeSpawnSpec::new(
119            daemon.dataflow(),
120            NodeId::new(producer)?,
121            0,
122            NodeSource::Dynamic,
123        )
124        .with_output(OutputSpec::new(DataId::new(output)?));
125        let consumer_spec = NodeSpawnSpec::new(
126            daemon.dataflow(),
127            NodeId::new(consumer)?,
128            0,
129            NodeSource::Dynamic,
130        )
131        .with_input(InputSpec::new(
132            DataId::new(input)?,
133            PortRef::from_parts(producer, output)?,
134        ));
135
136        let (producer_node, producer_events) = daemon.connect_node(producer_spec)?;
137        let (consumer_node, consumer_events) = daemon.connect_node(consumer_spec)?;
138        Ok((
139            Self {
140                node: producer_node,
141                events: producer_events,
142                daemon: daemon.clone(),
143            },
144            Self {
145                node: consumer_node,
146                events: consumer_events,
147                daemon,
148            },
149        ))
150    }
151
152    /// The default specification: one input, one output, both wired to a
153    /// notional peer.
154    ///
155    /// # Errors
156    ///
157    /// [`NodeError::Id`] when the built-in names fail the grammar, which they
158    /// cannot.
159    pub fn default_spec(daemon: &MockDaemon) -> Result<NodeSpawnSpec> {
160        Ok(NodeSpawnSpec::new(
161            daemon.dataflow(),
162            NodeId::new(Self::DEFAULT_NODE)?,
163            0,
164            NodeSource::Dynamic,
165        )
166        .with_input(InputSpec::new(
167            DataId::new(Self::DEFAULT_INPUT)?,
168            PortRef::from_parts("peer", "out")?,
169        ))
170        .with_output(OutputSpec::new(DataId::new(Self::DEFAULT_OUTPUT)?)))
171    }
172
173    /// The node's id.
174    #[must_use]
175    pub fn node_id(&self) -> NodeId {
176        self.node.id().clone()
177    }
178
179    /// Delivers one message to the node's default input.
180    ///
181    /// # Errors
182    ///
183    /// As [`MockDaemon::send_input`].
184    pub fn feed(&self, payload: Vec<u8>) -> Result<()> {
185        self.feed_input(Self::DEFAULT_INPUT, payload)
186    }
187
188    /// Delivers one message to a named input.
189    ///
190    /// # Errors
191    ///
192    /// [`NodeError::Id`] for a malformed name, plus whatever
193    /// [`MockDaemon::send_input`] reports.
194    pub fn feed_input(&self, input: &str, payload: Vec<u8>) -> Result<()> {
195        let metadata = self.node.metadata();
196        self.daemon
197            .send_input(self.node.id(), &DataId::new(input)?, metadata, payload)
198    }
199
200    /// Reads the next event, failing rather than hanging.
201    ///
202    /// # Errors
203    ///
204    /// [`NodeError::Timeout`] when nothing arrives in [`DEFAULT_WAIT`], and
205    /// [`NodeError::Stopped`] when the stream has ended.
206    pub fn next_event(&mut self) -> Result<crate::Event> {
207        match self.events.recv_timeout(DEFAULT_WAIT)? {
208            Some(event) => Ok(event),
209            None if self.events.is_fused() || self.events.session_ended() => {
210                Err(NodeError::Stopped)
211            }
212            None => Err(NodeError::Timeout {
213                operation: "TestHarness::next_event",
214                millis: u64::try_from(DEFAULT_WAIT.as_millis()).unwrap_or(u64::MAX),
215            }),
216        }
217    }
218
219    /// Stops the node and drains the stop event.
220    ///
221    /// # Errors
222    ///
223    /// As [`MockDaemon::stop`].
224    pub fn stop(&mut self, cause: StopCause) -> Result<()> {
225        self.daemon.stop(self.node.id(), cause)?;
226        while let Ok(event) = self.next_event() {
227            if event.is_stop() {
228                return Ok(());
229            }
230        }
231        Ok(())
232    }
233
234    /// Shuts the harness down.
235    pub fn shutdown(&mut self) {
236        let _ = self.node.shutdown();
237        self.daemon.shutdown();
238    }
239}
240
241impl Drop for TestHarness {
242    fn drop(&mut self) {
243        self.shutdown();
244    }
245}
246
247#[cfg(test)]
248mod tests {
249    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
250
251    use super::*;
252    use crate::Event;
253
254    #[test]
255    fn the_default_harness_has_one_input_and_one_output() {
256        let mut harness = TestHarness::start().unwrap();
257        assert_eq!(harness.node_id().as_str(), TestHarness::DEFAULT_NODE);
258        assert_eq!(harness.node.descriptor().inputs.len(), 1);
259        assert_eq!(harness.node.descriptor().outputs.len(), 1);
260
261        harness.feed(vec![1, 2, 3]).unwrap();
262        let event = harness.next_event().unwrap();
263        let Some((id, _, data)) = event.into_input() else {
264            panic!("expected an input");
265        };
266        assert_eq!(id.as_str(), TestHarness::DEFAULT_INPUT);
267        assert_eq!(data.to_vec(), vec![1, 2, 3]);
268    }
269
270    #[test]
271    fn a_paired_harness_routes_between_two_nodes() {
272        let (mut producer, mut consumer) =
273            TestHarness::pair("camera", "image", "detect", "frames").unwrap();
274        let mut image = producer.node.raw_output("image").unwrap();
275        image
276            .send_bytes(vec![4, 5, 6], producer.node.metadata())
277            .unwrap();
278
279        let event = consumer.next_event().unwrap();
280        let Some((id, _, data)) = event.into_input() else {
281            panic!("expected an input");
282        };
283        assert_eq!(id.as_str(), "frames");
284        assert_eq!(data.to_vec(), vec![4, 5, 6]);
285    }
286
287    #[test]
288    fn stopping_the_harness_fuses_the_stream() {
289        let mut harness = TestHarness::start().unwrap();
290        harness.stop(StopCause::Requested).unwrap();
291        assert!(harness.events.is_fused());
292        assert!(matches!(harness.next_event(), Err(NodeError::Stopped)));
293    }
294
295    #[test]
296    fn an_empty_stream_times_out_rather_than_hanging() {
297        let mut harness = TestHarness::start().unwrap();
298        let error = harness
299            .events
300            .recv_timeout(Duration::from_millis(20))
301            .unwrap();
302        assert!(error.is_none());
303    }
304
305    #[test]
306    fn a_custom_specification_is_honoured() {
307        let daemon = MockDaemon::start().unwrap();
308        let spec = NodeSpawnSpec::new(
309            daemon.dataflow(),
310            NodeId::new("custom").unwrap(),
311            7,
312            NodeSource::Dynamic,
313        );
314        let harness = TestHarness::with_spec(spec).unwrap();
315        assert_eq!(harness.node.id().as_str(), "custom");
316        assert_eq!(harness.node.restart_count(), 7);
317        assert!(harness.node.is_restart());
318    }
319
320    #[test]
321    fn a_message_for_an_undeclared_input_is_reported() {
322        let mut harness = TestHarness::start().unwrap();
323        harness.feed_input("nope", vec![1]).unwrap();
324        let event = harness.next_event().unwrap();
325        assert!(matches!(event, Event::Error(_)), "{event}");
326    }
327
328    #[test]
329    fn the_documented_names_are_stable() {
330        assert_eq!(TestHarness::DEFAULT_NODE, "node-under-test");
331        assert_eq!(TestHarness::DEFAULT_INPUT, "in");
332        assert_eq!(TestHarness::DEFAULT_OUTPUT, "out");
333        assert_eq!(DEFAULT_WAIT, Duration::from_secs(5));
334    }
335}