assert_cli-0.6.3/.editorconfig010066600017500001750000000006371316162235600145650ustar0000000000000000# EditorConfig helps developers define and maintain consistent # coding styles between different editors and IDEs # editorconfig.org root = true [*] end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true indent_style = space indent_size = 4 [*.rs] indent_style = space indent_size = 4 [*.toml] indent_style = space indent_size = 4 [*.md] trim_trailing_whitespace = false assert_cli-0.6.3/.github/ISSUE_TEMPLATE.md010066600017500001750000000004561323510424500161460ustar0000000000000000 - `assert_cli` version: - Rust version: - OS and version: assert_cli-0.6.3/.github/PULL_REQUEST_TEMPLATE.md010066600017500001750000000010471323510424500172370ustar0000000000000000 - [ ] I have created tests for any new feature, or added regression tests for bugfixes. - [ ] `cargo test` succeeds - [ ] Clippy is happy: `cargo +nightly clippy` succeeds - [ ] Rustfmt is happy: `cargo +nightly fmt` succeeds assert_cli-0.6.3/.gitignore010066600017500001750000000003661316162235600140770ustar0000000000000000# Project specific stuff target Cargo.lock # rustfmt *.bk # Editor Stuff *.sublime-project *.sublime-workspace .*.swp *.bak *~ .vscode # System stuff .DS_Store .Spotlight-V100 .Trashes Thumbs.db ehthumbs.db Desktop.ini $RECYCLE.BIN/ .directory assert_cli-0.6.3/.travis.yml010066600017500001750000000031641325431132100142050ustar0000000000000000sudo: false language: rust cache: cargo rust: - beta - stable - nightly matrix: include: - rust: nightly-2017-10-09 env: CLIPPY_VERS="0.0.165" before_script: | [[ "$(cargo +nightly-2017-10-09 clippy --version)" != "$CLIPPY_VERS" ]] && \ cargo +nightly-2017-10-09 install clippy --vers "$CLIPPY_VERS" --force || true script: | cargo +nightly-2017-10-09 clippy -- -D warnings - rust: 1.24.0 # `stable`: Locking down for consistent behavior env: RUSTFMT install: - rustup component add rustfmt-preview script: - cargo fmt -- --write-mode=diff before_script: - | pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH script: - | travis-cargo build && travis-cargo clean && travis-cargo test && travis-cargo bench notifications: email: on_success: never branches: only: - master - staging - trying env: global: - TRAVIS_CARGO_NIGHTLY_FEATURE="" - secure: OUHDuY7h82pYkis1oJW/dO029Rp/HLGT7od5VQJ1eki0M+Oawj7L0tjQPGLKLjj6hA1Sh8XeeelQgrlwVQfkrvwgYLRfmEdbP8z2PclmbxvXmRFysM5R9dN15HYx9AlUsDiHF9otmkNzJPBghlLvvKbzjp7Mlr5cdBaFZ9psafJLOgIWTIpiuHvYhmKhaXG6bIpLw6pi9NWdUYcd5s/gy1n1v5a4oPH/JB9V3Zc8+tv/EPvRynzSRK1jghD7KtppQoRRt92OCQGZ2BYLoTVpkt/bPS50D558xbVoDPyNNgcPM86eSSNbgp8llASJMFVNWWBZYLmbQ5x/219G907YbKWDLbcwMJL0H/JFbtErLarDU5XiEFBELs0Zx2t0S96xOM+ZWxZvWBk3UuKTBaXIKc921JEU+uHHUsPp3zasiMZWN3Rv2ia68HZGvYtwAPG5PWJTeh7BAo6dLGNDISVE/uHhf64E+ZvH3ToEmadx/yimedE7IOBh7kvPTnr1X5RFWNEJYOVSWJ531LoE3WHO9/UKPRLx01fGHzJKXMyWcp2fQjwCsu9zwThk3N4kYQJfi5YNmJw1EiOERiQ0nRckaUC5sA5KE+ZJmEa4ztfe7RMTVceCNagVdsqH8IHWgM+ROKNNKYDjqKbGSiE0RVwUdITUFLeQDWzQYfzsWRQpFV0= assert_cli-0.6.3/CONTRIBUTING.md010066600017500001750000000023671324667044700143530ustar0000000000000000Thanks for wanting to contribute! Feel free to create issues or make pull requests, we'll try to quickly review them. If you need to reach out to us, find a relevant [issue][Issues] or open a new one. # Pull Requests ## Project Ideas If you're looking for things to do check out the [open issues][Issues]. Or take a grep through [all TODO comments][TODO] in the code and feel free to help us out there! ## Best Practices We appreciate your help as-is. We'd love to help you through the process for contributing. We have some suggestions to help make things go more smoothly. Before spending too much time on a PR, consider opening an issue so we can make sure we're aligned on how the problem should be solved. # Releasing When we're ready to release, a project owner should do the following - Determine what the next version is, according to semver - Update the version in `Cargo.toml` and in the `README.md` and commit - Run `git tag v..` - Push all of this to `master` - Create a github release - Identify what fixes, features, and breaking changes are in the release. - Run `cargo publish` (run `cargo login` first if needed) [Issues]: https://github.com/assert-rs/assert_cli/issues [TODO]: https://github.com/assert-rs/assert_cli/search?q=TODO assert_cli-0.6.3/Cargo.toml.orig010066600017500001750000000013721332424255000147670ustar0000000000000000[package] name = "assert_cli" version = "0.6.3" description = "Test CLI Applications." authors = ["Pascal Hertleif ", "Ed Page "] license = "MIT OR Apache-2.0" repository = "https://github.com/assert-rs/assert_cli.git" homepage = "https://github.com/assert-rs/assert_cli" documentation = "http://docs.rs/assert_cli/" readme = "README.md" categories = ["development-tools::testing"] keywords = ["cli", "testing", "assert"] [[bin]] name = "assert_fixture" [dependencies] colored = "1.5" difference = "2.0" failure = "0.1" failure_derive = "0.1" serde_json = "1.0" environment = "0.1" [dev-dependencies] docmatic = "0.1" [badges] travis-ci = { repository = "assert-rs/assert_cli" } maintenance = { status = "deprecated" } assert_cli-0.6.3/Cargo.toml0000644000000026110000000000000112270ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g. crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "assert_cli" version = "0.6.3" authors = ["Pascal Hertleif ", "Ed Page "] description = "Test CLI Applications." homepage = "https://github.com/assert-rs/assert_cli" documentation = "http://docs.rs/assert_cli/" readme = "README.md" keywords = ["cli", "testing", "assert"] categories = ["development-tools::testing"] license = "MIT OR Apache-2.0" repository = "https://github.com/assert-rs/assert_cli.git" [[bin]] name = "assert_fixture" [dependencies.colored] version = "1.5" [dependencies.difference] version = "2.0" [dependencies.environment] version = "0.1" [dependencies.failure] version = "0.1" [dependencies.failure_derive] version = "0.1" [dependencies.serde_json] version = "1.0" [dev-dependencies.docmatic] version = "0.1" [badges.maintenance] status = "deprecated" [badges.travis-ci] repository = "assert-rs/assert_cli" assert_cli-0.6.3/LICENSE-APACHE010066600017500001750000000261361316162235600140360ustar0000000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. assert_cli-0.6.3/LICENSE-MIT010066600017500001750000000020551316162235600135400ustar0000000000000000Copyright (c) 2015 The assert_cli Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. assert_cli-0.6.3/README.md010066600017500001750000000025441332424246300133640ustar0000000000000000# Assert CLI > **Test CLI Applications** - This crate checks the output of a child process is as expected. [![Build Status](https://travis-ci.org/assert-rs/assert_cli.svg)][Travis] [![Documentation](https://img.shields.io/badge/docs-master-blue.svg)][Documentation] ![License](https://img.shields.io/crates/l/assert_cli.svg) [![crates.io](https://img.shields.io/crates/v/assert_cli.svg)][Crates.io] Note: `assert_cli`, in its current form, is deprecated. The spiritual successor to `assert_cli` is [`assert_cmd`][assert_cmd]. Stayed tuned to [Issue #41][future] for our reinventing `assert_cli` on top of `assert_cmd`. ## License Licensed under either of * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. [Travis]: https://travis-ci.org/assert-rs/assert_cli [Crates.io]: https://crates.io/crates/assert_cli [Documentation]: https://docs.rs/assert_cli [assert_cmd]: https://crates.io/crates/assert_cmd [future]: https://github.com/assert-rs/assert_cli/issues/41 assert_cli-0.6.3/rustfmt.toml010066600017500001750000000000561316776637500145240ustar0000000000000000format_strings = false reorder_imports = true assert_cli-0.6.3/src/assert.rs010066600017500001750000000500301330055713400145320ustar0000000000000000use std::default; use std::ffi::{OsStr, OsString}; use std::io::Write; use std::path::PathBuf; use std::process::{Command, Stdio}; use std::vec::Vec; use environment::Environment; use failure; use failure::Fail; use errors::*; use output::{Content, Output, OutputKind, OutputPredicate}; /// Assertions for a specific command. #[derive(Debug)] #[must_use] pub struct Assert { cmd: Vec, env: Environment, current_dir: Option, expect_success: Option, expect_exit_code: Option, expect_output: Vec, stdin_contents: Option>, } impl default::Default for Assert { /// Construct an assert using `cargo run --` as command. /// /// Defaults to asserting _successful_ execution. fn default() -> Self { Assert { cmd: vec![ "cargo", "run", #[cfg(not(debug_assertions))] "--release", "--quiet", "--", ].into_iter() .map(OsString::from) .collect(), env: Environment::inherit(), current_dir: None, expect_success: Some(true), expect_exit_code: None, expect_output: vec![], stdin_contents: None, } } } impl Assert { /// Run the crate's main binary. /// /// Defaults to asserting _successful_ execution. pub fn main_binary() -> Self { Assert::default() } /// Run a specific binary of the current crate. /// /// Defaults to asserting _successful_ execution. pub fn cargo_binary>(name: S) -> Self { Assert { cmd: vec![ OsStr::new("cargo"), OsStr::new("run"), #[cfg(not(debug_assertions))] OsStr::new("--release"), OsStr::new("--quiet"), OsStr::new("--bin"), name.as_ref(), OsStr::new("--"), ].into_iter() .map(OsString::from) .collect(), ..Self::default() } } /// Run a specific example of the current crate. /// /// Defaults to asserting _successful_ execution. pub fn example>(name: S) -> Self { Assert { cmd: vec![ OsStr::new("cargo"), OsStr::new("run"), #[cfg(not(debug_assertions))] OsStr::new("--release"), OsStr::new("--quiet"), OsStr::new("--example"), name.as_ref(), OsStr::new("--"), ].into_iter() .map(OsString::from) .collect(), ..Self::default() } } /// Run a custom command. /// /// Defaults to asserting _successful_ execution. /// /// # Examples /// /// ```rust /// extern crate assert_cli; /// /// assert_cli::Assert::command(&["echo", "1337"]) /// .unwrap(); /// ``` pub fn command>(cmd: &[S]) -> Self { Assert { cmd: cmd.into_iter().map(OsString::from).collect(), ..Self::default() } } /// Add arguments to the command. /// /// # Examples /// /// ```rust /// extern crate assert_cli; /// /// assert_cli::Assert::command(&["echo"]) /// .with_args(&["42"]) /// .stdout().contains("42") /// .unwrap(); /// /// ``` pub fn with_args>(mut self, args: &[S]) -> Self { self.cmd.extend(args.into_iter().map(OsString::from)); self } /// Add stdin to the command. /// /// # Examples /// /// ```rust /// extern crate assert_cli; /// /// assert_cli::Assert::command(&["cat"]) /// .stdin("42") /// .stdout().contains("42") /// .unwrap(); /// ``` pub fn stdin>>(mut self, contents: S) -> Self { self.stdin_contents = Some(contents.into()); self } /// Sets the working directory for the command. /// /// # Examples /// /// ```rust /// extern crate assert_cli; /// /// assert_cli::Assert::command(&["wc", "lib.rs"]) /// .current_dir(std::path::Path::new("src")) /// .stdout().contains("lib.rs") /// .execute() /// .unwrap(); /// ``` pub fn current_dir>(mut self, dir: P) -> Self { self.current_dir = Some(dir.into()); self } /// Sets environments variables for the command. /// /// # Examples /// /// ```rust /// extern crate assert_cli; /// /// assert_cli::Assert::command(&["printenv"]) /// .with_env(&[("TEST_ENV", "OK")]) /// .stdout().contains("TEST_ENV=OK") /// .execute() /// .unwrap(); /// /// let env = assert_cli::Environment::empty() /// .insert("FOO", "BAR"); /// /// assert_cli::Assert::command(&["printenv"]) /// .with_env(&env) /// .stdout().is("FOO=BAR") /// .execute() /// .unwrap(); /// /// ::std::env::set_var("BAZ", "BAR"); /// /// assert_cli::Assert::command(&["printenv"]) /// .stdout().contains("BAZ=BAR") /// .execute() /// .unwrap(); /// ``` pub fn with_env>(mut self, env: E) -> Self { self.env = env.into(); self } /// Small helper to make chains more readable. /// /// # Examples /// /// ```rust /// extern crate assert_cli; /// /// assert_cli::Assert::command(&["cat", "non-existing-file"]) /// .fails() /// .and() /// .stderr().contains("non-existing-file") /// .unwrap(); /// ``` pub fn and(self) -> Self { self } /// Expect the command to be executed successfully. /// /// # Examples /// /// ```rust /// extern crate assert_cli; /// /// assert_cli::Assert::command(&["echo", "42"]) /// .succeeds() /// .unwrap(); /// ``` pub fn succeeds(mut self) -> Self { self.expect_exit_code = None; self.expect_success = Some(true); self } /// Expect the command to fail. /// /// Note: This does not include shell failures like `command not found`. I.e. the /// command must _run_ and fail for this assertion to pass. /// /// # Examples /// /// ```rust /// extern crate assert_cli; /// /// assert_cli::Assert::command(&["cat", "non-existing-file"]) /// .fails() /// .and() /// .stderr().contains("non-existing-file") /// .unwrap(); /// ``` pub fn fails(mut self) -> Self { self.expect_success = Some(false); self } /// Expect the command to fail and return a specific error code. /// /// # Examples /// /// ```rust /// extern crate assert_cli; /// /// assert_cli::Assert::command(&["cat", "non-existing-file"]) /// .fails_with(1) /// .and() /// .stderr().is("cat: non-existing-file: No such file or directory") /// .unwrap(); /// ``` pub fn fails_with(mut self, expect_exit_code: i32) -> Self { self.expect_success = Some(false); self.expect_exit_code = Some(expect_exit_code); self } /// Do not care whether the command exits successfully or if it fails. /// /// This function removes any assertions that were already set, including /// any expected exit code that was set with [`fails_with`]. /// /// # Examples /// /// ```rust /// extern crate assert_cli; /// /// assert_cli::Assert::command(&["cat", "non-existing-file"]) /// .ignore_status() /// .and() /// .stderr().is("cat: non-existing-file: No such file or directory") /// .unwrap(); /// ``` /// /// [`fails_with`]: #method.fails_with pub fn ignore_status(mut self) -> Self { self.expect_exit_code = None; self.expect_success = None; self } /// Create an assertion for stdout's contents /// /// # Examples /// /// ```rust /// extern crate assert_cli; /// /// assert_cli::Assert::command(&["echo", "42"]) /// .stdout().contains("42") /// .unwrap(); /// ``` pub fn stdout(self) -> OutputAssertionBuilder { OutputAssertionBuilder { assertion: self, kind: OutputKind::StdOut, } } /// Create an assertion for stdout's contents /// /// # Examples /// /// ```rust /// extern crate assert_cli; /// /// assert_cli::Assert::command(&["cat", "non-existing-file"]) /// .fails_with(1) /// .and() /// .stderr().is("cat: non-existing-file: No such file or directory") /// .unwrap(); /// ``` pub fn stderr(self) -> OutputAssertionBuilder { OutputAssertionBuilder { assertion: self, kind: OutputKind::StdErr, } } /// Execute the command and check the assertions. /// /// # Examples /// /// ```rust /// extern crate assert_cli; /// /// let test = assert_cli::Assert::command(&["echo", "42"]) /// .stdout().contains("42") /// .execute(); /// assert!(test.is_ok()); /// ``` pub fn execute(self) -> Result<(), AssertionError> { let bin = &self.cmd[0]; let args: Vec<_> = self.cmd.iter().skip(1).collect(); let mut command = Command::new(bin); let command = command .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .env_clear() .envs(self.env.clone().compile()) .args(&args); let command = match self.current_dir { Some(ref dir) => command.current_dir(dir), None => command, }; let mut spawned = command .spawn() .chain_with(|| AssertionError::new(self.cmd.clone()))?; if let Some(ref contents) = self.stdin_contents { spawned .stdin .as_mut() .expect("Couldn't get mut ref to command stdin") .write_all(contents) .chain_with(|| AssertionError::new(self.cmd.clone()))?; } let output = spawned .wait_with_output() .chain_with(|| AssertionError::new(self.cmd.clone()))?; if let Some(expect_success) = self.expect_success { let actual_success = output.status.success(); if expect_success != actual_success { return Err( AssertionError::new(self.cmd.clone()).chain(StatusError::new( actual_success, output.stdout.clone(), output.stderr.clone(), )), )?; } } if self.expect_exit_code.is_some() && self.expect_exit_code != output.status.code() { return Err( AssertionError::new(self.cmd.clone()).chain(ExitCodeError::new( self.expect_exit_code, output.status.code(), output.stdout.clone(), output.stderr.clone(), )), ); } self.expect_output .iter() .map(|a| { a.verify(&output) .chain_with(|| AssertionError::new(self.cmd.clone())) }) .collect::, AssertionError>>()?; Ok(()) } /// Execute the command, check the assertions, and panic when they fail. /// /// # Examples /// /// ```rust,should_panic="Assert CLI failure" /// extern crate assert_cli; /// /// assert_cli::Assert::command(&["echo", "42"]) /// .fails() /// .unwrap(); // panics /// ``` pub fn unwrap(self) { if let Err(err) = self.execute() { panic!(Self::format_causes(err.causes())); } } fn format_causes(mut causes: failure::Causes) -> String { let mut result = causes.next().expect("an error should exist").to_string(); for cause in causes { result.push_str(&format!("\nwith: {}", cause)); } result } } /// Assertions for command output. #[derive(Debug)] #[must_use] pub struct OutputAssertionBuilder { assertion: Assert, kind: OutputKind, } impl OutputAssertionBuilder { /// Expect the command's output to **contain** `output`. /// /// # Examples /// /// ```rust /// extern crate assert_cli; /// /// assert_cli::Assert::command(&["echo", "42"]) /// .stdout().contains("42") /// .unwrap(); /// ``` pub fn contains>(mut self, output: O) -> Assert { let pred = OutputPredicate::new(self.kind, Output::contains(output)); self.assertion.expect_output.push(pred); self.assertion } /// Expect the command to output **exactly** this `output`. /// /// # Examples /// /// ```rust /// extern crate assert_cli; /// /// assert_cli::Assert::command(&["echo", "42"]) /// .stdout().is("42") /// .unwrap(); /// ``` pub fn is>(mut self, output: O) -> Assert { let pred = OutputPredicate::new(self.kind, Output::is(output)); self.assertion.expect_output.push(pred); self.assertion } /// Expect the command's output to not **contain** `output`. /// /// # Examples /// /// ```rust /// extern crate assert_cli; /// /// assert_cli::Assert::command(&["echo", "42"]) /// .stdout().doesnt_contain("73") /// .unwrap(); /// ``` pub fn doesnt_contain>(mut self, output: O) -> Assert { let pred = OutputPredicate::new(self.kind, Output::doesnt_contain(output)); self.assertion.expect_output.push(pred); self.assertion } /// Expect the command to output to not be **exactly** this `output`. /// /// # Examples /// /// ```rust /// extern crate assert_cli; /// /// assert_cli::Assert::command(&["echo", "42"]) /// .stdout().isnt("73") /// .unwrap(); /// ``` pub fn isnt>(mut self, output: O) -> Assert { let pred = OutputPredicate::new(self.kind, Output::isnt(output)); self.assertion.expect_output.push(pred); self.assertion } /// Expect the command output to satisfy the given predicate. /// /// # Examples /// /// ```rust /// extern crate assert_cli; /// /// assert_cli::Assert::command(&["echo", "-n", "42"]) /// .stdout().satisfies(|x| x.len() == 2, "bad length") /// .unwrap(); /// ``` pub fn satisfies(mut self, pred: F, msg: M) -> Assert where F: 'static + Fn(&str) -> bool, M: Into, { let pred = OutputPredicate::new(self.kind, Output::satisfies(pred, msg)); self.assertion.expect_output.push(pred); self.assertion } } #[cfg(test)] mod test { use super::*; use std::ffi::OsString; fn command() -> Assert { Assert::command(&["printenv"]) } #[test] fn main_binary_default_uses_active_profile() { let assert = Assert::main_binary(); let expected = if cfg!(debug_assertions) { OsString::from("cargo run --quiet -- ") } else { OsString::from("cargo run --release --quiet -- ") }; assert_eq!( expected, assert .cmd .into_iter() .fold(OsString::from(""), |mut cmd, token| { cmd.push(token); cmd.push(" "); cmd }) ); } #[test] fn cargo_binary_default_uses_active_profile() { let assert = Assert::cargo_binary("hello"); let expected = if cfg!(debug_assertions) { OsString::from("cargo run --quiet --bin hello -- ") } else { OsString::from("cargo run --release --quiet --bin hello -- ") }; assert_eq!( expected, assert .cmd .into_iter() .fold(OsString::from(""), |mut cmd, token| { cmd.push(token); cmd.push(" "); cmd }) ); } #[test] fn take_ownership() { let x = Environment::inherit(); command() .with_env(x.clone()) .with_env(&x) .with_env(x) .unwrap(); } #[test] fn in_place_mod() { let y = Environment::empty(); let y = y.insert("key", "value"); assert_eq!( y.compile(), vec![(OsString::from("key"), OsString::from("value"))] ); } #[test] fn in_place_mod2() { let x = Environment::inherit(); command() .with_env(&x.insert("key", "value").insert("key", "vv")) .stdout() .contains("key=vv") .execute() .unwrap(); // Granted, `insert` moved `x`, so we can no longer reference it, even // though only a reference was passed to `with_env` } #[test] fn in_place_mod3() { // In-place modification while allowing later accesses to the `Environment` let y = Environment::empty(); assert_eq!( y.clone().insert("key", "value").compile(), vec![(OsString::from("key"), OsString::from("value"))] ); command() .with_env(y) .stdout() .doesnt_contain("key=value") .execute() .unwrap(); } #[test] fn empty_env() { // In-place modification while allowing later accesses to the `Environment` let y = Environment::empty(); assert!(command().with_env(y).stdout().is("").execute().is_ok()); } #[test] fn take_vec() { let v = vec![("bar".to_string(), "baz".to_string())]; command() .with_env(&vec![("bar", "baz")]) .stdout() .contains("bar=baz") .execute() .unwrap(); command() .with_env(&v) .stdout() .contains("bar=baz") .execute() .unwrap(); command() .with_env(&vec![("bar", "baz")]) .stdout() .isnt("") .execute() .unwrap(); } #[test] fn take_slice_of_strs() { command() .with_env(&[("bar", "BAZ")]) .stdout() .contains("bar=BAZ") .execute() .unwrap(); command() .with_env(&[("bar", "BAZ")][..]) .stdout() .contains("bar=BAZ") .execute() .unwrap(); command() .with_env([("bar", "BAZ")].as_ref()) .stdout() .contains("bar=BAZ") .execute() .unwrap(); } #[test] fn take_slice_of_strings() { // same deal as above command() .with_env(&[("bar".to_string(), "BAZ".to_string())]) .stdout() .contains("bar=BAZ") .execute() .unwrap(); command() .with_env(&[("bar".to_string(), "BAZ".to_string())][..]) .stdout() .contains("bar=BAZ") .execute() .unwrap(); } #[test] fn take_slice() { command() .with_env(&[("hey", "ho")]) .stdout() .contains("hey=ho") .execute() .unwrap(); command() .with_env(&[("hey", "ho".to_string())]) .stdout() .contains("hey=ho") .execute() .unwrap(); } #[test] fn take_string_i32() { command() .with_env(&[("bar", 3 as i32)]) .stdout() .contains("bar=3") .execute() .unwrap(); } } assert_cli-0.6.3/src/bin/assert_fixture.rs010066600017500001750000000013671327437247300170740ustar0000000000000000extern crate failure; use std::env; use std::io; use std::io::Write; use std::process; use failure::ResultExt; fn run() -> Result<(), failure::Error> { if let Ok(text) = env::var("stdout") { println!("{}", text); } if let Ok(text) = env::var("stderr") { eprintln!("{}", text); } let code = env::var("exit") .ok() .map(|v| v.parse::()) .map_or(Ok(None), |r| r.map(Some)) .context("Invalid exit code")? .unwrap_or(0); process::exit(code); } fn main() { let code = match run() { Ok(_) => 0, Err(ref e) => { write!(&mut io::stderr(), "{}", e).expect("writing to stderr won't fail"); 1 } }; process::exit(code); } assert_cli-0.6.3/src/diff.rs010066600017500001750000000074171331553742300141610ustar0000000000000000use std::fmt::{Error as fmtError, Write}; use colored::Colorize; use difference::{Changeset, Difference}; pub fn render(&Changeset { ref diffs, .. }: &Changeset) -> Result { let mut t = String::new(); for (i, diff) in diffs.iter().enumerate() { match *diff { Difference::Same(ref x) => { writeln!(t, " {}", x)?; } Difference::Rem(ref x) => { writeln!(t, "{}", format!("-{}", x).red())?; } Difference::Add(ref x) => { if i == 0 { writeln!(t, "{}", format!("+{}", x).green())?; } else { match diffs[i - 1] { Difference::Rem(ref y) => { write!(t, "{}", "+".green())?; let Changeset { diffs, .. } = Changeset::new(y, x, " "); for c in diffs { match c { Difference::Same(ref z) if !z.is_empty() => { write!(t, "{}", z.green())?; write!(t, " ")?; } Difference::Add(ref z) if !z.is_empty() => { write!(t, "{}", z.green().reverse())?; write!(t, " ")?; } _ => (), } } writeln!(t, "")?; } _ => { writeln!(t, "{}", format!("+{}", x).green().dimmed())?; } }; } } } } Ok(t) } #[cfg(test)] mod tests { use super::*; #[test] fn basic_diff() { let diff = Changeset::new("lol", "yay", "\n"); println!("{}", render(&diff).unwrap()); assert_eq!( render(&diff).unwrap(), "\u{1b}[31m-lol\u{1b}[0m\n\u{1b}[32m+\u{1b}[0m\u{1b}[7;32myay\u{1b}[0m \n" ) } #[test] fn multiline_diff() { let diff = Changeset::new( "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor **incididunt** ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", "\n", ); println!("{}", render(&diff).unwrap()); assert_eq!( render(&diff).unwrap(), " Lorem ipsum dolor sit amet, consectetur adipisicing elit,\n\ \u{1b}[31m-sed do eiusmod tempor incididunt ut labore et dolore \ magna\u{1b}[0m\n\u{1b}[32m+\u{1b}[0m\u{1b}[32msed do eiusmod tempor\ \u{1b}[0m \u{1b}[7;32m**incididunt**\u{1b}[0m \u{1b}[32mut labore \ et dolore magna\u{1b}[0m \n aliqua. Ut enim ad minim veniam, quis \ nostrud exercitation\nullamco laboris nisi ut aliquip ex ea \ commodo consequat.\n" ); } #[test] fn added_first_line_diff() { let diff = Changeset::new( "Line 1\nLine 2\nLine 3", "Line 0\nLine 1\nLine 2\nLine 3", "\n", ); println!("{}", render(&diff).unwrap()); assert_eq!( render(&diff).unwrap(), "\u{1b}[32m+Line 0\u{1b}[0m\n Line 1\nLine 2\nLine 3\n" ); } } assert_cli-0.6.3/src/errors.rs010066600017500001750000000112311325721240700145470ustar0000000000000000use std::ffi; use std::fmt; use std::io; use failure; fn format_cmd(cmd: &[ffi::OsString]) -> String { let result: Vec = cmd.iter() .map(|s| s.to_string_lossy().into_owned()) .collect(); result.join(" ") } pub trait ChainFail { fn chain(self, cause: E) -> Self where E: Into; } pub trait ResultChainExt { fn chain(self, chainable: C) -> Result where C: ChainFail; fn chain_with(self, chainable: F) -> Result where F: FnOnce() -> C, C: ChainFail; } impl ResultChainExt for Result { fn chain(self, chainable: C) -> Result where C: ChainFail, { self.map_err(|e| chainable.chain(e)) } fn chain_with(self, chainable: F) -> Result where F: FnOnce() -> C, C: ChainFail, { self.map_err(|e| chainable().chain(e)) } } impl ResultChainExt for Result { fn chain(self, chainable: C) -> Result where C: ChainFail, { self.map_err(|e| chainable.chain(e)) } fn chain_with(self, chainable: F) -> Result where F: FnOnce() -> C, C: ChainFail, { self.map_err(|e| chainable().chain(e)) } } /// Failure when processing assertions. #[derive(Debug)] pub struct AssertionError { cmd: Vec, cause: Option, } impl AssertionError { pub(crate) fn new(cmd: Vec) -> Self { Self { cmd, cause: None } } } impl failure::Fail for AssertionError { fn cause(&self) -> Option<&failure::Fail> { self.cause.as_ref().map(failure::Error::cause) } fn backtrace(&self) -> Option<&failure::Backtrace> { None } } impl ChainFail for AssertionError { fn chain(mut self, error: E) -> Self where E: Into, { self.cause = Some(error.into()); self } } impl fmt::Display for AssertionError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Assertion failed for `{}`", format_cmd(&self.cmd)) } } #[derive(Debug)] pub struct StatusError { unexpected: bool, stdout: Vec, stderr: Vec, cause: Option, } impl StatusError { pub fn new(unexpected: bool, stdout: Vec, stderr: Vec) -> Self { Self { unexpected, stdout, stderr, cause: None, } } } impl failure::Fail for StatusError { fn cause(&self) -> Option<&failure::Fail> { self.cause.as_ref().map(failure::Error::cause) } fn backtrace(&self) -> Option<&failure::Backtrace> { None } } impl ChainFail for StatusError { fn chain(mut self, error: E) -> Self where E: Into, { self.cause = Some(error.into()); self } } impl fmt::Display for StatusError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let out = String::from_utf8_lossy(&self.stdout); let err = String::from_utf8_lossy(&self.stderr); writeln!( f, "Unexpected return status: {}", if self.unexpected { "success" } else { "failure" } )?; writeln!(f, "stdout=```{}```", out)?; write!(f, "stderr=```{}```", err) } } #[derive(Debug)] pub struct ExitCodeError { expected: Option, got: Option, stdout: Vec, stderr: Vec, cause: Option, } impl ExitCodeError { pub fn new(expected: Option, got: Option, stdout: Vec, stderr: Vec) -> Self { Self { expected, got, stdout, stderr, cause: None, } } } impl failure::Fail for ExitCodeError { fn cause(&self) -> Option<&failure::Fail> { self.cause.as_ref().map(failure::Error::cause) } fn backtrace(&self) -> Option<&failure::Backtrace> { None } } impl ChainFail for ExitCodeError { fn chain(mut self, error: E) -> Self where E: Into, { self.cause = Some(error.into()); self } } impl fmt::Display for ExitCodeError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let out = String::from_utf8_lossy(&self.stdout); let err = String::from_utf8_lossy(&self.stderr); writeln!(f, "expected={:?}", self.expected)?; writeln!(f, "got={:?}", self.got)?; writeln!(f, "stdout=```{}```", out)?; write!(f, "stderr=```{}```", err) } } assert_cli-0.6.3/src/lib.rs010066600017500001750000000074331327437246000140170ustar0000000000000000//! # Test CLI Applications //! //! This crate's goal is to provide you some very easy tools to test your CLI //! applications. It can currently execute child processes and validate their //! exit status as well as stdout and stderr output against your assertions. //! //! Include the crate like //! //! ```rust //! #[macro_use] // <-- import the convenience macro (optional) //! extern crate assert_cli; //! # fn main() { } //! ``` //! //! ## Basic Examples //! //! Here's a trivial example: //! //! ```rust //! assert_cli::Assert::command(&["echo", "42"]) //! .stdout().contains("42") //! .unwrap(); //! ``` //! //! And here is one that will fail: //! //! ```rust,should_panic //! assert_cli::Assert::command(&["echo", "42"]) //! .stdout().is("1337") //! .unwrap(); //! ``` //! //! this will show a nice, colorful diff in your terminal, like this: //! //! ```diff //! -1337 //! +42 //! ``` //! //! ## `assert_cmd!` Macro //! //! Alternatively, you can use the `assert_cmd!` macro to construct the command more conveniently, //! but please carefully read the limitations below, or this may seriously go wrong. //! //! ```rust //! # #[macro_use] extern crate assert_cli; //! # fn main() { //! assert_cmd!(echo "42").stdout().contains("42").unwrap(); //! # } //! ``` //! //! **Tips** //! //! - Don't forget to import the crate with `#[macro_use]`. ;-) //! - Enclose arguments in the `assert_cmd!` macro in quotes `"`, //! if there are special characters, which the macro doesn't accept, e.g. //! `assert_cmd!(cat "foo.txt")`. //! //! ## Exit Status //! //! All assertion default to checking that the command exited with success. //! //! However, when you expect a command to fail, you can express it like this: //! //! ```rust //! # #[macro_use] extern crate assert_cli; //! # fn main() { //! assert_cmd!(cat "non-existing-file") //! .fails() //! .unwrap(); //! # } //! ``` //! //! Some notes on this: //! //! - Use `fails_with` to assert a specific exit status. //! - There is also a `succeeds` method, but this is already the implicit default //! and can usually be omitted. //! - The `and` method has no effect, other than to make everything more readable. //! Feel free to use it. :-) //! //! ## stdout / stderr //! //! You can add assertions on the content of **stdout** and **stderr**. They //! can be mixed together or even multiple of one stream can be used. //! //! ```rust //! # #[macro_use] extern crate assert_cli; //! # fn main() { //! assert_cmd!(echo "Hello world! The ansswer is 42.") //! .stdout().contains("Hello world") //! .stdout().contains("42") //! .stderr().is("") //! .unwrap(); //! # } //! ``` //! //! ## Assert CLI Crates //! //! If you are testing a Rust binary crate, you can start with //! `Assert::main_binary()` to use `cargo run` as command. Or, if you want to //! run a specific binary (if you have more than one), use //! `Assert::cargo_binary`. //! //! ## Don't Panic! //! //! If you don't want it to panic when the assertions are not met, simply call //! `.execute` instead of `.unwrap` to get a `Result`: //! //! ```rust //! # #[macro_use] extern crate assert_cli; //! # fn main() { //! let x = assert_cmd!(echo "1337").stdout().is("42").execute(); //! assert!(x.is_err()); //! # } //! ``` #![deny(missing_docs)] extern crate colored; extern crate difference; extern crate environment; #[macro_use] extern crate failure; #[macro_use] extern crate failure_derive; extern crate serde_json; mod errors; pub use errors::AssertionError; #[macro_use] mod macros; pub use macros::flatten_escaped_string; mod assert; mod diff; mod output; pub use assert::Assert; pub use assert::OutputAssertionBuilder; /// Environment is a re-export of the Environment crate /// /// It allow you to define/override environment variables for one or more assertions. pub use environment::Environment; assert_cli-0.6.3/src/macros.rs010066600017500001750000000063111324667044700145340ustar0000000000000000use serde_json; use std::borrow::Cow; /// Easily construct an `Assert` with a custom command. /// /// Make sure to include the crate as `#[macro_use] extern crate assert_cli;` if /// you want to use this macro. /// /// # Examples /// /// To test that our very complex cli applications succeeds and prints some /// text to stdout that contains /// /// ```plain /// No errors whatsoever /// ``` /// /// ..., you would call it like this: /// /// ```rust /// #[macro_use] extern crate assert_cli; /// # fn main() { /// assert_cmd!(echo "Launch sequence initiated.\nNo errors whatsoever!\n") /// .succeeds() /// .stdout().contains("No errors whatsoever") /// .unwrap(); /// # } /// ``` /// /// The macro will try to convert its arguments as strings, but is limited by /// Rust's default tokenizer, e.g., you always need to quote CLI arguments /// like `"--verbose"`. #[macro_export] macro_rules! assert_cmd { ($($x:tt)+) => {{ $(__assert_single_token_expression!(@CHECK $x);)* $crate::Assert::command( &[$( $crate::flatten_escaped_string(stringify!($x)).as_ref() ),*] ) }} } /// Deserialize a JSON-encoded `String`. /// /// # Panics /// /// If `x` can not be decoded as `String`. #[doc(hidden)] fn deserialize_json_string(x: &str) -> String { serde_json::from_str(x).expect(&format!("Unable to deserialize `{:?}` as string.", x)) } /// Deserialize a JSON-encoded `String`. /// /// # Panics /// /// If `x` can not be decoded as `String`. #[doc(hidden)] pub fn flatten_escaped_string(x: &str) -> Cow { if x.starts_with('"') && x.ends_with('"') { Cow::Owned(deserialize_json_string(x)) } else { Cow::Borrowed(x) } } /// Inspect a single token and decide if it is safe to `stringify!`, without loosing /// information about whitespaces, to address [issue 22]. /// /// [issue 22]: https://github.com/assert-rs/assert_cli/issues/22 /// /// Call like `__assert_single_token_expression!(@CHECK x)`, where `x` can be any token to check. /// /// This macro will only accept single tokens, which parse as expressions, e.g. /// - strings "foo", r#"foo" /// - idents `foo`, `foo42` /// - numbers `42` /// - chars `'a'` /// /// Delimited token trees `{...}` and the like are rejected. Everything thats not an expression /// will also be rejected. #[doc(hidden)] #[macro_export] macro_rules! __assert_single_token_expression { // deny `{...}` (@CHECK {$( $x:tt )*}) => { assert_cmd!(@DENY {$( $x )*}) }; // deny `(...)` (@CHECK ($( $x:tt )*)) => { assert_cmd!(@DENY {$( $x )*}) }; // deny `[...]` (@CHECK [$( $x:tt )*]) => { assert_cmd!(@DENY {$( $x )*}) }; // only allow tokens that parse as expression (@CHECK $x:expr) => { }; // little helper (@DENY) => { }; } #[cfg(test)] mod test { use super::*; #[test] fn flatten_unquoted() { assert_eq!(flatten_escaped_string("hello world"), "hello world"); } #[test] fn flatten_quoted() { assert_eq!(flatten_escaped_string(r#""hello world""#), "hello world"); } #[test] fn flatten_escaped() { assert_eq!( flatten_escaped_string(r#""hello world \u0042 A""#), "hello world B A" ); } } assert_cli-0.6.3/src/output.rs010066600017500001750000000335541327437247300146200ustar0000000000000000use std::fmt; use std::process; use std::rc; use difference::Changeset; use failure; use diff; use errors::*; #[derive(Clone, PartialEq, Eq)] pub enum Content { Str(String), Bytes(Vec), } impl fmt::Debug for Content { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Content::Str(ref data) => write!(f, "{}", data), Content::Bytes(ref data) => write!(f, "{:?}", data), } } } impl<'a> From<&'a str> for Content { fn from(data: &'a str) -> Self { Content::Str(data.into()) } } impl<'a> From<&'a [u8]> for Content { fn from(data: &'a [u8]) -> Self { Content::Bytes(data.into()) } } #[derive(Debug, Clone, PartialEq, Eq)] struct IsPredicate { pub expect: Content, pub expected_result: bool, } impl IsPredicate { pub fn verify(&self, got: &[u8]) -> Result<(), failure::Error> { match self.expect { Content::Str(ref expect) => { self.verify_str(expect, String::from_utf8_lossy(got).as_ref()) } Content::Bytes(ref expect) => self.verify_bytes(expect, got), } } fn verify_bytes(&self, expect: &[u8], got: &[u8]) -> Result<(), failure::Error> { let result = expect == got; if result != self.expected_result { if self.expected_result { bail!(BytesDoesntMatch::new(expect.to_owned(), got.to_owned())); } else { bail!(BytesMatches::new(got.to_owned())); } } Ok(()) } fn verify_str(&self, expect: &str, got: &str) -> Result<(), failure::Error> { let differences = Changeset::new(expect.trim(), got.trim(), "\n"); let result = differences.distance == 0; if result != self.expected_result { if self.expected_result { let nice_diff = diff::render(&differences)?; bail!(StrDoesntMatch::new( expect.to_owned(), got.to_owned(), nice_diff )); } else { bail!(StrMatches::new(got.to_owned())); } } Ok(()) } } #[derive(Debug, Clone, PartialEq, Eq)] struct ContainsPredicate { pub expect: Content, pub expected_result: bool, } fn find_subsequence(haystack: &[u8], needle: &[u8]) -> Option { haystack .windows(needle.len()) .position(|window| window == needle) } #[test] fn test_find_subsequence() { assert_eq!(find_subsequence(b"qwertyuiop", b"tyu"), Some(4)); assert_eq!(find_subsequence(b"qwertyuiop", b"asd"), None); } impl ContainsPredicate { pub fn verify(&self, got: &[u8]) -> Result<(), failure::Error> { match self.expect { Content::Str(ref expect) => { self.verify_str(expect, String::from_utf8_lossy(got).as_ref()) } Content::Bytes(ref expect) => self.verify_bytes(expect, got), } } pub fn verify_bytes(&self, expect: &[u8], got: &[u8]) -> Result<(), failure::Error> { let result = find_subsequence(got, expect).is_some(); if result != self.expected_result { if self.expected_result { bail!(BytesDoesntContain::new(expect.to_owned(), got.to_owned())); } else { bail!(BytesContains::new(expect.to_owned(), got.to_owned())); } } Ok(()) } pub fn verify_str(&self, expect: &str, got: &str) -> Result<(), failure::Error> { let result = got.contains(expect); if result != self.expected_result { if self.expected_result { bail!(StrDoesntContain::new(expect.to_owned(), got.to_owned())); } else { bail!(StrContains::new(expect.to_owned(), got.to_owned())); } } Ok(()) } } #[derive(Clone)] struct FnPredicate { pub pred: rc::Rc bool>, pub msg: String, } impl FnPredicate { pub fn verify(&self, got: &[u8]) -> Result<(), failure::Error> { let got = String::from_utf8_lossy(got); let pred = &self.pred; if !pred(&got) { bail!(PredicateFailed::new(self.msg.clone(), got.into_owned())); } Ok(()) } } impl fmt::Debug for FnPredicate { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.msg) } } #[derive(Debug, Clone)] enum ContentPredicate { Is(IsPredicate), Contains(ContainsPredicate), Fn(FnPredicate), } impl ContentPredicate { pub fn verify(&self, got: &[u8]) -> Result<(), failure::Error> { match *self { ContentPredicate::Is(ref pred) => pred.verify(got), ContentPredicate::Contains(ref pred) => pred.verify(got), ContentPredicate::Fn(ref pred) => pred.verify(got), } } } /// Assertions for command output. #[derive(Debug, Clone)] pub struct Output { pred: ContentPredicate, } impl Output { /// Expect the command's output to **contain** `output`. /// /// # Examples /// /// ```rust /// extern crate assert_cli; /// /// assert_cli::Assert::command(&["echo"]) /// .with_args(&["42"]) /// .stdout().contains("42") /// .unwrap(); /// ``` pub fn contains>(output: O) -> Self { let pred = ContainsPredicate { expect: output.into(), expected_result: true, }; Self::new(ContentPredicate::Contains(pred)) } /// Expect the command to output **exactly** this `output`. /// /// # Examples /// /// ```rust /// extern crate assert_cli; /// /// assert_cli::Assert::command(&["echo"]) /// .with_args(&["42"]) /// .stdout().is("42") /// .unwrap(); /// ``` pub fn is>(output: O) -> Self { let pred = IsPredicate { expect: output.into(), expected_result: true, }; Self::new(ContentPredicate::Is(pred)) } /// Expect the command's output to not **contain** `output`. /// /// # Examples /// /// ```rust /// extern crate assert_cli; /// /// assert_cli::Assert::command(&["echo"]) /// .with_args(&["42"]) /// .stdout().doesnt_contain("73") /// .unwrap(); /// ``` pub fn doesnt_contain>(output: O) -> Self { let pred = ContainsPredicate { expect: output.into(), expected_result: false, }; Self::new(ContentPredicate::Contains(pred)) } /// Expect the command to output to not be **exactly** this `output`. /// /// # Examples /// /// ```rust /// extern crate assert_cli; /// /// assert_cli::Assert::command(&["echo"]) /// .with_args(&["42"]) /// .stdout().isnt("73") /// .unwrap(); /// ``` pub fn isnt>(output: O) -> Self { let pred = IsPredicate { expect: output.into(), expected_result: false, }; Self::new(ContentPredicate::Is(pred)) } /// Expect the command output to satisfy the given predicate. /// /// # Examples /// /// ```rust /// extern crate assert_cli; /// /// assert_cli::Assert::command(&["echo", "-n", "42"]) /// .stdout().satisfies(|x| x.len() == 2, "bad length") /// .unwrap(); /// ``` pub fn satisfies(pred: F, msg: M) -> Self where F: 'static + Fn(&str) -> bool, M: Into, { let pred = FnPredicate { pred: rc::Rc::new(pred), msg: msg.into(), }; Self::new(ContentPredicate::Fn(pred)) } fn new(pred: ContentPredicate) -> Self { Self { pred } } pub(crate) fn verify(&self, got: &[u8]) -> Result<(), failure::Error> { self.pred.verify(got) } } #[derive(Debug, Clone, Copy)] pub enum OutputKind { StdOut, StdErr, } impl OutputKind { pub fn select(self, o: &process::Output) -> &[u8] { match self { OutputKind::StdOut => &o.stdout, OutputKind::StdErr => &o.stderr, } } } impl fmt::Display for OutputKind { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { OutputKind::StdOut => write!(f, "stdout"), OutputKind::StdErr => write!(f, "stderr"), } } } #[derive(Debug, Clone)] pub struct OutputPredicate { kind: OutputKind, pred: Output, } impl OutputPredicate { pub fn new(kind: OutputKind, pred: Output) -> Self { Self { kind, pred } } pub(crate) fn verify(&self, got: &process::Output) -> Result<(), OutputError> { let got = self.kind.select(got); self.pred.verify(got).chain(OutputError::new(self.kind))?; Ok(()) } } #[derive(Fail, Debug)] pub struct StrDoesntContain { needle: String, haystack: String, } impl StrDoesntContain { pub fn new(needle: String, haystack: String) -> Self { Self { needle, haystack } } } impl fmt::Display for StrDoesntContain { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Expected to contain needle.\n")?; write!(f, "needle=```{}```\n", self.needle)?; write!(f, "haystack=```{}```", self.haystack) } } #[derive(Fail, Debug)] pub struct BytesDoesntContain { needle: Vec, haystack: Vec, } impl BytesDoesntContain { pub fn new(needle: Vec, haystack: Vec) -> Self { Self { needle, haystack } } } impl fmt::Display for BytesDoesntContain { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Expected to contain needle.\n")?; write!(f, "needle=```{:?}```\n", self.needle)?; write!(f, "haystack=```{:?}```", self.haystack) } } #[derive(Fail, Debug)] pub struct StrContains { needle: String, haystack: String, } impl StrContains { pub fn new(needle: String, haystack: String) -> Self { Self { needle, haystack } } } impl fmt::Display for StrContains { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Expected to not contain needle.\n")?; write!(f, "needle=```{}```\n", self.needle)?; write!(f, "haystack=```{}```", self.haystack) } } #[derive(Fail, Debug)] pub struct BytesContains { needle: Vec, haystack: Vec, } impl BytesContains { pub fn new(needle: Vec, haystack: Vec) -> Self { Self { needle, haystack } } } impl fmt::Display for BytesContains { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Expected to not contain needle.\n")?; write!(f, "needle=```{:?}```\n", self.needle)?; write!(f, "haystack=```{:?}```", self.haystack) } } #[derive(Fail, Debug)] pub struct StrDoesntMatch { expected: String, got: String, diff: String, } impl StrDoesntMatch { pub fn new(expected: String, got: String, diff: String) -> Self { Self { expected, got, diff, } } } impl fmt::Display for StrDoesntMatch { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Didn't match.\n")?; write!(f, "diff=\n``{}```", self.diff) } } #[derive(Fail, Debug)] pub struct BytesDoesntMatch { expected: Vec, got: Vec, } impl BytesDoesntMatch { pub fn new(expected: Vec, got: Vec) -> Self { Self { expected, got } } } impl fmt::Display for BytesDoesntMatch { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Didn't match.\n")?; write!(f, "expected=```{:?}```\n", self.expected)?; write!(f, "got=```{:?}```", self.got) } } #[derive(Fail, Debug)] pub struct StrMatches { output: String, } impl StrMatches { pub fn new(output: String) -> Self { Self { output } } } impl fmt::Display for StrMatches { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Expected to not match.")?; write!(f, "output=```{}```", self.output) } } #[derive(Fail, Debug)] pub struct BytesMatches { output: Vec, } impl BytesMatches { pub fn new(output: Vec) -> Self { Self { output } } } impl fmt::Display for BytesMatches { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Expected to not match.")?; write!(f, "output=```{:?}```", self.output) } } #[derive(Fail, Debug)] pub struct PredicateFailed { msg: String, got: String, } impl PredicateFailed { pub fn new(msg: String, got: String) -> Self { Self { msg, got } } } impl fmt::Display for PredicateFailed { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Predicate failed: {}", self.msg)?; write!(f, "got=```{}```\n", self.got) } } #[derive(Debug)] pub struct OutputError { kind: OutputKind, cause: Option, } impl OutputError { pub fn new(kind: OutputKind) -> Self { Self { kind, cause: None } } } impl failure::Fail for OutputError { fn cause(&self) -> Option<&failure::Fail> { self.cause.as_ref().map(failure::Error::cause) } fn backtrace(&self) -> Option<&failure::Backtrace> { None } } impl ChainFail for OutputError { fn chain(mut self, error: E) -> Self where E: Into, { self.cause = Some(error.into()); self } } impl fmt::Display for OutputError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "Unexpected {}", self.kind) } } impl ResultChainExt for Result { fn chain(self, chainable: C) -> Result where C: ChainFail, { self.map_err(|e| chainable.chain(e)) } fn chain_with(self, chainable: F) -> Result where F: FnOnce() -> C, C: ChainFail, { self.map_err(|e| chainable().chain(e)) } } assert_cli-0.6.3/tests/cargo.rs010066600017500001750000000007771324667044200147230ustar0000000000000000extern crate assert_cli; #[test] fn main_binary() { assert_cli::Assert::main_binary() .with_env(assert_cli::Environment::inherit().insert("stdout", "42")) .stdout() .is("42") .stderr() .is("") .unwrap(); } #[test] fn cargo_binary() { assert_cli::Assert::cargo_binary("assert_fixture") .with_env(assert_cli::Environment::inherit().insert("stdout", "42")) .stdout() .is("42") .stderr() .is("") .unwrap(); } assert_cli-0.6.3/tests/docmatic.rs010066600017500001750000000001351327437247300154030ustar0000000000000000extern crate docmatic; #[test] fn test_readme() { docmatic::assert_file("README.md"); }