use futures_util::{SinkExt, StreamExt};
use std::time::Duration;
use tempfile::NamedTempFile;
use tokio_tungstenite::tungstenite::protocol::Message;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn cli_replay_file_path_reaches_the_handler() {
let replay = NamedTempFile::new().unwrap();
let replay_path = replay.path().to_path_buf();
std::fs::write(
&replay_path,
r#"{"ts":0,"dir":"out","text":"CLI-REPLAY-MARKER {{uuid}}","waitFor":"^CLIENT_READY$"}
"#,
)
.unwrap();
std::env::set_var("MOCKFORGE_WS_REPLAY_FILE", &replay_path);
std::env::set_var("MOCKFORGE_RESPONSE_TEMPLATE_EXPAND", "true");
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let _server =
tokio::spawn(async move { axum::serve(listener, mockforge_ws::router()).await.unwrap() });
tokio::time::sleep(Duration::from_millis(50)).await;
let url = format!("ws://{}/ws", addr);
let (mut ws, _) =
tokio::time::timeout(Duration::from_secs(3), tokio_tungstenite::connect_async(url))
.await
.expect("ws handshake should not time out")
.expect("ws handshake ok");
ws.send(Message::Text("CLIENT_READY".into())).await.unwrap();
let got = tokio::time::timeout(Duration::from_secs(3), ws.next())
.await
.expect("replay frame should arrive")
.expect("stream produced a message")
.expect("no transport error");
let text = match got {
Message::Text(t) => t.to_string(),
other => panic!("expected text frame, got {other:?}"),
};
assert!(
text.contains("CLI-REPLAY-MARKER"),
"expected replay content from the temp file, got: {text}"
);
assert!(!text.contains("{{uuid}}"), "template token should have been expanded: {text}");
std::env::remove_var("MOCKFORGE_WS_REPLAY_FILE");
std::env::remove_var("MOCKFORGE_RESPONSE_TEMPLATE_EXPAND");
}