Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing dynamic state between #[test]s

Tags:

rust

How do I share state between tests, short of storing it externally (e.g. environment variables, file, etc)?

Stainless has a setup macro thing named before_each, and I'm thinking of a similar thing, say shared_values, but whose variables would be accessible to all tests, and which would also be ran once (at the beginning of the test suite).

like image 868
tshepang Avatar asked Jan 09 '17 15:01

tshepang


1 Answers

There's nothing special about tests. They are "just" functions that run in multiple threads. Therefore, one solution is do the same thing you would in other code: create a global mutable singleton:

use once_cell::sync::Lazy; // 1.5.2

static DATABASE: Lazy<String> = Lazy::new(|| format!("{} {}", "This was", "expensive"));

#[test]
fn one() {
    println!("{}", *DATABASE);
}

#[test]
fn two() {
    println!("{}", *DATABASE);
}

The test framework provides no hooks for an "after" callback, so there is no nice avenue to clean up this resource. Drop will not be called for singleton variables either.

like image 61
Shepmaster Avatar answered Oct 18 '22 23:10

Shepmaster