mockall_double/lib.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
// 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: <Token![as]>::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, "");
}
}
}