9

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).

tshepang
  • 12,111
  • 21
  • 91
  • 136
  • In my case, I want to run tests against some web-based API, and I need to get a login token to be used by each test (which in turn will be used by each API call). – tshepang Jan 09 '17 at 15:14

1 Answers1

13

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 1
    Note: I confirm `Drop` is not called for `lazy_static` variables; valgrind *will* complain :) – Matthieu M. Jan 09 '17 at 16:02
  • 1
    @MatthieuM. what's one more memory leak between friends, really? On a serious note, you can always add a suppression to Valgrind if you are deliberately attempting to leak one thing but still want to be warned about other accidental leaks. – Shepmaster Jan 09 '17 at 16:09