Files
FlySimOperationSystem/terminal/tests/integration/runtime.rs
T
lain 7f331565c7 Add terminal service implementation and integration tests
- Introduced terminal.h header file defining the terminal service API.
- Implemented integration tests for terminal service registration and health checks.
- Added unit tests for FFI layer, health checks, and terminal service functionality.
- Created a mock center for testing terminal registration and deregistration.
- Ensured proper error handling and response validation in tests.
2026-09-20 10:55:38 +08:00

192 lines
6.2 KiB
Rust

use std::sync::{Arc, Mutex, mpsc};
use std::time::Duration;
use axum::Router;
use buffa_types::google::protobuf::{Empty, StringValue};
use connectrpc::client::{ClientConfig, Http2Connection};
use connectrpc::{
ConnectError, Protocol, RequestContext, Response, ServiceRequest, ServiceResult, ServiceStream,
};
use futures_util::stream;
use proto::proto::control::{
Center, Command, InvokeResponse, TerminalClient, TerminalInfo, TerminalInfos,
TerminalRegisterResponse,
};
use proto::proto::grpc::health::v1::{
HealthCheckRequest, HealthClient, health_check_response::ServingStatus,
};
use tokio::runtime::Runtime;
use tokio::sync::oneshot;
use crate::runtime::RunningServer;
use crate::terminal::Service;
const CENTER_ASSIGNED_ID: &str = "center-terminal-1";
#[derive(Default)]
struct FakeCenter {
registered: Mutex<Option<TerminalInfo>>,
deregistered_id: Mutex<Option<String>>,
}
#[allow(refining_impl_trait)]
impl Center for FakeCenter {
async fn register_terminal(
&self,
_context: RequestContext,
request: ServiceRequest<'_, TerminalInfo>,
) -> ServiceResult<TerminalRegisterResponse> {
*self.registered.lock().unwrap() = Some(request.to_owned_message());
Response::ok(TerminalRegisterResponse {
success: true,
message: CENTER_ASSIGNED_ID.to_owned(),
..Default::default()
})
}
async fn deregister_terminal(
&self,
_context: RequestContext,
request: ServiceRequest<'_, StringValue>,
) -> ServiceResult<InvokeResponse> {
*self.deregistered_id.lock().unwrap() = Some(request.to_owned_message().value);
Response::ok(InvokeResponse {
success: true,
..Default::default()
})
}
async fn subscribe_terminal(
&self,
_context: RequestContext,
_request: ServiceRequest<'_, Empty>,
) -> ServiceResult<ServiceStream<TerminalInfos>> {
Response::stream_ok(stream::empty::<Result<TerminalInfos, ConnectError>>())
}
}
#[test]
fn start_registers_actual_port_and_stop_deregisters_same_id() {
let center = Arc::new(FakeCenter::default());
let center_runtime = Runtime::new().unwrap();
let listener = center_runtime
.block_on(tokio::net::TcpListener::bind(("127.0.0.1", 0)))
.unwrap();
let center_port = listener.local_addr().unwrap().port();
let rpc = connectrpc::Router::new().add_service(Arc::clone(&center));
let app = Router::new().fallback_service(rpc.into_axum_service());
let (shutdown_tx, shutdown_rx) = oneshot::channel();
let (started_tx, started_rx) = mpsc::sync_channel(1);
let center_task = center_runtime.spawn(async move {
started_tx.send(()).unwrap();
axum::serve(listener, app)
.with_graceful_shutdown(async move {
let _ = shutdown_rx.await;
})
.await
});
started_rx.recv_timeout(Duration::from_secs(1)).unwrap();
let service = Service::new_value();
service
.configure(TerminalInfo {
terminal_host: "127.0.0.1".to_owned(),
terminal_port: 0,
terminal_mac: "00:11:22:33:44:55".to_owned(),
..Default::default()
})
.unwrap();
let server = RunningServer::start(&service, "127.0.0.1".to_owned(), center_port).unwrap();
let registered = center.registered.lock().unwrap().clone().unwrap();
assert_ne!(registered.terminal_port, 0);
assert_eq!(registered.terminal_port, u32::from(server.bound_port()));
assert_eq!(
service.meta_status_receiver().borrow().terminal_id,
CENTER_ASSIGNED_ID
);
let terminal_uri: axum::http::Uri = format!("http://127.0.0.1:{}", server.bound_port())
.parse()
.unwrap();
center_runtime.block_on(async {
let connection = Http2Connection::connect_plaintext(terminal_uri.clone())
.await
.unwrap();
let connection = connection.shared(32);
let config = ClientConfig::new(terminal_uri)
.with_protocol(Protocol::Grpc)
.with_default_timeout(Duration::from_secs(2));
let health = HealthClient::new(connection.clone(), config.clone());
for name in ["", "control.Terminal"] {
let response = health
.check(HealthCheckRequest {
service: name.into(),
..Default::default()
})
.await
.unwrap()
.into_owned();
assert_eq!(response.status, ServingStatus::SERVING);
}
let error = health
.check(HealthCheckRequest {
service: "missing".into(),
..Default::default()
})
.await
.unwrap_err();
assert_eq!(error.code, connectrpc::ErrorCode::NotFound);
let mut watcher = health.watch(HealthCheckRequest::default()).await.unwrap();
assert_eq!(
watcher
.message()
.await
.unwrap()
.unwrap()
.to_owned_message()
.status,
ServingStatus::SERVING
);
drop(watcher);
let mut watcher = health
.watch(HealthCheckRequest {
service: "missing".into(),
..Default::default()
})
.await
.unwrap();
assert_eq!(
watcher
.message()
.await
.unwrap()
.unwrap()
.to_owned_message()
.status,
ServingStatus::SERVICE_UNKNOWN
);
drop(watcher);
let client = TerminalClient::new(connection, config);
let response = client
.execute(Command {
id: "not-registered".to_owned(),
..Default::default()
})
.await
.unwrap()
.into_owned();
assert!(!response.success);
});
server.stop(&service).unwrap();
assert_eq!(
center.deregistered_id.lock().unwrap().as_deref(),
Some(CENTER_ASSIGNED_ID)
);
shutdown_tx.send(()).unwrap();
center_runtime.block_on(center_task).unwrap().unwrap();
}