1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// The Test Context Crate is private and should not be consumed by any external APIs.
// It exists solely as a way for the mock_me crate to store injected functions
// to replace the functions that the programmer has mocked.

// This needs to be in its own crate due to limitations in proc-macro crates.

#[macro_use]
extern crate lazy_static;

use std::ops::Drop;
use std::sync::Mutex;
use std::collections::HashMap;

lazy_static! {
    // Protected by Mutex since tests can be run in parallel
    // usize represents the pointer to the function that we are storing
    static ref GLOBAL_FUNCTION_LOOKUP: Mutex<HashMap<String, usize>> = {
        let m = HashMap::new();
        Mutex::new(m)
    };
}

pub struct TextContext;

impl TextContext {
    pub fn set(&self, key: String, value: usize) {
        let mut lookup = GLOBAL_FUNCTION_LOOKUP.lock().unwrap();
        lookup.insert(key, value);
    }

    pub fn get(&self, key: &str) -> usize {
        let lookup   = GLOBAL_FUNCTION_LOOKUP.lock().unwrap();
        *lookup.get(key).unwrap()
    }
}

impl Drop for TextContext {
    fn drop(&mut self) {
        let mut lookup = GLOBAL_FUNCTION_LOOKUP.lock().unwrap();
        lookup.clear();
    }
}


pub fn get_test_context() -> TextContext {
    TextContext
}