shelly-test 0.6.0

Testing helpers and macros for Shelly LiveView apps.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//! Test helpers for Shelly LiveView apps.
//!
//! This crate provides:
//! - small constructors for protocol events
//! - assertion helpers for common `ServerMessage` shapes
//! - macros to keep tests concise

pub use serde_json;
pub use shelly;

use shelly::{ClientMessage, DynamicSlotPatch, LiveSession, ServerMessage, StreamPosition};

/// Deterministic server-transcript fault used by the chaos harness.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ChaosFault {
    DropEvery { every: usize },
    DuplicateEvery { every: usize },
    ReorderAdjacent { first_index: usize },
    CorruptFirstPatchTarget,
}

/// Deterministic fault scenario for server transcript verification.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChaosScenario {
    pub id: String,
    pub faults: Vec<ChaosFault>,
}

impl ChaosScenario {
    pub fn new(id: impl Into<String>, faults: Vec<ChaosFault>) -> Self {
        Self {
            id: id.into(),
            faults,
        }
    }
}

/// Result of applying a deterministic chaos scenario to a server transcript.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChaosTranscriptReport {
    pub scenario_id: String,
    pub input_messages: usize,
    pub output_messages: usize,
    pub dropped_frames: usize,
    pub duplicated_frames: usize,
    pub reordered_frames: usize,
    pub corrupted_frames: usize,
    pub invariant_ok: bool,
    pub violation_code: Option<String>,
}

/// Apply deterministic transcript faults and validate server message invariants.
pub fn run_chaos_transcript(
    scenario: &ChaosScenario,
    transcript: &[ServerMessage],
) -> (Vec<ServerMessage>, ChaosTranscriptReport) {
    let mut output = transcript.to_vec();
    let mut dropped_frames = 0usize;
    let mut duplicated_frames = 0usize;
    let mut reordered_frames = 0usize;
    let mut corrupted_frames = 0usize;

    for fault in &scenario.faults {
        match *fault {
            ChaosFault::DropEvery { every } => {
                let every = every.max(1);
                let before = output.len();
                output = output
                    .into_iter()
                    .enumerate()
                    .filter_map(|(idx, message)| {
                        if (idx + 1) % every == 0 {
                            None
                        } else {
                            Some(message)
                        }
                    })
                    .collect();
                dropped_frames = dropped_frames.saturating_add(before.saturating_sub(output.len()));
            }
            ChaosFault::DuplicateEvery { every } => {
                let every = every.max(1);
                let mut duplicated = Vec::with_capacity(output.len().saturating_mul(2));
                for (idx, message) in output.into_iter().enumerate() {
                    duplicated.push(message.clone());
                    if (idx + 1) % every == 0 {
                        duplicated.push(message);
                        duplicated_frames = duplicated_frames.saturating_add(1);
                    }
                }
                output = duplicated;
            }
            ChaosFault::ReorderAdjacent { first_index } => {
                if first_index + 1 < output.len() {
                    output.swap(first_index, first_index + 1);
                    reordered_frames = reordered_frames.saturating_add(1);
                }
            }
            ChaosFault::CorruptFirstPatchTarget => {
                if let Some(
                    ServerMessage::Patch { target, .. } | ServerMessage::Diff { target, .. },
                ) = output.iter_mut().find(|message| {
                    matches!(
                        message,
                        ServerMessage::Patch { .. } | ServerMessage::Diff { .. }
                    )
                }) {
                    target.clear();
                    corrupted_frames = corrupted_frames.saturating_add(1);
                }
            }
        }
    }

    let invariant_result = shelly::validate_server_message_sequence(&output);
    let (invariant_ok, violation_code) = match invariant_result {
        Ok(()) => (true, None),
        Err(violation) => (false, Some(violation.code)),
    };

    let report = ChaosTranscriptReport {
        scenario_id: scenario.id.clone(),
        input_messages: transcript.len(),
        output_messages: output.len(),
        dropped_frames,
        duplicated_frames,
        reordered_frames,
        corrupted_frames,
        invariant_ok,
        violation_code,
    };
    (output, report)
}

/// Build a `ClientMessage::Event` with explicit fields.
pub fn client_event(
    name: impl Into<String>,
    target: Option<String>,
    value: serde_json::Value,
    metadata: serde_json::Map<String, serde_json::Value>,
) -> ClientMessage {
    ClientMessage::Event {
        event: name.into(),
        target,
        value,
        metadata,
    }
}

/// Dispatch one client message into a live session.
pub fn dispatch(session: &mut LiveSession, message: ClientMessage) -> Vec<ServerMessage> {
    session.handle_client_message(message)
}

/// Expect exactly one `patch` message.
pub fn expect_single_patch(messages: &[ServerMessage]) -> (&str, &str, u64) {
    match messages {
        [ServerMessage::Patch {
            target,
            html,
            revision,
        }] => (target.as_str(), html.as_str(), *revision),
        _ => panic!("expected exactly one patch message, got: {messages:?}"),
    }
}

/// Expect exactly one `diff` message.
pub fn expect_single_diff(messages: &[ServerMessage]) -> (&str, u64, &[DynamicSlotPatch]) {
    match messages {
        [ServerMessage::Diff {
            target,
            revision,
            slots,
        }] => (target.as_str(), *revision, slots.as_slice()),
        _ => panic!("expected exactly one diff message, got: {messages:?}"),
    }
}

/// Expect exactly one `stream_insert` message.
pub fn expect_single_stream_insert(
    messages: &[ServerMessage],
) -> (&str, &str, &str, &StreamPosition) {
    match messages {
        [ServerMessage::StreamInsert {
            target,
            id,
            html,
            at,
        }] => (target.as_str(), id.as_str(), html.as_str(), at),
        _ => panic!("expected exactly one stream_insert message, got: {messages:?}"),
    }
}

/// Expect exactly one `stream_delete` message.
pub fn expect_single_stream_delete(messages: &[ServerMessage]) -> (&str, &str) {
    match messages {
        [ServerMessage::StreamDelete { target, id }] => (target.as_str(), id.as_str()),
        _ => panic!("expected exactly one stream_delete message, got: {messages:?}"),
    }
}

/// Expect exactly one `error` message.
pub fn expect_single_error(messages: &[ServerMessage]) -> (&str, Option<&str>) {
    match messages {
        [ServerMessage::Error { message, code }] => (message.as_str(), code.as_deref()),
        _ => panic!("expected exactly one error message, got: {messages:?}"),
    }
}

/// Build a `ClientMessage::Event`.
#[macro_export]
macro_rules! event {
    ($name:expr $(,)?) => {
        $crate::client_event(
            $name,
            None,
            $crate::serde_json::Value::Null,
            $crate::serde_json::Map::new(),
        )
    };
    ($name:expr, value = $value:expr $(,)?) => {
        $crate::client_event($name, None, $value, $crate::serde_json::Map::new())
    };
    ($name:expr, target = $target:expr $(,)?) => {
        $crate::client_event(
            $name,
            Some(($target).to_string()),
            $crate::serde_json::Value::Null,
            $crate::serde_json::Map::new(),
        )
    };
    ($name:expr, target = $target:expr, value = $value:expr $(,)?) => {
        $crate::client_event(
            $name,
            Some(($target).to_string()),
            $value,
            $crate::serde_json::Map::new(),
        )
    };
    ($name:expr, value = $value:expr, target = $target:expr $(,)?) => {
        $crate::client_event(
            $name,
            Some(($target).to_string()),
            $value,
            $crate::serde_json::Map::new(),
        )
    };
    ($name:expr, target = $target:expr, value = $value:expr, metadata = $metadata:expr $(,)?) => {
        $crate::client_event($name, Some(($target).to_string()), $value, $metadata)
    };
    ($name:expr, value = $value:expr, target = $target:expr, metadata = $metadata:expr $(,)?) => {
        $crate::client_event($name, Some(($target).to_string()), $value, $metadata)
    };
}

/// Mount a fresh live session from a `Default` live view.
#[macro_export]
macro_rules! mount_session {
    ($view_ty:ty $(,)?) => {{
        let mut session = $crate::shelly::LiveSession::new(Box::<$view_ty>::default(), "root");
        session
            .mount()
            .expect("mount_session! should mount live view");
        session
    }};
    ($view_ty:ty, target = $target:expr $(,)?) => {{
        let mut session = $crate::shelly::LiveSession::new(Box::<$view_ty>::default(), $target);
        session
            .mount()
            .expect("mount_session! should mount live view");
        session
    }};
}

/// Dispatch one message into the session.
#[macro_export]
macro_rules! dispatch {
    ($session:expr, $message:expr $(,)?) => {
        $crate::dispatch(&mut $session, $message)
    };
}

/// Assert one patch message with exact target/revision.
#[macro_export]
macro_rules! assert_patch {
    ($messages:expr, target = $target:expr, revision = $revision:expr $(,)?) => {{
        let (actual_target, _actual_html, actual_revision) =
            $crate::expect_single_patch(&($messages));
        assert_eq!(actual_target, $target, "unexpected patch target");
        assert_eq!(actual_revision, $revision, "unexpected patch revision");
    }};
    ($messages:expr, target = $target:expr, revision = $revision:expr, html = $html:expr $(,)?) => {{
        let (actual_target, actual_html, actual_revision) =
            $crate::expect_single_patch(&($messages));
        assert_eq!(actual_target, $target, "unexpected patch target");
        assert_eq!(actual_revision, $revision, "unexpected patch revision");
        assert_eq!(actual_html, $html, "unexpected patch html");
    }};
    ($messages:expr, target = $target:expr, revision = $revision:expr, html_contains = $needle:expr $(,)?) => {{
        let (actual_target, actual_html, actual_revision) =
            $crate::expect_single_patch(&($messages));
        assert_eq!(actual_target, $target, "unexpected patch target");
        assert_eq!(actual_revision, $revision, "unexpected patch revision");
        assert!(
            actual_html.contains($needle),
            "expected patch html to contain `{}`, actual html: {}",
            $needle,
            actual_html
        );
    }};
}

/// Assert one diff message.
#[macro_export]
macro_rules! assert_diff {
    ($messages:expr, target = $target:expr, revision = $revision:expr, slots_len = $slots_len:expr $(,)?) => {{
        let (actual_target, actual_revision, actual_slots) =
            $crate::expect_single_diff(&($messages));
        assert_eq!(actual_target, $target, "unexpected diff target");
        assert_eq!(actual_revision, $revision, "unexpected diff revision");
        assert_eq!(actual_slots.len(), $slots_len, "unexpected diff slot count");
    }};
}

/// Assert one stream-insert message.
#[macro_export]
macro_rules! assert_stream_insert {
    ($messages:expr, target = $target:expr, id = $id:expr $(,)?) => {{
        let (actual_target, actual_id, _actual_html, _actual_at) =
            $crate::expect_single_stream_insert(&($messages));
        assert_eq!(actual_target, $target, "unexpected stream target");
        assert_eq!(actual_id, $id, "unexpected stream id");
    }};
}

/// Assert one stream-delete message.
#[macro_export]
macro_rules! assert_stream_delete {
    ($messages:expr, target = $target:expr, id = $id:expr $(,)?) => {{
        let (actual_target, actual_id) = $crate::expect_single_stream_delete(&($messages));
        assert_eq!(actual_target, $target, "unexpected stream target");
        assert_eq!(actual_id, $id, "unexpected stream id");
    }};
}

/// Assert one error code.
#[macro_export]
macro_rules! assert_error_code {
    ($messages:expr, $code:expr $(,)?) => {{
        let (_actual_message, actual_code) = $crate::expect_single_error(&($messages));
        assert_eq!(actual_code, Some($code), "unexpected error code");
    }};
    ($messages:expr, none $(,)?) => {{
        let (_actual_message, actual_code) = $crate::expect_single_error(&($messages));
        assert_eq!(actual_code, None, "expected no error code");
    }};
}

#[cfg(test)]
mod tests {
    use super::{run_chaos_transcript, ChaosFault, ChaosScenario};
    use shelly::{ResumeStatus, ServerMessage};

    fn transcript() -> Vec<ServerMessage> {
        vec![
            ServerMessage::Hello {
                session_id: "sid".to_string(),
                target: "root".to_string(),
                revision: 0,
                protocol: shelly::PROTOCOL_VERSION_V1.to_string(),
                server_revision: Some(0),
                resume_status: Some(ResumeStatus::Fresh),
                resume_reason: None,
                resume_token: Some("resume".to_string()),
                resume_expires_in_ms: Some(60_000),
            },
            ServerMessage::Patch {
                target: "root".to_string(),
                html: "<p>1</p>".to_string(),
                revision: 1,
            },
            ServerMessage::Patch {
                target: "root".to_string(),
                html: "<p>2</p>".to_string(),
                revision: 2,
            },
        ]
    }

    #[test]
    fn chaos_transcript_drop_preserves_invariants_when_sequence_remains_valid() {
        let scenario = ChaosScenario::new("drop-last", vec![ChaosFault::DropEvery { every: 3 }]);
        let (_messages, report) = run_chaos_transcript(&scenario, &transcript());

        assert_eq!(report.dropped_frames, 1);
        assert!(report.invariant_ok);
        assert_eq!(report.violation_code, None);
    }

    #[test]
    fn chaos_transcript_duplicate_detects_revision_regression() {
        let scenario = ChaosScenario::new(
            "duplicate-patch",
            vec![ChaosFault::DuplicateEvery { every: 2 }],
        );
        let (_messages, report) = run_chaos_transcript(&scenario, &transcript());

        assert_eq!(report.duplicated_frames, 1);
        assert!(!report.invariant_ok);
        assert_eq!(
            report.violation_code.as_deref(),
            Some("non_monotonic_revision")
        );
    }

    #[test]
    fn chaos_transcript_corrupt_detects_invalid_message_shape() {
        let scenario =
            ChaosScenario::new("corrupt-target", vec![ChaosFault::CorruptFirstPatchTarget]);
        let (_messages, report) = run_chaos_transcript(&scenario, &transcript());

        assert_eq!(report.corrupted_frames, 1);
        assert!(!report.invariant_ok);
        assert_eq!(report.violation_code.as_deref(), Some("empty_field"));
    }
}