1use crate::{Error, Result};
7use reqwest::Client;
8use serde::{Deserialize, Serialize};
9use std::collections::HashMap;
10
11pub struct AdminClient {
13 base_url: String,
14 client: Client,
15}
16
17#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct MockConfig {
20 #[serde(skip_serializing_if = "String::is_empty")]
22 pub id: String,
23 pub name: String,
25 pub method: String,
27 pub path: String,
29 pub response: MockResponse,
31 #[serde(default = "default_true")]
33 pub enabled: bool,
34 #[serde(skip_serializing_if = "Option::is_none")]
36 pub latency_ms: Option<u64>,
37 #[serde(skip_serializing_if = "Option::is_none")]
39 pub status_code: Option<u16>,
40 #[serde(skip_serializing_if = "Option::is_none")]
42 pub request_match: Option<RequestMatchCriteria>,
43 #[serde(skip_serializing_if = "Option::is_none")]
45 pub priority: Option<i32>,
46 #[serde(skip_serializing_if = "Option::is_none")]
48 pub scenario: Option<String>,
49 #[serde(skip_serializing_if = "Option::is_none")]
51 pub required_scenario_state: Option<String>,
52 #[serde(skip_serializing_if = "Option::is_none")]
54 pub new_scenario_state: Option<String>,
55}
56
57const fn default_true() -> bool {
58 true
59}
60
61#[derive(Debug, Clone, Serialize, Deserialize)]
63pub struct MockResponse {
64 pub body: serde_json::Value,
66 #[serde(skip_serializing_if = "Option::is_none")]
68 pub headers: Option<HashMap<String, String>>,
69}
70
71#[derive(Debug, Clone, Serialize, Deserialize, Default)]
73pub struct RequestMatchCriteria {
74 #[serde(skip_serializing_if = "HashMap::is_empty")]
76 pub headers: HashMap<String, String>,
77 #[serde(skip_serializing_if = "HashMap::is_empty")]
79 pub query_params: HashMap<String, String>,
80 #[serde(skip_serializing_if = "Option::is_none")]
82 pub body_pattern: Option<String>,
83 #[serde(skip_serializing_if = "Option::is_none")]
85 pub json_path: Option<String>,
86 #[serde(skip_serializing_if = "Option::is_none")]
88 pub xpath: Option<String>,
89 #[serde(skip_serializing_if = "Option::is_none")]
91 pub custom_matcher: Option<String>,
92}
93
94#[derive(Debug, Clone, Serialize, Deserialize)]
96pub struct ServerStats {
97 pub uptime_seconds: u64,
99 pub total_requests: u64,
101 pub active_mocks: usize,
103 pub enabled_mocks: usize,
105 pub registered_routes: usize,
107}
108
109#[derive(Debug, Clone, Serialize, Deserialize)]
111pub struct ServerConfig {
112 pub version: String,
114 pub port: u16,
116 pub has_openapi_spec: bool,
118 #[serde(skip_serializing_if = "Option::is_none")]
120 pub spec_path: Option<String>,
121}
122
123#[derive(Debug, Clone, Serialize, Deserialize)]
125pub struct MockList {
126 pub mocks: Vec<MockConfig>,
128 pub total: usize,
130 pub enabled: usize,
132}
133
134impl AdminClient {
135 pub fn new(base_url: impl Into<String>) -> Self {
150 let mut url = base_url.into();
151
152 while url.ends_with('/') {
154 url.pop();
155 }
156
157 Self {
158 base_url: url,
159 client: Client::new(),
160 }
161 }
162
163 pub async fn list_mocks(&self) -> Result<MockList> {
165 let url = format!("{}/api/mocks", self.base_url);
166 let response = self
167 .client
168 .get(&url)
169 .send()
170 .await
171 .map_err(|e| Error::General(format!("Failed to list mocks: {e}")))?;
172
173 if !response.status().is_success() {
174 return Err(Error::General(format!(
175 "Failed to list mocks: HTTP {}",
176 response.status()
177 )));
178 }
179
180 response
181 .json()
182 .await
183 .map_err(|e| Error::General(format!("Failed to parse response: {e}")))
184 }
185
186 pub async fn get_mock(&self, id: &str) -> Result<MockConfig> {
188 let url = format!("{}/api/mocks/{}", self.base_url, id);
189 let response = self
190 .client
191 .get(&url)
192 .send()
193 .await
194 .map_err(|e| Error::General(format!("Failed to get mock: {e}")))?;
195
196 if response.status() == reqwest::StatusCode::NOT_FOUND {
197 return Err(Error::General(format!("Mock not found: {id}")));
198 }
199
200 if !response.status().is_success() {
201 return Err(Error::General(format!("Failed to get mock: HTTP {}", response.status())));
202 }
203
204 response
205 .json()
206 .await
207 .map_err(|e| Error::General(format!("Failed to parse response: {e}")))
208 }
209
210 pub async fn create_mock(&self, mock: MockConfig) -> Result<MockConfig> {
212 let url = format!("{}/api/mocks", self.base_url);
213 let response = self
214 .client
215 .post(&url)
216 .json(&mock)
217 .send()
218 .await
219 .map_err(|e| Error::General(format!("Failed to create mock: {e}")))?;
220
221 if response.status() == reqwest::StatusCode::CONFLICT {
222 return Err(Error::General(format!("Mock with ID {} already exists", mock.id)));
223 }
224
225 if !response.status().is_success() {
226 return Err(Error::General(format!(
227 "Failed to create mock: HTTP {}",
228 response.status()
229 )));
230 }
231
232 response
233 .json()
234 .await
235 .map_err(|e| Error::General(format!("Failed to parse response: {e}")))
236 }
237
238 pub async fn update_mock(&self, id: &str, mock: MockConfig) -> Result<MockConfig> {
240 let url = format!("{}/api/mocks/{}", self.base_url, id);
241 let response = self
242 .client
243 .put(&url)
244 .json(&mock)
245 .send()
246 .await
247 .map_err(|e| Error::General(format!("Failed to update mock: {e}")))?;
248
249 if response.status() == reqwest::StatusCode::NOT_FOUND {
250 return Err(Error::General(format!("Mock not found: {id}")));
251 }
252
253 if !response.status().is_success() {
254 return Err(Error::General(format!(
255 "Failed to update mock: HTTP {}",
256 response.status()
257 )));
258 }
259
260 response
261 .json()
262 .await
263 .map_err(|e| Error::General(format!("Failed to parse response: {e}")))
264 }
265
266 pub async fn delete_mock(&self, id: &str) -> Result<()> {
268 let url = format!("{}/api/mocks/{}", self.base_url, id);
269 let response = self
270 .client
271 .delete(&url)
272 .send()
273 .await
274 .map_err(|e| Error::General(format!("Failed to delete mock: {e}")))?;
275
276 if response.status() == reqwest::StatusCode::NOT_FOUND {
277 return Err(Error::General(format!("Mock not found: {id}")));
278 }
279
280 if !response.status().is_success() {
281 return Err(Error::General(format!(
282 "Failed to delete mock: HTTP {}",
283 response.status()
284 )));
285 }
286
287 Ok(())
288 }
289
290 pub async fn get_stats(&self) -> Result<ServerStats> {
292 let url = format!("{}/api/stats", self.base_url);
293 let response = self
294 .client
295 .get(&url)
296 .send()
297 .await
298 .map_err(|e| Error::General(format!("Failed to get stats: {e}")))?;
299
300 if !response.status().is_success() {
301 return Err(Error::General(format!("Failed to get stats: HTTP {}", response.status())));
302 }
303
304 response
305 .json()
306 .await
307 .map_err(|e| Error::General(format!("Failed to parse response: {e}")))
308 }
309
310 pub async fn get_config(&self) -> Result<ServerConfig> {
312 let url = format!("{}/api/config", self.base_url);
313 let response = self
314 .client
315 .get(&url)
316 .send()
317 .await
318 .map_err(|e| Error::General(format!("Failed to get config: {e}")))?;
319
320 if !response.status().is_success() {
321 return Err(Error::General(format!(
322 "Failed to get config: HTTP {}",
323 response.status()
324 )));
325 }
326
327 response
328 .json()
329 .await
330 .map_err(|e| Error::General(format!("Failed to parse response: {e}")))
331 }
332
333 pub async fn reset(&self) -> Result<()> {
335 let url = format!("{}/api/reset", self.base_url);
336 let response = self
337 .client
338 .post(&url)
339 .send()
340 .await
341 .map_err(|e| Error::General(format!("Failed to reset mocks: {e}")))?;
342
343 if !response.status().is_success() {
344 return Err(Error::General(format!(
345 "Failed to reset mocks: HTTP {}",
346 response.status()
347 )));
348 }
349
350 Ok(())
351 }
352}
353
354pub struct MockConfigBuilder {
384 config: MockConfig,
385}
386
387impl MockConfigBuilder {
388 pub fn new(method: impl Into<String>, path: impl Into<String>) -> Self {
394 Self {
395 config: MockConfig {
396 id: String::new(),
397 name: String::new(),
398 method: method.into().to_uppercase(),
399 path: path.into(),
400 response: MockResponse {
401 body: serde_json::json!({}),
402 headers: None,
403 },
404 enabled: true,
405 latency_ms: None,
406 status_code: None,
407 request_match: None,
408 priority: None,
409 scenario: None,
410 required_scenario_state: None,
411 new_scenario_state: None,
412 },
413 }
414 }
415
416 pub fn id(mut self, id: impl Into<String>) -> Self {
418 self.config.id = id.into();
419 self
420 }
421
422 pub fn name(mut self, name: impl Into<String>) -> Self {
424 self.config.name = name.into();
425 self
426 }
427
428 #[must_use]
430 pub fn body(mut self, body: serde_json::Value) -> Self {
431 self.config.response.body = body;
432 self
433 }
434
435 #[must_use]
437 pub const fn status(mut self, status: u16) -> Self {
438 self.config.status_code = Some(status);
439 self
440 }
441
442 #[must_use]
444 pub fn headers(mut self, headers: HashMap<String, String>) -> Self {
445 self.config.response.headers = Some(headers);
446 self
447 }
448
449 pub fn header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
451 let headers = self.config.response.headers.get_or_insert_with(HashMap::new);
452 headers.insert(key.into(), value.into());
453 self
454 }
455
456 #[must_use]
458 pub const fn latency_ms(mut self, ms: u64) -> Self {
459 self.config.latency_ms = Some(ms);
460 self
461 }
462
463 #[must_use]
465 pub const fn enabled(mut self, enabled: bool) -> Self {
466 self.config.enabled = enabled;
467 self
468 }
469
470 pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
483 let match_criteria =
484 self.config.request_match.get_or_insert_with(RequestMatchCriteria::default);
485 match_criteria.headers.insert(name.into(), value.into());
486 self
487 }
488
489 pub fn with_headers(mut self, headers: HashMap<String, String>) -> Self {
491 let match_criteria =
492 self.config.request_match.get_or_insert_with(RequestMatchCriteria::default);
493 match_criteria.headers.extend(headers);
494 self
495 }
496
497 pub fn with_query_param(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
508 let match_criteria =
509 self.config.request_match.get_or_insert_with(RequestMatchCriteria::default);
510 match_criteria.query_params.insert(name.into(), value.into());
511 self
512 }
513
514 pub fn with_query_params(mut self, params: HashMap<String, String>) -> Self {
516 let match_criteria =
517 self.config.request_match.get_or_insert_with(RequestMatchCriteria::default);
518 match_criteria.query_params.extend(params);
519 self
520 }
521
522 pub fn with_body_pattern(mut self, pattern: impl Into<String>) -> Self {
533 let match_criteria =
534 self.config.request_match.get_or_insert_with(RequestMatchCriteria::default);
535 match_criteria.body_pattern = Some(pattern.into());
536 self
537 }
538
539 pub fn with_json_path(mut self, json_path: impl Into<String>) -> Self {
550 let match_criteria =
551 self.config.request_match.get_or_insert_with(RequestMatchCriteria::default);
552 match_criteria.json_path = Some(json_path.into());
553 self
554 }
555
556 pub fn with_xpath(mut self, xpath: impl Into<String>) -> Self {
566 let match_criteria =
567 self.config.request_match.get_or_insert_with(RequestMatchCriteria::default);
568 match_criteria.xpath = Some(xpath.into());
569 self
570 }
571
572 pub fn with_custom_matcher(mut self, expression: impl Into<String>) -> Self {
583 let match_criteria =
584 self.config.request_match.get_or_insert_with(RequestMatchCriteria::default);
585 match_criteria.custom_matcher = Some(expression.into());
586 self
587 }
588
589 #[must_use]
595 pub const fn priority(mut self, priority: i32) -> Self {
596 self.config.priority = Some(priority);
597 self
598 }
599
600 pub fn scenario(mut self, scenario: impl Into<String>) -> Self {
605 self.config.scenario = Some(scenario.into());
606 self
607 }
608
609 pub fn when_scenario_state(mut self, state: impl Into<String>) -> Self {
613 self.config.required_scenario_state = Some(state.into());
614 self
615 }
616
617 pub fn will_set_scenario_state(mut self, state: impl Into<String>) -> Self {
621 self.config.new_scenario_state = Some(state.into());
622 self
623 }
624
625 #[must_use]
627 pub fn build(self) -> MockConfig {
628 self.config
629 }
630}
631
632#[cfg(test)]
633mod tests {
634 use super::*;
635
636 #[test]
637 fn test_mock_config_builder_basic() {
638 let mock = MockConfigBuilder::new("GET", "/api/users")
639 .name("Get Users")
640 .status(200)
641 .body(serde_json::json!([{"id": 1, "name": "Alice"}]))
642 .latency_ms(100)
643 .header("Content-Type", "application/json")
644 .build();
645
646 assert_eq!(mock.method, "GET");
647 assert_eq!(mock.path, "/api/users");
648 assert_eq!(mock.name, "Get Users");
649 assert_eq!(mock.status_code, Some(200));
650 assert_eq!(mock.latency_ms, Some(100));
651 assert!(mock.enabled);
652 }
653
654 #[test]
655 fn test_mock_config_builder_with_matching() {
656 let mut headers = HashMap::new();
657 headers.insert("Authorization".to_string(), "Bearer.*".to_string());
658
659 let mut query_params = HashMap::new();
660 query_params.insert("role".to_string(), "admin".to_string());
661
662 let mock = MockConfigBuilder::new("POST", "/api/users")
663 .name("Create User")
664 .with_headers(headers.clone())
665 .with_query_params(query_params.clone())
666 .with_body_pattern(r#"{"name":".*"}"#)
667 .status(201)
668 .body(serde_json::json!({"id": 123, "created": true}))
669 .priority(10)
670 .build();
671
672 assert_eq!(mock.method, "POST");
673 assert!(mock.request_match.is_some());
674 let match_criteria = mock.request_match.unwrap();
675 assert_eq!(match_criteria.headers.get("Authorization"), Some(&"Bearer.*".to_string()));
676 assert_eq!(match_criteria.query_params.get("role"), Some(&"admin".to_string()));
677 assert_eq!(match_criteria.body_pattern, Some(r#"{"name":".*"}"#.to_string()));
678 assert_eq!(mock.priority, Some(10));
679 }
680
681 #[test]
682 fn test_mock_config_builder_with_scenario() {
683 let mock = MockConfigBuilder::new("GET", "/api/checkout")
684 .name("Checkout Step 1")
685 .scenario("checkout-flow")
686 .when_scenario_state("started")
687 .will_set_scenario_state("payment")
688 .status(200)
689 .body(serde_json::json!({"step": 1}))
690 .build();
691
692 assert_eq!(mock.scenario, Some("checkout-flow".to_string()));
693 assert_eq!(mock.required_scenario_state, Some("started".to_string()));
694 assert_eq!(mock.new_scenario_state, Some("payment".to_string()));
695 }
696
697 #[test]
698 fn test_mock_config_builder_fluent_chaining() {
699 let mock = MockConfigBuilder::new("GET", "/api/users/{id}")
700 .id("user-get-123")
701 .name("Get User by ID")
702 .with_header("Accept", "application/json")
703 .with_query_param("include", "profile")
704 .with_json_path("$.id")
705 .status(200)
706 .body(serde_json::json!({"id": "{{request.path.id}}", "name": "Alice"}))
707 .header("X-Request-ID", "{{uuid}}")
708 .latency_ms(50)
709 .priority(5)
710 .enabled(true)
711 .build();
712
713 assert_eq!(mock.id, "user-get-123");
714 assert_eq!(mock.name, "Get User by ID");
715 assert!(mock.request_match.is_some());
716 let match_criteria = mock.request_match.unwrap();
717 assert!(match_criteria.headers.contains_key("Accept"));
718 assert!(match_criteria.query_params.contains_key("include"));
719 assert_eq!(match_criteria.json_path, Some("$.id".to_string()));
720 assert_eq!(mock.priority, Some(5));
721 }
722}