Debian Codegraph @

cli/tests/common/test_environment.rs

raw
1 // Copyright 2020 The Jujutsu Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::cell::RefCell;
16 use std::collections::HashMap;
17 use std::ffi::OsStr;
18 use std::ffi::OsString;
19 use std::path::Path;
20 use std::path::PathBuf;
21
22 use bstr::BString;
23 use indoc::formatdoc;
24 use itertools::Itertools as _;
25 use regex::Captures;
26 use regex::Regex;
27 use tempfile::TempDir;
28
29 use super::command_output::CommandOutput;
30 use super::command_output::CommandOutputString;
31 use super::fake_bisector_path;
32 use super::fake_diff_editor_path;
33 use super::fake_editor_path;
34 use super::to_toml_value;
35
36 pub struct TestEnvironment {
37 _env_dir: TempDir,
38 env_root: PathBuf,
39 home_dir: PathBuf,
40 tmp_dir: PathBuf,
41 config_path: PathBuf,
42 env_vars: HashMap<OsString, OsString>,
43 paths_to_normalize: Vec<(PathBuf, String)>,
44 config_file_number: RefCell<i64>,
45 command_number: RefCell<i64>,
46 }
47
48 impl Default for TestEnvironment {
49 fn default() -> Self {
50 testutils::hermetic_git();
51
52 let env_dir = testutils::new_temp_dir();
53 let env_root = dunce::canonicalize(env_dir.path()).unwrap();
54 let home_dir = env_root.join("home");
55 std::fs::create_dir(&home_dir).unwrap();
56 let tmp_dir = env_root.join("tmp");
57 std::fs::create_dir(&tmp_dir).unwrap();
58 let config_dir = env_root.join("config");
59 std::fs::create_dir(&config_dir).unwrap();
60 let env_vars = HashMap::new();
61 let paths_to_normalize = [(env_root.clone(), "$TEST_ENV".to_string())]
62 .into_iter()
63 .collect();
64 let env = Self {
65 _env_dir: env_dir,
66 env_root,
67 home_dir,
68 tmp_dir,
69 config_path: config_dir,
70 env_vars,
71 paths_to_normalize,
72 config_file_number: RefCell::new(0),
73 command_number: RefCell::new(0),
74 };
75 // Use absolute timestamps in the operation log to make tests independent of the
76 // current time. Use non-colocated workspaces by default for simplicity.
77 env.add_config(
78 r#"
79 [template-aliases]
80 'format_time_range(time_range)' = 'time_range.start() ++ " - " ++ time_range.end()'
81
82 [git]
83 colocate = false
84 "#,
85 );
86
87 env
88 }
89 }
90
91 impl TestEnvironment {
92 /// Returns test helper for the specified directory.
93 ///
94 /// The `root` path usually points to the workspace root, but it may be
95 /// arbitrary path including non-existent directory.
96 #[must_use]
97 pub fn work_dir(&self, root: impl AsRef<Path>) -> TestWorkDir<'_> {
98 let root = self.env_root.join(root);
99 TestWorkDir { env: self, root }
100 }
101
102 /// Runs `jj args..` in the `current_dir`, returns the output.
103 #[must_use = "either snapshot the output or assert the exit status with .success()"]
104 pub fn run_jj_in<I>(&self, current_dir: impl AsRef<Path>, args: I) -> CommandOutput
105 where
106 I: IntoIterator,
107 I::Item: AsRef<OsStr>,
108 {
109 self.work_dir(current_dir).run_jj(args)
110 }
111
112 /// Runs `jj` command with additional configuration, returns the output.
113 #[must_use = "either snapshot the output or assert the exit status with .success()"]
114 pub fn run_jj_with(
115 &self,
116 configure: impl FnOnce(&mut assert_cmd::Command) -> &mut assert_cmd::Command,
117 ) -> CommandOutput {
118 self.work_dir("").run_jj_with(configure)
119 }
120
121 /// Returns command builder to run `jj` in the test environment.
122 ///
123 /// Use `run_jj_with()` to run command within customized environment.
124 #[must_use]
125 pub fn new_jj_cmd(&self) -> assert_cmd::Command {
126 let jj_path = assert_cmd::cargo::cargo_bin!("jj");
127 let mut cmd = assert_cmd::Command::new(jj_path);
128 cmd.current_dir(&self.env_root);
129 cmd.env_clear();
130 cmd.env("COLUMNS", "100");
131 cmd.env("RUST_BACKTRACE", "1");
132 // We want to keep the "PATH" environment variable to allow accessing
133 // executables like `git` from the PATH.
134 cmd.env("PATH", std::env::var_os("PATH").unwrap_or_default());
135 cmd.env("HOME", &self.home_dir);
136 if !cfg!(windows) {
137 // Override TMPDIR so editor-* files won't be left in global /tmp.
138 // https://doc.rust-lang.org/stable/std/env/fn.temp_dir.html
139 cmd.env("TMPDIR", &self.tmp_dir);
140 } else {
141 // Ensure that our tests don't write to the real %USERPROFILE% or %APPDATA%.
142 cmd.env("USERPROFILE", &self.home_dir);
143 cmd.env("APPDATA", self.home_dir.join(".config"));
144 // On Windows, "/tmp" mounted in Git Bash appears to be leaked to
145 // other Git Bash processes running concurrently, so the TEMP path
146 // has to be stable.
147 cmd.env("TEMP", std::env::temp_dir());
148 }
149 // Prevent git.subprocess from reading outside git config
150 cmd.env("GIT_CONFIG_SYSTEM", "/dev/null");
151 cmd.env("GIT_CONFIG_GLOBAL", "/dev/null");
152 for (i, (key, value)) in testutils::HERMETIC_GIT_CONFIGS.iter().enumerate() {
153 cmd.env(format!("GIT_CONFIG_KEY_{i}"), key);
154 cmd.env(format!("GIT_CONFIG_VALUE_{i}"), value);
155 }
156 cmd.env(
157 "GIT_CONFIG_COUNT",
158 testutils::HERMETIC_GIT_CONFIGS.len().to_string(),
159 );
160 cmd.env("JJ_CONFIG", &self.config_path);
161 cmd.env("JJ_USER", "Test User");
162 cmd.env("JJ_EMAIL", "[email protected]");
163 cmd.env("JJ_OP_HOSTNAME", "host.example.com");
164 cmd.env("JJ_OP_USERNAME", "test-username");
165 cmd.env("JJ_TZ_OFFSET_MINS", "660");
166 // Coverage files should not pollute the working directory
167 if let Some(cov_var) = std::env::var_os("LLVM_PROFILE_FILE") {
168 cmd.env("LLVM_PROFILE_FILE", cov_var);
169 }
170
171 let mut command_number = self.command_number.borrow_mut();
172 *command_number += 1;
173 cmd.env("JJ_RANDOMNESS_SEED", command_number.to_string());
174 let timestamp = chrono::DateTime::parse_from_rfc3339("2001-02-03T04:05:06+07:00").unwrap();
175 let timestamp = timestamp + chrono::Duration::try_seconds(*command_number).unwrap();
176 cmd.env("JJ_TIMESTAMP", timestamp.to_rfc3339());
177 cmd.env("JJ_OP_TIMESTAMP", timestamp.to_rfc3339());
178 for (key, value) in &self.env_vars {
179 cmd.env(key, value);
180 }
181
182 cmd
183 }
184
185 pub fn env_root(&self) -> &Path {
186 &self.env_root
187 }
188
189 pub fn home_dir(&self) -> &Path {
190 &self.home_dir
191 }
192
193 pub fn config_path(&self) -> &PathBuf {
194 &self.config_path
195 }
196
197 pub fn first_config_file_path(&self) -> PathBuf {
198 let config_file_number = 1;
199 self.config_path
200 .join(format!("config{config_file_number:04}.toml"))
201 }
202
203 pub fn last_config_file_path(&self) -> PathBuf {
204 let config_file_number = self.config_file_number.borrow();
205 self.config_path
206 .join(format!("config{config_file_number:04}.toml"))
207 }
208
209 pub fn set_config_path(&mut self, config_path: impl Into<PathBuf>) {
210 self.config_path = config_path.into();
211 }
212
213 pub fn add_config(&self, content: impl AsRef<[u8]>) {
214 if self.config_path.is_file() {
215 panic!("add_config not supported when config_path is a file");
216 }
217 // Concatenating two valid TOML files does not (generally) result in a valid
218 // TOML file, so we create a new file every time instead.
219 let mut config_file_number = self.config_file_number.borrow_mut();
220 *config_file_number += 1;
221 let config_file_number = *config_file_number;
222 std::fs::write(
223 self.config_path
224 .join(format!("config{config_file_number:04}.toml")),
225 content,
226 )
227 .unwrap();
228 }
229
230 pub fn add_env_var(&mut self, key: impl Into<OsString>, val: impl Into<OsString>) {
231 self.env_vars.insert(key.into(), val.into());
232 }
233
234 pub fn add_paths_to_normalize(
235 &mut self,
236 path: impl Into<PathBuf>,
237 replacement: impl Into<String>,
238 ) {
239 self.paths_to_normalize
240 .push((path.into(), replacement.into()));
241 }
242
243 /// Sets up echo as a merge tool.
244 ///
245 /// Windows machines may not have the echo executable installed.
246 pub fn set_up_fake_echo_merge_tool(&self) {
247 let echo_path = assert_cmd::cargo::cargo_bin!("fake-echo");
248 assert!(echo_path.is_file());
249 let echo_path = to_toml_value(echo_path.to_str().unwrap());
250 self.add_config(formatdoc!("merge-tools.fake-echo.program = {echo_path}"));
251 }
252
253 /// Sets up the fake bisection test command to read a script from the
254 /// returned path
255 pub fn set_up_fake_bisector(&mut self) -> PathBuf {
256 self.add_paths_to_normalize(fake_bisector_path(), "$FAKE_BISECTOR_PATH");
257 let bisection_script = self.env_root().join("bisection_script");
258 std::fs::write(&bisection_script, "").unwrap();
259 self.add_env_var("BISECTION_SCRIPT", &bisection_script);
260 bisection_script
261 }
262
263 /// Sets up the fake editor to read an edit script from the returned path
264 /// Also sets up the fake editor as a merge tool named "fake-editor"
265 pub fn set_up_fake_editor(&mut self) -> PathBuf {
266 let editor_path = to_toml_value(fake_editor_path());
267 self.add_config(formatdoc! {r#"
268 [ui]
269 editor = {editor_path}
270 merge-editor = "fake-editor"
271
272 [merge-tools]
273 fake-editor.program = {editor_path}
274 fake-editor.merge-args = ["$output"]
275 "#});
276 let edit_script = self.env_root().join("edit_script");
277 std::fs::write(&edit_script, "").unwrap();
278 self.add_env_var("EDIT_SCRIPT", &edit_script);
279 edit_script
280 }
281
282 /// Sets up the fake diff-editor to read an edit script from the returned
283 /// path
284 pub fn set_up_fake_diff_editor(&mut self) -> PathBuf {
285 let diff_editor_path = to_toml_value(fake_diff_editor_path());
286 self.add_config(formatdoc! {r#"
287 ui.diff-editor = "fake-diff-editor"
288 merge-tools.fake-diff-editor.program = {diff_editor_path}
289 "#});
290 let edit_script = self.env_root().join("diff_edit_script");
291 std::fs::write(&edit_script, "").unwrap();
292 self.add_env_var("DIFF_EDIT_SCRIPT", &edit_script);
293 edit_script
294 }
295
296 #[must_use]
297 fn normalize_output(&self, raw: String) -> CommandOutputString {
298 let mut normalized = raw.replace("jj.exe", "jj");
299 for (path, replacement) in &self.paths_to_normalize {
300 let path = path.display().to_string();
301 // Platform-native $TEST_ENV
302 let regex = Regex::new(&format!(r"{}((:?[/\\]\S+)?)", regex::escape(&path))).unwrap();
303 normalized = regex
304 .replace_all(&normalized, |caps: &Captures| {
305 format!("{}{}", replacement, caps[1].replace('\\', "/"))
306 })
307 .to_string();
308 // Slash-separated $TEST_ENV
309 if cfg!(windows) {
310 let regex = Regex::new(&regex::escape(&path.replace('\\', "/"))).unwrap();
311 normalized = regex
312 .replace_all(&normalized, regex::NoExpand(replacement))
313 .to_string();
314 }
315 }
316 CommandOutputString { raw, normalized }
317 }
318
319 /// Used before mutating operations to create more predictable commit ids
320 /// and change ids in tests
321 ///
322 /// `test_env.advance_test_rng_seed_to_multiple_of(200_000)` can be inserted
323 /// wherever convenient throughout your test. If desired, you can have
324 /// "subheadings" with steps of (e.g.) 10_000, 500, 25.
325 pub fn advance_test_rng_seed_to_multiple_of(&self, step: i64) {
326 assert!(step > 0, "step must be >0, got {step}");
327 let mut command_number = self.command_number.borrow_mut();
328 *command_number = step * (*command_number / step) + step;
329 }
330 }
331
332 /// Helper to execute `jj` or file operation in sub directory.
333 pub struct TestWorkDir<'a> {
334 env: &'a TestEnvironment,
335 root: PathBuf,
336 }
337
338 impl TestWorkDir<'_> {
339 /// Path to the working directory.
340 pub fn root(&self) -> &Path {
341 &self.root
342 }
343
344 /// Runs `jj args..` in the working directory, returns the output.
345 #[must_use = "either snapshot the output or assert the exit status with .success()"]
346 pub fn run_jj<I>(&self, args: I) -> CommandOutput
347 where
348 I: IntoIterator,
349 I::Item: AsRef<OsStr>,
350 {
351 self.run_jj_with(|cmd| cmd.args(args))
352 }
353
354 /// Runs `jj` command with additional configuration, returns the output.
355 #[must_use = "either snapshot the output or assert the exit status with .success()"]
356 pub fn run_jj_with(
357 &self,
358 configure: impl FnOnce(&mut assert_cmd::Command) -> &mut assert_cmd::Command,
359 ) -> CommandOutput {
360 let env = &self.env;
361 let mut cmd = env.new_jj_cmd();
362 let output = configure(cmd.current_dir(&self.root)).output().unwrap();
363 CommandOutput {
364 stdout: env.normalize_output(String::from_utf8(output.stdout).unwrap()),
365 stderr: env.normalize_output(String::from_utf8(output.stderr).unwrap()),
366 status: output.status,
367 }
368 }
369
370 /// Reads the current operation id without resolving divergence nor
371 /// snapshotting. `TestWorkDir` must be at the workspace root.
372 #[track_caller]
373 pub fn current_operation_id(&self) -> String {
374 let heads_dir = self
375 .root()
376 .join(PathBuf::from_iter([".jj", "repo", "op_heads", "heads"]));
377 let head_entry = heads_dir
378 .read_dir()
379 .expect("TestWorkDir must point to the workspace root")
380 .exactly_one()
381 .expect("divergence not supported")
382 .unwrap();
383 head_entry.file_name().into_string().unwrap()
384 }
385
386 /// Returns test helper for the specified sub directory.
387 #[must_use]
388 pub fn dir(&self, path: impl AsRef<Path>) -> Self {
389 let env = self.env;
390 let root = self.root.join(path);
391 TestWorkDir { env, root }
392 }
393
394 #[track_caller]
395 pub fn create_dir(&self, path: impl AsRef<Path>) -> Self {
396 let dir = self.dir(path);
397 std::fs::create_dir(&dir.root).unwrap();
398 dir
399 }
400
401 #[track_caller]
402 pub fn create_dir_all(&self, path: impl AsRef<Path>) -> Self {
403 let dir = self.dir(path);
404 std::fs::create_dir_all(&dir.root).unwrap();
405 dir
406 }
407
408 #[track_caller]
409 pub fn remove_dir_all(&self, path: impl AsRef<Path>) {
410 std::fs::remove_dir_all(self.root.join(path)).unwrap();
411 }
412
413 #[track_caller]
414 pub fn remove_file(&self, path: impl AsRef<Path>) {
415 std::fs::remove_file(self.root.join(path)).unwrap();
416 }
417
418 #[track_caller]
419 pub fn read_file(&self, path: impl AsRef<Path>) -> BString {
420 std::fs::read(self.root.join(path)).unwrap().into()
421 }
422
423 #[track_caller]
424 pub fn write_file(&self, path: impl AsRef<Path>, contents: impl AsRef<[u8]>) {
425 let path = path.as_ref();
426 if let Some(dir) = path.parent() {
427 self.create_dir_all(dir);
428 }
429 std::fs::write(self.root.join(path), contents).unwrap();
430 }
431 }