Mocktopus icon indicating copy to clipboard operation
Mocktopus copied to clipboard

Not able to mock unsafe function

Open tobiaskrause opened this issue 5 years ago • 1 comments

Trying to mock an unsafe function results in an error. Is there any particular reason my unsafe function cannot be mocked?

Minimal test:

    unsafe fn count() -> i32 {
        1
    }

    #[test]
    fn unsafe_test() {
            unsafe {
                count.mock_raw(|| MockResult::Return(0));
                assert_eq!(0, count());
            }

    }

Output:

error[E0599]: no method named `mock_raw` found for type `unsafe fn() -> i32 {test::count}` in the current scope
   --> src\example.rs:10:23
    |
    |                 count.mock_raw(|| MockResult::Return(0));
    |                       ^^^^^^^^
    |
    = note: count is a function, perhaps you wish to call it
    = note: the method `mock_raw` exists but the following trait bounds were not satisfied:
            `unsafe fn() -> i32 {test::count} : mocktopus::mocking::Mockable<_, _>`

tobiaskrause avatar Jul 29 '19 14:07 tobiaskrause

Yes, unsafe funcions don't implement Fn.

One solution could be to switch whole API to using fn, but it lacks some first class citizenshipness. For example you can't implement a trait for fn item and you can't cast fn item to fn pointer without manually writing its signature. Also fn pointers are not unique, two functions can have the same address.

CodeSandwich avatar Jul 29 '19 15:07 CodeSandwich