Debian Codegraph @

.cargo/vendor/thiserror/tests/test_display.rs

raw
1 #![allow(
2 clippy::elidable_lifetime_names,
3 clippy::needless_lifetimes,
4 clippy::needless_raw_string_hashes,
5 clippy::trivially_copy_pass_by_ref,
6 clippy::uninlined_format_args
7 )]
8
9 use core::fmt::{self, Display};
10 use thiserror::Error;
11
12 fn assert<T: Display>(expected: &str, value: T) {
13 assert_eq!(expected, value.to_string());
14 }
15
16 #[test]
17 fn test_braced() {
18 #[derive(Error, Debug)]
19 #[error("braced error: {msg}")]
20 struct Error {
21 msg: String,
22 }
23
24 let msg = "T".to_owned();
25 assert("braced error: T", Error { msg });
26 }
27
28 #[test]
29 fn test_braced_unused() {
30 #[derive(Error, Debug)]
31 #[error("braced error")]
32 struct Error {
33 extra: usize,
34 }
35
36 assert("braced error", Error { extra: 0 });
37 }
38
39 #[test]
40 fn test_tuple() {
41 #[derive(Error, Debug)]
42 #[error("tuple error: {0}")]
43 struct Error(usize);
44
45 assert("tuple error: 0", Error(0));
46 }
47
48 #[test]
49 fn test_unit() {
50 #[derive(Error, Debug)]
51 #[error("unit error")]
52 struct Error;
53
54 assert("unit error", Error);
55 }
56
57 #[test]
58 fn test_enum() {
59 #[derive(Error, Debug)]
60 enum Error {
61 #[error("braced error: {id}")]
62 Braced { id: usize },
63 #[error("tuple error: {0}")]
64 Tuple(usize),
65 #[error("unit error")]
66 Unit,
67 }
68
69 assert("braced error: 0", Error::Braced { id: 0 });
70 assert("tuple error: 0", Error::Tuple(0));
71 assert("unit error", Error::Unit);
72 }
73
74 #[test]
75 fn test_constants() {
76 #[derive(Error, Debug)]
77 #[error("{MSG}: {id:?} (code {CODE:?})")]
78 struct Error {
79 id: &'static str,
80 }
81
82 const MSG: &str = "failed to do";
83 const CODE: usize = 9;
84
85 assert("failed to do: \"\" (code 9)", Error { id: "" });
86 }
87
88 #[test]
89 fn test_inherit() {
90 #[derive(Error, Debug)]
91 #[error("{0}")]
92 enum Error {
93 Some(&'static str),
94 #[error("other error")]
95 Other(&'static str),
96 }
97
98 assert("some error", Error::Some("some error"));
99 assert("other error", Error::Other("..."));
100 }
101
102 #[test]
103 fn test_brace_escape() {
104 #[derive(Error, Debug)]
105 #[error("fn main() {{}}")]
106 struct Error;
107
108 assert("fn main() {}", Error);
109 }
110
111 #[test]
112 fn test_expr() {
113 #[derive(Error, Debug)]
114 #[error("1 + 1 = {}", 1 + 1)]
115 struct Error;
116 assert("1 + 1 = 2", Error);
117 }
118
119 #[test]
120 fn test_nested() {
121 #[derive(Error, Debug)]
122 #[error("!bool = {}", not(.0))]
123 struct Error(bool);
124
125 #[allow(clippy::trivially_copy_pass_by_ref)]
126 fn not(bool: &bool) -> bool {
127 !*bool
128 }
129
130 assert("!bool = false", Error(true));
131 }
132
133 #[test]
134 fn test_match() {
135 #[derive(Error, Debug)]
136 #[error("{intro}: {0}", intro = match .1 {
137 Some(n) => format!("error occurred with {}", n),
138 None => "there was an empty error".to_owned(),
139 })]
140 struct Error(String, Option<usize>);
141
142 assert(
143 "error occurred with 1: ...",
144 Error("...".to_owned(), Some(1)),
145 );
146 assert(
147 "there was an empty error: ...",
148 Error("...".to_owned(), None),
149 );
150 }
151
152 #[test]
153 fn test_nested_display() {
154 // Same behavior as the one in `test_match`, but without String allocations.
155 #[derive(Error, Debug)]
156 #[error("{}", {
157 struct Msg<'a>(&'a String, &'a Option<usize>);
158 impl<'a> Display for Msg<'a> {
159 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
160 match self.1 {
161 Some(n) => write!(formatter, "error occurred with {}", n),
162 None => write!(formatter, "there was an empty error"),
163 }?;
164 write!(formatter, ": {}", self.0)
165 }
166 }
167 Msg(.0, .1)
168 })]
169 struct Error(String, Option<usize>);
170
171 assert(
172 "error occurred with 1: ...",
173 Error("...".to_owned(), Some(1)),
174 );
175 assert(
176 "there was an empty error: ...",
177 Error("...".to_owned(), None),
178 );
179 }
180
181 #[test]
182 fn test_void() {
183 #[allow(clippy::empty_enum)]
184 #[derive(Error, Debug)]
185 #[error("...")]
186 pub enum Error {}
187
188 let _: Error;
189 }
190
191 #[test]
192 fn test_mixed() {
193 #[derive(Error, Debug)]
194 #[error("a={a} :: b={} :: c={c} :: d={d}", 1, c = 2, d = 3)]
195 struct Error {
196 a: usize,
197 d: usize,
198 }
199
200 assert("a=0 :: b=1 :: c=2 :: d=3", Error { a: 0, d: 0 });
201 }
202
203 #[test]
204 fn test_ints() {
205 #[derive(Error, Debug)]
206 enum Error {
207 #[error("error {0}")]
208 Tuple(usize, usize),
209 #[error("error {0}", '?')]
210 Struct { v: usize },
211 }
212
213 assert("error 9", Error::Tuple(9, 0));
214 assert("error ?", Error::Struct { v: 0 });
215 }
216
217 #[test]
218 fn test_trailing_comma() {
219 #[derive(Error, Debug)]
220 #[error(
221 "error {0}",
222 )]
223 #[rustfmt::skip]
224 struct Error(char);
225
226 assert("error ?", Error('?'));
227 }
228
229 #[test]
230 fn test_field() {
231 #[derive(Debug)]
232 struct Inner {
233 data: usize,
234 }
235
236 #[derive(Error, Debug)]
237 #[error("{}", .0.data)]
238 struct Error(Inner);
239
240 assert("0", Error(Inner { data: 0 }));
241 }
242
243 #[test]
244 fn test_nested_tuple_field() {
245 #[derive(Debug)]
246 struct Inner(usize);
247
248 #[derive(Error, Debug)]
249 #[error("{}", .0.0)]
250 struct Error(Inner);
251
252 assert("0", Error(Inner(0)));
253 }
254
255 #[test]
256 fn test_pointer() {
257 #[derive(Error, Debug)]
258 #[error("{field:p}")]
259 pub struct Struct {
260 field: Box<i32>,
261 }
262
263 let s = Struct {
264 field: Box::new(-1),
265 };
266 assert_eq!(s.to_string(), format!("{:p}", s.field));
267 }
268
269 #[test]
270 fn test_macro_rules_variant_from_call_site() {
271 // Regression test for https://github.com/dtolnay/thiserror/issues/86
272
273 macro_rules! decl_error {
274 ($variant:ident($value:ident)) => {
275 #[derive(Error, Debug)]
276 pub enum Error0 {
277 #[error("{0:?}")]
278 $variant($value),
279 }
280
281 #[derive(Error, Debug)]
282 #[error("{0:?}")]
283 pub enum Error1 {
284 $variant($value),
285 }
286 };
287 }
288
289 decl_error!(Repro(u8));
290
291 assert("0", Error0::Repro(0));
292 assert("0", Error1::Repro(0));
293 }
294
295 #[test]
296 fn test_macro_rules_message_from_call_site() {
297 // Regression test for https://github.com/dtolnay/thiserror/issues/398
298
299 macro_rules! decl_error {
300 ($($errors:tt)*) => {
301 #[derive(Error, Debug)]
302 pub enum Error {
303 $($errors)*
304 }
305 };
306 }
307
308 decl_error! {
309 #[error("{0}")]
310 Unnamed(u8),
311 #[error("{x}")]
312 Named { x: u8 },
313 }
314
315 assert("0", Error::Unnamed(0));
316 assert("0", Error::Named { x: 0 });
317 }
318
319 #[test]
320 fn test_raw() {
321 #[derive(Error, Debug)]
322 #[error("braced raw error: {fn}")]
323 struct Error {
324 r#fn: &'static str,
325 }
326
327 assert("braced raw error: T", Error { r#fn: "T" });
328 }
329
330 #[test]
331 fn test_raw_enum() {
332 #[derive(Error, Debug)]
333 enum Error {
334 #[error("braced raw error: {fn}")]
335 Braced { r#fn: &'static str },
336 }
337
338 assert("braced raw error: T", Error::Braced { r#fn: "T" });
339 }
340
341 #[test]
342 fn test_keyword() {
343 #[derive(Error, Debug)]
344 #[error("error: {type}", type = 1)]
345 struct Error;
346
347 assert("error: 1", Error);
348 }
349
350 #[test]
351 fn test_self() {
352 #[derive(Error, Debug)]
353 #[error("error: {self:?}")]
354 struct Error;
355
356 assert("error: Error", Error);
357 }
358
359 #[test]
360 fn test_str_special_chars() {
361 #[derive(Error, Debug)]
362 pub enum Error {
363 #[error("brace left {{")]
364 BraceLeft,
365 #[error("brace left 2 \x7B\x7B")]
366 BraceLeft2,
367 #[error("brace left 3 \u{7B}\u{7B}")]
368 BraceLeft3,
369 #[error("brace right }}")]
370 BraceRight,
371 #[error("brace right 2 \x7D\x7D")]
372 BraceRight2,
373 #[error("brace right 3 \u{7D}\u{7D}")]
374 BraceRight3,
375 #[error(
376 "new_\
377 line"
378 )]
379 NewLine,
380 #[error("escape24 \u{78}")]
381 Escape24,
382 }
383
384 assert("brace left {", Error::BraceLeft);
385 assert("brace left 2 {", Error::BraceLeft2);
386 assert("brace left 3 {", Error::BraceLeft3);
387 assert("brace right }", Error::BraceRight);
388 assert("brace right 2 }", Error::BraceRight2);
389 assert("brace right 3 }", Error::BraceRight3);
390 assert("new_line", Error::NewLine);
391 assert("escape24 x", Error::Escape24);
392 }
393
394 #[test]
395 fn test_raw_str() {
396 #[derive(Error, Debug)]
397 pub enum Error {
398 #[error(r#"raw brace left {{"#)]
399 BraceLeft,
400 #[error(r#"raw brace left 2 \x7B"#)]
401 BraceLeft2,
402 #[error(r#"raw brace right }}"#)]
403 BraceRight,
404 #[error(r#"raw brace right 2 \x7D"#)]
405 BraceRight2,
406 }
407
408 assert(r#"raw brace left {"#, Error::BraceLeft);
409 assert(r#"raw brace left 2 \x7B"#, Error::BraceLeft2);
410 assert(r#"raw brace right }"#, Error::BraceRight);
411 assert(r#"raw brace right 2 \x7D"#, Error::BraceRight2);
412 }
413
414 mod util {
415 use core::fmt::{self, Octal};
416
417 pub fn octal<T: Octal>(value: &T, formatter: &mut fmt::Formatter) -> fmt::Result {
418 write!(formatter, "0o{:o}", value)
419 }
420 }
421
422 #[test]
423 fn test_fmt_path() {
424 fn unit(formatter: &mut fmt::Formatter) -> fmt::Result {
425 formatter.write_str("unit=")
426 }
427
428 fn pair(k: &i32, v: &i32, formatter: &mut fmt::Formatter) -> fmt::Result {
429 write!(formatter, "pair={k}:{v}")
430 }
431
432 #[derive(Error, Debug)]
433 pub enum Error {
434 #[error(fmt = unit)]
435 Unit,
436 #[error(fmt = pair)]
437 Tuple(i32, i32),
438 #[error(fmt = pair)]
439 Entry { k: i32, v: i32 },
440 #[error(fmt = crate::util::octal)]
441 I16(i16),
442 #[error(fmt = crate::util::octal::<i32>)]
443 I32 { n: i32 },
444 #[error(fmt = core::fmt::Octal::fmt)]
445 I64(i64),
446 #[error("...{0}")]
447 Other(bool),
448 }
449
450 assert("unit=", Error::Unit);
451 assert("pair=10:0", Error::Tuple(10, 0));
452 assert("pair=10:0", Error::Entry { k: 10, v: 0 });
453 assert("0o777", Error::I16(0o777));
454 assert("0o777", Error::I32 { n: 0o777 });
455 assert("777", Error::I64(0o777));
456 assert("...false", Error::Other(false));
457 }
458
459 #[test]
460 fn test_fmt_path_inherited() {
461 #[derive(Error, Debug)]
462 #[error(fmt = crate::util::octal)]
463 pub enum Error {
464 I16(i16),
465 I32 {
466 n: i32,
467 },
468 #[error(fmt = core::fmt::Octal::fmt)]
469 I64(i64),
470 #[error("...{0}")]
471 Other(bool),
472 }
473
474 assert("0o777", Error::I16(0o777));
475 assert("0o777", Error::I32 { n: 0o777 });
476 assert("777", Error::I64(0o777));
477 assert("...false", Error::Other(false));
478 }