delopay 0.20.0

Official Rust SDK for the DeloPay payments API
Documentation
//! A scripted [`Transport`] for testing retry and error-mapping behavior
//! without a socket.

#![cfg(test)]

use std::sync::Mutex;

use crate::http::transport::{
    RawRequest, RawResponse, Transport, TransportError, TransportErrorKind,
};

/// One scripted outcome.
pub(crate) enum Step {
    /// Return an HTTP response with this status, headers, and body.
    Respond(u16, Vec<(Box<str>, Box<str>)>, Vec<u8>),
    /// Fail at the transport level with this classification.
    Fail(TransportErrorKind),
}

impl Step {
    pub(crate) fn ok(body: &str) -> Self {
        Step::Respond(200, Vec::new(), body.as_bytes().to_vec())
    }

    pub(crate) fn status(status: u16, body: &str) -> Self {
        Step::Respond(status, Vec::new(), body.as_bytes().to_vec())
    }

    pub(crate) fn status_with_header(status: u16, name: &str, value: &str) -> Self {
        Step::Respond(status, vec![(name.into(), value.into())], Vec::new())
    }
}

/// Everything the mock recorded about one request, so tests can pin the verb,
/// URL, headers, and body a resource method actually put on the wire.
pub(crate) struct SeenRequest {
    pub(crate) method: &'static str,
    pub(crate) url: String,
    pub(crate) headers: Vec<(String, String)>,
    pub(crate) body: Option<Vec<u8>>,
    /// The body's content type when the caller set one explicitly. `None`
    /// means the transport's `application/json` default applies — so a test
    /// asserting a multipart upload must see `Some(...)` here.
    pub(crate) content_type: Option<String>,
}

impl SeenRequest {
    pub(crate) fn had_idempotency_key(&self) -> bool {
        self.header("idempotency-key").is_some()
    }

    /// Case-insensitive header lookup, mirroring `RawResponse::header`.
    pub(crate) fn header(&self, name: &str) -> Option<&str> {
        self.headers
            .iter()
            .find(|(k, _)| k.eq_ignore_ascii_case(name))
            .map(|(_, v)| v.as_str())
    }

    /// The recorded body parsed as JSON. Panics on a missing or non-JSON body —
    /// this is a test helper, and a panic message beats a silent `None`.
    pub(crate) fn body_json(&self) -> serde_json::Value {
        let body = self.body.as_deref().expect("request had no body");
        serde_json::from_slice(body).expect("request body was not valid JSON")
    }
}

#[derive(Default)]
pub(crate) struct MockTransport {
    steps: Mutex<std::collections::VecDeque<Step>>,
    /// Every request the mock saw, in order.
    pub(crate) seen: Mutex<Vec<SeenRequest>>,
}

impl std::fmt::Debug for MockTransport {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("MockTransport")
    }
}

impl MockTransport {
    pub(crate) fn new(steps: Vec<Step>) -> Self {
        Self {
            steps: Mutex::new(steps.into()),
            seen: Mutex::new(Vec::new()),
        }
    }

    pub(crate) fn call_count(&self) -> usize {
        self.seen.lock().unwrap().len()
    }
}

/// A [`crate::Delopay`] over a scripted mock, plus the mock for assertions.
/// Base URL is `https://api.test`, so a request to `/x` is seen as
/// `https://api.test/x`. Shared by every resource test module.
pub(crate) fn client_with(steps: Vec<Step>) -> (crate::Delopay, std::sync::Arc<MockTransport>) {
    client_with_retries(steps, 0)
}

/// [`client_with`] with a retry budget, for tests that pin **whether** a write
/// is replayed rather than what it sent.
pub(crate) fn client_with_retries(
    steps: Vec<Step>,
    max_retries: u32,
) -> (crate::Delopay, std::sync::Arc<MockTransport>) {
    use std::sync::Arc;
    let mock = Arc::new(MockTransport::new(steps));
    let inner = crate::http::client::Inner::with_transport(
        mock.clone(),
        "https://api.test".to_string(),
        "https://checkout.test".to_string(),
        "prd_test".to_string(),
        max_retries,
    );
    (
        crate::Delopay {
            inner: Arc::new(inner),
        },
        mock,
    )
}

impl Transport for MockTransport {
    fn execute<'a>(
        &'a self,
        req: RawRequest<'a>,
    ) -> std::pin::Pin<
        Box<dyn std::future::Future<Output = Result<RawResponse, TransportError>> + Send + 'a>,
    > {
        // Join the query pairs into the recorded URL so tests can pin the
        // effective request target in one assertion. Deliberately *without*
        // percent-encoding: that is the hyper backend's job and is covered by
        // its own `append_query` tests; the mock records intent, not bytes.
        let mut url = req.url.to_string();
        if !req.query.is_empty() {
            url.push(if url.contains('?') { '&' } else { '?' });
            let joined: Vec<String> = req.query.iter().map(|(k, v)| format!("{k}={v}")).collect();
            url.push_str(&joined.join("&"));
        }
        self.seen.lock().unwrap().push(SeenRequest {
            method: req.method.as_str(),
            url,
            headers: req
                .headers
                .iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect(),
            body: req.body.map(<[u8]>::to_vec),
            content_type: req.content_type.map(str::to_owned),
        });
        let step = self.steps.lock().unwrap().pop_front();

        Box::pin(async move {
            match step {
                Some(Step::Respond(status, headers, body)) => {
                    Ok(RawResponse::new(status, headers, body))
                }
                Some(Step::Fail(kind)) => Err(TransportError {
                    kind,
                    source: Box::new(std::io::Error::other("scripted failure")),
                }),
                None => panic!("MockTransport ran out of scripted steps"),
            }
        })
    }
}