rusteron_media_driver/
testing.rs1use crate::{Aeron, AeronCError, AeronDriver, AeronDriverContext, IntoCString};
6use std::sync::Arc;
7use std::sync::atomic::{AtomicBool, Ordering};
8use std::thread::JoinHandle;
9
10pub struct EmbeddedDriver {
20 dir: String,
21 context: AeronDriverContext,
22 stop: Arc<AtomicBool>,
23 handle: Option<JoinHandle<Result<(), AeronCError>>>,
24}
25
26impl EmbeddedDriver {
27 pub fn launch() -> Result<Self, AeronCError> {
29 Self::launch_with(|_| Ok(()))
30 }
31
32 pub fn launch_with(
35 configure: impl FnOnce(&AeronDriverContext) -> Result<(), AeronCError>,
36 ) -> Result<Self, AeronCError> {
37 let context = AeronDriverContext::new()?;
38 context.set_dir_delete_on_shutdown(true)?;
39 context.set_dir_delete_on_start(true)?;
40 context.set_dir(&format!("{}{}", context.get_dir(), Aeron::nano_clock()).into_c_string())?;
41 configure(&context)?;
42 let dir = context.get_dir().to_string();
43 let (stop, handle) = AeronDriver::launch_embedded(context.clone(), false);
44 Ok(Self {
45 dir,
46 context,
47 stop,
48 handle: Some(handle),
49 })
50 }
51
52 #[inline]
54 pub fn dir(&self) -> &str {
55 &self.dir
56 }
57
58 #[inline]
60 pub fn context(&self) -> &AeronDriverContext {
61 &self.context
62 }
63
64 pub fn stop(mut self) {
66 self.stop_and_join();
67 }
68
69 fn stop_and_join(&mut self) {
70 self.stop.store(true, Ordering::SeqCst);
71 if let Some(handle) = self.handle.take() {
72 let _ = handle.join();
73 }
74 }
75}
76
77impl Drop for EmbeddedDriver {
78 fn drop(&mut self) {
79 self.stop_and_join();
80 }
81}
82
83pub fn find_unused_udp_port(start: u16) -> Option<u16> {
85 (start..65535).find(|p| std::net::UdpSocket::bind(("127.0.0.1", *p)).is_ok())
86}
87
88#[cfg(test)]
89mod tests {
90 use super::*;
91
92 #[test]
93 fn embedded_driver_launches_and_stops_on_drop() {
94 let driver = EmbeddedDriver::launch().unwrap();
95 assert!(!driver.dir().is_empty());
96 let dir = driver.dir().to_string();
97 drop(driver); assert!(!std::path::Path::new(&dir).join("cnc.dat").exists());
99 }
100
101 #[test]
102 fn find_unused_udp_port_returns_bindable_port() {
103 let port = find_unused_udp_port(23000).unwrap();
104 assert!(std::net::UdpSocket::bind(("127.0.0.1", port)).is_ok());
105 }
106}