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
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use {
    crate::appendable::{Appendable, BufferTooSmall},
    fuchsia_async::{DurationExt, OnTimeout, TimeoutExt},
    fuchsia_zircon as zx,
    futures::Future,
};

pub mod fake_capabilities;
pub mod fake_features;
pub mod fake_frames;
pub mod fake_stas;

/// A trait which allows to expect a future to terminate within a given time or panic otherwise.
pub trait ExpectWithin: Future + Sized {
    fn expect_within<S: ToString + Clone>(
        self,
        duration: zx::Duration,
        msg: S,
    ) -> OnTimeout<Self, Box<dyn FnOnce() -> Self::Output>> {
        let msg = msg.clone().to_string();
        self.on_timeout(duration.after_now(), Box::new(move || panic!("{}", msg)))
    }
}

impl<F: Future + Sized> ExpectWithin for F {}

pub struct FixedSizedTestBuffer(Vec<u8>);
impl FixedSizedTestBuffer {
    pub fn new(capacity: usize) -> Self {
        Self(Vec::with_capacity(capacity))
    }
}
impl Appendable for FixedSizedTestBuffer {
    fn append_bytes(&mut self, bytes: &[u8]) -> Result<(), BufferTooSmall> {
        if !self.can_append(bytes.len()) {
            return Err(BufferTooSmall);
        }
        self.0.append_bytes(bytes)
    }

    fn append_bytes_zeroed(&mut self, len: usize) -> Result<&mut [u8], BufferTooSmall> {
        if !self.can_append(len) {
            return Err(BufferTooSmall);
        }
        self.0.append_bytes_zeroed(len)
    }

    fn bytes_written(&self) -> usize {
        self.0.len()
    }

    fn can_append(&self, bytes: usize) -> bool {
        self.0.len() + bytes <= self.0.capacity()
    }
}

/// Macro to assert a value matches a variant.
/// This macro is particularly useful when partially matching a variant.
///
/// Example:
/// ```
/// // Basic matching:
/// let foo = Foo::B(42);
/// assert_variant!(foo, Foo::B(_)); // Success
/// assert_variant!(foo, Foo::A); // Panics: "unexpected variant: B(42)"
///
/// // Multiple variants matching:
/// let foo = Foo::B(42);
/// assert_variant!(foo, Foo::A | Foo::B(_)); // Success
/// assert_variant!(foo, Foo::A | Foo::C); // Panics: "unexpected variant: B(42)"
///
/// // Advanced matching:
/// let foo: Result<Option<u8>, u8> = Result::Ok(Some(5));
/// assert_variant!(foo, Result::Ok(Some(1...5))); // Success
/// assert_variant!(foo, Result::Ok(Some(1...4))); // Panics: "unexpected variant: Ok(Some(5))"
///
/// // Custom message
/// let foo = Foo::B(42);
/// // Panics: "expected Foo::A, actual: B(42)"
/// assert_variant!(foo, Foo::A, "expected Foo::A, actual: {:?}", foo);
///
/// // Optional expression:
/// let foo = Foo::B(...);
/// assert_variant!(foo, Foo::B(v) => {
///     assert_eq!(v.id, 5);
///     ...
/// });
///
/// // Unwrapping partially matched variant:
/// let foo = Foo::B(...);
/// let bar = assert_variant!(foo, Foo::B(bar) => bar);
/// let xyz = bar.foo_bar(...);
/// assert_eq!(xyz, ...);
/// ```
#[macro_export]
macro_rules! assert_variant {
    // Use custom formatting when panicking.
    ($test:expr, $variant:pat_param $( | $others:pat)* => $e:expr, $fmt:expr $(, $args:tt)* $(,)?) => {
        match $test {
            $variant $(| $others)* => $e,
            _ => panic!($fmt, $($args,)*),
        }
    };
    // Use default message when panicking.
    ($test:expr, $variant:pat_param $( | $others:pat)* => $e:expr $(,)?) => {
        match $test {
            $variant $(| $others)* => $e,
            other => panic!("unexpected variant: {:?}", other),
        }
    };
    // Custom error message.
    ($test:expr, $variant:pat_param $( | $others:pat)* , $fmt:expr $(, $args:tt)* $(,)?) => {
        $crate::assert_variant!($test, $variant $( | $others)* => {}, $fmt $(, $args)*)
    };
    // Default error message.
    ($test:expr, $variant:pat_param $( | $others:pat)* $(,)?) => {
        $crate::assert_variant!($test, $variant $( | $others)* => {})
    };
}

/// Asserts the value at a particular index of an expression
/// evaluating to a type implementing the Index trait. This macro
/// is effectively a thin wrapper around `assert_variant` that will
/// pretty-print the entire indexable value if the assertion fails.
///
/// This macro is particularly useful when failure to assert a single
/// value in a Vec requires more context to debug the failure.
///
/// # Examples
///
/// ```
/// let v = vec![0, 2];
/// // Success
/// assert_variant_at_idx!(v, 0, 0);
/// // Panics: "unexpected variant at 0 in v:
/// // [
/// //   0,
/// //   2,
/// // ]"
/// assert_variant_at_idx!(v, 0, 2);
/// ```
#[macro_export]
macro_rules! assert_variant_at_idx {
    // Use custom formatting when panicking.
    ($indexable:expr, $idx:expr, $variant:pat_param $( | $others:pat)* => $e:expr, $fmt:expr $(, $args:tt)* $(,)?) => {
        $crate::assert_variant!(&$indexable[$idx], $variant $( | $others)* => { $e }, $fmt $(, $args)*)
    };
    // Use default message when panicking.
    ($indexable:expr, $idx:expr, $variant:pat_param $( | $others:pat)* => $e:expr $(,)?) => {{
        let indexable_name = stringify!($indexable);
        $crate::assert_variant_at_idx!($indexable, $idx, $variant $( | $others)* => { $e },
                                       "unexpected variant at {:?} in {}:\n{:#?}", $idx, indexable_name, $indexable)
    }};
    // Custom error message.
    ($indexable:expr, $idx:expr, $variant:pat_param $( | $others:pat)*, $fmt:expr $(, $args:tt)* $(,)?) => {
        $crate::assert_variant_at_idx!($indexable, $idx, $variant $( | $others)* => {}, $fmt $(, $args)*)
    };
    // Default error message.
    ($indexable:expr, $idx:expr, $variant:pat_param $( | $others:pat)* $(,)?) => {
        $crate::assert_variant_at_idx!($indexable, $idx, $variant $( | $others)* => {})
    };
}

#[cfg(test)]
mod tests {
    use std::panic;

    #[derive(Debug)]
    enum Foo {
        A(u8),
        B {
            named: u8,
            // TODO(https://fxbug.dev/42165549)
            #[allow(unused)]
            bar: u16,
        },
        C,
    }

    #[test]
    fn assert_variant_full_match_success() {
        assert_variant!(Foo::A(8), Foo::A(8));
    }

    #[test]
    fn assert_variant_no_expr_value() {
        assert_variant!(0, 0);
    }

    #[test]
    #[should_panic(expected = "unexpected variant")]
    // TODO(https://fxbug.dev/42169733): LeakSanitizer flags leaks caused by panic.
    #[cfg_attr(feature = "variant_asan", ignore)]
    fn assert_variant_full_match_fail_with_same_variant_different_value() {
        assert_variant!(Foo::A(8), Foo::A(7));
    }

    #[test]
    #[should_panic(expected = "unexpected variant")]
    // TODO(https://fxbug.dev/42169733): LeakSanitizer flags leaks caused by panic.
    #[cfg_attr(feature = "variant_asan", ignore)]
    fn assert_variant_full_match_fail_with_different_variant() {
        assert_variant!(Foo::A(8), Foo::C);
    }

    #[test]
    fn assert_variant_multi_variant_success() {
        assert_variant!(Foo::A(8), Foo::A(8) | Foo::C);
        assert_variant!(Foo::C, Foo::A(8) | Foo::C);
    }

    #[test]
    #[should_panic(expected = "unexpected variant")]
    // TODO(https://fxbug.dev/42169733): LeakSanitizer flags leaks caused by panic.
    #[cfg_attr(feature = "variant_asan", ignore)]
    fn assert_variant_multi_variant_failure() {
        assert_variant!(Foo::C, Foo::A(_) | Foo::B { .. });
    }

    #[test]
    fn assert_variant_partial_match_success() {
        assert_variant!(Foo::A(8), Foo::A(_));
        assert_variant!(Foo::B { named: 7, bar: 8 }, Foo::B { .. });
        assert_variant!(Foo::B { named: 7, bar: 8 }, Foo::B { named: 7, .. });
    }

    #[test]
    #[should_panic(expected = "unexpected variant")]
    // TODO(https://fxbug.dev/42169733): LeakSanitizer flags leaks caused by panic.
    #[cfg_attr(feature = "variant_asan", ignore)]
    fn assert_variant_partial_match_failure() {
        assert_variant!(Foo::A(8), Foo::B { .. });
    }

    #[test]
    fn assert_variant_expr() {
        assert_variant!(Foo::A(8), Foo::A(value) => {
            assert_eq!(value, 8);
        });
        assert_variant!(Foo::B { named: 7, bar: 8 }, Foo::B { named, .. } => {
            assert_eq!(named, 7);
        });

        let named = assert_variant!(Foo::B { named: 7, bar: 8 }, Foo::B { named, .. } => named);
        assert_eq!(named, 7);

        let named = assert_variant!(Foo::B { named: 7, bar: 8 }, Foo::B { named, .. } => named, "custom error message");
        assert_eq!(named, 7);

        assert_variant!(Foo::B { named: 7, bar: 8 }, Foo::B { .. } => (), "custom error message");
    }

    #[test]
    fn assert_variant_custom_message_success() {
        assert_variant!(Foo::A(8), Foo::A(_), "custom error message");
    }

    #[test]
    #[should_panic(expected = "custom error message")]
    // TODO(https://fxbug.dev/42169733): LeakSanitizer flags leaks caused by panic.
    #[cfg_attr(feature = "variant_asan", ignore)]
    fn assert_variant_custom_message_failure() {
        assert_variant!(Foo::A(8), Foo::B { .. }, "custom error message");
    }

    #[test]
    #[should_panic(expected = "custom error message token1 token2")]
    // TODO(https://fxbug.dev/42169733): LeakSanitizer flags leaks caused by panic.
    #[cfg_attr(feature = "variant_asan", ignore)]
    fn assert_variant_custom_message_with_multiple_fmt_tokens_failure() {
        assert_variant!(Foo::A(8), Foo::B { .. }, "custom error message {} {}", "token1", "token2");
    }

    #[test]
    fn assert_variant_at_idx_success() {
        let v = vec![0, 2];
        assert_variant_at_idx!(v, 0, 0);
    }

    #[test]
    fn assert_variant_at_idx_no_expr_value() {
        let v = vec![0, 2];
        assert_variant_at_idx!(v, 0, 0);
    }

    #[test]
    #[should_panic(expected = "unexpected variant at 0 in v:\n[\n    0,\n    2,\n]")]
    // TODO(https://fxbug.dev/42169733): LeakSanitizer flags leaks caused by panic.
    #[cfg_attr(feature = "variant_asan", ignore)]
    fn assert_variant_at_idx_failure() {
        let v = vec![0, 2];
        assert_variant_at_idx!(v, 0, 2);
    }

    #[test]
    fn assert_variant_at_idx_custom_message_success() {
        let v = vec![0, 2];
        assert_variant_at_idx!(v, 0, 0, "custom error message");
    }

    #[test]
    #[should_panic(expected = "custom error message")]
    // TODO(https://fxbug.dev/42169733): LeakSanitizer flags leaks caused by panic.
    #[cfg_attr(feature = "variant_asan", ignore)]
    fn assert_variant_at_idx_custom_message_failure() {
        let v = vec![0, 2];
        assert_variant_at_idx!(v, 0, 2, "custom error message");
    }

    #[test]
    #[should_panic(expected = "custom error message token1 token2")]
    // TODO(https://fxbug.dev/42169733): LeakSanitizer flags leaks caused by panic.
    #[cfg_attr(feature = "variant_asan", ignore)]
    fn assert_variant_at_idx_custom_message_with_multiple_tokens_failure() {
        let v = vec![0, 2];
        assert_variant_at_idx!(v, 0, 2, "custom error message {} {}", "token1", "token2");
    }

    #[test]
    fn assert_variant_at_idx_expr() {
        let v = vec![0, 2];
        assert_variant_at_idx!(v, 0, 0 => {
            assert_eq!(1, 1);
        });

        let named = assert_variant_at_idx!(v, 0, 0 => 1);
        assert_eq!(named, 1);

        let named = assert_variant_at_idx!(v, 0, 0 => 1, "custom error message");
        assert_eq!(named, 1);

        assert_variant_at_idx!(v, 0, 0 => (), "custom error message");
    }
}