/tests/cli.rs

https://github.com/lunaryorn/mdcat · Rust · 92 lines · 72 code · 12 blank · 8 comment · 2 complexity · 9f790c7b19861ac3b40aa6d78099fe47 MD5 · raw file

  1. // Copyright 2020 Sebastian Wiesner <sebastian@swsnr.de>
  2. // This Source Code Form is subject to the terms of the Mozilla Public
  3. // License, v. 2.0. If a copy of the MPL was not distributed with this
  4. // file, You can obtain one at http://mozilla.org/MPL/2.0/.
  5. //! Test the command line interface of mdcat
  6. #![deny(warnings, missing_docs, clippy::all)]
  7. mod cli {
  8. use std::ffi::OsStr;
  9. use std::io::Read;
  10. use std::process::{Command, Output, Stdio};
  11. fn cargo_mdcat() -> Command {
  12. Command::new(env!("CARGO_BIN_EXE_mdcat"))
  13. }
  14. fn run_cargo_mdcat<I, S>(args: I) -> Output
  15. where
  16. I: IntoIterator<Item = S>,
  17. S: AsRef<OsStr>,
  18. {
  19. cargo_mdcat().args(args).output().unwrap()
  20. }
  21. #[test]
  22. fn show_help() {
  23. let output = run_cargo_mdcat(&["--help"]);
  24. let stdout = std::str::from_utf8(&output.stdout).unwrap();
  25. assert!(
  26. output.status.success(),
  27. "non-zero exit code: {:?}",
  28. output.status,
  29. );
  30. assert!(output.stderr.is_empty());
  31. assert!(stdout.contains("mdcat uses the standardized CommonMark dialect"));
  32. }
  33. #[test]
  34. fn file_list_fail_late() {
  35. let output = run_cargo_mdcat(&["does-not-exist", "sample/common-mark.md"]);
  36. let stderr = std::str::from_utf8(&output.stderr).unwrap();
  37. let stdout = std::str::from_utf8(&output.stdout).unwrap();
  38. assert!(!output.status.success());
  39. // We failed to read the first file but still printed the second.
  40. assert!(
  41. stderr.contains("Error: does-not-exist:") && stderr.contains("(os error 2)"),
  42. "Stderr: {}",
  43. stderr
  44. );
  45. assert!(stdout.contains("CommonMark sample document"));
  46. }
  47. #[test]
  48. fn file_list_fail_fast() {
  49. let output = run_cargo_mdcat(&["--fail", "does-not-exist", "sample/common-mark.md"]);
  50. let stderr = std::str::from_utf8(&output.stderr).unwrap();
  51. assert!(!output.status.success());
  52. // We failed to read the first file and exited early, so nothing was printed at all
  53. assert!(
  54. stderr.contains("Error: does-not-exist:") && stderr.contains("(os error 2)"),
  55. "Stderr: {}",
  56. stderr
  57. );
  58. assert!(output.stdout.is_empty());
  59. }
  60. #[test]
  61. fn ignore_broken_pipe() {
  62. let mut child = cargo_mdcat()
  63. .arg("sample/common-mark.md")
  64. .stdout(Stdio::piped())
  65. .stderr(Stdio::piped())
  66. .spawn()
  67. .unwrap();
  68. let mut stderr = Vec::new();
  69. // use std::os::unix::io::AsRawFd;
  70. drop(child.stdout.take());
  71. child
  72. .stderr
  73. .as_mut()
  74. .unwrap()
  75. .read_to_end(&mut stderr)
  76. .unwrap();
  77. use pretty_assertions::assert_eq;
  78. assert_eq!(String::from_utf8_lossy(&stderr), "")
  79. }
  80. }