Debian Codegraph @

third_party/rust/error-chain/tests/tests.rs

raw
1 #![allow(dead_code)]
2
3 #[macro_use]
4 extern crate error_chain;
5
6 #[test]
7 fn smoke_test_1() {
8 error_chain! {
9 types {
10 Error, ErrorKind, ResultExt, Result;
11 }
12
13 links { }
14
15 foreign_links { }
16
17 errors { }
18 };
19 }
20
21 #[test]
22 fn smoke_test_2() {
23 error_chain! {
24 types { }
25
26 links { }
27
28 foreign_links { }
29
30 errors { }
31 };
32 }
33
34 #[test]
35 fn smoke_test_3() {
36 error_chain! {
37 links { }
38
39 foreign_links { }
40
41 errors { }
42 };
43 }
44
45 #[test]
46 fn smoke_test_4() {
47 error_chain! {
48 links { }
49
50 foreign_links { }
51
52 errors {
53 HttpStatus(e: u32) {
54 description("http request returned an unsuccessful status code")
55 display("http request returned an unsuccessful status code: {}", e)
56 }
57 }
58 };
59 }
60
61 #[test]
62 fn smoke_test_5() {
63 error_chain! {
64 types { }
65
66 links { }
67
68 foreign_links { }
69
70 errors {
71 HttpStatus(e: u32) {
72 description("http request returned an unsuccessful status code")
73 display("http request returned an unsuccessful status code: {}", e)
74 }
75 }
76 };
77 }
78
79 #[test]
80 fn smoke_test_6() {
81 error_chain! {
82 errors {
83 HttpStatus(e: u32) {
84 description("http request returned an unsuccessful status code")
85 display("http request returned an unsuccessful status code: {}", e)
86 }
87 }
88 };
89 }
90
91 #[test]
92 fn smoke_test_7() {
93 error_chain! {
94 types { }
95
96 foreign_links { }
97
98 errors {
99 HttpStatus(e: u32) {
100 description("http request returned an unsuccessful status code")
101 display("http request returned an unsuccessful status code: {}", e)
102 }
103 }
104 };
105 }
106
107 #[test]
108 fn smoke_test_8() {
109 error_chain! {
110 types { }
111
112 links { }
113 links { }
114
115 foreign_links { }
116 foreign_links { }
117
118 errors {
119 FileNotFound
120 AccessDenied
121 }
122 };
123 }
124
125 #[test]
126 fn order_test_1() {
127 error_chain! { types { } links { } foreign_links { } errors { } };
128 }
129
130 #[test]
131 fn order_test_2() {
132 error_chain! { links { } types { } foreign_links { } errors { } };
133 }
134
135 #[test]
136 fn order_test_3() {
137 error_chain! { foreign_links { } links { } errors { } types { } };
138 }
139
140 #[test]
141 fn order_test_4() {
142 error_chain! { errors { } types { } foreign_links { } };
143 }
144
145 #[test]
146 fn order_test_5() {
147 error_chain! { foreign_links { } types { } };
148 }
149
150 #[test]
151 fn order_test_6() {
152 error_chain! {
153 links { }
154
155 errors {
156 HttpStatus(e: u32) {
157 description("http request returned an unsuccessful status code")
158 display("http request returned an unsuccessful status code: {}", e)
159 }
160 }
161
162
163 foreign_links { }
164 };
165 }
166
167 #[test]
168 fn order_test_7() {
169 error_chain! {
170 links { }
171
172 foreign_links { }
173
174 types {
175 Error, ErrorKind, ResultExt, Result;
176 }
177 };
178 }
179
180 #[test]
181 fn order_test_8() {
182 error_chain! {
183 links { }
184
185 foreign_links { }
186 foreign_links { }
187
188 types {
189 Error, ErrorKind, ResultExt, Result;
190 }
191 };
192 }
193
194 #[test]
195 fn empty() {
196 error_chain! {};
197 }
198
199 #[test]
200 #[cfg(feature = "backtrace")]
201 fn has_backtrace_depending_on_env() {
202 use std::path::PathBuf;
203 use std::process::Command;
204
205 let cmd_folder = if cfg!(build = "debug") {
206 "debug"
207 } else if cfg!(build = "release") {
208 "release"
209 } else {
210 panic!("Unknown build config");
211 };
212
213 let cmd_path = if cfg!(windows) {
214 PathBuf::from(format!(
215 "./target/{}/examples/has_backtrace.exe",
216 cmd_folder
217 ))
218 } else {
219 PathBuf::from(format!("./target/{}/examples/has_backtrace", cmd_folder))
220 };
221 let mut cmd = Command::new(cmd_path);
222
223 // missing RUST_BACKTRACE and RUST_BACKTRACE=0
224 cmd.env_remove("RUST_BACKTRACE");
225 assert_eq!(cmd.status().unwrap().code().unwrap(), 0);
226
227 cmd.env("RUST_BACKTRACE", "0");
228 assert_eq!(cmd.status().unwrap().code().unwrap(), 0);
229
230 // RUST_BACKTRACE set to anything but 0
231 cmd.env("RUST_BACKTRACE", "yes");
232 assert_eq!(cmd.status().unwrap().code().unwrap(), 1);
233
234 cmd.env("RUST_BACKTRACE", "1");
235 assert_eq!(cmd.status().unwrap().code().unwrap(), 1);
236 }
237
238 #[test]
239 fn chain_err() {
240 use std::fmt;
241
242 error_chain! {
243 foreign_links {
244 Fmt(fmt::Error);
245 }
246 errors {
247 Test
248 }
249 }
250
251 let _: Result<()> = Err(fmt::Error).chain_err(|| "");
252 let _: Result<()> = Err(Error::from_kind(ErrorKind::Test)).chain_err(|| "");
253 }
254
255 /// Verify that an error chain is extended one by `Error::chain_err`, with
256 /// the new error added to the end.
257 #[test]
258 fn error_chain_err() {
259 error_chain! {
260 errors {
261 Test
262 }
263 }
264
265 let base = Error::from(ErrorKind::Test);
266 let ext = base.chain_err(|| "Test passes");
267
268 if let Error(ErrorKind::Msg(_), _) = ext {
269 // pass
270 } else {
271 panic!("The error should be wrapped. {:?}", ext);
272 }
273 }
274
275 #[test]
276 fn links() {
277 mod test {
278 error_chain! {}
279 }
280
281 error_chain! {
282 links {
283 Test(test::Error, test::ErrorKind);
284 }
285 }
286 }
287
288 #[cfg(test)]
289 mod foreign_link_test {
290
291 use std::fmt;
292
293 // Note: foreign errors must be `pub` because they appear in the
294 // signature of the public foreign_link_error_path
295 #[derive(Debug)]
296 pub struct ForeignError {
297 cause: ForeignErrorCause,
298 }
299
300 impl ::std::error::Error for ForeignError {
301 fn description(&self) -> &'static str {
302 "Foreign error description"
303 }
304
305 #[cfg(not(has_error_source))]
306 fn cause(&self) -> Option<&::std::error::Error> {
307 Some(&self.cause)
308 }
309
310 #[cfg(has_error_source)]
311 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
312 Some(&self.cause)
313 }
314 }
315
316 impl fmt::Display for ForeignError {
317 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
318 write!(formatter, "Foreign error display")
319 }
320 }
321
322 #[derive(Debug)]
323 pub struct ForeignErrorCause {}
324
325 impl ::std::error::Error for ForeignErrorCause {
326 fn description(&self) -> &'static str {
327 "Foreign error cause description"
328 }
329
330 #[cfg(not(has_error_source))]
331 fn cause(&self) -> Option<&::std::error::Error> {
332 None
333 }
334
335 #[cfg(has_error_source)]
336 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
337 None
338 }
339 }
340
341 impl fmt::Display for ForeignErrorCause {
342 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
343 write!(formatter, "Foreign error cause display")
344 }
345 }
346
347 error_chain! {
348 types{
349 Error, ErrorKind, ResultExt, Result;
350 }
351 links {}
352 foreign_links {
353 Foreign(ForeignError);
354 Io(::std::io::Error);
355 }
356 errors {}
357 }
358
359 #[test]
360 fn display_underlying_error() {
361 let chained_error = try_foreign_error().err().unwrap();
362 assert_eq!(
363 format!(
364 "{}",
365 ForeignError {
366 cause: ForeignErrorCause {}
367 }
368 ),
369 format!("{}", chained_error)
370 );
371 }
372
373 #[test]
374 #[cfg(not(has_error_source))]
375 fn finds_cause() {
376 let chained_error = try_foreign_error().err().unwrap();
377 assert_eq!(
378 format!("{}", ForeignErrorCause {}),
379 format!("{}", ::std::error::Error::cause(&chained_error).unwrap())
380 );
381 }
382
383 #[test]
384 #[cfg(has_error_source)]
385 fn finds_source() {
386 let chained_error = try_foreign_error().err().unwrap();
387 assert_eq!(
388 format!("{}", ForeignErrorCause {}),
389 format!("{}", ::std::error::Error::source(&chained_error).unwrap())
390 );
391 }
392
393 #[test]
394 #[allow(unknown_lints, bare_trait_objects)]
395 fn iterates() {
396 let chained_error = try_foreign_error().err().unwrap();
397 let mut error_iter = chained_error.iter();
398 assert!(!format!("{:?}", error_iter).is_empty());
399 assert_eq!(
400 format!(
401 "{}",
402 ForeignError {
403 cause: ForeignErrorCause {}
404 }
405 ),
406 format!("{}", error_iter.next().unwrap())
407 );
408 assert_eq!(
409 format!("{}", ForeignErrorCause {}),
410 format!("{}", error_iter.next().unwrap())
411 );
412 assert_eq!(
413 format!("{:?}", None as Option<&::std::error::Error>),
414 format!("{:?}", error_iter.next())
415 );
416 }
417
418 fn try_foreign_error() -> Result<()> {
419 Err(ForeignError {
420 cause: ForeignErrorCause {},
421 })?;
422 Ok(())
423 }
424 }
425
426 #[cfg(test)]
427 mod attributes_test {
428 #[allow(unused_imports)]
429 use std::io;
430
431 #[cfg(not(test))]
432 mod inner {
433 error_chain! {}
434 }
435
436 error_chain! {
437 types {
438 Error, ErrorKind, ResultExt, Result;
439 }
440
441 links {
442 Inner(inner::Error, inner::ErrorKind) #[cfg(not(test))];
443 }
444
445 foreign_links {
446 Io(io::Error) #[cfg(not(test))];
447 }
448
449 errors {
450 #[cfg(not(test))]
451 AnError {
452
453 }
454 }
455 }
456 }
457
458 #[test]
459 fn with_result() {
460 error_chain! {
461 types {
462 Error, ErrorKind, ResultExt, Result;
463 }
464 }
465 let _: Result<()> = Ok(());
466 }
467
468 #[test]
469 fn without_result() {
470 error_chain! {
471 types {
472 Error, ErrorKind, ResultExt;
473 }
474 }
475 let _: Result<(), ()> = Ok(());
476 }
477
478 #[test]
479 fn documentation() {
480 mod inner {
481 error_chain! {}
482 }
483
484 error_chain! {
485 links {
486 Inner(inner::Error, inner::ErrorKind) #[doc = "Doc"];
487 }
488 foreign_links {
489 Io(::std::io::Error) #[doc = "Doc"];
490 }
491 errors {
492 /// Doc
493 Variant
494 }
495 }
496 }
497
498 #[cfg(test)]
499 mod multiple_error_same_mod {
500 error_chain! {
501 types {
502 MyError, MyErrorKind, MyResultExt, MyResult;
503 }
504 }
505 error_chain! {}
506 }
507
508 #[doc(test)]
509 #[deny(dead_code)]
510 mod allow_dead_code {
511 error_chain! {}
512 }
513
514 // Make sure links actually work!
515 #[test]
516 fn rustup_regression() {
517 error_chain! {
518 links {
519 Download(error_chain::mock::Error, error_chain::mock::ErrorKind);
520 }
521
522 foreign_links { }
523
524 errors {
525 LocatingWorkingDir {
526 description("could not locate working directory")
527 }
528 }
529 }
530 }
531
532 #[test]
533 fn error_patterns() {
534 error_chain! {
535 links { }
536
537 foreign_links { }
538
539 errors { }
540 }
541
542 // Tuples look nice when matching errors
543 match Error::from("Test") {
544 Error(ErrorKind::Msg(_), _) => {}
545 _ => {}
546 }
547 }
548
549 #[test]
550 fn result_match() {
551 error_chain! {}
552
553 fn ok() -> Result<()> {
554 Ok(())
555 }
556
557 match ok() {
558 Ok(()) => {}
559 Err(Error(ErrorKind::Msg(_), _)) => {}
560 Err(..) => {}
561 }
562 }
563
564 #[test]
565 fn error_first() {
566 error_chain! {
567 errors {
568 LocatingWorkingDir {
569 description("could not locate working directory")
570 }
571 }
572
573 links {
574 Download(error_chain::mock::Error, error_chain::mock::ErrorKind);
575 }
576
577 foreign_links { }
578 }
579 }
580
581 #[test]
582 fn bail() {
583 error_chain! {
584 errors { Foo }
585 }
586
587 fn foo() -> Result<()> {
588 bail!(ErrorKind::Foo)
589 }
590
591 fn bar() -> Result<()> {
592 bail!("bar")
593 }
594
595 fn baz() -> Result<()> {
596 bail!("{}", "baz")
597 }
598 }
599
600 #[test]
601 fn ensure() {
602 error_chain! {
603 errors { Bar }
604 }
605
606 fn foo(x: u8) -> Result<()> {
607 ensure!(x == 42, ErrorKind::Bar);
608 Ok(())
609 }
610
611 assert!(foo(42).is_ok());
612 assert!(foo(0).is_err());
613 }
614
615 /// Since the `types` declaration is a list of symbols, check if we
616 /// don't change their meaning or order.
617 #[test]
618 fn types_declarations() {
619 error_chain! {
620 types {
621 MyError, MyErrorKind, MyResultExt, MyResult;
622 }
623 }
624
625 MyError::from_kind(MyErrorKind::Msg("".into()));
626
627 let err: Result<(), ::std::io::Error> = Ok(());
628 MyResultExt::chain_err(err, || "").unwrap();
629
630 let _: MyResult<()> = Ok(());
631 }
632
633 #[test]
634 /// Calling chain_err over a `Result` containing an error to get a chained error
635 /// and constructing a MyError directly, passing it an error should be equivalent.
636 fn rewrapping() {
637 use std::env::VarError::{self, NotPresent, NotUnicode};
638
639 error_chain! {
640 foreign_links {
641 VarErr(VarError);
642 }
643
644 types {
645 MyError, MyErrorKind, MyResultExt, MyResult;
646 }
647 }
648
649 let result_a_from_func: Result<String, _> = Err(VarError::NotPresent);
650 let result_b_from_func: Result<String, _> = Err(VarError::NotPresent);
651
652 let our_error_a = result_a_from_func.map_err(|e| match e {
653 NotPresent => MyError::with_chain(e, "env var wasn't provided"),
654 NotUnicode(_) => MyError::with_chain(e, "env var was bork文字化ã"),
655 });
656
657 let our_error_b = result_b_from_func.or_else(|e| match e {
658 NotPresent => Err(e).chain_err(|| "env var wasn't provided"),
659 NotUnicode(_) => Err(e).chain_err(|| "env var was bork文字化ã"),
660 });
661
662 assert_eq!(
663 format!("{}", our_error_a.unwrap_err()),
664 format!("{}", our_error_b.unwrap_err())
665 );
666 }
667
668 #[test]
669 fn comma_in_errors_impl() {
670 error_chain! {
671 links { }
672
673 foreign_links { }
674
675 errors {
676 HttpStatus(e: u32) {
677 description("http request returned an unsuccessful status code"),
678 display("http request returned an unsuccessful status code: {}", e)
679 }
680 }
681 };
682 }
683
684 #[test]
685 fn trailing_comma_in_errors_impl() {
686 error_chain! {
687 links { }
688
689 foreign_links { }
690
691 errors {
692 HttpStatus(e: u32) {
693 description("http request returned an unsuccessful status code"),
694 display("http request returned an unsuccessful status code: {}", e),
695 }
696 }
697 };
698 }
699
700 #[test]
701 fn skipping_msg_variant() {
702 error_chain! {
703 skip_msg_variant
704
705 errors {
706 MyMsg(s: String) {
707 description(&s)
708 display("{}", s)
709 }
710 }
711 }
712
713 let x = Error::from_kind(ErrorKind::MyMsg("some string".into()));
714 // This would fail to compile if we generate a `Msg` variant
715 match *x.kind() {
716 ErrorKind::MyMsg(_) => {}
717 ErrorKind::__Nonexhaustive {} => {}
718 }
719 }