http_endpoint_server_harness/entities/
response.rs1use std::collections::HashMap;
2
3#[derive(Debug, Clone)]
5pub struct Response {
6 pub status: u16,
7 pub headers: HashMap<String, String>,
8 pub body: Vec<u8>,
9}
10
11impl Response {
12 pub fn new(status: u16) -> Self {
13 Self {
14 status,
15 headers: HashMap::new(),
16 body: Vec::new(),
17 }
18 }
19
20 pub fn ok() -> Self {
21 Self::new(200)
22 }
23
24 pub fn created() -> Self {
25 Self::new(201)
26 }
27
28 pub fn not_found() -> Self {
29 Self::new(404)
30 }
31
32 pub fn internal_error() -> Self {
33 Self::new(500)
34 }
35
36 pub fn with_header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
37 self.headers.insert(key.into(), value.into());
38 self
39 }
40
41 pub fn with_body(mut self, body: impl Into<Vec<u8>>) -> Self {
42 self.body = body.into();
43 self
44 }
45
46 pub fn with_json<T: serde::Serialize>(mut self, value: &T) -> Self {
47 self.headers.insert("content-type".to_string(), "application/json".to_string());
48 self.body = serde_json::to_vec(value).unwrap_or_default();
49 self
50 }
51}
52
53impl Default for Response {
54 fn default() -> Self {
55 Self::ok()
56 }
57}
58
59#[cfg(test)]
60mod tests {
61 use super::*;
62
63 #[test]
64 fn test_response_new() {
65 let response = Response::new(200);
66 assert_eq!(response.status, 200);
67 assert!(response.headers.is_empty());
68 assert!(response.body.is_empty());
69 }
70
71 #[test]
72 fn test_response_with_body() {
73 let response = Response::new(200).with_body("Hello");
74 assert_eq!(response.body, b"Hello");
75 }
76
77 #[test]
78 fn test_response_with_json_body() {
79 let response = Response::new(200).with_json(&serde_json::json!({"key": "value"}));
80 assert!(response.body.contains(&b"key"[0]));
81 assert!(response.headers.get("content-type").unwrap().contains("application/json"));
82 }
83
84 #[test]
85 fn test_response_with_header() {
86 let response = Response::new(200).with_header("X-Custom", "value");
87 assert_eq!(response.headers.get("X-Custom").unwrap(), "value");
88 }
89
90 #[test]
91 fn test_response_ok() {
92 let response = Response::ok();
93 assert_eq!(response.status, 200);
94 }
95
96 #[test]
97 fn test_response_created() {
98 let response = Response::created();
99 assert_eq!(response.status, 201);
100 }
101
102 #[test]
103 fn test_response_not_found() {
104 let response = Response::not_found();
105 assert_eq!(response.status, 404);
106 }
107
108 #[test]
109 fn test_response_internal_error() {
110 let response = Response::internal_error();
111 assert_eq!(response.status, 500);
112 }
113}
114