Skip to main content

ustar_test_utils/
mock_http_client.rs

1//! Mock HTTP client for testing download functionality
2
3use std::collections::HashMap;
4
5/// Mock HTTP client for testing with pre-recorded responses
6pub 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    /// Add a text response for a URL
20    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    /// Add a binary response for a URL
26    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    /// Add a response from a file
32    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    /// Get a text response for a URL
39    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    /// Get binary response for a URL
47    pub fn get_bytes(&self, url: &str) -> Result<Vec<u8>, String> {
48        // Try binary responses first
49        if let Some(binary) = self.binary_responses.get(url) {
50            return Ok(binary.clone());
51        }
52
53        // Fall back to text response as bytes
54        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}