SSE stream response test
Learn how to test a server-sent events endpoint, how to read its stream body in a test, and how to assert the wire format and Last-Event-ID resume
A server-sent events endpoint does not return a single answer. It returns a stream: a series of events, each written as lines of text, arriving over time on one open response. A test of such an endpoint has to read that stream, check the content type, check the exact bytes of each event, and check that a reconnect with a Last-Event-ID header replays only the events the client missed. This page does all of that with oneshot, because an SSE response is still a plain HTTP response, and the stream it carries can be collected and read in the test.
Where This Fits
The previous page needed a real socket because a WebSocket is a conversation on an open connection. An SSE stream is simpler: it is a normal HTTP response whose body arrives in pieces. The oneshot helper works again here, because it returns the response, and the body it carries is a stream the test can read to the end. The endpoint is the tick stream and the news feed from the server-sent events chapter, and the test checks both the wire format and the resume behaviour.
Think of a ticker tape. The machine prints one line at a time, and the test reads the tape after the machine stops, checking each printed line. When the tape is cut and the machine restarts, the reader tells it the number of the last line it saw, and the machine reprints only what came after. The test below reads the tape, cuts it, and checks the reprint.
The Smallest Working Version
The smallest SSE test hits a route that sends three events and then ends, and asserts the content type and the exact body bytes. The stream is finite, so the test can collect the whole body and compare it with the expected text.
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
futures-util = "0.3"
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
http-body-util = "0.1"
use std::convert::Infallible;
use axum::{
Router,
response::sse::{Event, Sse},
routing::get,
};
use futures_util::stream;
async fn ticks() -> Sse<impl futures_util::Stream<Item = Result<Event, Infallible>>> {
let events = (1..=3).map(|n| {
Ok(Event::default()
.data(format!("tick {n}"))
.id(n.to_string()))
});
Sse::new(stream::iter(events))
}
pub fn sse_app() -> Router {
Router::new().route("/ticks", get(ticks))
}
The handler builds three events and wraps them in an Sse response. Each event carries a data: line with the text tick 1, tick 2, or tick 3, and an id: line with the matching number. Sse::new takes a stream of Result<Event, Infallible> items, and stream::iter turns the in-memory list into such a stream. Infallible is the error type that can never happen, which is the honest type for a stream that never fails.
The test collects the body and compares it byte for byte:
use axum::{body::Body, http::{Request, StatusCode}};
use axum_project::sse_app;
use http_body_util::BodyExt;
use tower::ServiceExt;
#[tokio::test]
async fn ticks_stream_has_the_sse_content_type_and_three_events() {
let request = Request::builder()
.uri("/ticks")
.body(Body::empty())
.unwrap();
let response = sse_app().oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.headers()["content-type"], "text/event-stream");
let bytes = response.into_body().collect().await.unwrap().to_bytes();
let text = String::from_utf8(bytes.to_vec()).unwrap();
assert_eq!(
text,
"data: tick 1\nid: 1\n\ndata: tick 2\nid: 2\n\ndata: tick 3\nid: 3\n\n"
);
}
Run it with:
cargo test --test sse_test
The test passes, and it proves three things at once: the route answers 200, the response is an event stream, and the bytes on the wire are exactly the three events in order.
Working Setup:
If the ticks test passes, the stream, the content type, and the wire format all match. The exact string comparison is the strongest check on this page, because it leaves no room for a missing id line, a wrong order, or an extra blank line to hide.
The Wire Format, Line by Line
The expected body is worth reading line by line, because it is the wire format itself, and every line has a job:
data: tick 1
id: 1
data: tick 2
id: 2
data: tick 3
id: 3
Each event is two lines followed by a blank line. The data: line carries the payload, the text the client cares about. The id: line carries the event number, which the client remembers so it can resume after a disconnect. The blank line ends the event. A client reading this stream treats the blank line as the signal that one event is complete and the next one is starting.
The order of the lines follows the order the builder methods were called: .data() first, then .id(). The blank line is not something the handler writes by hand. The Sse response writes it when it turns each Event into bytes. A test that compares the whole body at once checks the order, the ids, the data, and the blank lines in a single assertion, which is why the exact comparison is the first test on this page rather than the last.
The content type matters as much as the body. A response with the right bytes and the wrong content type is not an event stream. A browser would render it as text or download it as a file, and an EventSource client would refuse it. The header assertion catches a handler that returns event-shaped text as text/plain, which is the most common SSE mistake there is.
Reading the Body, Piece by Piece
The test reads the body in three steps, and each step is a different tool:
let bytes = response.into_body().collect().await.unwrap().to_bytes();
let text = String::from_utf8(bytes.to_vec()).unwrap();
into_body takes the body out of the response. collect comes from http_body_util::BodyExt, and it reads the stream until it ends, gathering every chunk into one buffer. to_bytes turns that buffer into a single Bytes value. String::from_utf8 turns the bytes into text, which fails loudly if the stream ever sends bytes that are not valid UTF-8. For an SSE stream, which is text by definition, that failure would mean the server sent something badly broken.
collect only returns when the stream ends. That is why the handler on this page sends a finite stream of three events. A stream that never ends, like a live feed with a keep-alive comment every few seconds, would keep collect waiting forever, and the test would hang. The rule is simple: collect only streams the test knows will end, and read infinite streams frame by frame instead, as the next section shows.
Reading Frame by Frame
Sometimes the test needs to prove the events arrive one at a time, not all at once in a single chunk. The body can be turned into a stream of data chunks, and each chunk read as it arrives:
use futures_util::StreamExt;
#[tokio::test]
async fn events_arrive_one_by_one_as_separate_frames() {
let request = Request::builder()
.uri("/ticks")
.body(Body::empty())
.unwrap();
let response = sse_app().oneshot(request).await.unwrap();
let mut frames = Vec::new();
let mut stream = response.into_body().into_data_stream();
while let Some(chunk) = stream.next().await {
frames.push(String::from_utf8(chunk.unwrap().to_vec()).unwrap());
}
assert_eq!(frames.len(), 3);
assert!(frames[0].contains("data: tick 1"));
assert!(frames[2].contains("id: 3"));
}
into_data_stream turns the body into a stream of byte chunks, and next reads one chunk at a time. The loop collects each chunk as a string until the stream ends. The test then asserts there were three chunks, one per event, and that the first holds the first event and the last holds the third id. This is a weaker check on the exact bytes than the full comparison, and a stronger check on the delivery: it proves the server sent three separate frames, which is the shape a client watching a live stream actually sees.
The two reading styles answer different questions. collect answers "what did the stream contain, in total". The frame loop answers "how did the stream arrive". Use collect when the test is about the content, and the frame loop when the test is about the delivery. Most SSE tests need the first, and only a few need the second.
Collect Ends, Frames Arrive:
collect waits for the stream to finish and returns everything at once. The frame loop returns each piece as it arrives and finishes when the stream ends. Both need the stream to end eventually. Neither one can read a stream that never ends, and a test that tries will hang instead of failing.
Resuming with Last-Event-ID
An event id is useful because a client that disconnects can reconnect and ask for only what it missed. The client sends the id of the last event it saw in the Last-Event-ID header, and the server replays the events after it. The handler reads that header from the raw HeaderMap, because there is no typed extractor for it in the headers crate version this book uses, and the lookup is one line:
use axum::http::HeaderMap;
async fn news(headers: HeaderMap) -> Sse<impl futures_util::Stream<Item = Result<Event, Infallible>>> {
let headlines = [
(1, "First headline"),
(2, "Second headline"),
(3, "Third headline"),
];
let last_seen: usize = headers
.get("last-event-id")
.and_then(|value| value.to_str().ok())
.and_then(|value| value.parse().ok())
.unwrap_or(0);
let events = headlines
.into_iter()
.filter(move |(id, _)| *id > last_seen)
.map(|(id, text)| {
Ok(Event::default().data(text).id(id.to_string()))
});
Sse::new(stream::iter(events))
}
The header name is lowercase in the code, and HTTP header names are case-insensitive, so last-event-id matches the Last-Event-ID a client sends. The value is parsed as a number, and anything unparsable, or a missing header, becomes 0, which means the client saw nothing and gets everything. The filter keeps only the headlines with an id greater than the last seen one, so a client that saw event 1 gets events 2 and 3, and a client that saw event 3 gets an empty stream.
The tests check all three positions:
async fn get(uri: &str, last_event_id: Option<&str>) -> axum::response::Response {
let mut builder = Request::builder().uri(uri);
if let Some(id) = last_event_id {
builder = builder.header("last-event-id", id);
}
sse_app().oneshot(builder.body(Body::empty()).unwrap()).await.unwrap()
}
#[tokio::test]
async fn news_without_last_event_id_replays_everything() {
let response = get("/news", None).await;
let bytes = response.into_body().collect().await.unwrap().to_bytes();
let text = String::from_utf8(bytes.to_vec()).unwrap();
assert!(text.contains("data: First headline\nid: 1\n\n"));
assert!(text.contains("data: Third headline\nid: 3\n\n"));
}
#[tokio::test]
async fn news_with_last_event_id_replays_only_what_was_missed() {
let response = get("/news", Some("1")).await;
let bytes = response.into_body().collect().await.unwrap().to_bytes();
let text = String::from_utf8(bytes.to_vec()).unwrap();
assert!(!text.contains("First headline"));
assert!(text.contains("data: Second headline\nid: 2\n\n"));
assert!(text.contains("data: Third headline\nid: 3\n\n"));
}
#[tokio::test]
async fn news_with_the_latest_id_sends_an_empty_body() {
let response = get("/news", Some("3")).await;
let bytes = response.into_body().collect().await.unwrap().to_bytes();
assert!(bytes.is_empty());
}
The get helper adds the header only when an id is given, so the three tests differ by one argument. The first test proves a fresh client gets everything. The second proves a client that saw event 1 does not get it again, and does get events 2 and 3. The third proves a client that is already caught up gets an empty body, not a repeat of the last event. The contains checks here are deliberate: they assert the presence or absence of whole events, including the blank line that ends each one, so a partial match cannot pass.
Client asks with no Last-Event-ID
|
v
Server sends events 1, 2, 3
|
v
Client disconnects after event 1
|
v
Client reconnects with Last-Event-ID: 1
|
v
Server sends events 2 and 3 only
The Concept Behind It
An SSE test is a test of bytes and headers, not of a parsed object. There is no client library in the test that turns the stream into events. The test reads the raw body and compares it with the raw text, because the wire format is the contract, and a client in a browser will read exactly those bytes. A test that parsed the events into structs and compared the structs would pass while the wire format was wrong, and the browser would still fail. The raw comparison is the honest one.
That is also why the content-type assertion sits next to the body assertion in every test on this page. The two together are the contract: the right bytes, labelled the right way. A handler can get either one wrong on its own, and the test catches whichever it is.
Common Beginner Mistakes
Collecting a stream that never ends
// Wrong - this stream sends a keep-alive comment forever, so collect never returns
use std::time::Duration;
async fn live() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
let stream = futures_util::stream::unfold((), |_| async {
tokio::time::sleep(Duration::from_secs(1)).await;
Some((Ok(Event::default().comment("keep-alive")), ()))
});
Sse::new(stream)
}
A live feed with keep-alive comments never ends, by design, and collect waits for the end that never comes. The test hangs, and the failure is a timeout rather than an assertion. Test infinite streams frame by frame with a limit, reading a fixed number of chunks and then stopping, or test them through a route that sends a fixed number of events and ends, as the routes on this page do. The keep-alive behaviour itself is better checked by hand with curl, where a human can watch the comments arrive and stop the command.
Reading the body as JSON
// Wrong - an SSE body is event text, not a JSON document
let body: Value = serde_json::from_slice(&bytes).unwrap();
The body starts with data: tick 1, which is not JSON, and parsing it as JSON fails at once. The failure looks like the server sent a broken response, when the real mistake is the test reading the response in the wrong format. Read the body as text with String::from_utf8, and assert on the text.
Forgetting the content-type check
A test that only checks the body passes while the handler returns the events as text/plain. The browser then refuses to treat the response as a stream, and the test has checked the wrong thing. Assert the content type in the first SSE test of every suite, and keep it there. It is one line, and it catches a mistake that is invisible in the body.
Expecting a typed Last-Event-ID extractor
There is no typed extractor for the Last-Event-ID header in the headers crate version this book uses. Code that tries to extract one does not compile, and the fix is the raw HeaderMap lookup shown above. The lookup is three steps: get the header by name, turn the value into text, parse the text as a number. A missing header or an unparsable value becomes 0, which means replay everything.
A Hanging SSE Test Usually Means an Endless Stream:
When an SSE test hangs instead of failing, the stream almost certainly never ends, and collect is waiting for an end that will not come. Check the handler first: does the stream terminate, or does it loop forever with keep-alive comments? A test can only collect a stream that ends. For a stream that does not end, read a fixed number of frames and stop.
Final Complete Example
Everything from this page together: the two handlers, the app, the request helper, and all five tests:
use std::convert::Infallible;
use axum::{
Router,
http::HeaderMap,
response::sse::{Event, Sse},
routing::get,
};
use futures_util::stream;
async fn ticks() -> Sse<impl futures_util::Stream<Item = Result<Event, Infallible>>> {
let events = (1..=3).map(|n| {
Ok(Event::default()
.data(format!("tick {n}"))
.id(n.to_string()))
});
Sse::new(stream::iter(events))
}
async fn news(headers: HeaderMap) -> Sse<impl futures_util::Stream<Item = Result<Event, Infallible>>> {
let headlines = [
(1, "First headline"),
(2, "Second headline"),
(3, "Third headline"),
];
let last_seen: usize = headers
.get("last-event-id")
.and_then(|value| value.to_str().ok())
.and_then(|value| value.parse().ok())
.unwrap_or(0);
let events = headlines
.into_iter()
.filter(move |(id, _)| *id > last_seen)
.map(|(id, text)| {
Ok(Event::default().data(text).id(id.to_string()))
});
Sse::new(stream::iter(events))
}
pub fn sse_app() -> Router {
Router::new()
.route("/ticks", get(ticks))
.route("/news", get(news))
}
use axum::{body::Body, http::{Request, StatusCode}};
use axum_project::sse_app;
use futures_util::StreamExt;
use http_body_util::BodyExt;
use tower::ServiceExt;
async fn get(uri: &str, last_event_id: Option<&str>) -> axum::response::Response {
let mut builder = Request::builder().uri(uri);
if let Some(id) = last_event_id {
builder = builder.header("last-event-id", id);
}
sse_app().oneshot(builder.body(Body::empty()).unwrap()).await.unwrap()
}
#[tokio::test]
async fn ticks_stream_has_the_sse_content_type_and_three_events() {
let response = get("/ticks", None).await;
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.headers()["content-type"], "text/event-stream");
let bytes = response.into_body().collect().await.unwrap().to_bytes();
let text = String::from_utf8(bytes.to_vec()).unwrap();
assert_eq!(
text,
"data: tick 1\nid: 1\n\ndata: tick 2\nid: 2\n\ndata: tick 3\nid: 3\n\n"
);
}
#[tokio::test]
async fn events_arrive_one_by_one_as_separate_frames() {
let response = get("/ticks", None).await;
let mut frames = Vec::new();
let mut stream = response.into_body().into_data_stream();
while let Some(chunk) = stream.next().await {
frames.push(String::from_utf8(chunk.unwrap().to_vec()).unwrap());
}
assert_eq!(frames.len(), 3);
assert!(frames[0].contains("data: tick 1"));
assert!(frames[2].contains("id: 3"));
}
#[tokio::test]
async fn news_without_last_event_id_replays_everything() {
let response = get("/news", None).await;
let bytes = response.into_body().collect().await.unwrap().to_bytes();
let text = String::from_utf8(bytes.to_vec()).unwrap();
assert!(text.contains("data: First headline\nid: 1\n\n"));
assert!(text.contains("data: Third headline\nid: 3\n\n"));
}
#[tokio::test]
async fn news_with_last_event_id_replays_only_what_was_missed() {
let response = get("/news", Some("1")).await;
let bytes = response.into_body().collect().await.unwrap().to_bytes();
let text = String::from_utf8(bytes.to_vec()).unwrap();
assert!(!text.contains("First headline"));
assert!(text.contains("data: Second headline\nid: 2\n\n"));
assert!(text.contains("data: Third headline\nid: 3\n\n"));
}
#[tokio::test]
async fn news_with_the_latest_id_sends_an_empty_body() {
let response = get("/news", Some("3")).await;
let bytes = response.into_body().collect().await.unwrap().to_bytes();
assert!(bytes.is_empty());
}
Run the tests with:
cargo test --test sse_test
All five tests pass. The wire format matches byte for byte, the events arrive as three separate frames, and the resume behaviour replays exactly the events the client missed, including none at all when it is already caught up.
Summary
An SSE test reads the response the way a browser would: as bytes on a wire, labelled with a content type, in the order the server sent them. The exact body comparison is the strongest check, the frame loop proves the delivery, and the Last-Event-ID tests prove the resume, which is the reason event ids exist at all. The one hard rule is that the stream under test must end, because a test can only collect what finishes.
The pattern to carry forward is to test streams as text, not as objects, and to check the label with the content. The next page turns to the last piece of the chapter: testing code that calls out to other services, where the test replaces the real service with a mock that answers on a local port.