use std::{
error::Error as StdError,
fmt,
sync::{Arc, Mutex},
};
#[cfg(any(feature = "tokio1", feature = "async-std1"))]
use async_trait::async_trait;
#[cfg(any(feature = "tokio1", feature = "async-std1"))]
use crate::AsyncTransport;
use crate::{Transport, address::Envelope};
#[non_exhaustive]
#[derive(Debug, Copy, Clone)]
pub struct Error;
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("stub error")
}
}
impl StdError for Error {}
#[derive(Debug, Clone)]
pub struct StubTransport {
response: Result<(), Error>,
message_log: Arc<Mutex<Vec<(Envelope, String)>>>,
}
#[derive(Debug, Clone)]
#[cfg(any(feature = "tokio1", feature = "async-std1"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "tokio1", feature = "async-std1"))))]
pub struct AsyncStubTransport {
response: Result<(), Error>,
message_log: Arc<Mutex<Vec<(Envelope, String)>>>,
}
impl StubTransport {
pub fn new(response: Result<(), Error>) -> Self {
Self {
response,
message_log: Arc::new(Mutex::new(vec![])),
}
}
pub fn new_ok() -> Self {
Self {
response: Ok(()),
message_log: Arc::new(Mutex::new(vec![])),
}
}
pub fn new_error() -> Self {
Self {
response: Err(Error),
message_log: Arc::new(Mutex::new(vec![])),
}
}
pub fn messages(&self) -> Vec<(Envelope, String)> {
self.message_log
.lock()
.expect("Couldn't acquire lock to write message log")
.clone()
}
}
#[cfg(any(feature = "async-std1", feature = "tokio1"))]
impl AsyncStubTransport {
pub fn new(response: Result<(), Error>) -> Self {
Self {
response,
message_log: Arc::new(Mutex::new(vec![])),
}
}
pub fn new_ok() -> Self {
Self {
response: Ok(()),
message_log: Arc::new(Mutex::new(vec![])),
}
}
pub fn new_error() -> Self {
Self {
response: Err(Error),
message_log: Arc::new(Mutex::new(vec![])),
}
}
#[cfg(any(feature = "tokio1", feature = "async-std1"))]
pub async fn messages(&self) -> Vec<(Envelope, String)> {
self.message_log.lock().unwrap().clone()
}
}
impl Transport for StubTransport {
type Ok = ();
type Error = Error;
fn send_raw(&self, envelope: &Envelope, email: &[u8]) -> Result<Self::Ok, Self::Error> {
self.message_log
.lock()
.expect("Couldn't acquire lock to write message log")
.push((envelope.clone(), String::from_utf8_lossy(email).into()));
self.response
}
}
#[cfg(any(feature = "tokio1", feature = "async-std1"))]
#[async_trait]
impl AsyncTransport for AsyncStubTransport {
type Ok = ();
type Error = Error;
async fn send_raw(&self, envelope: &Envelope, email: &[u8]) -> Result<Self::Ok, Self::Error> {
self.message_log
.lock()
.unwrap()
.push((envelope.clone(), String::from_utf8_lossy(email).into()));
self.response
}
}