serial_test-2.0.0/.cargo_vcs_info.json0000644000000001510000000000100133460ustar { "git": { "sha1": "7e3a5ca6f33c5da1d49e36e436025b3d2e91e59e" }, "path_in_vcs": "serial_test" }serial_test-2.0.0/Cargo.toml0000644000000033620000000000100113530ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "serial_test" version = "2.0.0" authors = ["Tom Parker-Shemilt "] description = "Allows for the creation of serialised Rust tests" readme = "README.md" keywords = ["sequential"] categories = ["development-tools::testing"] license = "MIT" repository = "https://github.com/palfrey/serial_test/" [package.metadata.docs.rs] all-features = true rustdoc-args = [ "--cfg", "docsrs", ] [package.metadata.cargo-all-features] skip_optional_dependencies = true denylist = ["docsrs"] [dependencies.dashmap] version = "5" [dependencies.document-features] version = "0.2" optional = true [dependencies.fslock] version = "0.2" optional = true [dependencies.futures] version = "^0.3" features = ["executor"] optional = true default_features = false [dependencies.lazy_static] version = "1.2" [dependencies.log] version = "0.4" optional = true [dependencies.parking_lot] version = "^0.12" [dependencies.serial_test_derive] version = "~2.0.0" [dev-dependencies.itertools] version = "0.10" [dev-dependencies.tokio] version = "^1.27" features = [ "macros", "rt", ] [features] async = [ "futures", "serial_test_derive/async", ] default = [ "logging", "async", ] docsrs = ["document-features"] file_locks = ["fslock"] logging = ["log"] serial_test-2.0.0/Cargo.toml.orig000064400000000000000000000027541046102023000150400ustar 00000000000000[package] name = "serial_test" description = "Allows for the creation of serialised Rust tests" license = "MIT" version = "2.0.0" authors = ["Tom Parker-Shemilt "] edition = "2018" repository = "https://github.com/palfrey/serial_test/" readme = "README.md" categories = ["development-tools::testing"] keywords = ["sequential"] [dependencies] lazy_static = "1.2" parking_lot = "^0.12" serial_test_derive = { version = "~2.0.0", path = "../serial_test_derive" } fslock = { version = "0.2", optional = true } document-features = { version = "0.2", optional = true } log = { version = "0.4", optional = true } futures = { version = "^0.3", default_features = false, features = [ "executor", ], optional = true} dashmap = { version = "5"} [dev-dependencies] itertools = "0.10" tokio = { version = "^1.27", features = ["macros", "rt"] } [features] default = ["logging", "async"] ## Switches on debug logging (and requires the `log` package) logging = ["log"] ## Enables async features (and requires the `futures` package) async = ["futures", "serial_test_derive/async"] ## The file_locks feature unlocks the `file_serial`/`file_parallel` macros (and requires the `fslock` package) file_locks = ["fslock"] docsrs = ["document-features"] # docs.rs-specific configuration [package.metadata.docs.rs] all-features = true # defines the configuration attribute `docsrs` rustdoc-args = ["--cfg", "docsrs"] [package.metadata.cargo-all-features] skip_optional_dependencies = true denylist = ["docsrs"]serial_test-2.0.0/LICENSE000064400000000000000000000020451046102023000131470ustar 00000000000000Copyright (c) 2018 Tom Parker-Shemilt Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.serial_test-2.0.0/README.md000064400000000000000000000042531046102023000134240ustar 00000000000000# serial_test [![Version](https://img.shields.io/crates/v/serial_test.svg)](https://crates.io/crates/serial_test) [![Downloads](https://img.shields.io/crates/d/serial_test)](https://crates.io/crates/serial_test) [![Docs](https://docs.rs/serial_test/badge.svg)](https://docs.rs/serial_test/) [![MIT license](https://img.shields.io/crates/l/serial_test.svg)](./LICENSE) [![Build Status](https://github.com/palfrey/serial_test/workflows/Continuous%20integration/badge.svg?branch=main)](https://github.com/palfrey/serial_test/actions) [![MSRV: 1.68.2](https://flat.badgen.net/badge/MSRV/1.68.2/purple)](https://blog.rust-lang.org/2023/03/28/Rust-1.68.2.html) `serial_test` allows for the creation of serialised Rust tests using the `serial` attribute e.g. ```rust #[test] #[serial] fn test_serial_one() { // Do things } #[test] #[serial] fn test_serial_another() { // Do things } #[tokio::test] #[serial] async fn test_serial_another() { // Do things asynchronously } ``` Multiple tests with the `serial` attribute are guaranteed to be executed in serial. Ordering of the tests is not guaranteed however. Other tests with the `parallel` attribute may run at the same time as each other, but not at the same time as a test with `serial`. Tests with neither attribute may run at any time and no guarantees are made about their timing! For cases like doctests and integration tests where the tests are run as separate processes, we also support `file_serial`, with similar properties but based off file locking. Note that there are no guarantees about one test with `serial` and another with `file_serial` as they lock using different methods, and `parallel` doesn't support `file_serial` yet (patches welcomed!). ## Usage The minimum supported Rust version here is 1.68.2. Note this is minimum _supported_, as it may well compile with lower versions, but they're not supported at all. Upgrades to this will require at a major version bump. 1.x supports 1.51 if you need a lower version than that. Add to your Cargo.toml ```toml [dev-dependencies] serial_test = "*" ``` plus `use serial_test::serial;` in your imports section. You can then either add `#[serial]` or `#[serial(some_text)]` to tests as required. serial_test-2.0.0/src/code_lock.rs000064400000000000000000000045301046102023000152220ustar 00000000000000use crate::rwlock::{Locks, MutexGuardWrapper}; use dashmap::{try_result::TryResult, DashMap}; use lazy_static::lazy_static; #[cfg(feature = "logging")] use log::debug; use std::sync::{atomic::AtomicU32, Arc}; #[cfg(feature = "logging")] use std::time::Instant; pub(crate) struct UniqueReentrantMutex { locks: Locks, // Only actually used for tests #[allow(dead_code)] pub(crate) id: u32, } impl UniqueReentrantMutex { pub(crate) fn lock(&self) -> MutexGuardWrapper { self.locks.serial() } pub(crate) fn start_parallel(&self) { self.locks.start_parallel(); } pub(crate) fn end_parallel(&self) { self.locks.end_parallel(); } #[cfg(test)] pub fn parallel_count(&self) -> u32 { self.locks.parallel_count() } #[cfg(test)] pub fn is_locked(&self) -> bool { self.locks.is_locked() } } lazy_static! { pub(crate) static ref LOCKS: Arc> = Arc::new(DashMap::new()); static ref MUTEX_ID: Arc = Arc::new(AtomicU32::new(1)); } impl Default for UniqueReentrantMutex { fn default() -> Self { Self { locks: Locks::new(), id: MUTEX_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst), } } } pub(crate) fn check_new_key(name: &str) { #[cfg(feature = "logging")] let start = Instant::now(); loop { #[cfg(feature = "logging")] { let duration = start.elapsed(); debug!("Waiting for '{}' {:?}", name, duration); } // Check if a new key is needed. Just need a read lock, which can be done in sync with everyone else match LOCKS.try_get(name) { TryResult::Present(_) => { return; } TryResult::Locked => { continue; // wasn't able to get read lock } TryResult::Absent => {} // do the write path below }; // This is the rare path, which avoids the multi-writer situation mostly let try_entry = LOCKS.try_entry(name.to_string()); if let Some(entry) = try_entry { entry.or_default(); return; } // If the try_entry fails, then go around the loop again // Odds are another test was also locking on the write and has now written the key } } serial_test-2.0.0/src/file_lock.rs000064400000000000000000000070261046102023000152320ustar 00000000000000use fslock::LockFile; #[cfg(feature = "logging")] use log::debug; use std::{ env, fs::{self, File}, io::{Read, Write}, path::Path, thread, time::Duration, }; pub(crate) struct Lock { lockfile: LockFile, pub(crate) parallel_count: u32, path: String, } impl Lock { // Can't use the same file as fslock truncates it fn gen_count_file(path: &str) -> String { format!("{}-count", path) } fn read_parallel_count(path: &str) -> u32 { let parallel_count = match File::open(Lock::gen_count_file(path)) { Ok(mut file) => { let mut count_buf = [0; 4]; match file.read_exact(&mut count_buf) { Ok(_) => u32::from_ne_bytes(count_buf), Err(_err) => { #[cfg(feature = "logging")] debug!("Error loading count file: {}", _err); 0u32 } } } Err(_) => 0, }; #[cfg(feature = "logging")] debug!("Parallel count for {:?} is {}", path, parallel_count); parallel_count } pub(crate) fn new(path: &str) -> Lock { if !Path::new(path).exists() { fs::write(path, "").unwrap_or_else(|_| panic!("Lock file path was {:?}", path)) } let mut lockfile = LockFile::open(path).unwrap(); #[cfg(feature = "logging")] debug!("Waiting on {:?}", path); lockfile.lock().unwrap(); #[cfg(feature = "logging")] debug!("Locked for {:?}", path); Lock { lockfile, parallel_count: Lock::read_parallel_count(path), path: String::from(path), } } pub(crate) fn start_serial(self: &mut Lock) { loop { if self.parallel_count == 0 { return; } #[cfg(feature = "logging")] debug!("Waiting because parallel count is {}", self.parallel_count); // unlock here is safe because we re-lock before returning self.unlock(); thread::sleep(Duration::from_secs(1)); self.lockfile.lock().unwrap(); #[cfg(feature = "logging")] debug!("Locked for {:?}", self.path); self.parallel_count = Lock::read_parallel_count(&self.path) } } fn unlock(self: &mut Lock) { #[cfg(feature = "logging")] debug!("Unlocking {}", self.path); self.lockfile.unlock().unwrap(); } pub(crate) fn end_serial(mut self: Lock) { self.unlock(); } fn write_parallel(self: &Lock) { let mut file = File::create(&Lock::gen_count_file(&self.path)).unwrap(); file.write_all(&self.parallel_count.to_ne_bytes()).unwrap(); } pub(crate) fn start_parallel(mut self: Lock) { self.parallel_count += 1; self.write_parallel(); self.unlock(); } pub(crate) fn end_parallel(mut self: Lock) { assert!(self.parallel_count > 0); self.parallel_count -= 1; self.write_parallel(); self.unlock(); } } pub(crate) fn path_for_name(name: &str) -> String { let mut pathbuf = env::temp_dir(); pathbuf.push(format!("serial-test-{}", name)); pathbuf.into_os_string().into_string().unwrap() } pub(crate) fn make_lock_for_name_and_path(name: &str, path: Option<&str>) -> Lock { if let Some(opt_path) = path { Lock::new(opt_path) } else { let default_path = path_for_name(name); Lock::new(&default_path) } } serial_test-2.0.0/src/lib.rs000064400000000000000000000056551046102023000140570ustar 00000000000000#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] #![deny(unused_variables)] #![deny(missing_docs)] #![deny(unused_imports)] //! # serial_test //! `serial_test` allows for the creation of serialised Rust tests using the [serial](macro@serial) attribute //! e.g. //! ```` //! #[test] //! #[serial] //! fn test_serial_one() { //! // Do things //! } //! //! #[test] //! #[serial] //! fn test_serial_another() { //! // Do things //! } //! //! #[test] //! #[parallel] //! fn test_parallel_another() { //! // Do parallel things //! } //! ```` //! Multiple tests with the [serial](macro@serial) attribute are guaranteed to be executed in serial. Ordering //! of the tests is not guaranteed however. Other tests with the [parallel](macro@parallel) attribute may run //! at the same time as each other, but not at the same time as a test with [serial](macro@serial). Tests with //! neither attribute may run at any time and no guarantees are made about their timing! //! //! For cases like doctests and integration tests where the tests are run as separate processes, we also support //! [file_serial](macro@file_serial)/[file_parallel](macro@file_parallel), with similar properties but based off file locking. Note that there are no //! guarantees about one test with [serial](macro@serial)/[parallel](macro@parallel) and another with [file_serial](macro@file_serial)/[file_parallel](macro@file_parallel) //! as they lock using different methods. //! ```` //! #[test] //! #[file_serial] //! fn test_serial_three() { //! // Do things //! } //! ```` //! //! ## Feature flags #![cfg_attr( feature = "docsrs", cfg_attr(doc, doc = ::document_features::document_features!()) )] mod code_lock; mod parallel_code_lock; mod rwlock; mod serial_code_lock; #[cfg(feature = "file_locks")] mod file_lock; #[cfg(feature = "file_locks")] mod parallel_file_lock; #[cfg(feature = "file_locks")] mod serial_file_lock; #[cfg(feature = "async")] pub use parallel_code_lock::{local_async_parallel_core, local_async_parallel_core_with_return}; pub use parallel_code_lock::{local_parallel_core, local_parallel_core_with_return}; #[cfg(feature = "async")] pub use serial_code_lock::{local_async_serial_core, local_async_serial_core_with_return}; pub use serial_code_lock::{local_serial_core, local_serial_core_with_return}; #[cfg(all(feature = "file_locks", feature = "async"))] pub use serial_file_lock::{fs_async_serial_core, fs_async_serial_core_with_return}; #[cfg(feature = "file_locks")] pub use serial_file_lock::{fs_serial_core, fs_serial_core_with_return}; #[cfg(all(feature = "file_locks", feature = "async"))] pub use parallel_file_lock::{fs_async_parallel_core, fs_async_parallel_core_with_return}; #[cfg(feature = "file_locks")] pub use parallel_file_lock::{fs_parallel_core, fs_parallel_core_with_return}; // Re-export #[serial/parallel]. pub use serial_test_derive::{parallel, serial}; #[cfg(feature = "file_locks")] pub use serial_test_derive::{file_parallel, file_serial}; serial_test-2.0.0/src/parallel_code_lock.rs000064400000000000000000000112361046102023000170770ustar 00000000000000#![allow(clippy::await_holding_lock)] use crate::code_lock::{check_new_key, LOCKS}; #[cfg(feature = "async")] use futures::FutureExt; use std::panic; #[doc(hidden)] pub fn local_parallel_core_with_return( name: &str, function: fn() -> Result<(), E>, ) -> Result<(), E> { check_new_key(name); let lock = LOCKS.get(name).unwrap(); lock.start_parallel(); let res = panic::catch_unwind(function); lock.end_parallel(); match res { Ok(ret) => ret, Err(err) => { panic::resume_unwind(err); } } } #[doc(hidden)] pub fn local_parallel_core(name: &str, function: fn()) { check_new_key(name); let lock = LOCKS.get(name).unwrap(); lock.start_parallel(); let res = panic::catch_unwind(|| { function(); }); lock.end_parallel(); if let Err(err) = res { panic::resume_unwind(err); } } #[doc(hidden)] #[cfg(feature = "async")] pub async fn local_async_parallel_core_with_return( name: &str, fut: impl std::future::Future> + panic::UnwindSafe, ) -> Result<(), E> { check_new_key(name); let lock = LOCKS.get(name).unwrap(); lock.start_parallel(); let res = fut.catch_unwind().await; lock.end_parallel(); match res { Ok(ret) => ret, Err(err) => { panic::resume_unwind(err); } } } #[doc(hidden)] #[cfg(feature = "async")] pub async fn local_async_parallel_core( name: &str, fut: impl std::future::Future + panic::UnwindSafe, ) { check_new_key(name); let lock = LOCKS.get(name).unwrap(); lock.start_parallel(); let res = fut.catch_unwind().await; lock.end_parallel(); if let Err(err) = res { panic::resume_unwind(err); } } #[cfg(test)] mod tests { #[cfg(feature = "async")] use crate::{local_async_parallel_core, local_async_parallel_core_with_return}; use crate::{code_lock::LOCKS, local_parallel_core, local_parallel_core_with_return}; use std::{io::Error, panic}; #[test] fn unlock_on_assert_sync_without_return() { let _ = panic::catch_unwind(|| { local_parallel_core("unlock_on_assert_sync_without_return", || { assert!(false); }) }); assert_eq!( LOCKS .get("unlock_on_assert_sync_without_return") .unwrap() .parallel_count(), 0 ); } #[test] fn unlock_on_assert_sync_with_return() { let _ = panic::catch_unwind(|| { local_parallel_core_with_return( "unlock_on_assert_sync_with_return", || -> Result<(), Error> { assert!(false); Ok(()) }, ) }); assert_eq!( LOCKS .get("unlock_on_assert_sync_with_return") .unwrap() .parallel_count(), 0 ); } #[tokio::test] #[cfg(feature = "async")] async fn unlock_on_assert_async_without_return() { async fn demo_assert() { assert!(false); } async fn call_serial_test_fn() { local_async_parallel_core("unlock_on_assert_async_without_return", demo_assert()).await } // as per https://stackoverflow.com/a/66529014/320546 let _ = panic::catch_unwind(|| { let handle = tokio::runtime::Handle::current(); let _enter_guard = handle.enter(); futures::executor::block_on(call_serial_test_fn()); }); assert_eq!( LOCKS .get("unlock_on_assert_async_without_return") .unwrap() .parallel_count(), 0 ); } #[tokio::test] #[cfg(feature = "async")] async fn unlock_on_assert_async_with_return() { async fn demo_assert() -> Result<(), Error> { assert!(false); Ok(()) } #[allow(unused_must_use)] async fn call_serial_test_fn() { local_async_parallel_core_with_return( "unlock_on_assert_async_with_return", demo_assert(), ) .await; } // as per https://stackoverflow.com/a/66529014/320546 let _ = panic::catch_unwind(|| { let handle = tokio::runtime::Handle::current(); let _enter_guard = handle.enter(); futures::executor::block_on(call_serial_test_fn()); }); assert_eq!( LOCKS .get("unlock_on_assert_async_with_return") .unwrap() .parallel_count(), 0 ); } } serial_test-2.0.0/src/parallel_file_lock.rs000064400000000000000000000115541046102023000171070ustar 00000000000000use std::panic; #[cfg(feature = "async")] use futures::FutureExt; use crate::file_lock::make_lock_for_name_and_path; #[doc(hidden)] pub fn fs_parallel_core(name: &str, path: Option<&str>, function: fn()) { make_lock_for_name_and_path(name, path).start_parallel(); let res = panic::catch_unwind(|| { function(); }); make_lock_for_name_and_path(name, path).end_parallel(); if let Err(err) = res { panic::resume_unwind(err); } } #[doc(hidden)] pub fn fs_parallel_core_with_return( name: &str, path: Option<&str>, function: fn() -> Result<(), E>, ) -> Result<(), E> { make_lock_for_name_and_path(name, path).start_parallel(); let res = panic::catch_unwind(function); make_lock_for_name_and_path(name, path).end_parallel(); match res { Ok(ret) => ret, Err(err) => { panic::resume_unwind(err); } } } #[doc(hidden)] #[cfg(feature = "async")] pub async fn fs_async_parallel_core_with_return( name: &str, path: Option<&str>, fut: impl std::future::Future> + panic::UnwindSafe, ) -> Result<(), E> { make_lock_for_name_and_path(name, path).start_parallel(); let res = fut.catch_unwind().await; make_lock_for_name_and_path(name, path).end_parallel(); match res { Ok(ret) => ret, Err(err) => { panic::resume_unwind(err); } } } #[doc(hidden)] #[cfg(feature = "async")] pub async fn fs_async_parallel_core( name: &str, path: Option<&str>, fut: impl std::future::Future + panic::UnwindSafe, ) { make_lock_for_name_and_path(name, path).start_parallel(); let res = fut.catch_unwind().await; make_lock_for_name_and_path(name, path).end_parallel(); if let Err(err) = res { panic::resume_unwind(err); } } #[cfg(test)] mod tests { #[cfg(feature = "async")] use crate::{fs_async_parallel_core, fs_async_parallel_core_with_return}; use crate::{ file_lock::{path_for_name, Lock}, fs_parallel_core, fs_parallel_core_with_return, }; use std::{io::Error, panic}; fn unlock_ok(lock_path: &str) { let lock = Lock::new(lock_path); assert_eq!(lock.parallel_count, 0); } #[test] fn unlock_on_assert_sync_without_return() { let lock_path = path_for_name("unlock_on_assert_sync_without_return"); let _ = panic::catch_unwind(|| { fs_parallel_core( "unlock_on_assert_sync_without_return", Some(&lock_path), || { assert!(false); }, ) }); unlock_ok(&lock_path); } #[test] fn unlock_on_assert_sync_with_return() { let lock_path = path_for_name("unlock_on_assert_sync_with_return"); let _ = panic::catch_unwind(|| { fs_parallel_core_with_return( "unlock_on_assert_sync_with_return", Some(&lock_path), || -> Result<(), Error> { assert!(false); Ok(()) }, ) }); unlock_ok(&lock_path); } #[tokio::test] #[cfg(feature = "async")] async fn unlock_on_assert_async_without_return() { let lock_path = path_for_name("unlock_on_assert_async_without_return"); async fn demo_assert() { assert!(false); } async fn call_serial_test_fn(lock_path: &str) { fs_async_parallel_core( "unlock_on_assert_async_without_return", Some(&lock_path), demo_assert(), ) .await } // as per https://stackoverflow.com/a/66529014/320546 let _ = panic::catch_unwind(|| { let handle = tokio::runtime::Handle::current(); let _enter_guard = handle.enter(); futures::executor::block_on(call_serial_test_fn(&lock_path)); }); unlock_ok(&lock_path); } #[tokio::test] #[cfg(feature = "async")] async fn unlock_on_assert_async_with_return() { let lock_path = path_for_name("unlock_on_assert_async_with_return"); async fn demo_assert() -> Result<(), Error> { assert!(false); Ok(()) } #[allow(unused_must_use)] async fn call_serial_test_fn(lock_path: &str) { fs_async_parallel_core_with_return( "unlock_on_assert_async_with_return", Some(&lock_path), demo_assert(), ) .await; } // as per https://stackoverflow.com/a/66529014/320546 let _ = panic::catch_unwind(|| { let handle = tokio::runtime::Handle::current(); let _enter_guard = handle.enter(); futures::executor::block_on(call_serial_test_fn(&lock_path)); }); unlock_ok(&lock_path); } } serial_test-2.0.0/src/rwlock.rs000064400000000000000000000054361046102023000146070ustar 00000000000000use parking_lot::{Condvar, Mutex, ReentrantMutex, ReentrantMutexGuard}; use std::{sync::Arc, time::Duration}; struct LockState { parallels: u32, } struct LockData { mutex: Mutex, serial: ReentrantMutex<()>, condvar: Condvar, } #[derive(Clone)] pub(crate) struct Locks { arc: Arc, } pub(crate) struct MutexGuardWrapper<'a> { #[allow(dead_code)] // need it around to get dropped mutex_guard: ReentrantMutexGuard<'a, ()>, locks: Locks, } impl<'a> Drop for MutexGuardWrapper<'a> { fn drop(&mut self) { self.locks.arc.condvar.notify_one(); } } impl Locks { pub fn new() -> Locks { Locks { arc: Arc::new(LockData { mutex: Mutex::new(LockState { parallels: 0 }), condvar: Condvar::new(), serial: Default::default(), }), } } #[cfg(test)] pub fn is_locked(&self) -> bool { self.arc.serial.is_locked() } pub fn serial(&self) -> MutexGuardWrapper { let mut lock_state = self.arc.mutex.lock(); loop { // If all the things we want are true, try to lock out serial if lock_state.parallels == 0 { let possible_serial_lock = self.arc.serial.try_lock(); if let Some(serial_lock) = possible_serial_lock { return MutexGuardWrapper { mutex_guard: serial_lock, locks: self.clone(), }; } } self.arc .condvar .wait_for(&mut lock_state, Duration::from_secs(1)); } } pub fn start_parallel(&self) { let mut lock_state = self.arc.mutex.lock(); loop { if lock_state.parallels > 0 { // fast path, as someone else already has it locked lock_state.parallels += 1; return; } let possible_serial_lock = self.arc.serial.try_lock(); if possible_serial_lock.is_some() { // We now know no-one else has the serial lock, so we can add to parallel lock_state.parallels = 1; // Had to have been 0 before, as otherwise we'd have hit the fast path return; } self.arc .condvar .wait_for(&mut lock_state, Duration::from_secs(1)); } } pub fn end_parallel(&self) { let mut lock_state = self.arc.mutex.lock(); assert!(lock_state.parallels > 0); lock_state.parallels -= 1; drop(lock_state); self.arc.condvar.notify_one(); } #[cfg(test)] pub fn parallel_count(&self) -> u32 { let lock_state = self.arc.mutex.lock(); lock_state.parallels } } serial_test-2.0.0/src/serial_code_lock.rs000064400000000000000000000063101046102023000165570ustar 00000000000000#![allow(clippy::await_holding_lock)] use crate::code_lock::{check_new_key, LOCKS}; #[doc(hidden)] pub fn local_serial_core_with_return( name: &str, function: fn() -> Result<(), E>, ) -> Result<(), E> { check_new_key(name); let unlock = LOCKS.get(name).expect("key to be set"); // _guard needs to be named to avoid being instant dropped let _guard = unlock.lock(); function() } #[doc(hidden)] pub fn local_serial_core(name: &str, function: fn()) { check_new_key(name); let unlock = LOCKS.get(name).expect("key to be set"); // _guard needs to be named to avoid being instant dropped let _guard = unlock.lock(); function(); } #[doc(hidden)] #[cfg(feature = "async")] pub async fn local_async_serial_core_with_return( name: &str, fut: impl std::future::Future>, ) -> Result<(), E> { check_new_key(name); let unlock = LOCKS.get(name).expect("key to be set"); // _guard needs to be named to avoid being instant dropped let _guard = unlock.lock(); fut.await } #[doc(hidden)] #[cfg(feature = "async")] pub async fn local_async_serial_core(name: &str, fut: impl std::future::Future) { check_new_key(name); let unlock = LOCKS.get(name).expect("key to be set"); // _guard needs to be named to avoid being instant dropped let _guard = unlock.lock(); fut.await; } #[cfg(test)] #[allow(clippy::print_stdout)] mod tests { use super::local_serial_core; use crate::code_lock::{check_new_key, LOCKS}; use itertools::Itertools; use parking_lot::RwLock; use std::{ sync::{Arc, Barrier}, thread, time::Duration, }; #[test] fn test_hammer_check_new_key() { let ptrs = Arc::new(RwLock::new(Vec::new())); let mut threads = Vec::new(); let count = 100; let barrier = Arc::new(Barrier::new(count)); for _ in 0..count { let local_locks = LOCKS.clone(); let local_ptrs = ptrs.clone(); let c = barrier.clone(); threads.push(thread::spawn(move || { c.wait(); check_new_key("foo"); { let unlock = local_locks.get("foo").expect("read didn't work"); let mutex = unlock.value(); let mut ptr_guard = local_ptrs .try_write_for(Duration::from_secs(1)) .expect("write lock didn't work"); ptr_guard.push(mutex.id); } c.wait(); })); } for thread in threads { thread.join().expect("thread join worked"); } let ptrs_read_lock = ptrs .try_read_recursive_for(Duration::from_secs(1)) .expect("ptrs read work"); assert_eq!(ptrs_read_lock.len(), count); println!("{:?}", ptrs_read_lock); assert_eq!(ptrs_read_lock.iter().unique().count(), 1); } #[test] fn unlock_on_assert() { let _ = std::panic::catch_unwind(|| { local_serial_core("assert", || { assert!(false); }) }); assert!(!LOCKS.get("assert").unwrap().is_locked()); } } serial_test-2.0.0/src/serial_file_lock.rs000064400000000000000000000035031046102023000165650ustar 00000000000000use crate::file_lock::make_lock_for_name_and_path; #[doc(hidden)] pub fn fs_serial_core(name: &str, path: Option<&str>, function: fn()) { let mut lock = make_lock_for_name_and_path(name, path); lock.start_serial(); function(); lock.end_serial(); } #[doc(hidden)] pub fn fs_serial_core_with_return( name: &str, path: Option<&str>, function: fn() -> Result<(), E>, ) -> Result<(), E> { let mut lock = make_lock_for_name_and_path(name, path); lock.start_serial(); let ret = function(); lock.end_serial(); ret } #[doc(hidden)] #[cfg(feature = "async")] pub async fn fs_async_serial_core_with_return( name: &str, path: Option<&str>, fut: impl std::future::Future>, ) -> Result<(), E> { let mut lock = make_lock_for_name_and_path(name, path); lock.start_serial(); let ret = fut.await; lock.end_serial(); ret } #[doc(hidden)] #[cfg(feature = "async")] pub async fn fs_async_serial_core( name: &str, path: Option<&str>, fut: impl std::future::Future, ) { let mut lock = make_lock_for_name_and_path(name, path); lock.start_serial(); fut.await; lock.end_serial(); } #[cfg(test)] mod tests { use std::panic; use fslock::LockFile; use super::fs_serial_core; use crate::file_lock::path_for_name; #[test] fn test_serial() { fs_serial_core("test", None, || {}); } #[test] fn unlock_on_assert_sync_without_return() { let lock_path = path_for_name("unlock_on_assert_sync_without_return"); let _ = panic::catch_unwind(|| { fs_serial_core("foo", Some(&lock_path), || { assert!(false); }) }); let mut lockfile = LockFile::open(&lock_path).unwrap(); assert!(lockfile.try_lock().unwrap()); } } serial_test-2.0.0/tests/tests.rs000064400000000000000000000002211046102023000150060ustar 00000000000000use serial_test::local_serial_core; #[test] fn test_empty_serial_call() { local_serial_core("beta", || { println!("Bar"); }); }