Tests: assert!() inside a thread


I want to test that a server on a separate thread received a message correctly.
Therefore I tried to put an assert!() into the closure I hand to the server:

let mut server = NotificationServer::new();
    server.start( |notification|{
        assert!(notification.actions[0] == "action1");

The assertion causes the thread to panic, but the test does not count as failed.

running 1 test
thread '<unnamed>' panicked at 'index out of bounds: the len is 4 but the index is 4', ../src/libcollections/vec.rs:1041
test actions_vec ... ok

What do I have to do to make the test recognize the panicked thread?


You can try to join the thread. It should return Err(...) if the thread panics.


Thank you, that did it. I hadn’t used thread extensively before.
Do you know of a way to force tests to run single threaded without adding -j1 to cargo test, perhaps by adding something to Cargo.toml. My tests start a server each and therefore must not be run in parallel :smiley:


Not off the top of my head. I seem to remember someone asking something about it here or on Reddit, but I didn’t stay around for the answer. They had problems with initializing some global value, or something like that…


Thank you anyway. :slight_smile:


Maybe you could grab a global testing mutex to effectively serialize them.


You can use the RUST_TEST_THREADS environment variable to control the number of parallel tests.