crates/edge/api/tests/sse.rs 2.5 KiB 75 lines Raw
1 //! SSE framing, byte for byte.2 //!3 //! Requirement R18 compares bytes, so this test does not use a JSON writer to4 //! make the expected frame: the expected frame is a literal. A change to a field5 //! name, a separator, or the final token fails here and nowhere else.6 7 use inf3r_api::event::{Body, Event};8 use inf3r_api::sse;9 10 /// One event with every envelope field set, so the order of the fields is part11 /// of the golden.12 fn event() -> Event {13     Event {14         job: Some("j-00000001".to_string()),15         request_id: Some("req-1".to_string()),16         at: Some("2026-01-02T03:04:05.006Z".to_string()),17         body: Body::Text {18             channel: "text".to_string(),19             text: "hello".to_string(),20         },21     }22 }23 24 #[test]25 fn one_event_frame_is_exactly_these_bytes() {26     let mut out = Vec::new();27     sse::write_event(&mut out, &event().to_json(1)).expect("write");28     // The writer sorts keys, so the envelope reads in alphabetical order. The29     // golden holds that order, because a client that parses one frame twice30     // must not see two orders.31     let expected = concat!(32         "data: {\"at\":\"2026-01-02T03:04:05.006Z\",",33         "\"body\":{\"channel\":\"text\",\"t\":\"delta\",\"text\":\"hello\"},",34         "\"job\":\"j-00000001\",\"request_id\":\"req-1\",\"seq\":1}\n\n"35     );36     assert_eq!(String::from_utf8(out).expect("utf8"), expected);37 }38 39 #[test]40 fn the_terminal_frame_is_exactly_these_bytes() {41     let mut out = Vec::new();42     sse::write_done(&mut out).expect("write");43     assert_eq!(out, b"data: [DONE]\n\n");44     assert_eq!(sse::DONE, "data: [DONE]\n\n");45 }46 47 #[test]48 fn a_comment_keeps_the_connection_and_cannot_start_a_field() {49     let mut out = Vec::new();50     sse::write_comment(&mut out, "keep\nfield: x").expect("write");51     assert_eq!(String::from_utf8(out).expect("utf8"), ": keep field: x\n\n");52 }53 54 #[test]55 fn a_done_event_of_a_finished_job_is_one_frame() {56     let event = Event {57         job: Some("j-00000002".to_string()),58         request_id: None,59         at: None,60         body: Body::Done {61             outcome: "completed".to_string(),62             artifacts: Vec::new(),63             meta: None,64         },65     };66     let mut out = Vec::new();67     sse::write_event(&mut out, &event.to_json(9)).expect("write");68     assert_eq!(69         String::from_utf8(out).expect("utf8"),70         concat!(71             "data: {\"body\":{\"artifacts\":[],\"outcome\":\"completed\",\"t\":\"done\"},",72             "\"job\":\"j-00000002\",\"seq\":9}\n\n"73         )74     );75 }