use bytes::Bytes;
use hitbox_core::Cacheable;
use hitbox_http::{BufferedBody, CacheableHttpResponse, SerializableHttpResponse};
use http::Response;
use http_body_util::Full;
#[test]
fn test_serializable_http_response_is_cacheable() {
fn assert_cacheable<T: Cacheable>() {}
assert_cacheable::<SerializableHttpResponse>();
}
#[tokio::test]
async fn test_cacheable_response_serialization_roundtrip() {
use hitbox::CacheableResponse;
let body = Bytes::from(r#"{"message": "Hello, World!", "status": "success"}"#);
let response = Response::builder()
.status(200)
.header("content-type", "application/json")
.header("cache-control", "public, max-age=3600")
.header("x-custom-header", "test-value")
.body(BufferedBody::<Full<Bytes>>::Complete(Some(body.clone())))
.unwrap();
let cacheable = CacheableHttpResponse::from_response(response);
let cached = cacheable.into_cached().await;
let serializable = match cached {
hitbox::CachePolicy::Cacheable(data) => data,
hitbox::CachePolicy::NonCacheable(_) => panic!("Expected cacheable response"),
};
let serialized = serde_json::to_vec(&serializable).expect("Failed to serialize");
let deserialized: SerializableHttpResponse =
serde_json::from_slice(&serialized).expect("Failed to deserialize");
assert_eq!(
serde_json::to_value(&serializable).unwrap(),
serde_json::to_value(&deserialized).unwrap()
);
}
#[cfg(feature = "rkyv_format")]
#[tokio::test]
async fn test_cacheable_response_rkyv_roundtrip() {
use hitbox::CacheableResponse;
use rkyv::{from_bytes, rancor, to_bytes};
let body = Bytes::from(r#"{"message": "Hello, World!", "status": "success"}"#);
let response = Response::builder()
.status(200)
.header("content-type", "application/json")
.header("cache-control", "public, max-age=3600")
.header("x-custom-header", "test-value")
.header("x-request-id", "12345")
.body(BufferedBody::<Full<Bytes>>::Complete(Some(body.clone())))
.unwrap();
let cacheable = CacheableHttpResponse::from_response(response);
let cached = cacheable.into_cached().await;
let serializable = match cached {
hitbox::CachePolicy::Cacheable(data) => data,
hitbox::CachePolicy::NonCacheable(_) => panic!("Expected cacheable response"),
};
let serialized =
to_bytes::<rancor::Error>(&serializable).expect("Failed to serialize with rkyv");
let deserialized: SerializableHttpResponse =
from_bytes::<SerializableHttpResponse, rancor::Error>(&serialized)
.expect("Failed to deserialize with rkyv");
assert_eq!(
serde_json::to_value(&serializable).unwrap(),
serde_json::to_value(&deserialized).unwrap()
);
}