#![allow(
clippy::unwrap_used,
reason = "tests use unwrap for clarity and brevity"
)]
#![allow(
clippy::expect_used,
reason = "tests use expect for clarity and brevity"
)]
#![allow(clippy::str_to_string, reason = "tests use to_string/to_owned freely")]
#![allow(
clippy::shadow_reuse,
reason = "tests shadow variables for readability"
)]
#![allow(
clippy::shadow_unrelated,
reason = "tests shadow variables for readability"
)]
#![allow(
clippy::float_cmp,
reason = "tests compare exact f64 values through serde roundtrip"
)]
use mnesis::{DomainEvent, Message};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[allow(
clippy::enum_variant_names,
reason = "test enum uses Variant suffix for clarity"
)]
enum TestEvent {
UnitVariant,
TupleVariant(String, u64),
StructVariant { name: String, value: f64 },
}
impl Message for TestEvent {}
impl DomainEvent for TestEvent {
fn name(&self) -> &'static str {
match self {
Self::UnitVariant => "UnitVariant",
Self::TupleVariant(..) => "TupleVariant",
Self::StructVariant { .. } => "StructVariant",
}
}
}
fn encode_test_event(event: &TestEvent) -> Vec<u8> {
serde_json::to_vec(event).expect("TestEvent should always serialize to JSON")
}
fn decode_test_event(payload: &[u8]) -> Result<TestEvent, serde_json::Error> {
serde_json::from_slice(payload)
}
#[test]
fn roundtrip_unit_variant() {
let original = TestEvent::UnitVariant;
let bytes = encode_test_event(&original);
let decoded = decode_test_event(&bytes).unwrap();
assert_eq!(original, decoded);
assert_eq!(original.name(), "UnitVariant");
}
#[test]
fn roundtrip_tuple_variant() {
let original = TestEvent::TupleVariant("hello".to_owned(), 42);
let bytes = encode_test_event(&original);
let decoded = decode_test_event(&bytes).unwrap();
assert_eq!(original, decoded);
assert_eq!(original.name(), "TupleVariant");
}
#[test]
fn roundtrip_struct_variant() {
let original = TestEvent::StructVariant {
name: "temperature".to_owned(),
value: 98.6,
};
let bytes = encode_test_event(&original);
let decoded = decode_test_event(&bytes).unwrap();
assert_eq!(original, decoded);
assert_eq!(original.name(), "StructVariant");
}
#[test]
fn decode_corrupted_payload() {
let garbage: &[u8] = &[0xFF, 0xFE, 0x00, 0x01, 0xDE, 0xAD];
let result = decode_test_event(garbage);
assert!(result.is_err(), "corrupted payload should fail to decode");
}
#[test]
fn decode_wrong_format() {
let original = TestEvent::StructVariant {
name: "test".to_owned(),
value: 1.0,
};
let bytes = encode_test_event(&original);
let decoded = decode_test_event(&bytes).unwrap();
assert_eq!(original, decoded);
let wrong_json = br#"{"UnknownVariant": {"x": 1}}"#;
let result = decode_test_event(wrong_json);
assert!(
result.is_err(),
"JSON with an unknown variant key should fail to deserialize into TestEvent. \
serde_json uses the externally-tagged enum representation by default, so \
the variant name in JSON must match a variant of TestEvent."
);
}