Skip to content

Commit

Permalink
Add is_locked_serially() to check if we are in a #[serial] context
Browse files Browse the repository at this point in the history
  • Loading branch information
pgerber committed Jul 2, 2024
1 parent b39310b commit 10ed8c8
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 2 deletions.
58 changes: 57 additions & 1 deletion serial_test/src/code_lock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ impl UniqueReentrantMutex {
self.locks.parallel_count()
}

#[cfg(test)]
pub fn is_locked(&self) -> bool {
self.locks.is_locked()
}
Expand All @@ -44,6 +43,63 @@ pub(crate) fn global_locks() -> &'static HashMap<String, UniqueReentrantMutex> {
LOCKS.get_or_init(HashMap::new)
}

/// Check if we are holding a serial lock
///
/// Can be used to assert that a piece of code can only be called
/// from a test marked `#[serial]`.
///
/// Example, with `#[serial]`:
///
/// ```
/// use serial_test::{is_locked_serially, serial};
///
/// fn do_something_in_need_of_serialization() {
/// assert!(is_locked_serially(None));
///
/// // ...
/// }
///
/// #[test]
/// # fn unused() {}
/// #[serial]
/// fn main() {
/// do_something_in_need_of_serialization();
/// }
/// ```
///
/// Example, missing `#[serial]`:
///
/// ```should_panic
/// use serial_test::{is_locked_serially, serial};
///
/// #[test]
/// # fn unused() {}
/// // #[serial] // <-- missing
/// fn main() {
/// assert!(is_locked_serially(None));
/// }
/// ```
///
/// Example, `#[test(some_key)]`:
///
/// ```
/// use serial_test::{is_locked_serially, serial};
///
/// #[test]
/// # fn unused() {}
/// #[serial(some_key)]
/// fn main() {
/// assert!(is_locked_serially(Some("some_key")));
/// assert!(!is_locked_serially(None));
/// }
/// ```
pub fn is_locked_serially(name: Option<&str>) -> bool {
global_locks()
.get(name.unwrap_or_default())
.map(|lock| lock.get().is_locked())
.unwrap_or_default()
}

static MUTEX_ID: AtomicU32 = AtomicU32::new(1);

impl UniqueReentrantMutex {
Expand Down
2 changes: 2 additions & 0 deletions serial_test/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,3 +112,5 @@ pub use serial_test_derive::{parallel, serial};

#[cfg(feature = "file_locks")]
pub use serial_test_derive::{file_parallel, file_serial};

pub use code_lock::is_locked_serially;
1 change: 0 additions & 1 deletion serial_test/src/rwlock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ impl Locks {
}
}

#[cfg(test)]
pub fn is_locked(&self) -> bool {
self.arc.serial.is_locked()
}
Expand Down

0 comments on commit 10ed8c8

Please sign in to comment.