httpmock 0.9.0

HTTP mocking library for Rust
Documentation
use std::{
    borrow::Cow,
    env,
    fs::File,
    io::Read,
    path::{Path, PathBuf},
    sync::{Arc, Mutex, MutexGuard},
    task::{Context, Poll, Wake, Waker},
    thread::{self, Thread},
    time::Duration,
};

#[cfg(feature = "record")]
use std::{fs::create_dir_all, io::Write};

use base64::{Engine, engine::general_purpose::STANDARD as BASE64};
use bytes::Bytes;
use futures_timer::Delay;
use serde::{Deserialize, Serialize};

// ===============================================================================================
// Misc
// ===============================================================================================
pub(crate) fn lock_mutex<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
    mutex.lock().expect("builder configuration mutex poisoned")
}

pub(crate) fn update_mutex<T, F: FnOnce(&mut T)>(mutex: &Mutex<T>, update_value: F) {
    update_value(&mut lock_mutex(mutex));
}

pub(crate) fn take_from_mutex<T: Default>(mutex: &Mutex<T>) -> T {
    std::mem::take(&mut *lock_mutex(mutex))
}

// ===============================================================================================
// Retry
// ===============================================================================================
#[doc(hidden)]
pub(crate) async fn with_retry<T, U>(retries: usize, f: impl AsyncFn() -> Result<T, U>) -> Result<T, U> {
    let mut result = (f)().await;
    for i in 1..=retries {
        if result.is_ok() {
            return result;
        } else {
            Delay::new(Duration::from_secs(i as u64)).await;
        }
        result = (f)().await;
    }
    result
}

// ===============================================================================================
// Environment
// ===============================================================================================
#[doc(hidden)]
pub(crate) fn read_env(name: &str, default: &str) -> String {
    match std::env::var(name) {
        Ok(value) => value,
        Err(_) => default.to_string(),
    }
}

// ===============================================================================================
// Futures
// ===============================================================================================
#[doc(hidden)]
pub trait Join: Future {
    fn join(self) -> <Self as Future>::Output;
}

impl<F: Future> Join for F {
    fn join(self) -> <Self as Future>::Output {
        /// Waker that unparks the blocked thread when the future is ready to
        /// make progress. `unpark` before `park` leaves a token that makes the
        /// next `park` return immediately, so no wakeups are lost.
        struct ThreadWaker(Thread);

        impl Wake for ThreadWaker {
            fn wake(self: Arc<Self>) {
                self.0.unpark();
            }

            fn wake_by_ref(self: &Arc<Self>) {
                self.0.unpark();
            }
        }

        let waker = Waker::from(Arc::new(ThreadWaker(thread::current())));
        let mut context = Context::from_waker(&waker);

        let mut future = std::pin::pin!(self);

        loop {
            match future.as_mut().poll(&mut context) {
                Poll::Ready(output) => return output,
                // `park` may wake spuriously, so we loop and re-poll rather
                // than assuming one park corresponds to exactly one wake.
                Poll::Pending => thread::park(),
            }
        }
    }
}

// ===============================================================================================
// Files
// ===============================================================================================
pub fn get_test_resource_file_path(relative_resource_path: &str) -> Result<PathBuf, String> {
    match env::var("CARGO_MANIFEST_DIR") {
        Ok(manifest_path) => Ok(Path::new(&manifest_path).join(relative_resource_path)),
        Err(e) => Err(e.to_string()),
    }
}

#[cfg(feature = "record")]
pub async fn write_file<P: AsRef<Path>>(
    resource_path: P,
    content: &Bytes,
    create_dir: bool,
) -> Result<PathBuf, Box<dyn std::error::Error>> {
    let mut path = resource_path.as_ref().to_path_buf();

    if path.is_relative() {
        let current_dir = env::current_dir()?;
        path = current_dir.join(path);
    }

    if create_dir && let Some(parent) = path.parent() {
        create_dir_all(parent)?;
    }

    let mut file = File::create_new(&path)?;
    file.write_all(content)?;
    file.flush()?;

    Ok(path)
}

/// A wrapper around `bytes::Bytes` providing utility methods for common operations.
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct HttpMockBytes(pub Bytes);

impl HttpMockBytes {
    /// Converts the bytes to a `Vec<u8>`.
    ///
    /// # Returns
    /// A `Vec<u8>` containing the bytes.
    pub fn to_vec(&self) -> Vec<u8> {
        self.0.to_vec()
    }

    /// Cheaply clones the bytes into a new `Bytes` instance.
    /// See
    ///
    /// # Returns
    /// A `Bytes` instance containing the same data.
    pub fn to_bytes(&self) -> Bytes {
        self.0.clone()
    }

    /// Checks if the byte slice is empty.
    ///
    /// # Returns
    /// `true` if the byte slice is empty, otherwise `false`.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Converts the bytes to a UTF-8 string, potentially lossy.
    /// Tries to parse input as a UTF-8 string first to avoid copying and creating an owned instance.
    /// If the bytes are not valid UTF-8, it creates a lossy string by replacing invalid characters
    /// with the Unicode replacement character.
    ///
    /// # Returns
    /// A `Cow<str>` which is either borrowed if the bytes are valid UTF-8 or owned if conversion was required.
    pub fn to_maybe_lossy_str(&self) -> Cow<'_, str> {
        match std::str::from_utf8(&self.0) {
            Ok(valid_str) => Cow::Borrowed(valid_str),
            Err(_) => Cow::Owned(String::from_utf8_lossy(&self.0).to_string()),
        }
    }
}

impl From<Bytes> for HttpMockBytes {
    fn from(value: Bytes) -> Self {
        Self(value)
    }
}

impl From<&Bytes> for HttpMockBytes {
    fn from(value: &Bytes) -> Self {
        Self(value.clone())
    } // cheap clone handle
}

impl From<bytes::BytesMut> for HttpMockBytes {
    fn from(value: bytes::BytesMut) -> Self {
        Self(value.freeze())
    }
}

// Owned conversions
impl From<Vec<u8>> for HttpMockBytes {
    fn from(value: Vec<u8>) -> Self {
        Self(Bytes::from(value))
    }
}

impl From<Box<[u8]>> for HttpMockBytes {
    fn from(value: Box<[u8]>) -> Self {
        Self(Bytes::from(value))
    }
}

impl From<()> for HttpMockBytes {
    fn from(_: ()) -> Self {
        Self(Bytes::new())
    }
}

impl From<&[u8]> for HttpMockBytes {
    fn from(value: &[u8]) -> Self {
        Self(Bytes::copy_from_slice(value))
    }
}

impl From<String> for HttpMockBytes {
    fn from(value: String) -> Self {
        Self(Bytes::from(value))
    }
}

impl From<&str> for HttpMockBytes {
    fn from(value: &str) -> Self {
        Self(Bytes::copy_from_slice(value.as_bytes()))
    }
}

impl<'a> From<Cow<'a, str>> for HttpMockBytes {
    fn from(value: Cow<'a, str>) -> Self {
        match value {
            Cow::Borrowed(s) => Self::from(s),
            Cow::Owned(s) => Self::from(s),
        }
    }
}

impl<'a> From<Cow<'a, [u8]>> for HttpMockBytes {
    fn from(value: Cow<'a, [u8]>) -> Self {
        match value {
            Cow::Borrowed(b) => Self::from(b),
            Cow::Owned(v) => Self::from(v),
        }
    }
}

// Reverse: HttpMockBytes -> Bytes
impl From<HttpMockBytes> for Bytes {
    fn from(value: HttpMockBytes) -> Bytes {
        value.0
    }
}

/* ===== AsRef / Borrow / Deref-ish ergonomics ===== */

impl AsRef<[u8]> for HttpMockBytes {
    fn as_ref(&self) -> &[u8] {
        self.0.as_ref()
    }
}

impl std::borrow::Borrow<[u8]> for HttpMockBytes {
    fn borrow(&self) -> &[u8] {
        self.0.as_ref()
    }
}

/* ===== Friendly equality with common counterparts ===== */

impl PartialEq<[u8]> for HttpMockBytes {
    fn eq(&self, other: &[u8]) -> bool {
        self.0.as_ref() == other
    }
}

impl PartialEq<&[u8]> for HttpMockBytes {
    fn eq(&self, other: &&[u8]) -> bool {
        self.0.as_ref() == *other
    }
}

impl PartialEq<Vec<u8>> for HttpMockBytes {
    fn eq(&self, other: &Vec<u8>) -> bool {
        self.0.as_ref() == other.as_slice()
    }
}

impl PartialEq<Bytes> for HttpMockBytes {
    fn eq(&self, other: &Bytes) -> bool {
        self.0 == other
    }
}

impl PartialEq<&str> for HttpMockBytes {
    fn eq(&self, other: &&str) -> bool {
        self.0.as_ref() == other.as_bytes()
    }
}

impl PartialEq<String> for HttpMockBytes {
    fn eq(&self, other: &String) -> bool {
        self.0.as_ref() == other.as_bytes()
    }
}

/* ===== Display / Debug ===== */

impl std::fmt::Display for HttpMockBytes {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match std::str::from_utf8(&self.0) {
            Ok(s) => write!(f, "{s}"),
            Err(_) => write!(f, "{}", BASE64.encode(&self.0)),
        }
    }
}

impl std::fmt::Debug for HttpMockBytes {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Show UTF-8 inline when possible; otherwise prefix and base64
        match std::str::from_utf8(&self.0) {
            Ok(s) => f.debug_tuple("HttpMockBytes").field(&s).finish(),
            Err(_) => f
                .debug_tuple("HttpMockBytes")
                .field(&format!("<{} bytes, b64:{}>", self.0.len(), BASE64.encode(&self.0)))
                .finish(),
        }
    }
}

pub fn title_case(s: &str) -> String {
    let mut result = String::new();
    let mut capitalize_next = true;

    for c in s.chars() {
        if c.is_whitespace() {
            capitalize_next = true;
            result.push(c);
        } else if capitalize_next {
            result.push(c.to_uppercase().next().unwrap());
            capitalize_next = false;
        } else {
            result.push(c.to_lowercase().next().unwrap());
        }
    }

    result
}

pub fn is_none_or_empty<T>(option: &Option<Vec<T>>) -> bool {
    match option {
        None => true,
        Some(vec) => vec.is_empty(),
    }
}

pub fn read_file<P: AsRef<Path>>(absolute_resource_path: P) -> Result<Vec<u8>, String> {
    let mut buffer = Vec::new();

    let len = File::open(&absolute_resource_path)
        .and_then(|mut f| f.read_to_end(&mut buffer))
        .map_err(|e| e.to_string())?;

    tracing::trace!(
        "Read {} bytes from file {:?}",
        &len,
        &absolute_resource_path
            .as_ref()
            .as_os_str()
            .to_str()
            .expect("Invalid file path")
    );

    Ok(buffer)
}

#[cfg(test)]
mod test {
    use crate::common::util::{Join, with_retry};

    #[test]
    fn with_retry_error_test() {
        let result: Result<(), &str> = with_retry(1, || async { Err("test error") }).join();

        assert!(result.is_err());
        assert_eq!(result.err().unwrap(), "test error")
    }
}