Skip to content

Commit

Permalink
Add test of Display impl nested inside display attribute
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed Oct 20, 2022
1 parent 29ee95e commit 4b06a3e
Showing 1 changed file with 30 additions and 1 deletion.
31 changes: 30 additions & 1 deletion tests/test_display.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::fmt::Display;
use std::fmt::{self, Display};
use thiserror::Error;

fn assert<T: Display>(expected: &str, value: T) {
Expand Down Expand Up @@ -141,6 +141,35 @@ fn test_match() {
);
}

#[test]
fn test_nested_display() {
// Same behavior as the one in `test_match`, but without String allocations.
#[derive(Error, Debug)]
#[error("{}", {
struct Msg<'a>(&'a String, &'a Option<usize>);
impl<'a> Display for Msg<'a> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
match self.1 {
Some(n) => write!(formatter, "error occurred with {}", n),
None => write!(formatter, "there was an empty error"),
}?;
write!(formatter, ": {}", self.0)
}
}
Msg(.0, .1)
})]
struct Error(String, Option<usize>);

assert(
"error occurred with 1: ...",
Error("...".to_owned(), Some(1)),
);
assert(
"there was an empty error: ...",
Error("...".to_owned(), None),
);
}

#[test]
fn test_void() {
#[allow(clippy::empty_enum)]
Expand Down

0 comments on commit 4b06a3e

Please sign in to comment.