similar-asserts-1.4.2/.cargo_vcs_info.json0000644000000001360000000000100141620ustar { "git": { "sha1": "1f589363dd47b568319b8b8e9f684cd30141c4e1" }, "path_in_vcs": "" }similar-asserts-1.4.2/.github/workflows/clippy.yml000064400000000000000000000005140072674642500204220ustar 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 similar-asserts-1.4.2/.github/workflows/rustfmt.yml000064400000000000000000000005260072674642500206310ustar 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 similar-asserts-1.4.2/.github/workflows/tests.yml000064400000000000000000000011440072674642500202640ustar 00000000000000name: Tests on: [push] jobs: build-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 build-stable: name: Test on 1.41.0 runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - uses: actions-rs/toolchain@v1 with: toolchain: 1.41.0 profile: minimal override: true - name: Test run: make test-141 similar-asserts-1.4.2/.gitignore000064400000000000000000000000230072674642500147650ustar 00000000000000target/ Cargo.lock similar-asserts-1.4.2/.vscode/launch.json000064400000000000000000000007540072674642500165160ustar 00000000000000{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "type": "lldb", "request": "launch", "name": "Debug", "program": "${workspaceFolder}/", "args": [], "cwd": "${workspaceFolder}" } ] }similar-asserts-1.4.2/Cargo.lock0000644000000110770000000000100121430ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "bstr" version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba3569f383e8f1598449f1a423e72e99569137b47740b1da11ef19af3d5c3223" dependencies = [ "lazy_static", "memchr", "regex-automata", ] [[package]] name = "console" version = "0.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a28b32d32ca44b70c3e4acd7db1babf555fa026e385fb95f18028f88848b3c31" dependencies = [ "encode_unicode", "libc", "once_cell", "terminal_size", "winapi", ] [[package]] name = "encode_unicode" version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f" [[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.112" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b03d17f364a3a042d5e5d46b053bbbf82c92c9430c592dd4c064dc6ee997125" [[package]] name = "memchr" version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a" [[package]] name = "once_cell" version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da32515d9f6e6e489d7bc9d84c71b060db7247dc035bbe44eac88cf87486d8d5" [[package]] name = "proc-macro2" version = "1.0.36" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c7342d5883fbccae1cc37a2353b09c87c9b0f3afd73f5fb9bba687a1f733b029" dependencies = [ "unicode-xid", ] [[package]] name = "quote" version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47aa80447ce4daf1717500037052af176af5d38cc3e571d9ec1c7353fc10c87d" dependencies = [ "proc-macro2", ] [[package]] name = "regex-automata" version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" [[package]] name = "serde" version = "1.0.133" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "97565067517b60e2d1ea8b268e59ce036de907ac523ad83a0475da04e818989a" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.133" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed201699328568d8d08208fdd080e3ff594e6c422e438b6705905da01005d537" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "similar" version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "62ac7f900db32bf3fd12e0117dd3dc4da74bc52ebaac97f39668446d89694803" dependencies = [ "bstr", "unicode-segmentation", ] [[package]] name = "similar-asserts" version = "1.4.2" dependencies = [ "console", "serde", "similar", ] [[package]] name = "syn" version = "1.0.84" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ecb2e6da8ee5eb9a61068762a32fa9619cc591ceb055b3687f4cd4051ec2e06b" dependencies = [ "proc-macro2", "quote", "unicode-xid", ] [[package]] name = "terminal_size" version = "0.1.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "633c1a546cee861a1a6d0dc69ebeca693bf4296661ba7852b9d21d159e0506df" dependencies = [ "libc", "winapi", ] [[package]] name = "unicode-segmentation" version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8895849a949e7845e06bd6dc1aa51731a103c42707010a5b591c0038fb73385b" [[package]] name = "unicode-xid" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" [[package]] name = "winapi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" dependencies = [ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu", ] [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" similar-asserts-1.4.2/Cargo.toml0000644000000024300000000000100121570ustar # 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 = "2018" rust-version = "1.41.0" name = "similar-asserts" version = "1.4.2" authors = ["Armin Ronacher "] exclude = ["assets/*"] description = "provides assert_eq! like macros with colorized diff output" readme = "README.md" keywords = [ "assert", "diff", "color", ] license = "Apache-2.0" repository = "https://github.com/mitsuhiko/similar-asserts" [package.metadata.docs.rs] all-features = true [[example]] name = "serde" required-features = ["serde"] [dependencies.console] version = "0.15.0" default-features = false [dependencies.serde] version = "1.0.123" optional = true [dependencies.similar] version = "2.2.0" features = ["inline"] [dev-dependencies.serde] version = "1.0.123" features = ["derive"] [features] default = ["unicode"] unicode = ["similar/unicode"] similar-asserts-1.4.2/Cargo.toml.orig000064400000000000000000000014620072674642500156740ustar 00000000000000[package] name = "similar-asserts" version = "1.4.2" authors = ["Armin Ronacher "] edition = "2018" license = "Apache-2.0" description = "provides assert_eq! like macros with colorized diff output" repository = "https://github.com/mitsuhiko/similar-asserts" keywords = ["assert", "diff", "color"] readme = "README.md" exclude = ["assets/*"] rust-version = "1.41.0" [package.metadata.docs.rs] all-features = true [features] default = ["unicode"] unicode = ["similar/unicode"] [dependencies] similar = { version = "2.2.0", features = ["inline"] } console = { version = "0.15.0", default-features = false } serde = { version = "1.0.123", optional = true } [dev-dependencies] serde = { version = "1.0.123", features = ["derive"] } [[example]] name = "serde" required-features = ["serde"] similar-asserts-1.4.2/LICENSE000064400000000000000000000251370072674642500140170ustar 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. similar-asserts-1.4.2/Makefile000064400000000000000000000011000072674642500144320ustar 00000000000000all: test build: @cargo build --all-features check: @cargo check --all-features @cargo check --all-features --examples doc: @cargo doc --all-features test: check @cargo test @cargo test --all-features @cargo test --no-default-features test-141: @cargo test @cargo test --no-default-features 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 similar-asserts-1.4.2/README.md000064400000000000000000000027440072674642500142700ustar 00000000000000# similar-asserts [![Build Status](https://github.com/mitsuhiko/similar-asserts/workflows/Tests/badge.svg?branch=main)](https://github.com/mitsuhiko/similar-asserts/actions?query=workflow%3ATests) [![Crates.io](https://img.shields.io/crates/d/similar-asserts.svg)](https://crates.io/crates/similar-asserts) [![License](https://img.shields.io/github/license/mitsuhiko/similar-asserts)](https://github.com/mitsuhiko/similar-asserts/blob/main/LICENSE) [![Documentation](https://docs.rs/similar-asserts/badge.svg)](https://docs.rs/similar-asserts) `similar-asserts` is a crate that enhances the default assertion experience by using [similar](https://crates.io/crates/similar) for diffing. It supports comparing either `Debug` or `Serialize` representations of values. On failed assertions it renders out a colorized diff to the terminal. ```rust fn main() { let reference = vec![1, 2, 3, 4]; similar_asserts::assert_eq!(reference, (0..4).collect::>()); } ``` ![](https://raw.githubusercontent.com/mitsuhiko/similar-asserts/main/assets/screenshot.png) ## Related Projects * [insta](https://insta.rs) snapshot testing library * [similar](https://insta.rs/similar) diffing library ## License and Links - [Documentation](https://docs.rs/similar-asserts/) - [Issue Tracker](https://github.com/mitsuhiko/similar-asserts/issues) - [Examples](https://github.com/mitsuhiko/similar-asserts/tree/main/examples) - License: [Apache-2.0](https://github.com/mitsuhiko/similar-asserts/blob/main/LICENSE) similar-asserts-1.4.2/examples/basic.rs000064400000000000000000000001740072674642500162510ustar 00000000000000fn main() { let reference = vec![1, 2, 3, 4]; similar_asserts::assert_eq!(reference, (0..4).collect::>()); } similar-asserts-1.4.2/examples/custom.rs000064400000000000000000000002400072674642500164740ustar 00000000000000use similar_asserts::SimpleDiff; fn main() { panic!( "Not equal\n\n{}", SimpleDiff::from_str("a\nb\n", "b\nb\n", "left", "right") ); } similar-asserts-1.4.2/examples/extended.rs000064400000000000000000000007130072674642500167670ustar 00000000000000#[derive(Debug, PartialEq)] enum Tag { Major, Minor, Value, } fn main() { let reference = vec![(Tag::Major, 2), (Tag::Minor, 20), (Tag::Value, 0)]; similar_asserts::assert_eq!( expected: reference, actual: vec![ (Tag::Major, 2), (Tag::Minor, 0), (Tag::Value, 0), (Tag::Value, 1) ], "some stuff here {}", 42, ); } similar-asserts-1.4.2/examples/long.rs000064400000000000000000000002110072674642500161170ustar 00000000000000fn main() { let reference = (1..100).collect::>(); similar_asserts::assert_eq!(reference, (0..98).collect::>()); } similar-asserts-1.4.2/examples/newlines-matter.rs000064400000000000000000000001500072674642500203000ustar 00000000000000fn main() { let reference = "foo\r\nbar"; similar_asserts::assert_eq!(reference, "foo\nbar"); } similar-asserts-1.4.2/examples/serde.rs000064400000000000000000000006460072674642500162760ustar 00000000000000use serde::Serialize; #[derive(Serialize, PartialEq)] pub enum MyEnum { One, Two, } #[derive(Serialize, PartialEq)] pub struct Foo { a: Vec, b: MyEnum, } fn main() { let reference = Foo { a: vec![1, 2, 3, 4], b: MyEnum::One, }; let actual = Foo { a: vec![1, 2, 4, 5], b: MyEnum::Two, }; similar_asserts::assert_serde_eq!(&reference, &actual); } similar-asserts-1.4.2/examples/str.rs000064400000000000000000000001600072674642500157730ustar 00000000000000fn main() { let reference = "Hello\nWorld"; similar_asserts::assert_eq!(reference, "Goodbye\nWorld"); } similar-asserts-1.4.2/src/lib.rs000064400000000000000000000357560072674642500147250ustar 00000000000000//! `similar-asserts` is a crate that enhances the default assertion //! experience by using [similar](https://crates.io/crates/similar) for diffing. //! On failed assertions it renders out a colorized diff to the terminal. //! //! It comes with a handful of macros to replace [`std::assert_eq!`] with: //! //! - [`assert_eq!`]: diffs `Debug` on assertion failure. #![cfg_attr( feature = "serde", doc = r#" - [`assert_serde_eq!`]: diffs `Serialize` on assertion failure. "# )] //! ![](https://raw.githubusercontent.com/mitsuhiko/similar-asserts/main/assets/screenshot.png) //! //! # Usage //! //! ```rust //! use similar_asserts::assert_eq; //! assert_eq!((1..3).collect::>(), vec![1, 2]); //! ``` //! //! Optionally the assertion macros also let you "name" the left and right //! side which will produce slightly more explicit output: //! //! ```rust //! use similar_asserts::assert_eq; //! assert_eq!(expected: vec![1, 2], actual: (1..3).collect::>()); //! ``` //! //! # Feature Flags //! //! * `unicode` enable improved character matching (enabled by default) //! * `serde` turns on support for serde. //! //! # Faster Builds //! //! This crate works best if you add it as `dev-dependency` only. To make your code //! still compile you can use conditional uses that override the default uses for the //! `assert_eq!` macro from the stdlib: //! //! ``` //! #[cfg(test)] //! use similar_asserts::assert_eq; //! ``` //! //! # Manual Diff Printing //! //! If you want to build your own comparison macros and you need a quick and simple //! way to render diffs, you can use the [`SimpleDiff`] type and display it: //! //! ```should_panic //! use similar_asserts::SimpleDiff; //! panic!("Not equal\n\n{}", SimpleDiff::from_str("a\nb\n", "b\nb\n", "left", "right")); //! ``` use std::borrow::Cow; use std::fmt; use std::time::Duration; use console::{style, Style}; use similar::{Algorithm, ChangeTag, TextDiff}; #[cfg(feature = "serde")] mod serde_impl; /// A console printable diff. /// /// The [`Display`](std::fmt::Display) implementation of this type renders out a /// diff with ANSI markers so it creates a nice colored diff. This can be used to /// build your own custom assertions in addition to the ones from this crate. /// /// It does not provide much customization beyond what's possible done by default. pub struct SimpleDiff<'a> { pub(crate) left: Cow<'a, str>, pub(crate) right: Cow<'a, str>, pub(crate) left_short: Option>, pub(crate) right_short: Option>, pub(crate) left_label: &'static str, pub(crate) right_label: &'static str, } impl<'a> SimpleDiff<'a> { /// Creates a diff from two strings. /// /// `left_label` and `right_label` are the labels used for the two sides. /// `"left"` and `"right"` are sensible defaults if you don't know what /// to pick. pub fn from_str( left: &'a str, right: &'a str, left_label: &'static str, right_label: &'static str, ) -> SimpleDiff<'a> { SimpleDiff { left: left.into(), right: right.into(), left_short: None, right_short: None, left_label, right_label, } } /// Returns the left side as string. #[doc(hidden)] pub fn _private_left(&self) -> &str { self.left_short.as_deref().unwrap_or(&self.left) } /// Returns the right side as string. #[doc(hidden)] pub fn _private_right(&self) -> &str { self.right_short.as_deref().unwrap_or(&self.right) } } fn trailing_newline(s: &str) -> &str { if s.ends_with("\r\n") { "\r\n" } else if s.ends_with("\r") { "\r" } else if s.ends_with("\n") { "\n" } else { "" } } fn detect_newlines(s: &str) -> (bool, bool, bool) { let mut last_char = None; let mut detected_crlf = false; let mut detected_cr = false; let mut detected_lf = false; for c in s.chars() { if c == '\n' { if last_char.take() == Some('\r') { detected_crlf = true; } else { detected_lf = true; } } if last_char == Some('\r') { detected_cr = true; } last_char = Some(c); } if last_char == Some('\r') { detected_cr = true; } (detected_cr, detected_crlf, detected_lf) } fn newlines_matter(left: &str, right: &str) -> bool { if trailing_newline(left) != trailing_newline(right) { return true; } let (cr1, crlf1, lf1) = detect_newlines(left); let (cr2, crlf2, lf2) = detect_newlines(right); match (cr1 || cr2, crlf1 || crlf2, lf1 || lf2) { (false, false, false) => false, (true, false, false) => false, (false, true, false) => false, (false, false, true) => false, _ => true, } } impl<'a> fmt::Display for SimpleDiff<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let newlines_matter = newlines_matter(&self.left, &self.right); if self.left == self.right { writeln!( f, "{}: the two values are the same in string form.", style("Invisible differences").bold(), )?; return Ok(()); } let diff = TextDiff::configure() .timeout(Duration::from_millis(200)) .algorithm(Algorithm::Patience) .diff_lines(&self.left, &self.right); writeln!( f, "{} ({}{}|{}{}):", style("Differences").bold(), style("-").red().dim(), style(self.left_label).red(), style("+").green().dim(), style(self.right_label).green(), )?; for (idx, group) in diff.grouped_ops(4).into_iter().enumerate() { if idx > 0 { writeln!(f, "@ {}", style("~~~").dim())?; } for op in group { for change in diff.iter_inline_changes(&op) { let (marker, style) = match change.tag() { ChangeTag::Delete => ('-', Style::new().red()), ChangeTag::Insert => ('+', Style::new().green()), ChangeTag::Equal => (' ', Style::new().dim()), }; write!(f, "{}", style.apply_to(marker).dim().bold())?; for &(emphasized, value) in change.values() { let value = if newlines_matter { Cow::Owned( value .replace("\r", "␍\r") .replace("\n", "␊\n") .replace("␍\r␊\n", "␍␊\r\n"), ) } else { Cow::Borrowed(value) }; if emphasized { write!(f, "{}", style.clone().underlined().bold().apply_to(value))?; } else { write!(f, "{}", style.apply_to(value))?; } } if change.missing_newline() { writeln!(f)?; } } } } Ok(()) } } /// This hidden module is used by the macro system to figure out which /// implementation of the string representation to use. The main trait is /// `MakeDiff` which has two primary implementations: One for `UsesFromStr` /// implementing types (strings) and one for all debuggable types. /// /// Additionally for the serde macro there is a `MakeSerdeDiff`. This uses /// the automatic deref system of Rust to disambiugate between strings and /// non strings. #[doc(hidden)] pub mod traits { use std::borrow::Cow; use std::fmt::Debug; pub trait UsesFromStr: AsRef {} impl UsesFromStr for str {} impl UsesFromStr for String {} impl<'a> UsesFromStr for Cow<'a, str> {} impl UsesFromStr for &T {} pub trait MakeDiff<'a> { fn make_diff( self, left_label: &'static str, right_label: &'static str, ) -> crate::SimpleDiff<'a> where Self: 'a; } impl<'a, T: Debug, U: Debug> MakeDiff<'a> for &'a (T, U) { fn make_diff( self, left_label: &'static str, right_label: &'static str, ) -> crate::SimpleDiff<'a> where Self: 'a, { let left = &self.0; let right = &self.1; let left_short = Some(format!("{:?}", left).into()); let right_short = Some(format!("{:?}", right).into()); let left = format!("{:#?}", left).into(); let right = format!("{:#?}", right).into(); crate::SimpleDiff { left, right, left_short, right_short, left_label, right_label, } } } impl<'a, T, U> MakeDiff<'a> for (&'a T, &'a U) where T: UsesFromStr + ?Sized, U: UsesFromStr + ?Sized, { fn make_diff( self, left_label: &'static str, right_label: &'static str, ) -> crate::SimpleDiff<'a> where Self: 'a, { crate::SimpleDiff::from_str(self.0.as_ref(), self.1.as_ref(), left_label, right_label) } } // if serde is compiled in, we also need `MakeSerdeDiff`. #[cfg(feature = "serde")] pub use super::serde_impl::MakeSerdeDiff; } #[doc(hidden)] #[macro_export] macro_rules! __assert_eq { ( $method:ident, $left_label:ident, $left:expr, $right_label:ident, $right:expr, $has_hint:expr, $hint_suffix:expr ) => {{ match (&($left), &($right)) { (left_val, right_val) => { if !(*left_val == *right_val) { use $crate::traits::*; let left_label = stringify!($left_label); let right_label = stringify!($right_label); let tup = (&*left_val, &*right_val); let diff = tup.$method(left_label, right_label); panic!( "assertion failed: `({} == {})`{}{}'\ \n {:>label_padding$}: `{:?}`\ \n {:>label_padding$}: `{:?}`\ \n\n{}\n", left_label, right_label, if $has_hint { ": " } else { "" }, $hint_suffix, left_label, diff._private_left(), right_label, diff._private_right(), &diff, label_padding = left_label.chars().count().max(right_label.chars().count()) ); } } } }}; } /// Asserts that two expressions are equal to each other (using [`PartialEq`]). /// /// On panic, this macro will print the values of the expressions with their /// [`Debug`] or [`ToString`] representations with a colorized diff of the /// changes in the debug output. It picks [`Debug`] for all types that are /// not strings themselves and [`ToString`] for [`str`] and [`String`]. /// /// Like [`assert!`], this macro has a second form, where a custom panic /// message can be provided. /// /// ```rust /// use similar_asserts::assert_eq; /// assert_eq!((1..3).collect::>(), vec![1, 2]); /// ``` #[macro_export] macro_rules! assert_eq { ($left_label:ident: $left:expr, $right_label:ident: $right:expr $(,)?) => ({ $crate::__assert_eq!(make_diff, $left_label, $left, $right_label, $right, false, ""); }); ($left_label:ident: $left:expr, $right_label:ident: $right:expr, $($arg:tt)*) => ({ $crate::__assert_eq!(make_diff, $left_label, $left, $right_label, $right, true, format_args!($($arg)*)); }); ($left:expr, $right:expr $(,)?) => ({ $crate::assert_eq!(left: $left, right: $right); }); ($left:expr, $right:expr, $($arg:tt)*) => ({ $crate::assert_eq!(left: $left, right: $right, $($arg)*); }); } /// Asserts that two expressions are equal to each other (using [`PartialEq`]) using [`Serialize`](serde::Serialize) for comparision. /// /// On panic, this macro will print the values of the expressions with their /// serde [`Serialize`](serde::Serialize) representations rendered in the same /// format that [`std::fmt::Debug`] would with a colorized diff of the changes in /// the debug output. /// /// Like [`assert!`], this macro has a second form, where a custom panic /// message can be provided. /// /// ```rust /// use similar_asserts::assert_serde_eq; /// assert_serde_eq!((1..3).collect::>(), vec![1, 2]); /// ``` /// /// This requires the `serde` feature. #[macro_export] #[cfg(feature = "serde")] macro_rules! assert_serde_eq { ($left_label:ident: $left:expr, $right_label:ident: $right:expr $(,)?) => ({ $crate::__assert_eq!(make_serde_diff, $left_label, $left, $right_label, $right, false, ""); }); ($left_label:ident: $left:expr, $right_label:ident: $right:expr, $($arg:tt)*) => ({ $crate::__assert_eq!(make_serde_diff, $left_label, $left, $right_label, $right, true, format_args!($($arg)*)); }); ($left:expr, $right:expr $(,)?) => ({ $crate::assert_serde_eq!(left: $left, right: $right); }); ($left:expr, $right:expr, $($arg:tt)*) => ({ $crate::assert_serde_eq!(left: $left, right: $right, $($arg)*); }); } /// Deprecated macro. Use [`assert_eq!`] instead. #[macro_export] #[doc(hidden)] #[deprecated(since = "1.4.0", note = "use assert_eq! instead")] macro_rules! assert_str_eq { ($left_label:ident: $left:expr, $right_label:ident: $right:expr $(,)?) => ({ $crate::assert_eq!($left_label: $left, $right_label: $right); }); ($left_label:ident: $left:expr, $right_label:ident: $right:expr, $($arg:tt)*) => ({ $crate::assert_eq!($left_label: $left, $right_label: $right, $($arg)*); }); ($left:expr, $right:expr $(,)?) => ({ $crate::assert_eq!($left, $right); }); ($left:expr, $right:expr, $($arg:tt)*) => ({ $crate::assert_eq!($left, $right, $($arg)*); }); } #[test] fn test_newlines_matter() { assert!(newlines_matter("\r\n", "\n")); assert!(newlines_matter("foo\n", "foo")); assert!(newlines_matter("foo\r\nbar", "foo\rbar")); assert!(newlines_matter("foo\r\nbar", "foo\nbar")); assert!(newlines_matter("foo\r\nbar\n", "foobar")); assert!(newlines_matter("foo\nbar\r\n", "foo\nbar\r\n")); assert!(newlines_matter("foo\nbar\n", "foo\nbar")); assert!(!newlines_matter("foo\nbar", "foo\nbar")); assert!(!newlines_matter("foo\nbar\n", "foo\nbar\n")); assert!(!newlines_matter("foo\r\nbar", "foo\r\nbar")); assert!(!newlines_matter("foo\r\nbar\r\n", "foo\r\nbar\r\n")); assert!(!newlines_matter("foo\r\nbar", "foo\r\nbar")); } similar-asserts-1.4.2/src/serde_impl.rs000064400000000000000000000211770072674642500162720ustar 00000000000000use std::fmt; use serde::ser::{ SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple, SerializeTupleStruct, SerializeTupleVariant, }; use serde::{Serialize, Serializer}; use crate::SimpleDiff; pub struct Debug<'a, T: Serialize + ?Sized>(pub &'a T); impl<'a, T: Serialize + ?Sized> fmt::Debug for Debug<'a, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.serialize(DebugSerializer(f))?; Ok(()) } } macro_rules! simple_serialize { ($name:ident, $type:ty) => { fn $name(self, v: $type) -> Result { fmt::Debug::fmt(&v, self.0) } }; } pub struct DebugSerializer<'a, 'b: 'a>(pub &'a mut fmt::Formatter<'b>); impl<'a, 'b: 'a> Serializer for DebugSerializer<'a, 'b> { type Ok = (); type Error = fmt::Error; type SerializeSeq = SeqSerializer<'a, 'b>; type SerializeTuple = TupleSerializer<'a, 'b>; type SerializeTupleStruct = TupleSerializer<'a, 'b>; type SerializeTupleVariant = TupleSerializer<'a, 'b>; type SerializeMap = MapSerializer<'a, 'b>; type SerializeStruct = StructSerializer<'a, 'b>; type SerializeStructVariant = StructSerializer<'a, 'b>; simple_serialize!(serialize_bool, bool); simple_serialize!(serialize_i8, i8); simple_serialize!(serialize_i16, i16); simple_serialize!(serialize_i32, i32); simple_serialize!(serialize_i64, i64); simple_serialize!(serialize_i128, i128); simple_serialize!(serialize_u8, u8); simple_serialize!(serialize_u16, u16); simple_serialize!(serialize_u32, u32); simple_serialize!(serialize_u64, u64); simple_serialize!(serialize_u128, u128); simple_serialize!(serialize_f32, f32); simple_serialize!(serialize_f64, f64); simple_serialize!(serialize_char, char); simple_serialize!(serialize_str, &str); simple_serialize!(serialize_bytes, &[u8]); fn serialize_none(self) -> Result { self.serialize_unit_struct("None") } fn serialize_some(self, value: &T) -> Result { self.serialize_newtype_struct("Some", value) } fn serialize_unit(self) -> Result { write!(self.0, "()") } fn serialize_unit_struct(self, name: &'static str) -> Result { SerializeTupleStruct::end(self.serialize_tuple_struct(name, 0)?) } fn serialize_unit_variant( self, _name: &'static str, _variant_index: u32, variant: &'static str, ) -> Result { self.serialize_unit_struct(variant) } fn serialize_newtype_struct( self, name: &'static str, value: &T, ) -> Result { let mut tuple = self.serialize_tuple_struct(name, 1)?; SerializeTupleStruct::serialize_field(&mut tuple, value)?; SerializeTupleStruct::end(tuple) } fn serialize_newtype_variant( self, _name: &'static str, _variant_index: u32, variant: &'static str, value: &T, ) -> Result { self.serialize_newtype_struct(variant, value) } fn serialize_seq(self, _len: Option) -> Result { Ok(SeqSerializer(self.0.debug_list())) } fn serialize_tuple_struct( self, name: &'static str, _len: usize, ) -> Result { Ok(TupleSerializer(self.0.debug_tuple(name))) } fn serialize_tuple(self, len: usize) -> Result { self.serialize_tuple_struct("", len) } fn serialize_tuple_variant( self, _name: &'static str, _variant_index: u32, variant: &'static str, len: usize, ) -> Result { self.serialize_tuple_struct(variant, len) } fn serialize_map(self, _len: Option) -> Result { Ok(MapSerializer(self.0.debug_map())) } fn serialize_struct( self, name: &'static str, _len: usize, ) -> Result { Ok(StructSerializer(self.0.debug_struct(name))) } fn serialize_struct_variant( self, _name: &'static str, _variant_index: u32, variant: &'static str, len: usize, ) -> Result { self.serialize_struct(variant, len) } } pub struct SeqSerializer<'a, 'b: 'a>(fmt::DebugList<'a, 'b>); impl<'a, 'b: 'a> SerializeSeq for SeqSerializer<'a, 'b> { type Ok = (); type Error = fmt::Error; fn serialize_element(&mut self, value: &T) -> Result<(), Self::Error> { self.0.entry(&Debug(value)); Ok(()) } fn end(mut self) -> Result<(), Self::Error> { self.0.finish() } } pub struct TupleSerializer<'a, 'b: 'a>(fmt::DebugTuple<'a, 'b>); impl<'a, 'b: 'a> SerializeTuple for TupleSerializer<'a, 'b> { type Ok = (); type Error = fmt::Error; fn serialize_element(&mut self, value: &T) -> Result<(), Self::Error> { self.0.field(&Debug(value)); Ok(()) } fn end(mut self) -> Result<(), Self::Error> { self.0.finish() } } impl<'a, 'b: 'a> SerializeTupleStruct for TupleSerializer<'a, 'b> { type Ok = (); type Error = fmt::Error; fn serialize_field(&mut self, value: &T) -> Result<(), Self::Error> { SerializeTuple::serialize_element(self, value) } fn end(self) -> Result<(), Self::Error> { SerializeTuple::end(self) } } impl<'a, 'b: 'a> SerializeTupleVariant for TupleSerializer<'a, 'b> { type Ok = (); type Error = fmt::Error; fn serialize_field(&mut self, value: &T) -> Result<(), Self::Error> { SerializeTuple::serialize_element(self, value) } fn end(self) -> Result<(), Self::Error> { SerializeTuple::end(self) } } pub struct MapSerializer<'a, 'b: 'a>(fmt::DebugMap<'a, 'b>); impl<'a, 'b: 'a> SerializeMap for MapSerializer<'a, 'b> { type Ok = (); type Error = fmt::Error; fn serialize_key(&mut self, key: &T) -> Result<(), Self::Error> { self.0.key(&Debug(key)); Ok(()) } fn serialize_value(&mut self, value: &T) -> Result<(), Self::Error> { self.0.value(&Debug(value)); Ok(()) } fn serialize_entry( &mut self, key: &K, value: &V, ) -> Result<(), Self::Error> { self.0.entry(&Debug(key), &Debug(value)); Ok(()) } fn end(mut self) -> Result<(), Self::Error> { self.0.finish() } } pub struct StructSerializer<'a, 'b: 'a>(fmt::DebugStruct<'a, 'b>); impl<'a, 'b: 'a> SerializeStruct for StructSerializer<'a, 'b> { type Ok = (); type Error = fmt::Error; fn serialize_field( &mut self, key: &'static str, value: &T, ) -> Result<(), Self::Error> { self.0.field(key, &Debug(value)); Ok(()) } fn end(mut self) -> Result<(), Self::Error> { self.0.finish() } } impl<'a, 'b: 'a> SerializeStructVariant for StructSerializer<'a, 'b> { type Ok = (); type Error = fmt::Error; fn serialize_field( &mut self, key: &'static str, value: &T, ) -> Result<(), Self::Error> { SerializeStruct::serialize_field(self, key, value) } fn end(self) -> Result<(), Self::Error> { SerializeStruct::end(self) } } pub trait MakeSerdeDiff<'a> { fn make_serde_diff(self, left_label: &'static str, right_label: &'static str) -> SimpleDiff<'a> where Self: 'a; } impl<'a, T, U> MakeSerdeDiff<'a> for (&'a T, &'a U) where T: Serialize + ?Sized, U: Serialize + ?Sized, { fn make_serde_diff(self, left_label: &'static str, right_label: &'static str) -> SimpleDiff<'a> where Self: 'a, { let left = &self.0; let right = &self.1; let left_short = Some(format!("{:?}", Debug(left)).into()); let right_short = Some(format!("{:?}", Debug(right)).into()); let left = format!("{:#?}", Debug(left)).into(); let right = format!("{:#?}", Debug(right)).into(); SimpleDiff { left, right, left_short, right_short, left_label, right_label, } } } similar-asserts-1.4.2/tests/test_unsized.rs000064400000000000000000000001370072674642500172330ustar 00000000000000#[test] fn test_unsized() { similar_asserts::assert_eq!("foo".to_string(), "bfoo"[1..]); }