on 5f6e310 help sign in
bat/tests/tester.rs
100 lines 3.0 kB history raw
1use std::env;
2use std::fs::{self, File};
3use std::io::Read;
4use std::path::{Path, PathBuf};
5use std::process::Command;
7use tempdir::TempDir;
9use git2::build::CheckoutBuilder;
10use git2::Repository;
11use git2::Signature;
13pub struct BatTester {
14 /// Temporary working directory
15 temp_dir: TempDir,
17 /// Path to the *bat* executable
18 exe: PathBuf,
21impl BatTester {
22 pub fn new() -> Self {
23 let temp_dir = create_sample_directory().expect("sample directory");
25 let root = env::current_exe()
26 .expect("tests executable")
27 .parent()
28 .expect("tests executable directory")
29 .parent()
30 .expect("bat executable directory")
31 .to_path_buf();
33 let exe_name = if cfg!(windows) { "bat.exe" } else { "bat" };
34 let exe = root.join(exe_name);
36 BatTester { temp_dir, exe }
37 }
39 pub fn test_snapshot(&self, name: &str, style: &str) {
40 let output = Command::new(&self.exe)
41 .current_dir(self.temp_dir.path())
42 .args(&[
43 "sample.rs",
44 "--no-config",
45 "--paging=never",
46 "--color=never",
47 "--decorations=always",
48 "--terminal-width=80",
49 &format!("--style={}", style),
50 ])
51 .output()
52 .expect("bat failed");
54 // have to do the replace because the filename in the header changes based on the current working directory
55 let actual = String::from_utf8_lossy(&output.stdout)
56 .as_ref()
57 .replace("tests/snapshots/", "");
59 let mut expected = String::new();
60 let mut file = File::open(format!("tests/snapshots/output/{}.snapshot.txt", name))
61 .expect("snapshot file missing");
62 file.read_to_string(&mut expected)
63 .expect("could not read snapshot file");
65 assert_eq!(expected, actual);
66 }
69fn create_sample_directory() -> Result<TempDir, git2::Error> {
70 // Create temp directory and initialize repository
71 let temp_dir = TempDir::new("bat-tests").expect("Temp directory");
72 let repo = Repository::init(&temp_dir)?;
74 // Copy over `sample.rs`
75 let sample_path = temp_dir.path().join("sample.rs");
76 println!("{:?}", &sample_path);
77 fs::copy("tests/snapshots/sample.rs", &sample_path).expect("successful copy");
79 // Commit
80 let mut index = repo.index()?;
81 index.add_path(Path::new("sample.rs"))?;
83 let oid = index.write_tree()?;
84 let signature = Signature::now("bat test runner", "bat@test.runner")?;
85 let tree = repo.find_tree(oid)?;
86 let _ = repo.commit(
87 Some("HEAD"), // point HEAD to our new commit
88 &signature, // author
89 &signature, // committer
90 "initial commit",
91 &tree,
92 &[],
93 );
94 let mut opts = CheckoutBuilder::new();
95 repo.checkout_head(Some(opts.force()))?;
97 fs::copy("tests/snapshots/sample.modified.rs", &sample_path).expect("successful copy");
99 Ok(temp_dir)