Skip to content

Commit 00f4790

Browse files
committed
test(rust): centralize environment variable guards
Add a shared test-support environment variable guard that holds a single process-wide mutex while temporarily setting environment variables. Replace module-local locks and direct unsafe env mutations in tests with the shared RAII guard so Rust 2024 unsafe environment access is isolated in one audited helper and restored consistently.
1 parent 315250c commit 00f4790

13 files changed

Lines changed: 73 additions & 230 deletions

File tree

‎rust/crates/ccusage-test-support/src/lib.rs‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,49 @@
11
use std::{
2+
ffi::{OsStr, OsString},
23
fs,
34
path::{Path, PathBuf},
5+
sync::{Mutex, MutexGuard},
46
};
57

68
use assert_fs::{
79
TempDir,
810
fixture::{ChildPath, FileWriteStr, PathChild, PathCreateDir},
911
};
1012

13+
static ENV_LOCK: Mutex<()> = Mutex::new(());
14+
15+
fn env_lock() -> MutexGuard<'static, ()> {
16+
ENV_LOCK.lock().unwrap()
17+
}
18+
19+
pub struct EnvVarGuard {
20+
key: &'static str,
21+
previous: Option<OsString>,
22+
_guard: MutexGuard<'static, ()>,
23+
}
24+
25+
impl EnvVarGuard {
26+
pub fn set(key: &'static str, value: impl AsRef<OsStr>) -> Self {
27+
let guard = env_lock();
28+
let previous = std::env::var_os(key);
29+
unsafe { std::env::set_var(key, value) };
30+
Self {
31+
key,
32+
previous,
33+
_guard: guard,
34+
}
35+
}
36+
}
37+
38+
impl Drop for EnvVarGuard {
39+
fn drop(&mut self) {
40+
match self.previous.take() {
41+
Some(value) => unsafe { std::env::set_var(self.key, value) },
42+
None => unsafe { std::env::remove_var(self.key) },
43+
}
44+
}
45+
}
46+
1147
pub struct Fixture {
1248
dir: TempDir,
1349
}

‎rust/crates/ccusage/src/adapter/codebuff/loader.rs‎

Lines changed: 3 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -80,44 +80,22 @@ use super::report::{report_from_rows, summarize_entries};
8080

8181
#[cfg(test)]
8282
mod tests {
83-
use std::{env, path::Path, sync::Mutex};
84-
8583
use super::super::{parser::parse_usage_object, paths::CODEBUFF_DATA_DIR_ENV};
8684
use super::*;
8785
use crate::{
8886
TokenUsageRaw, UsageEntry, UsageMessage, cli::AgentReportKind, parse_ts_timestamp,
8987
};
90-
use ccusage_test_support::fs_fixture;
91-
92-
static ENV_LOCK: Mutex<()> = Mutex::new(());
93-
94-
struct EnvDirGuard {
95-
key: &'static str,
96-
}
97-
98-
impl EnvDirGuard {
99-
fn set(key: &'static str, dir: &Path) -> Self {
100-
unsafe { env::set_var(key, dir) };
101-
Self { key }
102-
}
103-
}
104-
105-
impl Drop for EnvDirGuard {
106-
fn drop(&mut self) {
107-
unsafe { env::remove_var(self.key) };
108-
}
109-
}
88+
use ccusage_test_support::{EnvVarGuard, fs_fixture};
11089

11190
#[test]
11291
fn loads_assistant_usage_from_chat_messages() {
113-
let _guard = ENV_LOCK.lock().unwrap();
11492
let fixture = fs_fixture!({
11593
"projects/project-a/chats/2026-01-02T03-04-05.000Z/chat-messages.json": r#"[
11694
{"role":"user","text":"hello"},
11795
{"id":"assistant-message","role":"assistant","timestamp":"2026-01-02T03:04:06.000Z","metadata":{"model":"claude-sonnet-4-20250514","usage":{"inputTokens":100,"outputTokens":50,"cacheCreationInputTokens":20,"cacheReadInputTokens":10}},"credits":1.25}
11896
]"#,
11997
});
120-
let _cleanup = EnvDirGuard::set(CODEBUFF_DATA_DIR_ENV, fixture.root());
98+
let _cleanup = EnvVarGuard::set(CODEBUFF_DATA_DIR_ENV, fixture.root());
12199

122100
let pricing = PricingMap::load_embedded();
123101
let shared = SharedArgs {
@@ -145,7 +123,6 @@ mod tests {
145123

146124
#[test]
147125
fn falls_back_to_run_state_provider_usage() {
148-
let _guard = ENV_LOCK.lock().unwrap();
149126
let fixture = fs_fixture!({
150127
"projects/project-a/chats/2026-01-02T03-04-05.000Z/chat-messages.json": r#"[
151128
{"variant":"agent","metadata":{"runState":{"sessionState":{"mainAgentState":{"messageHistory":[
@@ -154,7 +131,7 @@ mod tests {
154131
]}}}}}
155132
]"#,
156133
});
157-
let _cleanup = EnvDirGuard::set(CODEBUFF_DATA_DIR_ENV, fixture.root());
134+
let _cleanup = EnvVarGuard::set(CODEBUFF_DATA_DIR_ENV, fixture.root());
158135

159136
let pricing = PricingMap::load_embedded();
160137
let entries = load_entries(&SharedArgs::default(), &pricing).unwrap();

‎rust/crates/ccusage/src/adapter/droid/loader.rs‎

Lines changed: 4 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -82,9 +82,7 @@ use super::report::{report_from_rows, summarize_entries};
8282

8383
#[cfg(test)]
8484
mod tests {
85-
use std::{env, path::Path, sync::Mutex};
86-
87-
use ccusage_test_support::fs_fixture;
85+
use ccusage_test_support::{EnvVarGuard, fs_fixture};
8886
use serde_json::json;
8987

9088
use super::super::{
@@ -95,26 +93,6 @@ mod tests {
9593
use crate::{
9694
TokenUsageRaw, UsageEntry, UsageMessage, cli::AgentReportKind, parse_ts_timestamp,
9795
};
98-
99-
static ENV_LOCK: Mutex<()> = Mutex::new(());
100-
101-
struct EnvDirGuard {
102-
key: &'static str,
103-
}
104-
105-
impl EnvDirGuard {
106-
fn set(key: &'static str, dir: &Path) -> Self {
107-
unsafe { env::set_var(key, dir) };
108-
Self { key }
109-
}
110-
}
111-
112-
impl Drop for EnvDirGuard {
113-
fn drop(&mut self) {
114-
unsafe { env::remove_var(self.key) };
115-
}
116-
}
117-
11896
#[test]
11997
fn normalizes_droid_model_names() {
12098
assert_eq!(
@@ -144,7 +122,6 @@ mod tests {
144122

145123
#[test]
146124
fn loads_usage_from_droid_settings_files() {
147-
let _guard = ENV_LOCK.lock().unwrap();
148125
let fixture = fs_fixture!({
149126
"session-a.settings.json": r#"{
150127
"model": "Claude-Sonnet-4-[Anthropic]",
@@ -160,7 +137,7 @@ mod tests {
160137
}"#,
161138
"zero.settings.json": r#"{"model":"gpt-5","tokenUsage":{"inputTokens":0}}"#,
162139
});
163-
let _cleanup = EnvDirGuard::set(DROID_SESSIONS_DIR_ENV, fixture.root());
140+
let _cleanup = EnvVarGuard::set(DROID_SESSIONS_DIR_ENV, fixture.root());
164141

165142
let pricing = PricingMap::load_embedded();
166143
let shared = SharedArgs {
@@ -185,7 +162,6 @@ mod tests {
185162

186163
#[test]
187164
fn falls_back_to_sidecar_jsonl_model() {
188-
let _guard = ENV_LOCK.lock().unwrap();
189165
let fixture = fs_fixture!({
190166
"session-b.settings.json": r#"{
191167
"providerLock": "anthropic",
@@ -194,7 +170,7 @@ mod tests {
194170
}"#,
195171
"session-b.jsonl": r#"{"content":"Model: Claude Opus 4.5 Thinking [Anthropic]"}"#,
196172
});
197-
let _cleanup = EnvDirGuard::set(DROID_SESSIONS_DIR_ENV, fixture.root());
173+
let _cleanup = EnvVarGuard::set(DROID_SESSIONS_DIR_ENV, fixture.root());
198174

199175
let pricing = PricingMap::load_embedded();
200176
let entries = load_entries(&SharedArgs::default(), &pricing).unwrap();
@@ -208,7 +184,6 @@ mod tests {
208184

209185
#[test]
210186
fn keeps_latest_snapshot_for_duplicate_session_ids() {
211-
let _guard = ENV_LOCK.lock().unwrap();
212187
let fixture = fs_fixture!({
213188
"archive/session-c.settings.json": r#"{
214189
"model": "gpt-5",
@@ -223,7 +198,7 @@ mod tests {
223198
"tokenUsage": {"inputTokens": 100, "outputTokens": 200}
224199
}"#,
225200
});
226-
let _cleanup = EnvDirGuard::set(DROID_SESSIONS_DIR_ENV, fixture.root());
201+
let _cleanup = EnvVarGuard::set(DROID_SESSIONS_DIR_ENV, fixture.root());
227202

228203
let pricing = PricingMap::load_embedded();
229204
let entries = load_entries(&SharedArgs::default(), &pricing).unwrap();

‎rust/crates/ccusage/src/adapter/gemini/loader.rs‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@ mod tests {
3535

3636
#[test]
3737
fn loads_jsonl_token_events_and_separates_cached_input() {
38-
let _guard = super::super::GEMINI_DATA_DIR_LOCK.lock().unwrap();
3938
let fixture = fs_fixture!({
4039
"project/chats/session-a.jsonl": [
4140
r#"{"sessionId":"session-a","projectHash":"project-a","startTime":"2026-05-17T11:07:00.000Z"}"#,

‎rust/crates/ccusage/src/adapter/gemini/mod.rs‎

Lines changed: 3 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -11,29 +11,16 @@ use crate::{
1111
pub(crate) use loader::load_entries;
1212
pub(crate) use report::{report_from_rows, summarize_entries};
1313

14-
#[cfg(test)]
15-
static GEMINI_DATA_DIR_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
16-
1714
#[cfg(test)]
1815
struct GeminiDataDirEnvGuard {
19-
previous: Option<std::ffi::OsString>,
16+
_guard: ccusage_test_support::EnvVarGuard,
2017
}
2118

2219
#[cfg(test)]
2320
impl GeminiDataDirEnvGuard {
2421
fn set(path: &std::path::Path) -> Self {
25-
let previous = std::env::var_os(paths::GEMINI_DATA_DIR_ENV);
26-
unsafe { std::env::set_var(paths::GEMINI_DATA_DIR_ENV, path) };
27-
Self { previous }
28-
}
29-
}
30-
31-
#[cfg(test)]
32-
impl Drop for GeminiDataDirEnvGuard {
33-
fn drop(&mut self) {
34-
match &self.previous {
35-
Some(value) => unsafe { std::env::set_var(paths::GEMINI_DATA_DIR_ENV, value) },
36-
None => unsafe { std::env::remove_var(paths::GEMINI_DATA_DIR_ENV) },
22+
Self {
23+
_guard: ccusage_test_support::EnvVarGuard::set(paths::GEMINI_DATA_DIR_ENV, path),
3724
}
3825
}
3926
}

‎rust/crates/ccusage/src/adapter/gemini/paths.rs‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,6 @@ mod tests {
4848

4949
#[test]
5050
fn discovers_json_and_jsonl_logs() {
51-
let _guard = super::super::GEMINI_DATA_DIR_LOCK.lock().unwrap();
5251
let fixture = fs_fixture!({
5352
"chats/a.json": "{}",
5453
"chats/b.jsonl": "{}\n",

‎rust/crates/ccusage/src/adapter/goose/paths.rs‎

Lines changed: 3 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -48,35 +48,17 @@ fn default_goose_db_candidates() -> Result<Vec<PathBuf>> {
4848

4949
#[cfg(test)]
5050
mod tests {
51-
use std::{env, path::Path, sync::Mutex};
51+
use std::path::Path;
5252

5353
use super::*;
54-
use ccusage_test_support::fs_fixture;
55-
56-
static ENV_LOCK: Mutex<()> = Mutex::new(());
57-
58-
struct EnvDirGuard;
59-
60-
impl EnvDirGuard {
61-
fn set(dir: &Path) -> Self {
62-
unsafe { env::set_var(GOOSE_PATH_ROOT_ENV, dir) };
63-
Self
64-
}
65-
}
66-
67-
impl Drop for EnvDirGuard {
68-
fn drop(&mut self) {
69-
unsafe { env::remove_var(GOOSE_PATH_ROOT_ENV) };
70-
}
71-
}
54+
use ccusage_test_support::{EnvVarGuard, fs_fixture};
7255

7356
#[test]
7457
fn discovers_goose_path_root_database() {
75-
let _guard = ENV_LOCK.lock().unwrap();
7658
let fixture = fs_fixture!({
7759
"data/sessions/sessions.db": "",
7860
});
79-
let _cleanup = EnvDirGuard::set(fixture.root());
61+
let _cleanup = EnvVarGuard::set(GOOSE_PATH_ROOT_ENV, fixture.root());
8062

8163
let paths = goose_db_paths().unwrap();
8264

‎rust/crates/ccusage/src/adapter/kilo/loader.rs‎

Lines changed: 8 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -102,13 +102,11 @@ fn load_entries_from_database(
102102

103103
#[cfg(test)]
104104
mod tests {
105-
use std::{env, path::Path, sync::Mutex};
105+
use std::path::Path;
106106

107107
use super::*;
108108
use crate::{PricingMap, cli::CostMode};
109-
use ccusage_test_support::fs_fixture;
110-
111-
static KILO_DATA_DIR_LOCK: Mutex<()> = Mutex::new(());
109+
use ccusage_test_support::{EnvVarGuard, fs_fixture};
112110

113111
fn create_db_message(path: &Path, id: &str, session_id: &str, data: &str) {
114112
let db = sqlite::open(path).unwrap();
@@ -125,22 +123,20 @@ mod tests {
125123

126124
#[test]
127125
fn loads_kilo_messages_from_sqlite() {
128-
let _guard = KILO_DATA_DIR_LOCK.lock().unwrap();
129126
let fixture = fs_fixture!({});
130127
create_db_message(
131128
&fixture.path(super::super::paths::KILO_DB_FILE_NAME),
132129
"row-1",
133130
"session-a",
134131
r#"{"id":"msg-1","role":"assistant","providerID":"anthropic","modelID":"claude-sonnet-4-20250514","time":{"created":1767312000000},"tokens":{"input":100,"output":50,"reasoning":5,"cache":{"read":10,"write":20}},"cost":0.02,"agent":"build"}"#,
135132
);
136-
unsafe { env::set_var(super::super::paths::KILO_DATA_DIR_ENV, fixture.root()) };
133+
let _cleanup = EnvVarGuard::set(super::super::paths::KILO_DATA_DIR_ENV, fixture.root());
137134
let shared = SharedArgs {
138135
mode: CostMode::Display,
139136
timezone: Some("UTC".to_string()),
140137
..SharedArgs::default()
141138
};
142139
let entries = load_entries(&shared, &PricingMap::load_embedded()).unwrap();
143-
unsafe { env::remove_var(super::super::paths::KILO_DATA_DIR_ENV) };
144140

145141
assert_eq!(entries.len(), 1);
146142
assert_eq!(entries[0].date, "2026-01-02");
@@ -162,25 +158,22 @@ mod tests {
162158

163159
#[test]
164160
fn ignores_kilo_messages_without_timestamps() {
165-
let _guard = KILO_DATA_DIR_LOCK.lock().unwrap();
166161
let fixture = fs_fixture!({});
167162
create_db_message(
168163
&fixture.path(super::super::paths::KILO_DB_FILE_NAME),
169164
"row-1",
170165
"session-a",
171166
r#"{"role":"assistant","providerID":"openai","modelID":"gpt-5","tokens":{"input":1,"output":1,"cache":{"read":0,"write":0}}}"#,
172167
);
173-
unsafe { env::set_var(super::super::paths::KILO_DATA_DIR_ENV, fixture.root()) };
168+
let _cleanup = EnvVarGuard::set(super::super::paths::KILO_DATA_DIR_ENV, fixture.root());
174169
let shared = SharedArgs::default();
175170
let entries = load_entries(&shared, &PricingMap::load_embedded()).unwrap();
176-
unsafe { env::remove_var(super::super::paths::KILO_DATA_DIR_ENV) };
177171

178172
assert!(entries.is_empty());
179173
}
180174

181175
#[test]
182176
fn deduplicates_kilo_messages_across_data_dirs() {
183-
let _guard = KILO_DATA_DIR_LOCK.lock().unwrap();
184177
let first = fs_fixture!({});
185178
let second = fs_fixture!({});
186179
for (fixture, input) in [(&first, 10), (&second, 20)] {
@@ -193,15 +186,12 @@ mod tests {
193186
),
194187
);
195188
}
196-
unsafe {
197-
env::set_var(
198-
super::super::paths::KILO_DATA_DIR_ENV,
199-
format!("{},{}", first.root().display(), second.root().display()),
200-
)
201-
};
189+
let _cleanup = EnvVarGuard::set(
190+
super::super::paths::KILO_DATA_DIR_ENV,
191+
format!("{},{}", first.root().display(), second.root().display()),
192+
);
202193
let shared = SharedArgs::default();
203194
let entries = load_entries(&shared, &PricingMap::load_embedded()).unwrap();
204-
unsafe { env::remove_var(super::super::paths::KILO_DATA_DIR_ENV) };
205195

206196
assert_eq!(entries.len(), 1);
207197
assert_eq!(entries[0].data.message.usage.input_tokens, 10);

0 commit comments

Comments
 (0)