Skip to main content

MockBus

Struct MockBus 

Source
pub struct MockBus {
    published: Arc<Mutex<Vec<(String, Vec<u8>)>>>,
    senders: Arc<Mutex<HashMap<String, Vec<Sender<Vec<u8>>>>>>,
    responders: Arc<Mutex<HashMap<String, Vec<Sender<(Vec<u8>, Sender<Vec<u8>>)>>>>>,
}
Expand description

Combined in-memory message bus for unit tests.

Implements Publisher, Subscriber, Requester, and Responder without a NATS server. Events published via publish() are delivered to any active subscribe() streams on the same subject, and also recorded so tests can assert on what was sent via MockBus::published_as. Commands sent via request() are routed to an active respond() stream on a matching subject, and the handler’s reply is delivered back to the caller.

Service code that takes impl Publisher + impl Subscriber parameters can be fully tested without a running NATS server:

use arminius_lib_message_bus::{
	Event, Publisher, Subscriber, mock::MockBus,
};
use futures::StreamExt;
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
struct OrderCreated {
	order_id: String,
}
impl Event for OrderCreated {
	const SUBJECT: &str = "OrderCreated.v1";
}

async fn handle_order(publisher: &impl Publisher, order_id: &str) {
	publisher
		.publish(OrderCreated { order_id: order_id.to_string() })
		.await
		.unwrap();
}

let bus = MockBus::new();
handle_order(&bus, "order-42").await;
let published = bus.published_as::<OrderCreated>();
assert_eq!(published[0].order_id, "order-42");

Fields§

§published: Arc<Mutex<Vec<(String, Vec<u8>)>>>

All published messages, recorded so tests can assert on what was sent.

§senders: Arc<Mutex<HashMap<String, Vec<Sender<Vec<u8>>>>>>

Active subscriber senders, keyed by subscribed subject pattern.

§responders: Arc<Mutex<HashMap<String, Vec<Sender<(Vec<u8>, Sender<Vec<u8>>)>>>>>

Active responder senders, keyed by the subject pattern they handle.

Implementations§

Source§

impl MockBus

Source

pub fn new() -> Self

Creates a new empty MockBus.

Source

pub fn published_as<E: Event>(&self) -> Vec<E>

Returns all events whose published subject matches E::SUBJECT, in order, deserialized. For per-instance events SUBJECT is a wildcard pattern, so every instance’s concrete subject is matched.

Trait Implementations§

Source§

impl Clone for MockBus

Source§

fn clone(&self) -> MockBus

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for MockBus

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for MockBus

Source§

fn default() -> MockBus

Returns the “default value” for a type. Read more
Source§

impl Publisher for MockBus

Source§

async fn publish<E: Event + Clone + 'static>( &self, message: E, ) -> Result<(), Error>

Publish an event to its subject. Read more
Source§

impl Requester for MockBus

Source§

async fn request<C: Command>(&self, cmd: C) -> Result<C::Reply, Error>

Send cmd and wait for a typed reply.
Source§

impl Responder for MockBus

Source§

async fn respond<C: Command + 'static>( self, ) -> Result<impl Stream<Item = Result<impl ReceivedCommand<C> + Send + Sync + 'static, Error>> + Send + 'static, Error>

Subscribe to commands of type C and return a stream of received commands.
Source§

impl Subscriber for MockBus

Source§

async fn subscribe<E: Event + 'static>( &self, ) -> Result<impl Stream<Item = Result<impl ReceivedEvent<E> + Send + Sync + 'static, Error>> + Send + 'static, Error>

Subscribe to events of type E. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> FutureExt for T

§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more