Skip to content

Commit

Permalink
Improve the automock_foreign_C test
Browse files Browse the repository at this point in the history
Improve it to ensure that the original, non-mock function can still be
called even when the mock version is present in the build.

Issue #602
  • Loading branch information
asomers committed Aug 20, 2024
1 parent 7dd21ad commit c2b31ab
Showing 1 changed file with 20 additions and 19 deletions.
39 changes: 20 additions & 19 deletions mockall/tests/automock_foreign_c.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,46 +7,47 @@ use std::sync::Mutex;
#[automock]
mod ffi {
extern "C" {
pub(super) fn foo(x: u32) -> i64;
// This is provided by the C library
pub(super) fn isupper(c: i32) -> i32;
}
}

static FOO_MTX: Mutex<()> = Mutex::new(());
static ISUPPER_MTX: Mutex<()> = Mutex::new(());

// Ensure we can still use the original mocked function
#[test]
pub fn normal_usage() {
let _m = FOO_MTX.lock();
unsafe {
ffi::foo(42);
}
let _m = ISUPPER_MTX.lock();
assert!(0 != unsafe { ffi::isupper('A' as i32)}); // 'A'
assert_eq!(0, !unsafe { ffi::isupper('a' as i32)}); // 'a'
}

#[test]
#[should_panic(expected = "mock_ffi::foo(5): No matching expectation found")]
#[should_panic(expected = "mock_ffi::isupper(5): No matching expectation found")]
fn with_no_matches() {
let _m = FOO_MTX.lock();
let ctx = mock_ffi::foo_context();
let _m = ISUPPER_MTX.lock();
let ctx = mock_ffi::isupper_context();
ctx.expect()
.with(predicate::eq(4))
.returning(i64::from);
unsafe{ mock_ffi::foo(5) };
.returning(i32::from);
unsafe{ mock_ffi::isupper(5) };
}

#[test]
fn returning() {
let _m = FOO_MTX.lock();
let ctx = mock_ffi::foo_context();
ctx.expect().returning(i64::from);
assert_eq!(42, unsafe{mock_ffi::foo(42)});
let _m = ISUPPER_MTX.lock();
let ctx = mock_ffi::isupper_context();
ctx.expect().returning(i32::from);
assert_eq!(42, unsafe{mock_ffi::isupper(42)});
}

/// Ensure that the mock function can be called from C by casting it to a C
/// function pointer.
#[test]
fn c_abi() {
let _m = FOO_MTX.lock();
let ctx = mock_ffi::foo_context();
ctx.expect().returning(i64::from);
let p: unsafe extern "C-unwind" fn(u32) -> i64 = mock_ffi::foo;
let _m = ISUPPER_MTX.lock();
let ctx = mock_ffi::isupper_context();
ctx.expect().returning(i32::from);
let p: unsafe extern "C-unwind" fn(i32) -> i32 = mock_ffi::isupper;
assert_eq!(42, unsafe{p(42)});
}

0 comments on commit c2b31ab

Please sign in to comment.