mockall_double-0.3.1/.cargo_vcs_info.json0000644000000001540000000000100140110ustar { "git": { "sha1": "7e4af040db6ed8282005cee80da89471562c6f3f" }, "path_in_vcs": "mockall_double" }mockall_double-0.3.1/CHANGELOG.md000064400000000000000000000006541046102023000144170ustar 00000000000000# Change Log All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/). ## [ 0.3.1 ] - 2023-12-10 Updated the `syn` dependency. No user-visible changes. ([#469](https://github.com/asomers/mockall/pull/469)) ## [ 0.3.0 ] - 2023-05-15 ### Added - Added the ability to mock type aliases. ([#374](https://github.com/asomers/mockall/pull/374)) mockall_double-0.3.1/Cargo.toml0000644000000031000000000000100120010ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "mockall_double" version = "0.3.1" authors = ["Alan Somers "] description = """ Test double adapter for Mockall """ documentation = "https://docs.rs/mockall_double" readme = "README.md" keywords = [ "mock", "mocking", "testing", ] categories = ["development-tools::testing"] license = "MIT/Apache-2.0" repository = "https://github.com/asomers/mockall" [package.metadata.release] tag-prefix = "mockall_double-" [[package.metadata.release.pre-release-replacements]] file = "README.md" replace = "mockall_double = \"{{version}}\"" search = 'mockall_double = "[a-z0-9\.-]+"' [[package.metadata.release.pre-release-replacements]] file = "CHANGELOG.md" replace = "{{version}}" search = "Unreleased" [[package.metadata.release.pre-release-replacements]] file = "CHANGELOG.md" replace = "{{date}}" search = "ReleaseDate" [lib] proc-macro = true [dependencies.cfg-if] version = "1.0" [dependencies.proc-macro2] version = "1.0.60" [dependencies.quote] version = "1.0" [dependencies.syn] version = "2.0" features = ["full"] [features] nightly = ["proc-macro2/nightly"] mockall_double-0.3.1/Cargo.toml.orig000064400000000000000000000016231046102023000154720ustar 00000000000000[package] name = "mockall_double" version = "0.3.1" authors = ["Alan Somers "] license = "MIT/Apache-2.0" repository = "https://github.com/asomers/mockall" categories = ["development-tools::testing"] keywords = ["mock", "mocking", "testing"] documentation = "https://docs.rs/mockall_double" edition = "2021" description = """ Test double adapter for Mockall """ [lib] proc-macro = true [package.metadata.release] tag-prefix = "mockall_double-" pre-release-replacements = [ { file="README.md", search="mockall_double = \"[a-z0-9\\.-]+\"", replace="mockall_double = \"{{version}}\""} , { file="CHANGELOG.md", search="Unreleased", replace="{{version}}" }, { file="CHANGELOG.md", search="ReleaseDate", replace="{{date}}" } ] [features] nightly = ["proc-macro2/nightly"] [dependencies] cfg-if = "1.0" proc-macro2 = "1.0.60" quote = "1.0" syn = { version = "2.0", features = ["full"] } mockall_double-0.3.1/LICENSE-APACHE000064400000000000000000000251371046102023000145350ustar 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. mockall_double-0.3.1/LICENSE-MIT000064400000000000000000000020371046102023000142370ustar 00000000000000Copyright (c) 2019 Alan Somers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. mockall_double-0.3.1/README.md000064400000000000000000000043241046102023000140630ustar 00000000000000# mockall_double A double test adapter that works well with Mockall. [![Build Status](https://api.cirrus-ci.com/github/asomers/mockall.svg)](https://cirrus-ci.com/github/asomers/mockall) [![Crates.io](https://img.shields.io/crates/v/mockall_double.svg)](https://crates.io/crates/mockall_double) [![Documentation](https://docs.rs/mockall_double/badge.svg)](https://docs.rs/mockall_double) ## Overview Mockall can easily create a mock version of a struct. But how does one convince the code under test to use the mock struct instead of the real one? In Rust, it's necessary to replace the real struct at compile time. That's very easy to do with a few `#[cfg(test)]` statements. But mockall_double makes it even easier. ## Usage Typically `mockall` is only used by unit tests, so it can be a dev-dependency. But `mockall_double` must be a full dependency. To use it this way, add this to your `Cargo.toml`: ```toml [dependencies] mockall_double = "0.3.1" [dev-dependencies] mockall = "0.12.0" ``` Then use it like this: ```rust use mockall_double::double; mod mockable { #[cfg(test)] use mockall::automock; pub struct Foo {} #[cfg_attr(test, automock)] impl Foo { pub fn foo(&self, x: u32) -> u32 { // ... 0 } } } #[double] use mockable::Foo; fn bar(f: Foo) -> u32 { f.foo(42) } #[cfg(test)] mod tests { use super::*; #[test] fn bar_test() { let mut mock = Foo::new(); mock.expect_foo() .returning(|x| x + 1); assert_eq!(43, bar(mock)); } } ``` See the [API docs](https://docs.rs/mockall_double) for more information. # Minimum Supported Rust Version (MSRV) `mockall_double` is tested with the same MSRV as Mockall itself. Currently, that's Rust 1.42.0. `mockall_double`'s MSRV will not be changed in the future without bumping the major or minor version. # License `mockall_double` is primarily distributed under the terms of both the MIT license and the Apache License (Version 2.0). See LICENSE-APACHE, and LICENSE-MIT for details # Acknowledgements `mockall_double` is inspired by Jason Grlicky's [double](https://crates.io/crates/double) crate, but tweaked to work better with Mockall's naming conventions. mockall_double-0.3.1/src/lib.rs000064400000000000000000000223241046102023000145070ustar 00000000000000// vim: tw=80 //! Test double adapter for use with Mockall //! //! This crate provides [`#[double]`](macro@double), which can swap in Mock //! objects for real objects while in test mode. It's intended to be used in //! tandem with the [`mockall`](https://docs.rs/mockall/latest/mockall) crate. //! However, it is defined in its own crate so that the bulk of Mockall can //! remain a dev-dependency, instead of a regular dependency. #![cfg_attr(feature = "nightly", feature(proc_macro_diagnostic))] #![cfg_attr(test, deny(warnings))] extern crate proc_macro; use cfg_if::cfg_if; use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote}; use syn::{ *, spanned::Spanned }; cfg_if! { // proc-macro2's Span::unstable method requires the nightly feature, and it // doesn't work in test mode. // https://github.com/alexcrichton/proc-macro2/issues/159 if #[cfg(all(feature = "nightly", not(test)))] { fn compile_error(span: Span, msg: &'static str) { span.unstable() .error(msg) .emit(); } } else { fn compile_error(_span: Span, msg: &str) { panic!("{msg}. More information may be available when mockall_double is built with the \"nightly\" feature."); } } } fn do_double(_attrs: TokenStream, input: TokenStream) -> TokenStream { let mut item: Item = match parse2(input.clone()) { Ok(u) => u, Err(e) => return e.to_compile_error() }; match &mut item { Item::Use(use_stmt) => mock_itemuse(use_stmt), Item::Type(item_type) => mock_itemtype(item_type), _ => { compile_error(item.span(), "Only use statements and type aliases may be doubled"); } }; quote!( #[cfg(not(test))] #input #[cfg(test)] #item ) } /// Import a mock type in test mode, or a real type otherwise. /// /// In a regular build, this macro is a no-op. But when `#[cfg(test)]`, it /// substitutes "MockXXX" for any imported "XXX". This makes it easy to to use /// mock objects, especially structs, in your unit tests. /// /// This macro uses the same naming convention as /// [`mockall`](https://docs.rs/mockall/latest/mockall), but doesn't strictly /// require it. It can work with hand-built Mock objects, or any other crate /// using the same naming convention. /// /// This is the most common way to use `#[double]`. In order to replace a type, /// it must come from a separate module. So to mock type `Foo`, place it into a /// submodule, along with its mock counterpart. Then simply import `Foo` with /// `#[double]` like this: /// ```no_run /// # use mockall_double::double; /// mod foo { /// pub(super) struct Foo { /// // ... /// } /// #[cfg(test)] /// pub(super) struct MockFoo { /// // ... /// } /// } /// #[double] /// use foo::Foo; /// ``` /// That will expand to the following: /// ```no_run /// # use mockall_double::double; /// # mod foo { pub struct Foo {} } /// #[cfg(not(test))] /// use foo::Foo; /// #[cfg(test)] /// use foo::MockFoo as Foo; /// ``` /// `#[double]` can handle deeply nested paths, /// ```no_run /// # use mockall_double::double; /// # mod foo { pub mod bar { pub struct Baz{} } } /// #[double] /// use foo::bar::Baz; /// ``` /// grouped imports, /// ```no_run /// # mod foo { pub mod bar { pub struct Baz{} pub struct Bean {} } } /// # use mockall_double::double; /// #[double] /// use foo::bar::{ /// Baz, /// Bean /// }; /// ``` /// type aliases, /// ```no_run /// # mod bar { pub struct Baz {} } /// # use mockall_double::double; /// #[double] /// type Foo = bar::Baz; /// ``` /// and renamed imports, too. With renamed imports, it isn't even necessary to /// declare a submodule. /// ```no_run /// # use mockall_double::double; /// # struct Foo {} /// #[double] /// use Foo as Bar; /// ``` /// Finally, `#[double]` can also import entire mocked modules, not just /// structures. In this case the naming convention is different. It will /// replace "xxx" with "mock_xxx". For example: /// ```no_run /// # use mockall_double::double; /// mod foo { /// pub mod inner { /// // ... /// } /// pub mod mock_inner { /// // ... /// } /// } /// #[double] /// use foo::inner; /// ``` /// will expand to: /// ```no_run /// # use mockall_double::double; /// # mod foo { pub mod inner { } pub mod mock_inner { } } /// #[cfg(not(test))] /// use foo::inner; /// #[cfg(test)] /// use foo::mock_inner as inner; /// ``` /// #[proc_macro_attribute] pub fn double(attrs: proc_macro::TokenStream, input: proc_macro::TokenStream) -> proc_macro::TokenStream { do_double(attrs.into(), input.into()).into() } fn mock_itemtype(orig: &mut ItemType) { match &mut *orig.ty { Type::Path(tp) => { let ident = &tp.path.segments.last_mut().unwrap().ident; tp.path.segments.last_mut().unwrap().ident = mock_ident(ident); } x => compile_error(x.span(), "Only path types may be doubled") } } fn mock_itemuse(orig: &mut ItemUse) { if let UseTree::Name(un) = &orig.tree { compile_error(un.span(), "Cannot double types in the current module. Use a submodule (use foo::Foo) or a rename (use Foo as Bar)"); } else { mock_usetree(&mut orig.tree) } } fn mock_ident(i: &Ident) -> Ident { let is_type = format!("{i}") .chars() .next() .expect("zero-length ident?") .is_uppercase(); if is_type { // probably a Type format_ident!("Mock{}", i) } else { // probably a module format_ident!("mock_{}", i) } } fn mock_usetree(mut orig: &mut UseTree) { match &mut orig { UseTree::Glob(star) => { compile_error(star.span(), "Cannot double glob imports. Import by fully qualified name instead."); }, UseTree::Group(ug) => { for ut in ug.items.iter_mut() { mock_usetree(ut); } }, UseTree::Name(un) => { *orig = UseTree::Rename(UseRename { ident: mock_ident(&un.ident), as_token: ::default(), rename: un.ident.clone() }); }, UseTree::Path(up) => { mock_usetree(up.tree.as_mut()); }, UseTree::Rename(ur) => { ur.ident = mock_ident(&ur.ident) }, } } #[cfg(test)] mod t { use super::*; mod double { use super::*; use std::str::FromStr; fn cmp(attrs: &str, code: &str, expected: &str) { let attrs_ts = TokenStream::from_str(attrs).unwrap(); let code_ts = TokenStream::from_str(code).unwrap(); let output = do_double(attrs_ts, code_ts); let output = output.to_string(); // Round-trip expected through proc_macro2 so whitespace will be // identically formatted let expected = TokenStream::from_str(expected) .unwrap() .to_string(); assert_eq!(output, expected); } #[test] #[should_panic(expected = "Cannot double glob")] fn glob() { let code = "use foo::*;"; cmp("", code, ""); } #[test] fn group() { let code = " use foo::bar::{ Baz, Bean }; "; let expected = " #[cfg(not(test))] use foo::bar::{ Baz, Bean }; #[cfg(test)] use foo::bar::{ MockBaz as Baz, MockBean as Bean }; "; cmp("", code, expected); } #[test] fn module() { let code = "use foo::bar;"; let expected = " #[cfg(not(test))] use foo::bar; #[cfg(test)] use foo::mock_bar as bar; "; cmp("", code, expected); } #[test] #[should_panic(expected = "Cannot double types in the current module")] fn name() { let code = "use Foo;"; cmp("", code, ""); } #[test] fn path() { let code = "use foo::bar::Baz;"; let expected = " #[cfg(not(test))] use foo::bar::Baz; #[cfg(test)] use foo::bar::MockBaz as Baz; "; cmp("", code, expected); } #[test] fn pub_use() { let code = "pub use foo::bar;"; let expected = " #[cfg(not(test))] pub use foo::bar; #[cfg(test)] pub use foo::mock_bar as bar; "; cmp("", code, expected); } #[test] fn rename() { let code = "use Foo as Bar;"; let expected = " #[cfg(not(test))] use Foo as Bar; #[cfg(test)] use MockFoo as Bar; "; cmp("", code, expected); } #[test] fn type_() { let code = "type Foo = bar::Baz;"; let expected = " #[cfg(not(test))] type Foo = bar::Baz; #[cfg(test)] type Foo = bar::MockBaz; "; cmp("", code, expected); } #[test] #[should_panic(expected = "Only use statements and type aliases")] fn undoubleable() { let code = "struct Foo{}"; cmp("", code, ""); } } }