use std::time::Duration;
use motorcortex_rust::ConnectionOptions;
use motorcortex_rust::core::{ConnectionState, Request};
use crate::{CERT_PATH, URL_REQ};
#[tokio::test]
async fn test_async_request_drop_without_disconnect_does_not_hang() {
let opts = ConnectionOptions::new(CERT_PATH.to_string(), 5000, 5000)
.with_token_refresh_interval(Duration::from_millis(200));
let req = Request::connect_to(URL_REQ, opts).await.expect("connect");
tokio::time::sleep(Duration::from_millis(300)).await;
tokio::time::timeout(Duration::from_secs(3), async move {
tokio::task::spawn_blocking(move || {
drop(req);
})
.await
.unwrap();
})
.await
.expect("Request drop without disconnect must not hang");
}
#[tokio::test]
async fn test_async_request_round_trips_connect_and_disconnect() {
let req = Request::new();
assert_eq!(*req.state().borrow(), ConnectionState::Disconnected);
let opts = ConnectionOptions::new(CERT_PATH.to_string(), 5000, 5000);
req.connect(URL_REQ, opts)
.await
.expect("connect must succeed against the vendored server");
assert_eq!(*req.state().borrow(), ConnectionState::Connected);
req.disconnect()
.await
.expect("disconnect must succeed after a successful connect");
assert_eq!(*req.state().borrow(), ConnectionState::Disconnected);
}
#[tokio::test]
async fn test_connection_state_watch_observes_every_transition() {
let req = Request::new();
let mut state = req.state();
assert_eq!(*state.borrow_and_update(), ConnectionState::Disconnected);
let opts = ConnectionOptions::new(CERT_PATH.to_string(), 5000, 5000);
req.connect(URL_REQ, opts.clone()).await.expect("connect");
state.changed().await.expect("state must update on connect");
assert_eq!(*state.borrow_and_update(), ConnectionState::Connected);
req.disconnect().await.expect("disconnect");
state
.changed()
.await
.expect("state must update on disconnect");
assert_eq!(*state.borrow_and_update(), ConnectionState::Disconnected);
req.connect(URL_REQ, opts).await.expect("reconnect");
state.changed().await.expect("state must update on reconnect");
assert_eq!(*state.borrow_and_update(), ConnectionState::Connected);
req.disconnect().await.expect("final disconnect");
state
.changed()
.await
.expect("state must update on final disconnect");
assert_eq!(*state.borrow_and_update(), ConnectionState::Disconnected);
}
#[tokio::test]
async fn test_async_request_clone_shares_driver() {
let req = Request::new();
let clone = req.clone();
let opts = ConnectionOptions::new(CERT_PATH.to_string(), 5000, 5000);
req.connect(URL_REQ, opts).await.expect("connect");
assert_eq!(*clone.state().borrow(), ConnectionState::Connected);
clone
.disconnect()
.await
.expect("disconnect from the clone must affect the shared driver");
assert_eq!(*req.state().borrow(), ConnectionState::Disconnected);
}