Only allow one unit test function read a global variable in a certain time?

⚓ Rust    📅 2025-09-23    👤 surdeus    👁️ 8      

surdeus

Warning

This post was published 38 days ago. The information described in this article may have changed.

Hi, I've met a strange lock issue, the scenario is a little bit complicated, let me explain:

I need to write some unit tests, in each unit test, I need to prepare some mock data for a global variable A, and keep it unchanged during the whole test function. To keep the global variable not changed by other test cases, I introduced another global variable LOCK to try to lock it inside a test case:

// common.rs

pub struct Data {
  data: String,
}

static A: Mutex<Option<Data>> = Mutex::new();
static LOCK: Mutex<()> = Mutex::new(());

pub fn acquire() -> MutexGuard {
  let lock_guard = LOCK.lock();
  
  // Create a mock "A" for test case here.
  let a = A.lock();
  a.data = ... // mock data here
  a.unlock();

  // return lock guard
  lock_guard
}

// tests.rs

fn test1() {
  let lock_guard = acquire();

  // start running test logic

  // Lock "A", clone the value, and release it
  for i in 0..100 {
    let data = A.lock().data.clone();
    // verify data logic
    ...
  }

  // lock_guard automatically release at end, so let other test cases run
}

// Same with test1, except the verification logic is different
fn test2() {
  let lock_guard = acquire();

  // start running test logic

  // Lock "A", clone the value, and release it
  for i in 0..100 {
    let data = A.lock().data.clone();
    // verify data logic
    ...
  }

  // lock_guard automatically release at end, so let other test cases run
}

But when running multiple test cases in GitHub Actions, there are still some test cases failed. I guess the global variable A is actually not locked by LOCK, what should I do?

6 posts - 2 participants

Read full topic

🏷️ Rust_feed