1use std::path::{Path, PathBuf};
2
3pub struct TmpFile {
4 dir: tempfile::TempDir,
6 path: PathBuf,
8}
9
10impl TmpFile {
11 pub fn new(file_name: impl AsRef<Path>) -> Self {
13 let dir = tempfile::TempDir::new().unwrap();
14 let path = dir.path().join(file_name);
15 std::fs::File::create_new(&path).unwrap();
16 Self { dir, path }
17 }
18
19 pub fn write(&self, data: impl AsRef<[u8]>) {
21 std::fs::write(&self.path, data.as_ref()).unwrap();
22 }
23
24 pub fn assert(&self, expected: impl AsRef<[u8]>) {
26 let actual = std::fs::read(&self.path).unwrap();
27 let expected = expected.as_ref();
28 if actual != expected {
29 println!("expected content: {:?}", expected);
30 println!(" actual content: {:?}", actual);
31 panic!("unexpected content")
32 }
33 }
34
35 pub fn dir(&self) -> &Path {
37 self.dir.path()
38 }
39
40 pub fn path(&self) -> &Path {
42 &self.path
43 }
44
45 pub fn set_readonly(&self, readonly: bool) {
47 let mut permissions = std::fs::metadata(self.path()).unwrap().permissions();
48 permissions.set_readonly(readonly);
49 std::fs::set_permissions(self.path(), permissions).unwrap();
50 }
51}