microsoft-webui-test-utils 0.0.5

Test utilities for WebUI framework
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

//! Test utilities for WebUI framework.
//!
//! This crate provides testing helpers and should only be used in test code.

use std::fs;
use std::{collections::HashMap, path::PathBuf};
use tempfile::TempDir;
pub use webui_protocol;

/// A macro that wraps `serde_json::json!` but allows bypassing clippy::disallowed_methods.
///
/// This macro should only be used in test code.
#[macro_export]
macro_rules! test_json {
    ($($json:tt)+) => {{
        #[allow(clippy::disallowed_methods)]
        let value = serde_json::json!($($json)+);
        value
    }};
}

/// Assert that a fragment list matches the expected pattern.
///
/// Each matcher is one of:
/// - `raw("text")` — Raw fragment with exact value
/// - `signal("name")` — Escaped signal
/// - `signal("name", raw)` — Raw (unescaped) signal
/// - `attr("name", value: "v")` — Simple dynamic attribute
/// - `attr("name", template: "id")` — Template attribute
/// - `attr("name", complex: "v")` — Complex (:-prefixed) attribute
/// - `bool_attr("name", "signal")` — Boolean attribute with identifier condition
/// - `attr_raw("name", "v")` — Static attribute with rawValue
/// - `attr_raw("name", "v", attr_start)` — Static rawValue with attrStart
/// - `attr_skip("name", "v")` — Skipped attribute
/// - `component("id")` — Component fragment
/// - `for_loop("item", "collection", "template")` — For loop
/// - `if_cond("template")` — If condition
#[macro_export]
macro_rules! assert_fragments {
    ($fragments:expr, [ $($matcher:expr),* $(,)? ]) => {{
        let matchers: Vec<$crate::FragmentMatcher> = vec![$($matcher),*];
        $crate::assert_fragment_list(&$fragments, &matchers);
    }};
}

/// Assert that a named stream in the records matches the expected pattern.
#[macro_export]
macro_rules! assert_stream {
    ($records:expr, $stream_id:expr, [ $($matcher:expr),* $(,)? ]) => {{
        let stream = $records.get($stream_id)
            .unwrap_or_else(|| panic!("Missing stream: {}", $stream_id));
        let matchers: Vec<$crate::FragmentMatcher> = vec![$($matcher),*];
        $crate::assert_fragment_list(&stream.fragments, &matchers);
    }};
}

// ── Fragment matcher types ──────────────────────────────────────────

/// Describes an expected fragment for assertion matching.
#[derive(Debug)]
pub enum FragmentMatcher {
    Raw(String),
    Signal {
        value: String,
        raw: bool,
    },
    Attribute(AttrMatcher),
    Component(String),
    ForLoop {
        item: String,
        collection: String,
        template: String,
    },
    IfCond {
        template: String,
    },
}

/// Describes expected attribute properties.
#[derive(Debug, Default)]
pub struct AttrMatcher {
    pub name: String,
    pub value: Option<String>,
    pub template: Option<String>,
    pub complex: bool,
    pub attr_start: bool,
    pub attr_skip: bool,
    pub raw_value: bool,
    pub bool_signal: Option<String>,
    /// Match a boolean attribute with a predicate condition (left, op, right).
    pub bool_predicate: Option<(String, i32, String)>,
    /// Match a boolean attribute with a negation condition (inner identifier).
    pub bool_not: Option<String>,
}

// ── Matcher constructors ────────────────────────────────────────────

/// Match a raw fragment.
pub fn raw(value: &str) -> FragmentMatcher {
    FragmentMatcher::Raw(value.to_string())
}

/// Match an escaped signal fragment.
pub fn signal(value: &str) -> FragmentMatcher {
    FragmentMatcher::Signal {
        value: value.to_string(),
        raw: false,
    }
}

/// Match a raw (unescaped) signal fragment.
pub fn signal_raw(value: &str) -> FragmentMatcher {
    FragmentMatcher::Signal {
        value: value.to_string(),
        raw: true,
    }
}

/// Match a simple dynamic attribute.
pub fn attr(name: &str, value: &str) -> FragmentMatcher {
    FragmentMatcher::Attribute(AttrMatcher {
        name: name.to_string(),
        value: Some(value.to_string()),
        ..Default::default()
    })
}

/// Match a template (mixed) attribute.
pub fn attr_template(name: &str, template: &str) -> FragmentMatcher {
    FragmentMatcher::Attribute(AttrMatcher {
        name: name.to_string(),
        template: Some(template.to_string()),
        ..Default::default()
    })
}

/// Match a complex (:-prefixed) attribute.
pub fn attr_complex(name: &str, value: &str) -> FragmentMatcher {
    FragmentMatcher::Attribute(AttrMatcher {
        name: name.to_string(),
        value: Some(value.to_string()),
        complex: true,
        ..Default::default()
    })
}

/// Match a complex attribute with attrStart.
pub fn attr_complex_start(name: &str, value: &str) -> FragmentMatcher {
    FragmentMatcher::Attribute(AttrMatcher {
        name: name.to_string(),
        value: Some(value.to_string()),
        complex: true,
        attr_start: true,
        ..Default::default()
    })
}

/// Match a boolean attribute with an identifier condition.
pub fn bool_attr(name: &str, signal: &str) -> FragmentMatcher {
    FragmentMatcher::Attribute(AttrMatcher {
        name: name.to_string(),
        bool_signal: Some(signal.to_string()),
        ..Default::default()
    })
}

/// Match a boolean attribute with attrStart.
pub fn bool_attr_start(name: &str, signal: &str) -> FragmentMatcher {
    FragmentMatcher::Attribute(AttrMatcher {
        name: name.to_string(),
        bool_signal: Some(signal.to_string()),
        attr_start: true,
        ..Default::default()
    })
}

/// Match a boolean attribute with a predicate condition (e.g., `?disabled={{count > 5}}`).
pub fn bool_attr_predicate(name: &str, left: &str, op: i32, right: &str) -> FragmentMatcher {
    FragmentMatcher::Attribute(AttrMatcher {
        name: name.to_string(),
        bool_predicate: Some((left.to_string(), op, right.to_string())),
        ..Default::default()
    })
}

/// Match a boolean attribute with a negated condition (e.g., `?disabled={{!isReady}}`).
pub fn bool_attr_not(name: &str, inner: &str) -> FragmentMatcher {
    FragmentMatcher::Attribute(AttrMatcher {
        name: name.to_string(),
        bool_not: Some(inner.to_string()),
        ..Default::default()
    })
}

/// Match a static rawValue attribute.
pub fn attr_raw(name: &str, value: &str) -> FragmentMatcher {
    FragmentMatcher::Attribute(AttrMatcher {
        name: name.to_string(),
        value: Some(value.to_string()),
        raw_value: true,
        ..Default::default()
    })
}

/// Match a static rawValue attribute with attrStart.
pub fn attr_raw_start(name: &str, value: &str) -> FragmentMatcher {
    FragmentMatcher::Attribute(AttrMatcher {
        name: name.to_string(),
        value: Some(value.to_string()),
        raw_value: true,
        attr_start: true,
        ..Default::default()
    })
}

/// Match a skipped attribute.
pub fn attr_skip(name: &str, value: &str) -> FragmentMatcher {
    FragmentMatcher::Attribute(AttrMatcher {
        name: name.to_string(),
        value: Some(value.to_string()),
        attr_skip: true,
        ..Default::default()
    })
}

/// Match a skipped attribute with a static raw value.
pub fn attr_skip_raw(name: &str, value: &str) -> FragmentMatcher {
    FragmentMatcher::Attribute(AttrMatcher {
        name: name.to_string(),
        raw_value: true,
        value: Some(value.to_string()),
        attr_skip: true,
        ..Default::default()
    })
}

/// Match a skipped attribute with an embedded binding template.
pub fn attr_skip_template(name: &str, template: &str) -> FragmentMatcher {
    FragmentMatcher::Attribute(AttrMatcher {
        name: name.to_string(),
        template: Some(template.to_string()),
        attr_skip: true,
        ..Default::default()
    })
}

/// Match a simple dynamic attribute with attrStart.
pub fn attr_start(name: &str, value: &str) -> FragmentMatcher {
    FragmentMatcher::Attribute(AttrMatcher {
        name: name.to_string(),
        value: Some(value.to_string()),
        attr_start: true,
        ..Default::default()
    })
}

/// Match a component fragment.
pub fn component(id: &str) -> FragmentMatcher {
    FragmentMatcher::Component(id.to_string())
}

/// Match a for-loop fragment.
pub fn for_loop(item: &str, collection: &str, template: &str) -> FragmentMatcher {
    FragmentMatcher::ForLoop {
        item: item.to_string(),
        collection: collection.to_string(),
        template: template.to_string(),
    }
}

/// Match an if-condition fragment.
pub fn if_cond(template: &str) -> FragmentMatcher {
    FragmentMatcher::IfCond {
        template: template.to_string(),
    }
}

// ── Assertion implementation ────────────────────────────────────────

/// Assert that a fragment list matches the expected matchers.
pub fn assert_fragment_list(
    fragments: &[webui_protocol::WebUIFragment],
    matchers: &[FragmentMatcher],
) {
    use webui_protocol::web_ui_fragment::Fragment;

    assert_eq!(
        fragments.len(),
        matchers.len(),
        "Fragment count mismatch: got {} fragments, expected {}\nFragments: {:#?}",
        fragments.len(),
        matchers.len(),
        fragments.iter().map(format_fragment).collect::<Vec<_>>()
    );

    for (i, (frag, matcher)) in fragments.iter().zip(matchers.iter()).enumerate() {
        match (frag.fragment.as_ref(), matcher) {
            (Some(Fragment::Raw(r)), FragmentMatcher::Raw(expected)) => {
                assert_eq!(r.value, *expected, "Fragment[{}]: raw value mismatch", i);
            }
            (Some(Fragment::Signal(s)), FragmentMatcher::Signal { value, raw }) => {
                assert_eq!(s.value, *value, "Fragment[{}]: signal value mismatch", i);
                assert_eq!(s.raw, *raw, "Fragment[{}]: signal raw flag mismatch", i);
            }
            (Some(Fragment::Attribute(a)), FragmentMatcher::Attribute(m)) => {
                assert_eq!(a.name, m.name, "Fragment[{}]: attr name mismatch", i);
                if let Some(ref v) = m.value {
                    assert_eq!(a.value, *v, "Fragment[{}]: attr value mismatch", i);
                }
                if let Some(ref t) = m.template {
                    assert_eq!(a.template, *t, "Fragment[{}]: attr template mismatch", i);
                }
                assert_eq!(
                    a.complex, m.complex,
                    "Fragment[{}]: attr complex mismatch",
                    i
                );
                assert_eq!(
                    a.attr_start, m.attr_start,
                    "Fragment[{}]: attr_start mismatch",
                    i
                );
                assert_eq!(
                    a.attr_skip, m.attr_skip,
                    "Fragment[{}]: attr_skip mismatch",
                    i
                );
                assert_eq!(
                    a.raw_value, m.raw_value,
                    "Fragment[{}]: raw_value mismatch",
                    i
                );
                if let Some(ref sig) = m.bool_signal {
                    let cond = a
                        .condition_tree
                        .as_ref()
                        .unwrap_or_else(|| panic!("Fragment[{}]: expected condition_tree", i));
                    match cond.expr.as_ref() {
                        Some(webui_protocol::condition_expr::Expr::Identifier(id)) => {
                            assert_eq!(
                                id.value, *sig,
                                "Fragment[{}]: bool attr signal mismatch",
                                i
                            );
                        }
                        other => panic!(
                            "Fragment[{}]: expected identifier condition, got {:?}",
                            i, other
                        ),
                    }
                }
                if let Some((ref left, op, ref right)) = m.bool_predicate {
                    let cond = a
                        .condition_tree
                        .as_ref()
                        .unwrap_or_else(|| panic!("Fragment[{}]: expected condition_tree", i));
                    match cond.expr.as_ref() {
                        Some(webui_protocol::condition_expr::Expr::Predicate(pred)) => {
                            assert_eq!(
                                pred.left, *left,
                                "Fragment[{}]: predicate left mismatch",
                                i
                            );
                            assert_eq!(
                                pred.operator, op,
                                "Fragment[{}]: predicate operator mismatch",
                                i
                            );
                            assert_eq!(
                                pred.right, *right,
                                "Fragment[{}]: predicate right mismatch",
                                i
                            );
                        }
                        other => panic!(
                            "Fragment[{}]: expected predicate condition, got {:?}",
                            i, other
                        ),
                    }
                }
                if let Some(ref inner) = m.bool_not {
                    let cond = a
                        .condition_tree
                        .as_ref()
                        .unwrap_or_else(|| panic!("Fragment[{}]: expected condition_tree", i));
                    match cond.expr.as_ref() {
                        Some(webui_protocol::condition_expr::Expr::Not(not_cond)) => {
                            let inner_cond = not_cond.condition.as_ref().unwrap_or_else(|| {
                                panic!("Fragment[{}]: not condition missing inner", i)
                            });
                            match inner_cond.expr.as_ref() {
                                Some(webui_protocol::condition_expr::Expr::Identifier(id)) => {
                                    assert_eq!(
                                        id.value, *inner,
                                        "Fragment[{}]: not inner identifier mismatch",
                                        i
                                    );
                                }
                                other => panic!(
                                    "Fragment[{}]: expected identifier inside not, got {:?}",
                                    i, other
                                ),
                            }
                        }
                        other => panic!("Fragment[{}]: expected not condition, got {:?}", i, other),
                    }
                }
            }
            (Some(Fragment::Component(c)), FragmentMatcher::Component(id)) => {
                assert_eq!(c.fragment_id, *id, "Fragment[{}]: component id mismatch", i);
            }
            (
                Some(Fragment::ForLoop(fl)),
                FragmentMatcher::ForLoop {
                    item,
                    collection,
                    template,
                },
            ) => {
                assert_eq!(fl.item, *item, "Fragment[{}]: for item mismatch", i);
                assert_eq!(
                    fl.collection, *collection,
                    "Fragment[{}]: for collection mismatch",
                    i
                );
                assert_eq!(
                    fl.fragment_id, *template,
                    "Fragment[{}]: for template mismatch",
                    i
                );
            }
            (Some(Fragment::IfCond(ic)), FragmentMatcher::IfCond { template }) => {
                assert_eq!(
                    ic.fragment_id, *template,
                    "Fragment[{}]: if template mismatch",
                    i
                );
            }
            (_actual, expected) => {
                panic!(
                    "Fragment[{}]: type mismatch\n  expected: {:?}\n  actual: {}",
                    i,
                    expected,
                    format_fragment(frag)
                );
            }
        }
    }
}

fn format_fragment(frag: &webui_protocol::WebUIFragment) -> String {
    use webui_protocol::web_ui_fragment::Fragment;
    match frag.fragment.as_ref() {
        Some(Fragment::Raw(r)) => format!("raw({:?})", r.value),
        Some(Fragment::Signal(s)) => format!("signal({:?}, raw={})", s.value, s.raw),
        Some(Fragment::Attribute(a)) => format!(
            "attr({:?}, value={:?}, template={:?}, complex={}, start={}, skip={}, raw_value={})",
            a.name, a.value, a.template, a.complex, a.attr_start, a.attr_skip, a.raw_value
        ),
        Some(Fragment::Component(c)) => format!("component({:?})", c.fragment_id),
        Some(Fragment::ForLoop(f)) => format!(
            "for({:?} in {:?}, template={:?})",
            f.item, f.collection, f.fragment_id
        ),
        Some(Fragment::IfCond(i)) => format!("if(template={:?})", i.fragment_id),
        Some(Fragment::Plugin(p)) => format!("plugin(data={:?})", p.data),
        Some(Fragment::Route(r)) => {
            format!("route(path={:?}, fragment={:?})", r.path, r.fragment_id)
        }
        Some(Fragment::Outlet(_)) => "outlet".to_string(),
        None => "None".to_string(),
    }
}

/// A test file system that manages temporary files and directories
pub struct TestFileSystem {
    files: HashMap<String, PathBuf>,

    // Keep directories alive for the lifetime of this struct
    _temp_dirs: Vec<TempDir>,
}

impl Default for TestFileSystem {
    fn default() -> Self {
        Self::new()
    }
}

impl TestFileSystem {
    /// Create a new empty test file system
    pub fn new() -> Self {
        Self {
            files: HashMap::new(),
            _temp_dirs: Vec::new(),
        }
    }

    /// Add a file to the test file system at the specified path
    pub fn add_file(&mut self, path: &str, content: &str) -> PathBuf {
        // Create a new temporary directory for this file
        let temp_dir = tempfile::tempdir().expect("Failed to create temporary directory");

        // Parse the path to separate directories and filename
        let path_parts: Vec<&str> = path.split('/').collect();
        let filename = path_parts.last().expect("Path must contain a filename");

        // Create the file within the temporary directory
        let file_path = temp_dir.path().join(filename);
        fs::write(&file_path, content).expect("Failed to write content to file");

        // Store the path and keep the directory alive
        self.files.insert(path.to_string(), file_path.clone());
        self._temp_dirs.push(temp_dir);

        // Return a reference to the stored path
        self.files
            .get(path)
            .expect("File path not found in the test file system");

        // Return the path by value (clone it)
        file_path
    }
}