insta-cmd-0.4.0/.cargo_vcs_info.json0000644000000001360000000000100127140ustar { "git": { "sha1": "9bc424a1b213b115c4ad66829cfd514ef83441b0" }, "path_in_vcs": "" }insta-cmd-0.4.0/.github/FUNDING.yml000064400000000000000000000000240072674642500147050ustar 00000000000000github: [mitsuhiko] insta-cmd-0.4.0/.github/ISSUE_TEMPLATE/1-bug.yml000064400000000000000000000017530072674642500167230ustar 00000000000000name: Bug Report description: Something does not seem right labels: [bug] body: - type: textarea id: what-happened attributes: label: What happened? description: What happened that shouldn't have? validations: required: true - type: textarea id: reproduction-steps attributes: label: Reproduction steps value: | 1. [First step] 2. [Second step] 3. etc. - type: input id: insta-version attributes: label: Insta Version description: What version of insta are you using? - type: input id: insta-cmd-version attributes: label: insta-cmd Version description: What version of insta-cmd are you using? - type: input id: rustc-version attributes: label: rustc Version description: What version of rustc are you using? - type: textarea id: expectations attributes: label: What did you expect? placeholder: What do you think should have happened? insta-cmd-0.4.0/.github/ISSUE_TEMPLATE/2-feature.md000064400000000000000000000001130072674642500173660ustar 00000000000000--- name: Suggestion about: Want to report a suggestion for a feature? --- insta-cmd-0.4.0/.github/workflows/clippy.yml000064400000000000000000000005140072674642500171540ustar 00000000000000name: Clippy on: [push] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - uses: actions-rs/toolchain@v1 with: toolchain: stable profile: minimal components: clippy, rustfmt override: true - name: Run clippy run: make lint insta-cmd-0.4.0/.github/workflows/rustfmt.yml000064400000000000000000000005260072674642500173630ustar 00000000000000name: Rustfmt on: [push] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - uses: actions-rs/toolchain@v1 with: toolchain: stable profile: minimal components: clippy, rustfmt override: true - name: Run rustfmt run: make format-check insta-cmd-0.4.0/.github/workflows/tests.yml000064400000000000000000000011540072674642500170170ustar 00000000000000name: Tests on: [push, pull_request] jobs: test-latest: name: Test on Latest runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - uses: actions-rs/toolchain@v1 with: toolchain: stable profile: minimal override: true - name: Test run: make test test-stable: name: Test on 1.57.0 runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - uses: actions-rs/toolchain@v1 with: toolchain: 1.57.0 profile: minimal override: true - name: Test run: make test insta-cmd-0.4.0/.gitignore000064400000000000000000000000230072674642500135170ustar 00000000000000/target Cargo.lock insta-cmd-0.4.0/Cargo.lock0000644000000136170000000000100106770ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "console" version = "0.15.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c926e00cc70edefdc64d3a5ff31cc65bb97a3460097762bd23afb4d8145fccf8" dependencies = [ "encode_unicode", "lazy_static", "libc", "windows-sys", ] [[package]] name = "encode_unicode" version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f" [[package]] name = "insta" version = "1.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a28d25139df397cbca21408bb742cf6837e04cdbebf1b07b760caf971d6a972" dependencies = [ "console", "lazy_static", "linked-hash-map", "serde", "similar", "yaml-rust", ] [[package]] name = "insta-cmd" version = "0.4.0" dependencies = [ "insta", "serde", "serde_json", ] [[package]] name = "itoa" version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "453ad9f582a441959e5f0d088b02ce04cfe8d51a8eaf077f12ac6d3e94164ca6" [[package]] name = "lazy_static" version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" [[package]] name = "libc" version = "0.2.146" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f92be4933c13fd498862a9e02a3055f8a8d9c039ce33db97306fd5a6caa7f29b" [[package]] name = "linked-hash-map" version = "0.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" [[package]] name = "proc-macro2" version = "1.0.60" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dec2b086b7a862cf4de201096214fa870344cf922b2b30c167badb3af3195406" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b9ab9c7eadfd8df19006f1cf1a4aed13540ed5cbc047010ece5826e10825488" dependencies = [ "proc-macro2", ] [[package]] name = "ryu" version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f91339c0467de62360649f8d3e185ca8de4224ff281f66000de5eb2a77a79041" [[package]] name = "serde" version = "1.0.164" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e8c8cf938e98f769bc164923b06dce91cea1751522f46f8466461af04c9027d" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.164" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9735b638ccc51c28bf6914d90a2e9725b377144fc612c49a611fddd1b631d68" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.97" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bdf3bf93142acad5821c99197022e170842cdbc1c30482b98750c688c640842a" dependencies = [ "itoa", "ryu", "serde", ] [[package]] name = "similar" version = "2.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "420acb44afdae038210c99e69aae24109f32f15500aa708e81d46c9f29d55fcf" [[package]] name = "syn" version = "2.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32d41677bcbe24c20c52e7c70b0d8db04134c5d1066bf98662e2871ad200ea3e" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "unicode-ident" version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b15811caf2415fb889178633e7724bad2509101cde276048e013b9def5e51fa0" [[package]] name = "windows-sys" version = "0.45.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" dependencies = [ "windows-targets", ] [[package]] name = "windows-targets" version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" dependencies = [ "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", "windows_i686_msvc", "windows_x86_64_gnu", "windows_x86_64_gnullvm", "windows_x86_64_msvc", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" [[package]] name = "windows_aarch64_msvc" version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" [[package]] name = "windows_i686_gnu" version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" [[package]] name = "windows_i686_msvc" version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" [[package]] name = "windows_x86_64_gnu" version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" [[package]] name = "windows_x86_64_gnullvm" version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" [[package]] name = "windows_x86_64_msvc" version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" [[package]] name = "yaml-rust" version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85" dependencies = [ "linked-hash-map", ] insta-cmd-0.4.0/Cargo.toml0000644000000020540000000000100107130ustar # 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 are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.57.0" name = "insta-cmd" version = "0.4.0" authors = ["Armin Ronacher "] description = "A command line extension to the insta testing library for Rust" homepage = "https://insta.rs/" readme = "README.md" keywords = [ "snapshot", "cmd", "trycmd", "assert-cmd", ] license = "Apache-2.0" repository = "https://github.com/mitsuhiko/insta-cmd" [dependencies.insta] version = "1.29.0" features = ["serde"] [dependencies.serde] version = "1.0.139" features = ["derive"] [dependencies.serde_json] version = "1.0.82" insta-cmd-0.4.0/Cargo.toml.orig000064400000000000000000000010540072674642500144230ustar 00000000000000[package] authors = ["Armin Ronacher "] description = "A command line extension to the insta testing library for Rust" edition = "2021" homepage = "https://insta.rs/" keywords = ["snapshot", "cmd", "trycmd", "assert-cmd"] license = "Apache-2.0" name = "insta-cmd" readme = "README.md" repository = "https://github.com/mitsuhiko/insta-cmd" rust-version = "1.57.0" version = "0.4.0" [dependencies] insta = { version = "1.29.0", features = ["serde"] } serde = { version = "1.0.139", features = ["derive"] } serde_json = "1.0.82" insta-cmd-0.4.0/LICENSE000064400000000000000000000251370072674642500125510ustar 00000000000000 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. insta-cmd-0.4.0/Makefile000064400000000000000000000010010072674642500131640ustar 00000000000000all: test build: @cargo build --all-features doc: @cargo doc --all-features test: @echo "CARGO TESTS" @rustup component add rustfmt 2> /dev/null @cargo build --bin hello @cargo build --example hello @cargo test --all-features --all format: @rustup component add rustfmt 2> /dev/null @cargo fmt --all format-check: @rustup component add rustfmt 2> /dev/null @cargo fmt --all -- --check lint: @rustup component add clippy 2> /dev/null @cargo clippy .PHONY: all doc test format format-check lint insta-cmd-0.4.0/README.md000064400000000000000000000022610072674642500130140ustar 00000000000000

insta-cmd: command line testing extension for insta

[![Build Status](https://github.com/mitsuhiko/insta-cmd/workflows/Tests/badge.svg?branch=main)](https://github.com/mitsuhiko/insta-cmd/actions?query=workflow%3ATests) [![Crates.io](https://img.shields.io/crates/d/insta-cmd.svg)](https://crates.io/crates/insta-cmd) [![License](https://img.shields.io/github/license/mitsuhiko/insta-cmd)](https://github.com/mitsuhiko/insta-cmd/blob/main/LICENSE) [![rustc 1.56.1](https://img.shields.io/badge/rust-1.57.0%2B-orange.svg)](https://img.shields.io/badge/rust-1.57.0%2B-orange.svg) [![Documentation](https://docs.rs/insta-cmd/badge.svg)](https://docs.rs/insta-cmd) ## Introduction This is an experimental extension to insta for command line app testing. ```rust use std::process::Command; use insta_cmd::assert_cmd_snapshot; assert_cmd_snapshot!(Command::new("echo").arg("Hello World!")); ``` ## License and Links - [Project Website](https://insta.rs/) - [Documentation](https://docs.rs/insta-cmd/) - [Issue Tracker](https://github.com/mitsuhiko/insta-cmd/issues) - License: [Apache-2.0](https://github.com/mitsuhiko/insta-cmd/blob/main/LICENSE) insta-cmd-0.4.0/examples/hello.rs000064400000000000000000000005110072674642500150200ustar 00000000000000fn main() { println!("Hello Example!"); } #[test] fn test_cli() { use insta_cmd::{assert_cmd_snapshot, get_cargo_example, Command}; assert_cmd_snapshot!(Command::new(get_cargo_example("hello")), @r###" success: true exit_code: 0 ----- stdout ----- Hello Example! ----- stderr ----- "###); } insta-cmd-0.4.0/src/bin/hello.rs000064400000000000000000000004710072674642500145460ustar 00000000000000fn main() { println!("Hello Bin!"); } #[test] fn test_cli() { use insta_cmd::{assert_cmd_snapshot, get_cargo_bin, Command}; assert_cmd_snapshot!(Command::new(get_cargo_bin("hello")), @r###" success: true exit_code: 0 ----- stdout ----- Hello Bin! ----- stderr ----- "###); } insta-cmd-0.4.0/src/cargo.rs000064400000000000000000000040160072674642500137650ustar 00000000000000use std::env; use std::path::PathBuf; use std::process::Command; use serde::Deserialize; #[derive(Deserialize)] struct MetaData { target_directory: PathBuf, } fn primary_target_dir() -> PathBuf { // the target dir is explicitly set and exists if let Some(target_dir) = env::var_os("CARGO_TARGET_DIR") { let target_dir = PathBuf::from(target_dir); if target_dir.is_dir() { println!("first out"); return target_dir; }; } // try to guess it from the current exe env::current_exe() .ok() .map(|mut path| { path.pop(); if path.ends_with("deps") || path.ends_with("examples") { path.pop(); } path }) .unwrap() } fn cargo_inferred_target_dir() -> PathBuf { let metadata = Command::new(env::var("CARGO").ok().unwrap_or_else(|| "cargo".into())) .arg("metadata") .output() .unwrap(); let meta: MetaData = serde_json::from_slice(&metadata.stdout).unwrap(); let mut rv = meta.target_directory; if cfg!(debug_assertions) { rv.push("debug"); } else { rv.push("release"); } rv } fn find_exe(name: &str) -> PathBuf { let mut first = primary_target_dir(); first.push(name); if first.is_file() { return first; } let mut alt = cargo_inferred_target_dir(); alt.push(name); if alt.is_file() { return alt; } panic!("Cannot determine path to executable '{}'", name); } /// Helper function to return the path to an executable that cargo is building. pub fn get_cargo_bin(name: &str) -> PathBuf { let env_var = format!("CARGO_BIN_EXE_{}", name); env::var_os(env_var) .map(|p| p.into()) .unwrap_or_else(|| find_exe(&format!("{}{}", name, env::consts::EXE_SUFFIX))) } /// Helper function to return the path to an example that cargo is building. pub fn get_cargo_example(name: &str) -> PathBuf { find_exe(&format!("examples/{}{}", name, env::consts::EXE_SUFFIX)) } insta-cmd-0.4.0/src/lib.rs000064400000000000000000000046020072674642500134410ustar 00000000000000//! `insta-cmd` is an extension to [insta](https://insta.rs/) that lets you snapshot //! a command that produces (text) output to stdout and stderr. It takes a //! [`Command`](std::process::Command) from the standard library, runs it and //! snapshots the output alongside the exit code. //! //! ```no_run //! use std::process::Command; //! use insta_cmd::assert_cmd_snapshot; //! //! assert_cmd_snapshot!(Command::new("echo").arg("Hello World!")); //! ``` //! //! ## Testing Binaries //! //! If you want to test binaries from your own project you can use the //! [`get_cargo_bin`] and [`get_cargo_example`] functions to retrieve the path to //! your binary. Note that it's unlikely that cargo will have built the binary //! under normal circumstances so you will have to run ``cargo build --bin my-bin`` //! or ``cargo build --example my-example`` before. //! //! Afterwards you can test it like this: //! //! ```no_run //! use std::process::Command; //! use insta_cmd::{assert_cmd_snapshot, get_cargo_bin}; //! //! assert_cmd_snapshot!(Command::new(get_cargo_bin("hello")).arg("first arg")); //! ``` //! //! ## Passing Stdin //! //! To pass data via stdin and to have it snapshotted alongside, use the //! [`pass_stdin`](SpawnExt::pass_stdin) extension method. Inside the macro //! it's automatically in scope. //! //! ```no_run //! use std::process::Command; //! use insta_cmd::assert_cmd_snapshot; //! //! assert_cmd_snapshot!(Command::new("cat").arg("-b").pass_stdin("Hello World")); //! ``` #[doc(hidden)] #[macro_use] mod macros; mod cargo; mod spawn; pub use crate::cargo::{get_cargo_bin, get_cargo_example}; pub use crate::spawn::{Spawn, SpawnExt}; #[allow(deprecated)] pub use crate::spawn::StdinCommand; pub use std::process::Command; #[doc(hidden)] pub mod _macro_support { pub use super::spawn::Spawn; pub use insta; } #[test] fn test_basic() { assert_cmd_snapshot!(["/bin/echo", "Hello World"]); } #[test] fn test_command() { assert_cmd_snapshot!(Command::new("echo").arg("Just some stuff")); } #[test] #[allow(deprecated)] fn test_stdin() { assert_cmd_snapshot!(StdinCommand::new("cat", "Hello World!")); } #[test] fn test_pass_stdin() { assert_cmd_snapshot!(Command::new("cat").pass_stdin("Hello World!")); } #[test] fn test_pass_stdin_on_array() { assert_cmd_snapshot!(["cat"].pass_stdin("Hello World!")); } #[test] fn test_failure() { assert_cmd_snapshot!(["false"]); } insta-cmd-0.4.0/src/macros.rs000064400000000000000000000032350072674642500141600ustar 00000000000000#[macro_export] #[doc(hidden)] macro_rules! _run_and_snapshot { ($cmd:expr, $body:expr) => {{ let (info, output) = $crate::_macro_support::Spawn::spawn_with_info(&mut $cmd, None); let mut settings = $crate::_macro_support::insta::Settings::clone_current(); settings.set_info(&info); settings.set_omit_expression(true); settings.bind(|| { #[allow(clippy::redundant_closure_call)] ($body)(&format!( "success: {:?}\nexit_code: {}\n----- stdout -----\n{}\n----- stderr -----\n{}", output.status.success(), output.status.code().unwrap_or(!0), String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr) )) }); }}; } /// Runs an [spawnable](crate::Spawn) and snapshots the output. #[macro_export] macro_rules! assert_cmd_snapshot { ($spawnable:expr, @$snapshot:literal) => {{ #[allow(unused)] use $crate::SpawnExt; $crate::_run_and_snapshot!($spawnable, |snapshot: &str| { $crate::_macro_support::insta::assert_snapshot!(snapshot, @$snapshot); }); }}; ($name:expr, $spawnable:expr) => {{ #[allow(unused)] use $crate::SpawnExt; $crate::_run_and_snapshot!($spawnable, |snapshot: &str| { $crate::_macro_support::insta::assert_snapshot!($name, snapshot); }); }}; ($spawnable:expr) => {{ #[allow(unused)] use $crate::SpawnExt; $crate::_run_and_snapshot!($spawnable, |snapshot: &str| { $crate::_macro_support::insta::assert_snapshot!(snapshot); }); }}; } insta-cmd-0.4.0/src/snapshots/insta_cmd__basic.snap000064400000000000000000000002320072674642500204660ustar 00000000000000--- source: src/lib.rs info: program: echo args: - Hello World --- success: true exit_code: 0 ----- stdout ----- Hello World ----- stderr ----- insta-cmd-0.4.0/src/snapshots/insta_cmd__command.snap000064400000000000000000000002420072674642500210240ustar 00000000000000--- source: src/lib.rs info: program: echo args: - Just some stuff --- success: true exit_code: 0 ----- stdout ----- Just some stuff ----- stderr ----- insta-cmd-0.4.0/src/snapshots/insta_cmd__failure.snap000064400000000000000000000002030072674642500210320ustar 00000000000000--- source: src/lib.rs info: program: "false" args: [] --- success: false exit_code: 1 ----- stdout ----- ----- stderr ----- insta-cmd-0.4.0/src/snapshots/insta_cmd__pass_stdin.snap000064400000000000000000000002400072674642500215530ustar 00000000000000--- source: src/lib.rs info: program: cat args: [] stdin: Hello World! --- success: true exit_code: 0 ----- stdout ----- Hello World! ----- stderr ----- insta-cmd-0.4.0/src/snapshots/insta_cmd__pass_stdin_on_array.snap000064400000000000000000000002400072674642500234450ustar 00000000000000--- source: src/lib.rs info: program: cat args: [] stdin: Hello World! --- success: true exit_code: 0 ----- stdout ----- Hello World! ----- stderr ----- insta-cmd-0.4.0/src/snapshots/insta_cmd__stdin.snap000064400000000000000000000002400072674642500205250ustar 00000000000000--- source: src/lib.rs info: program: cat args: [] stdin: Hello World! --- success: true exit_code: 0 ----- stdout ----- Hello World! ----- stderr ----- insta-cmd-0.4.0/src/spawn.rs000064400000000000000000000122720072674642500140250ustar 00000000000000use std::collections::HashMap; use std::env; use std::ffi::OsStr; use std::io::Write; use std::mem; use std::ops::{Deref, DerefMut}; use std::path::Path; use std::process::{Command, Output, Stdio}; use serde::Serialize; #[derive(Serialize)] pub struct Info { program: String, args: Vec, #[serde(skip_serializing_if = "HashMap::is_empty")] env: HashMap, #[serde(skip_serializing_if = "Option::is_none")] stdin: Option, } fn describe_program(cmd: &OsStr) -> String { let filename = Path::new(cmd).file_name().unwrap(); let name = filename.to_string_lossy(); let mut name = &name as &str; if !env::consts::EXE_SUFFIX.is_empty() { name = name.strip_suffix(env::consts::EXE_SUFFIX).unwrap_or(name); } name.into() } impl Info { fn from_std_command(cmd: &Command, stdin: Option<&[u8]>) -> Info { Info { program: describe_program(cmd.get_program()), args: cmd .get_args() .map(|x| x.to_string_lossy().into_owned()) .collect(), env: cmd .get_envs() .map(|(k, v)| { ( k.to_string_lossy().into_owned(), v.unwrap_or(OsStr::new("")).to_string_lossy().into_owned(), ) }) .collect(), stdin: stdin.as_ref().map(|x| String::from_utf8_lossy(x).into()), } } } /// Implemented by different types that can be spawned and snapshotted. pub trait Spawn { #[doc(hidden)] fn spawn_with_info(&mut self, stdin: Option>) -> (Info, Output); } /// Utility methods for spawning. pub trait SpawnExt { /// This passes the given input to stdin before spawning the command. fn pass_stdin(&mut self, stdin: impl Into>) -> SpawnWithStdin<'_>; } impl SpawnExt for T { fn pass_stdin(&mut self, stdin: impl Into>) -> SpawnWithStdin<'_> { SpawnWithStdin { spawn: self, stdin: stdin.into(), } } } pub struct SpawnWithStdin<'a> { spawn: &'a mut dyn Spawn, stdin: Vec, } impl<'a> Spawn for SpawnWithStdin<'a> { fn spawn_with_info(&mut self, stdin: Option>) -> (Info, Output) { self.spawn .spawn_with_info(Some(stdin.unwrap_or(mem::take(&mut self.stdin)))) } } impl Spawn for Command { fn spawn_with_info(&mut self, stdin: Option>) -> (Info, Output) { let info = Info::from_std_command(self, stdin.as_deref()); let output = if let Some(stdin) = stdin { self.stdin(Stdio::piped()); self.stdout(Stdio::piped()); self.stderr(Stdio::piped()); let mut child = self.spawn().unwrap(); let mut child_stdin = child.stdin.take().expect("Failed to open stdin"); std::thread::spawn(move || { child_stdin .write_all(&stdin) .expect("Failed to write to stdin"); }); child.wait_with_output().unwrap() } else { self.output().unwrap() }; (info, output) } } impl<'a> Spawn for &'a mut Command { fn spawn_with_info(&mut self, stdin: Option>) -> (Info, Output) { ::spawn_with_info(self, stdin) } } /// Like [`Command`] but sends some input to stdin. #[deprecated = "Use .pass_stdin(...) instead"] pub struct StdinCommand { command: Command, stdin: Vec, } #[allow(deprecated)] impl StdinCommand { /// Creates a new command that also gets some input value fed to stdin. pub fn new, I: Into>>(program: S, stdin: I) -> StdinCommand { let mut command = Command::new(program); command.stdin(Stdio::piped()); command.stdout(Stdio::piped()); command.stderr(Stdio::piped()); StdinCommand { command, stdin: stdin.into(), } } } #[allow(deprecated)] impl Deref for StdinCommand { type Target = Command; fn deref(&self) -> &Self::Target { &self.command } } #[allow(deprecated)] impl DerefMut for StdinCommand { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.command } } #[allow(deprecated)] impl Spawn for StdinCommand { fn spawn_with_info(&mut self, stdin: Option>) -> (Info, Output) { Command::spawn_with_info( &mut self.command, Some(stdin.unwrap_or(mem::take(&mut self.stdin))), ) } } impl<'a, T: AsRef> Spawn for &'a [T] { fn spawn_with_info(&mut self, stdin: Option>) -> (Info, Output) { let mut cmd = Command::new(self.get(0).expect("expected program name as first item")); for arg in &self[1..] { cmd.arg(arg); } cmd.spawn_with_info(stdin) } } impl, const N: usize> Spawn for [T; N] { fn spawn_with_info(&mut self, stdin: Option>) -> (Info, Output) { (&self[..]).spawn_with_info(stdin) } } impl> Spawn for Vec { fn spawn_with_info(&mut self, stdin: Option>) -> (Info, Output) { (&self[..]).spawn_with_info(stdin) } }