use std::sync::Arc;
use rstest::rstest;
use crate::{
WireframeError,
app::{Envelope, Handler, StreamingHandler, WireframeApp},
request::{RequestBodyStream, RequestParts},
};
const ROUTE_ID: u32 = 7;
#[derive(Clone, Copy, Debug)]
enum RouteKind {
Buffered,
Streaming,
}
fn register(app: WireframeApp, kind: RouteKind) -> Result<WireframeApp, WireframeError> {
match kind {
RouteKind::Buffered => app.route(ROUTE_ID, buffered_handler()),
RouteKind::Streaming => app.streaming_route(ROUTE_ID, streaming_handler()),
}
}
fn buffered_handler() -> Handler<Envelope> { Arc::new(|_: &Envelope| Box::pin(async {})) }
fn streaming_handler() -> StreamingHandler {
Arc::new(|_parts: RequestParts, _body: RequestBodyStream| Box::pin(async { None }))
}
#[rstest]
#[case::buffered_then_streaming(RouteKind::Buffered, RouteKind::Streaming)]
#[case::streaming_then_buffered(RouteKind::Streaming, RouteKind::Buffered)]
#[case::streaming_twice(RouteKind::Streaming, RouteKind::Streaming)]
#[case::buffered_twice(RouteKind::Buffered, RouteKind::Buffered)]
fn registering_one_identifier_twice_is_rejected(
#[case] first: RouteKind,
#[case] second: RouteKind,
) {
let app = WireframeApp::new().expect("the default application should build");
let registered = register(app, first).expect("the first registration should succeed");
let Err(error) = register(registered, second) else {
panic!("the second registration must be rejected");
};
assert!(
matches!(error, WireframeError::DuplicateRoute(id) if id == ROUTE_ID),
"a duplicate identifier must be reported as DuplicateRoute, got {error:?}"
);
}
#[test]
fn replacing_the_codec_keeps_streaming_routes() {
let app: WireframeApp = WireframeApp::new()
.expect("the default application should build")
.streaming_route(ROUTE_ID, streaming_handler())
.expect("the streaming route should register");
let replaced = app.with_codec(crate::codec::LengthDelimitedFrameCodec::new(4096));
assert!(
replaced.streaming_handlers.contains_key(&ROUTE_ID),
"a codec change must not unregister a streaming route"
);
}