pb_mapper_core/test_support.rs
1//! What the tests of this crate and the crates above it share: the
2//! administrator key they authenticate with, a temporary path of their own,
3//! and the lock around the process credential.
4//!
5//! Everything here is unconditionally `pub` rather than `#[cfg(test)]`: a
6//! test-only item is not visible to another crate's tests, because each crate
7//! compiles its own test configuration. Crates below `pb-mapper-testkit`
8//! cannot use the testkit, which depends on them, so this is their home.
9
10use std::ops::Deref;
11use std::path::{Path, PathBuf};
12
13/// The administrator key every test relay and test client uses, as the bytes
14/// a relay starts with.
15pub const TEST_ADMIN_KEY_BYTES: [u8; 32] = *b"0123456789abcdefghijklmnopqrstuv";
16
17/// [`TEST_ADMIN_KEY_BYTES`] as the text a key file or the process credential
18/// holds.
19pub const TEST_ADMIN_KEY: &str = match std::str::from_utf8(&TEST_ADMIN_KEY_BYTES) {
20 Ok(key) => key,
21 Err(_) => panic!("the test administrator key is ASCII"),
22};
23
24/// Serialises tests that set or clear the process credential.
25///
26/// The credential is process-global, so two such tests running on different
27/// runner threads would see each other's writes. Every test that calls
28/// `set_process_msg_header_key` — in this crate and in the auth, protocol, and
29/// server crates — takes this first.
30///
31/// It lives here, next to the state it guards.
32pub static PROCESS_CREDENTIAL_TEST_LOCK: std::sync::LazyLock<tokio::sync::Mutex<()>> =
33 std::sync::LazyLock::new(|| tokio::sync::Mutex::new(()));
34
35/// A path under the system temporary directory that no other test, in this
36/// process or another, uses. It is not created: a test makes a directory or a
37/// file there, and whichever it is goes when this drops, also when the test
38/// fails partway.
39#[derive(Debug)]
40pub struct TempPath(PathBuf);
41
42impl TempPath {
43 /// `pb-mapper-{label}-{pid}-{16 random hex digits}`.
44 pub fn new(label: &str) -> Self {
45 let suffix: u64 = rand::RngExt::random(&mut rand::rng());
46 Self(std::env::temp_dir().join(format!(
47 "pb-mapper-{label}-{}-{suffix:016x}",
48 std::process::id()
49 )))
50 }
51
52 pub fn path(&self) -> &Path {
53 &self.0
54 }
55}
56
57impl Deref for TempPath {
58 type Target = Path;
59
60 fn deref(&self) -> &Path {
61 &self.0
62 }
63}
64
65impl AsRef<Path> for TempPath {
66 fn as_ref(&self) -> &Path {
67 &self.0
68 }
69}
70
71impl Drop for TempPath {
72 fn drop(&mut self) {
73 // Best effort: what is left is only a stray entry in the temporary
74 // directory, and a destructor must not panic.
75 if std::fs::remove_dir_all(&self.0).is_err() {
76 let _ = std::fs::remove_file(&self.0);
77 }
78 }
79}