pub trait EventPublisher<T> {
fn publish(&self, envelope: &super::CloudEventsEnvelope<T>) -> crate::HexResult<()>;
fn publish_batch(&self, envelopes: &[super::CloudEventsEnvelope<T>]) -> crate::HexResult<()>;
}
#[cfg(test)]
mod tests {
use super::*;
struct TestEvent {
id: std::string::String,
}
impl crate::domain::DomainEvent for TestEvent {
fn event_type(&self) -> &str {
"com.test.event"
}
fn aggregate_id(&self) -> std::string::String {
self.id.clone()
}
}
struct MockPublisher {
published_count: std::cell::RefCell<usize>,
}
impl MockPublisher {
fn new() -> Self {
Self {
published_count: std::cell::RefCell::new(0),
}
}
fn get_published_count(&self) -> usize {
*self.published_count.borrow()
}
}
impl EventPublisher<TestEvent> for MockPublisher {
fn publish(
&self,
envelope: &crate::ports::events::cloud_events_envelope::CloudEventsEnvelope<TestEvent>,
) -> crate::HexResult<()> {
envelope.validate()?;
*self.published_count.borrow_mut() += 1;
std::result::Result::Ok(())
}
fn publish_batch(
&self,
envelopes: &[crate::ports::events::cloud_events_envelope::CloudEventsEnvelope<TestEvent>],
) -> crate::HexResult<()> {
for envelope in envelopes {
self.publish(envelope)?;
}
std::result::Result::Ok(())
}
}
#[test]
fn test_publish_single_event() {
let publisher = MockPublisher::new();
let event = TestEvent {
id: std::string::String::from("test-123"),
};
let envelope = super::super::CloudEventsEnvelope::from_domain_event(
std::string::String::from("evt-001"),
std::string::String::from("/test/source"),
event,
);
let result = publisher.publish(&envelope);
std::assert!(result.is_ok());
std::assert_eq!(publisher.get_published_count(), 1);
}
#[test]
fn test_publish_batch_events() {
let publisher = MockPublisher::new();
let envelopes = vec![
super::super::CloudEventsEnvelope::from_domain_event(
std::string::String::from("evt-001"),
std::string::String::from("/test/source"),
TestEvent {
id: std::string::String::from("test-1"),
},
),
super::super::CloudEventsEnvelope::from_domain_event(
std::string::String::from("evt-002"),
std::string::String::from("/test/source"),
TestEvent {
id: std::string::String::from("test-2"),
},
),
super::super::CloudEventsEnvelope::from_domain_event(
std::string::String::from("evt-003"),
std::string::String::from("/test/source"),
TestEvent {
id: std::string::String::from("test-3"),
},
),
];
let result = publisher.publish_batch(&envelopes);
std::assert!(result.is_ok());
std::assert_eq!(publisher.get_published_count(), 3);
}
#[test]
fn test_publish_validates_envelope() {
let publisher = MockPublisher::new();
let envelope = super::super::CloudEventsEnvelope::new(
std::string::String::from(""),
std::string::String::from("/test/source"),
std::string::String::from("com.test.event"),
);
let result = publisher.publish(&envelope);
std::assert!(result.is_err());
std::assert_eq!(publisher.get_published_count(), 0);
}
}