base/interface/exec/in_process/
network.rs1use std::collections::BTreeMap;
4use std::sync::{Arc, Mutex};
5
6use crate::interface::exec::{ExecError, HttpRequest, HttpResponse, Network, Origin};
7
8#[derive(Clone, Default)]
14pub struct OfflineNetwork {
15 fixtures: Arc<Mutex<BTreeMap<String, HttpResponse>>>,
16 asked: Arc<Mutex<Vec<String>>>,
17}
18
19impl OfflineNetwork {
20 pub fn new() -> Self {
21 Self::default()
22 }
23
24 pub fn with(self, url: impl Into<String>, status: u16, body: impl Into<String>) -> Self {
25 self.fixtures
26 .lock()
27 .unwrap_or_else(std::sync::PoisonError::into_inner)
28 .insert(
29 url.into(),
30 HttpResponse {
31 status,
32 headers: BTreeMap::new(),
33 body: body.into().into_bytes(),
34 },
35 );
36 self
37 }
38
39 pub fn asked(&self) -> Vec<String> {
41 self.asked
42 .lock()
43 .unwrap_or_else(std::sync::PoisonError::into_inner)
44 .clone()
45 }
46}
47
48#[async_trait::async_trait]
49impl Network for OfflineNetwork {
50 async fn send(&self, req: HttpRequest, _origin: Origin) -> Result<HttpResponse, ExecError> {
51 self.asked
52 .lock()
53 .unwrap_or_else(std::sync::PoisonError::into_inner)
54 .push(req.url.clone());
55 self.fixtures
56 .lock()
57 .unwrap_or_else(std::sync::PoisonError::into_inner)
58 .get(&req.url)
59 .cloned()
60 .ok_or_else(|| ExecError::unavailable(format!("offline: {}", req.url)))
61 }
62
63 fn permits(&self, _host: &str, _origin: Origin) -> bool {
64 true
68 }
69}