ustar_test_utils/
mock_http_client.rs1use std::collections::HashMap;
4
5pub struct MockHttpClient {
7 responses: HashMap<String, String>,
8 binary_responses: HashMap<String, Vec<u8>>,
9}
10
11impl MockHttpClient {
12 pub fn new() -> Self {
13 Self {
14 responses: HashMap::new(),
15 binary_responses: HashMap::new(),
16 }
17 }
18
19 pub fn with_response(mut self, url: &str, response: &str) -> Self {
21 self.responses.insert(url.to_string(), response.to_string());
22 self
23 }
24
25 pub fn with_binary_response(mut self, url: &str, response: Vec<u8>) -> Self {
27 self.binary_responses.insert(url.to_string(), response);
28 self
29 }
30
31 pub fn with_file_response(self, url: &str, file_path: &str) -> Self {
33 let content = std::fs::read_to_string(file_path)
34 .unwrap_or_else(|_| panic!("Failed to read mock file: {}", file_path));
35 self.with_response(url, &content)
36 }
37
38 pub fn get(&self, url: &str) -> Result<String, String> {
40 self.responses
41 .get(url)
42 .cloned()
43 .ok_or_else(|| format!("Mock: No response for URL: {}", url))
44 }
45
46 pub fn get_bytes(&self, url: &str) -> Result<Vec<u8>, String> {
48 if let Some(binary) = self.binary_responses.get(url) {
50 return Ok(binary.clone());
51 }
52
53 self.responses
55 .get(url)
56 .map(|s| s.as_bytes().to_vec())
57 .ok_or_else(|| format!("Mock: No response for URL: {}", url))
58 }
59}
60
61impl Default for MockHttpClient {
62 fn default() -> Self {
63 Self::new()
64 }
65}