Skip to content

Injected fake is called outside of scope sporadically #81

@schaffenrath

Description

@schaffenrath

In some cases, an injected fake is called outside the scope (test) it was defined in.

Test scenario

With the following simple structure:

.
├── main.rs
└── test_module
    ├── first.rs
    ├── mod.rs
    └── second.rs

and first.rs:

pub struct First {
    a: i32,
}

impl First {
    pub fn new() -> Self {
        First { a: 0 }
    }

    pub fn get(&self) -> i32 {
        self.a
    }
}

#[cfg(test)]
mod tests {
    use injectorpp::interface::injector::*;

    use crate::test_module::first::First;

    #[test]
    fn get_call_mock() {
        let mut injector = InjectorPP::new();
        injector
            .when_called(injectorpp::func!(fn (First::get)(&First) -> i32))
            .will_execute(injectorpp::fake!(func_type: fn(_i: &First)-> i32, returns: 7));

        assert_eq!(First::new().get(), 7);
    }
}

and second.rs:

use super::first::First;

pub struct Second {
    tm: First,
}

impl Second {
    pub fn new() -> Self {
        Second { tm: First::new() }
    }

    pub fn get(&self) -> i32 {
        self.tm.get()
    }
}

#[cfg(test)]
mod tests {
    use super::Second;

    #[test]
    fn get_do_not_call_mock() {
        assert_eq!(Second::new().get(), 0);
    }
}

Expected behavior

The .get() method in the test of second.rs should always return 0, since the new() initialized it that way, and the injected fake should only be valid in the test of first.rs.

Actual behavior

Running cargo test many times:

for i in $(seq 0 300); do cargo test; done

the following issue might occur:

running 2 tests
test test_module::first::tests::get_call_mock ... ok
test test_module::second::tests::get_do_not_call_mock ... FAILED

failures:

---- test_module::second::tests::get_do_not_call_mock stdout ----

thread 'test_module::second::tests::get_do_not_call_mock' panicked at src/test_module/second.rs:23:9:
assertion `left == right` failed
  left: 7
 right: 0
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
    test_module::second::tests::get_do_not_call_mock

test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions