similar-asserts-1.7.0/.cargo_vcs_info.json0000644000000001360000000000100141630ustar { "git": { "sha1": "30a6c8a78e7572fdb7b2dadca765236de793ca89" }, "path_in_vcs": "" }similar-asserts-1.7.0/.github/workflows/clippy.yml000064400000000000000000000005141046102023000203730ustar 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.7.0/.github/workflows/rustfmt.yml000064400000000000000000000005261046102023000206020ustar 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.7.0/.github/workflows/tests.yml000064400000000000000000000012551046102023000202400ustar 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.56.0 runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - uses: actions-rs/toolchain@v1 with: toolchain: 1.56.0 profile: minimal override: true - name: Use Cargo.lock.msrv run: cp Cargo.lock.msrv Cargo.lock - name: Test run: make test similar-asserts-1.7.0/.gitignore000064400000000000000000000000231046102023000147360ustar 00000000000000target/ Cargo.lock similar-asserts-1.7.0/.vscode/launch.json000064400000000000000000000007541046102023000164670ustar 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.7.0/CHANGELOG.md000064400000000000000000000007061046102023000145670ustar 00000000000000# Changelog All notable changes to `similar-asserts` are documented here. ## 1.7.0 - Added support for `SIMILAR_ASSERTS_CONTEXT_SIZE`. #13 ## 1.6.1 - Maintenance release with some clippy fixes. ## 1.6.0 - Loosen static lifetime bounds for labels. #9 ## 1.5.0 - Added automatic truncation of assertions. This behavior can be overridden with the new `SIMILAR_ASSERTS_MAX_STRING_LENGTH` environment variable. It defaults to `200` characters. similar-asserts-1.7.0/Cargo.lock0000644000000105710000000000100121420ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "bstr" version = "1.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "531a9155a481e2ee699d4f98f43c0ca4ff8ee1bfd55c31e9e98fb29d2b176fe0" dependencies = [ "memchr", "regex-automata", "serde", ] [[package]] name = "console" version = "0.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c050367d967ced717c04b65d8c619d863ef9292ce0c5760028655a2fb298718c" dependencies = [ "encode_unicode", "lazy_static", "libc", "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.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[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.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" [[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.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" dependencies = [ "bstr", "unicode-segmentation", ] [[package]] name = "similar-asserts" version = "1.7.0" 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.7.0/Cargo.lock.msrv000064400000000000000000000106001046102023000156430ustar 00000000000000# 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.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c050367d967ced717c04b65d8c619d863ef9292ce0c5760028655a2fb298718c" dependencies = [ "encode_unicode", "lazy_static", "libc", "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 = "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.6.0" 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.7.0/Cargo.toml0000644000000037460000000000100121730ustar # 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.46.0" name = "similar-asserts" version = "1.7.0" authors = ["Armin Ronacher "] build = false exclude = ["assets/*"] autolib = false autobins = false autoexamples = false autotests = false autobenches = false 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 [features] default = ["unicode"] unicode = ["similar/unicode"] [lib] name = "similar_asserts" path = "src/lib.rs" [[example]] name = "basic" path = "examples/basic.rs" [[example]] name = "custom" path = "examples/custom.rs" [[example]] name = "extended" path = "examples/extended.rs" [[example]] name = "long" path = "examples/long.rs" [[example]] name = "newlines-matter" path = "examples/newlines-matter.rs" [[example]] name = "no-debug" path = "examples/no-debug.rs" [[example]] name = "serde" path = "examples/serde.rs" required-features = ["serde"] [[example]] name = "str" path = "examples/str.rs" [[example]] name = "string" path = "examples/string.rs" [[test]] name = "test_unsized" path = "tests/test_unsized.rs" [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"] similar-asserts-1.7.0/Cargo.toml.orig000064400000000000000000000014621046102023000156450ustar 00000000000000[package] name = "similar-asserts" version = "1.7.0" 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.46.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.7.0/LICENSE000064400000000000000000000251371046102023000137700ustar 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.7.0/Makefile000064400000000000000000000010051046102023000144070ustar 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 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.7.0/README.md000064400000000000000000000024611046102023000142350ustar 00000000000000# similar-asserts [![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.7.0/examples/basic.rs000064400000000000000000000001741046102023000162220ustar 00000000000000fn main() { let reference = vec![1, 2, 3, 4]; similar_asserts::assert_eq!(reference, (0..4).collect::>()); } similar-asserts-1.7.0/examples/custom.rs000064400000000000000000000002401046102023000164450ustar 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.7.0/examples/extended.rs000064400000000000000000000007131046102023000167400ustar 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.7.0/examples/long.rs000064400000000000000000000002111046102023000160700ustar 00000000000000fn main() { let reference = (1..100).collect::>(); similar_asserts::assert_eq!(reference, (0..98).collect::>()); } similar-asserts-1.7.0/examples/newlines-matter.rs000064400000000000000000000001501046102023000202510ustar 00000000000000fn main() { let reference = "foo\r\nbar"; similar_asserts::assert_eq!(reference, "foo\nbar"); } similar-asserts-1.7.0/examples/no-debug.rs000064400000000000000000000003241046102023000166360ustar 00000000000000struct TypeWithoutDebug; impl PartialEq for TypeWithoutDebug { fn eq(&self, _other: &Self) -> bool { false } } fn main() { similar_asserts::assert_eq!(TypeWithoutDebug, TypeWithoutDebug); } similar-asserts-1.7.0/examples/serde.rs000064400000000000000000000006461046102023000162470ustar 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.7.0/examples/str.rs000064400000000000000000000001601046102023000157440ustar 00000000000000fn main() { let reference = "Hello\nWorld"; similar_asserts::assert_eq!(reference, "Goodbye\nWorld"); } similar-asserts-1.7.0/examples/string.rs000064400000000000000000000001741046102023000164470ustar 00000000000000fn main() { let reference = "Hello\nWorld".to_string(); similar_asserts::assert_eq!(reference, "Goodbye\nWorld"); } similar-asserts-1.7.0/src/lib.rs000064400000000000000000000400321046102023000146550ustar 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; //! ``` //! //! Since `similar_asserts` uses the `similar` library for diffing you can also //! enable optimziation for them in all build types for quicker diffing. Add //! this to your `Cargo.toml`: //! //! ```toml //! [profile.dev.package.similar] //! opt-level = 3 //! ``` //! //! # String Truncation //! //! By default the assertion only shows 200 characters. This can be changed with the //! `SIMILAR_ASSERTS_MAX_STRING_LENGTH` environment variable. Setting it to `0` disables //! all truncation, otherwise it sets the maximum number of characters before truncation //! kicks in. //! //! # Context Size //! //! Diffs displayed by assertions have a default context size of 4 (show up to 4 lines above and //! below changes). This can be changed with the `SIMILAR_ASSERTS_CONTEXT_SIZE` environment //! variable. //! //! # 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::{self, Display}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::Duration; use console::{style, Style}; use similar::{Algorithm, ChangeTag, TextDiff}; #[cfg(feature = "serde")] #[doc(hidden)] pub mod serde_impl; // This needs to be public as we are using it internally in a macro. #[doc(hidden)] pub mod print; /// The maximum number of characters a string can be long before truncating. fn get_max_string_length() -> usize { static TRUNCATE: AtomicUsize = AtomicUsize::new(!0); get_usize_from_env(&TRUNCATE, "SIMILAR_ASSERTS_MAX_STRING_LENGTH", 200) } /// The context size for diff groups. fn get_context_size() -> usize { static CONTEXT_SIZE: AtomicUsize = AtomicUsize::new(!0); get_usize_from_env(&CONTEXT_SIZE, "SIMILAR_ASSERTS_CONTEXT_SIZE", 4) } /// Parse a `usize` value from an environment variable, cached in a static atomic. fn get_usize_from_env(value: &'static AtomicUsize, var: &str, default: usize) -> usize { let rv = value.load(Ordering::Relaxed); if rv != !0 { return rv; } let rv: usize = std::env::var(var) .ok() .and_then(|x| x.parse().ok()) .unwrap_or(default); value.store(rv, Ordering::Relaxed); rv } /// 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_short: Cow<'a, str>, pub(crate) right_short: Cow<'a, str>, pub(crate) left_expanded: Option>, pub(crate) right_expanded: Option>, pub(crate) left_label: &'a str, pub(crate) right_label: &'a 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: &'a str, right_label: &'a str, ) -> SimpleDiff<'a> { SimpleDiff { left_short: left.into(), right_short: right.into(), left_expanded: None, right_expanded: None, left_label, right_label, } } #[doc(hidden)] pub fn __from_macro( left_short: Option>, right_short: Option>, left_expanded: Option>, right_expanded: Option>, left_label: &'a str, right_label: &'a str, ) -> SimpleDiff<'a> { SimpleDiff { left_short: left_short.unwrap_or_else(|| "".into()), right_short: right_short.unwrap_or_else(|| "".into()), left_expanded, right_expanded, left_label, right_label, } } /// Returns the left side as string. fn left(&self) -> &str { self.left_expanded.as_deref().unwrap_or(&self.left_short) } /// Returns the right side as string. fn right(&self) -> &str { self.right_expanded.as_deref().unwrap_or(&self.right_short) } /// Returns the label padding fn label_padding(&self) -> usize { self.left_label .chars() .count() .max(self.right_label.chars().count()) } #[doc(hidden)] #[track_caller] pub fn fail_assertion(&self, hint: &dyn Display) { // prefer the shortened version here. let len = get_max_string_length(); let (left, left_truncated) = truncate_str(&self.left_short, len); let (right, right_truncated) = truncate_str(&self.right_short, len); panic!( "assertion failed: `({} == {})`{}'\ \n {:>label_padding$}: `{:?}`{}\ \n {:>label_padding$}: `{:?}`{}\ \n\n{}\n", self.left_label, self.right_label, hint, self.left_label, DebugStrTruncated(left, left_truncated), if left_truncated { " (truncated)" } else { "" }, self.right_label, DebugStrTruncated(right, right_truncated), if right_truncated { " (truncated)" } else { "" }, &self, label_padding = self.label_padding(), ); } } fn truncate_str(s: &str, chars: usize) -> (&str, bool) { if chars == 0 { return (s, false); } s.char_indices() .enumerate() .find_map(|(idx, (offset, _))| { if idx == chars { Some((&s[..offset], true)) } else { None } }) .unwrap_or((s, false)) } struct DebugStrTruncated<'s>(&'s str, bool); impl fmt::Debug for DebugStrTruncated<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.1 { let s = format!("{}...", self.0); fmt::Debug::fmt(&s, f) } else { fmt::Debug::fmt(&self.0, f) } } } 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) } #[allow(clippy::match_like_matches_macro)] 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 fmt::Display for SimpleDiff<'_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let left = self.left(); let right = self.right(); let newlines_matter = newlines_matter(left, right); if left == 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(left, 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(get_context_size()).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(()) } } #[doc(hidden)] #[macro_export] macro_rules! __assert_eq { ( $method:ident, $left_label:ident, $left:expr, $right_label:ident, $right:expr, $hint_suffix:expr ) => {{ match (&($left), &($right)) { (left_val, right_val) => { #[allow(unused_mut)] if !(*left_val == *right_val) { use $crate::print::{PrintMode, PrintObject}; let left_label = stringify!($left_label); let right_label = stringify!($right_label); let mut left_val_tup1 = (&left_val,); let mut right_val_tup1 = (&right_val,); let mut left_val_tup2 = (&left_val,); let mut right_val_tup2 = (&right_val,); let left_short = left_val_tup1.print_object(PrintMode::Default); let right_short = right_val_tup1.print_object(PrintMode::Default); let left_expanded = left_val_tup2.print_object(PrintMode::Expanded); let right_expanded = right_val_tup2.print_object(PrintMode::Expanded); let diff = $crate::SimpleDiff::__from_macro( left_short, right_short, left_expanded, right_expanded, left_label, right_label, ); diff.fail_assertion(&$hint_suffix); } } } }}; } /// 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, ""); }); ($left_label:ident: $left:expr, $right_label:ident: $right:expr, $($arg:tt)*) => ({ $crate::__assert_eq!(make_diff, $left_label, $left, $right_label, $right, format_args!(": {}", 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)*); }); } /// 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")); } #[test] fn test_truncate_str() { assert_eq!(truncate_str("foobar", 20), ("foobar", false)); assert_eq!(truncate_str("foobar", 2), ("fo", true)); assert_eq!(truncate_str("🔥🔥🔥🔥🔥", 2), ("🔥🔥", true)); } similar-asserts-1.7.0/src/print.rs000064400000000000000000000055221046102023000152500ustar 00000000000000use std::borrow::Cow; use std::fmt::Debug; pub trait StringRepr: AsRef {} impl StringRepr for str {} impl StringRepr for String {} impl StringRepr for Cow<'_, str> {} impl StringRepr for &T {} /// Defines how the object is printed. pub enum PrintMode { /// The regular print mode. If an object does not return /// something for this print mode it's not formattable. Default, /// Some objects have an extra expanded print mode with pretty newlines. Expanded, } pub trait PrintObject<'a> { fn print_object(self, mode: PrintMode) -> Option>; } impl<'a, 'b: 'a, T: StringRepr + ?Sized + 'a> PrintObject<'a> for (&'b T,) { fn print_object(self, mode: PrintMode) -> Option> { match mode { PrintMode::Default => Some(Cow::Borrowed(self.0.as_ref())), PrintMode::Expanded => None, } } } impl<'a, 'b: 'a, T: Debug + 'a> PrintObject<'a> for &'b (T,) { fn print_object(self, mode: PrintMode) -> Option> { Some( match mode { PrintMode::Default => format!("{:?}", self.0), PrintMode::Expanded => format!("{:#?}", self.0), } .into(), ) } } impl<'a, 'b: 'a, T: 'a> PrintObject<'a> for &'b mut (T,) { fn print_object(self, _mode: PrintMode) -> Option> { fn type_name_of_val(_: T) -> &'static str { std::any::type_name::() } let s = type_name_of_val(&self.0).trim_start_matches('&'); if s.is_empty() { None } else { Some(Cow::Borrowed(s)) } } } #[test] fn test_object() { macro_rules! print_object { ($expr:expr, $mode:ident) => {{ use $crate::print::PrintObject; #[allow(unused_mut)] let mut _tmp = ($expr,); _tmp.print_object($crate::print::PrintMode::$mode) .map(|x| x.to_string()) }}; } struct NoDebugNoString; struct DoNotCallMe; impl DoNotCallMe { #[allow(unused)] fn print_object(&self, mode: PrintMode) { panic!("never call me"); } } assert_eq!( print_object!(&DoNotCallMe, Default).as_deref(), Some("similar_asserts::print::test_object::DoNotCallMe") ); assert_eq!( print_object!(&NoDebugNoString, Default).as_deref(), Some("similar_asserts::print::test_object::NoDebugNoString") ); assert_eq!( print_object!(vec![1, 2, 3], Default).as_deref(), Some("[1, 2, 3]") ); assert_eq!( print_object!(vec![1, 2, 3], Expanded).as_deref(), Some("[\n 1,\n 2,\n 3,\n]") ); assert_eq!(print_object!(&"Hello", Default).as_deref(), Some("Hello")); assert_eq!(print_object!(&"Hello", Expanded).as_deref(), None); } similar-asserts-1.7.0/src/serde_impl.rs000064400000000000000000000247021046102023000162400ustar 00000000000000use std::fmt; use serde::ser::{ SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple, SerializeTupleStruct, SerializeTupleVariant, }; use serde::{Serialize, Serializer}; 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) } } #[doc(hidden)] #[macro_export] macro_rules! __assert_serde_eq { ( $method:ident, $left_label:ident, $left:expr, $right_label:ident, $right:expr, $hint_suffix:expr ) => {{ match (&($left), &($right)) { (left_val, right_val) => { if !(*left_val == *right_val) { use std::borrow::Cow; use $crate::serde_impl::Debug; let left_label = stringify!($left_label); let right_label = stringify!($right_label); let left_short = Some(Cow::Owned(format!("{:?}", Debug(left_val)))); let right_short = Some(Cow::Owned(format!("{:?}", Debug(right_val)))); let left_expanded = Some(Cow::Owned(format!("{:#?}", Debug(left_val)))); let right_expanded = Some(Cow::Owned(format!("{:#?}", Debug(right_val)))); let diff = $crate::SimpleDiff::__from_macro( left_short, right_short, left_expanded, right_expanded, left_label, right_label, ); diff.fail_assertion(&$hint_suffix); } } } }}; } /// 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_serde_eq!(make_serde_diff, $left_label, $left, $right_label, $right, ""); }); ($left_label:ident: $left:expr, $right_label:ident: $right:expr, $($arg:tt)*) => ({ $crate::__assert_serde_eq!(make_serde_diff, $left_label, $left, $right_label, $right, format_args!(": {}", 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)*); }); } similar-asserts-1.7.0/tests/test_unsized.rs000064400000000000000000000001371046102023000172040ustar 00000000000000#[test] fn test_unsized() { similar_asserts::assert_eq!("foo".to_string(), "bfoo"[1..]); }