mundane/
util.rs

1// Copyright 2020 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5/// A trait that can be used to ensure that users of this crate can't implement
6/// a trait.
7///
8/// See the [API Guidelines] for details.
9///
10/// [API Guidelines]: https://rust-lang-nursery.github.io/api-guidelines/future-proofing.html#sealed-traits-protect-against-downstream-implementations-c-sealed
11pub trait Sealed {}
12
13/// Expects that a `Result` is an error.
14///
15/// `should_fail` ensures that `result` is an error, and that the error's
16/// `Debug` representation contains the string `expected_substr`. Otherwise, it
17/// panics.
18#[cfg(test)]
19pub fn should_fail<O, E: ::std::fmt::Debug>(
20    result: Result<O, E>,
21    desc: &str,
22    expected_substr: &str,
23) {
24    // Credit to agl@google.com for this implementation.
25    match result {
26        Ok(_) => panic!("{} unexpectedly succeeded", desc),
27        Err(err) => {
28            let err_str = format!("{:?}", err);
29            err_str.find(expected_substr).unwrap_or_else(|| {
30                panic!(
31                    "{} resulted in error that doesn't include {:?}: {:?}",
32                    desc, expected_substr, err_str
33                )
34            });
35        }
36    }
37}