Problem #
We embrace the concurrency for its efficiency and power. But when it comes to testing, parallel execution can introduce some complexities and unexpected behaviour when you are dealing with OS resources. Today I encountered one such uncertainity.
I was testing a feature which would
- Read the contents from clipboard. [Paste]
- Write some content back to clipboard. [Copy]
So, I was unaware upto this point that the tests in rust are concurrent and occurs randomly out of our control. It is important in such cases that tests are ran sequentially with consistent state and predicatable execution.
Other problems I can think of where similar problems would occur are about Testing Databases, File Systems, and other stateful components that requires a controlled environment to avoid unpredictable outcome.
Solution #
Using #[serial]
allows you to isolate and debug tests one by one for in sequence.
- Add use serial_test::serial; to your imports.
- Add attribute
#[serial]
or#[serial(some_text)]
along with#[test]
. - Run your tests with cargo test or cargo test --serial for explicit control.
Here #[serial(some_text)]
allows grouping the tests sequentially for a given group of tests.
You can find documentation for it here : https://docs.rs/serial_test/latest/serial_test/attr.serial.html