Skip to content

Commit

Permalink
Merge pull request #46 from orbwalk/clone_store
Browse files Browse the repository at this point in the history
Allow mock instances to be cloned by sharing the internal stubs
  • Loading branch information
nrxus authored Feb 23, 2022
2 parents 96ad4c6 + 9f94020 commit 85693fd
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 17 deletions.
17 changes: 4 additions & 13 deletions src/mock_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use std::{
/// implements_default(faux::MaybeFaux::Real(3));
/// ```
#[derive(Debug)]
#[derive(Clone, Debug)]
pub enum MaybeFaux<T> {
Real(T),
Faux(MockStore),
Expand All @@ -38,31 +38,22 @@ impl<T: Default> Default for MaybeFaux<T> {
}
}

impl<T: Clone> Clone for MaybeFaux<T> {
fn clone(&self) -> Self {
match self {
MaybeFaux::Real(r) => MaybeFaux::Real(r.clone()),
MaybeFaux::Faux(_) => panic!("cannot clone a mock"),
}
}
}

impl<T> MaybeFaux<T> {
pub fn faux() -> Self {
MaybeFaux::Faux(MockStore::new())
}
}

#[derive(Debug, Default)]
#[derive(Clone, Debug, Default)]
#[doc(hidden)]
pub struct MockStore {
stubs: Mutex<HashMap<usize, Arc<Mutex<Vec<stub::Saved<'static>>>>>>,
stubs: Arc<Mutex<HashMap<usize, Arc<Mutex<Vec<stub::Saved<'static>>>>>>>,
}

impl MockStore {
fn new() -> Self {
MockStore {
stubs: Mutex::new(HashMap::new()),
stubs: Arc::new(Mutex::new(HashMap::new())),
}
}

Expand Down
9 changes: 5 additions & 4 deletions tests/clone.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,9 @@ fn can_clone_real() {
}

#[test]
#[should_panic]
fn cloning_mock_panics() {
let real = Foo::faux();
let _ = real.clone();
fn can_clone_mock() {
let mut mock = Foo::faux();
let cloned = mock.clone();
faux::when!(mock.get()).then_return(4);
assert_eq!(cloned.get(), 4);
}

0 comments on commit 85693fd

Please sign in to comment.