focus/crates/focus-transport/tests/http_tests.rs

60 lines
1.8 KiB
Rust

//! HTTP/1.1 编解码的集成测试。
//! Integration tests for the HTTP/1.1 codec.
use focus_transport::http::{
body_length, parse_response_head, BodyLength, HttpRequest, HttpResponse,
};
use std::collections::HashMap;
#[test]
fn serializes_post_request() {
let req = HttpRequest::post("api.example.com", "/v1/messages")
.header("Authorization", "Bearer xyz")
.json_body(r#"{"hello":"world"}"#);
let wire = req.serialize();
let text = String::from_utf8(wire).unwrap();
assert!(text.starts_with("POST /v1/messages HTTP/1.1\r\n"));
assert!(text.contains("Host: api.example.com\r\n"));
assert!(text.contains("Authorization: Bearer xyz\r\n"));
assert!(text.contains("Content-Type: application/json\r\n"));
assert!(text.contains("Content-Length: 17\r\n"));
assert!(text.ends_with("{\"hello\":\"world\"}"));
}
#[test]
fn parses_response_head() {
let raw =
b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 5\r\n\r\nhello";
let (resp, consumed) = parse_response_head(raw).unwrap();
assert_eq!(resp.status, 200);
assert_eq!(
resp.headers.get("content-type").unwrap(),
"application/json"
);
assert_eq!(resp.headers.get("content-length").unwrap(), "5");
assert_eq!(consumed, raw.len() - 5);
assert_eq!(body_length(&resp), BodyLength::Fixed(5));
}
#[test]
fn detects_chunked() {
let raw = b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n";
let (resp, _) = parse_response_head(raw).unwrap();
assert_eq!(body_length(&resp), BodyLength::Chunked);
}
#[test]
fn is_success_for_2xx() {
let resp = HttpResponse {
status: 204,
headers: HashMap::new(),
body: vec![],
};
assert!(resp.is_success());
}
#[test]
fn rejects_incomplete_head() {
assert!(parse_response_head(b"HTTP/1.1 200 OK\r\n").is_err());
}