Skip to content

Commit

Permalink
locking: Add unit tests
Browse files Browse the repository at this point in the history
Add unit tests for correct behavior of rwlock and spinlock.

Signed-off-by: Carlos Bilbao <[email protected]>
  • Loading branch information
Zildj1an committed Oct 2, 2023
1 parent 16a0273 commit 27ef1ed
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
43 changes: 43 additions & 0 deletions src/locking/rwlock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,3 +155,46 @@ impl<T: Debug> RWLock<T> {
}
}
}

mod tests {

#[test]
fn test_lock_rw() {
use crate::locking::*;
let rwlock = RWLock::new(42);

// Acquire a read lock and check the initial value
let read_guard = rwlock.lock_read();
assert_eq!(*read_guard, 42);

drop(read_guard);

let read_guard2 = rwlock.lock_read();
assert_eq!(*read_guard2, 42);

// Create another RWLock instance for modification
let rwlock_modify = RWLock::new(0);

let mut write_guard = rwlock_modify.lock_write();
*write_guard = 99;
assert_eq!(*write_guard, 99);

drop(write_guard);

let read_guard = rwlock.lock_read();
assert_eq!(*read_guard, 42);

// Let's test two concurrent readers on a new RWLock instance
let rwlock_concurrent = RWLock::new(123);

let read_guard1 = rwlock_concurrent.lock_read();
let read_guard2 = rwlock_concurrent.lock_read();

// Assert that both readers can access the same value (123)
assert_eq!(*read_guard1, 123);
assert_eq!(*read_guard2, 123);

drop(read_guard1);
drop(read_guard2);
}
}
20 changes: 20 additions & 0 deletions src/locking/spinlock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,23 @@ impl<T: Debug> SpinLock<T> {
None
}
}

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

#[test]
fn test_spin_lock() {
let spin_lock = SpinLock::new(0);

let mut guard = spin_lock.lock();
*guard += 1;

// Ensure the locked data is updated.
assert_eq!(*guard, 1);

// Try to lock again; it should fail and return None.
let try_lock_result = spin_lock.try_lock();
assert!(try_lock_result.is_none());
}
}

0 comments on commit 27ef1ed

Please sign in to comment.