Read the contents of an existing golden file, or create it by turning `fallback` into string first.
(
prefix: &str,
name: &str,
ext: &str,
fallback: &T,
to_string: fn(&T) -> String,
)
| 18 | |
| 19 | /// Read the contents of an existing golden file, or create it by turning `fallback` into string first. |
| 20 | fn read_or_create<T>( |
| 21 | prefix: &str, |
| 22 | name: &str, |
| 23 | ext: &str, |
| 24 | fallback: &T, |
| 25 | to_string: fn(&T) -> String, |
| 26 | ) -> String { |
| 27 | let p = path(prefix, name, ext); |
| 28 | let p = Path::new(&p); |
| 29 | |
| 30 | if !p.exists() { |
| 31 | if let Some(p) = p.parent() { |
| 32 | fs::create_dir_all(p).expect("failed to create golden directory"); |
| 33 | } |
| 34 | let s = to_string(fallback); |
| 35 | let mut f = File::create(p) |
| 36 | .unwrap_or_else(|e| panic!("Cannot create golden file at {:?}: {}", p, e)); |
| 37 | f.write_all(s.as_bytes()).unwrap(); |
| 38 | } |
| 39 | |
| 40 | let mut f = |
| 41 | File::open(p).unwrap_or_else(|e| panic!("Cannot open golden file at {:?}: {}", p, e)); |
| 42 | |
| 43 | let mut s = String::new(); |
| 44 | f.read_to_string(&mut s).expect("Cannot read golden file."); |
| 45 | s.trim_end().to_owned() |
| 46 | } |
| 47 | |
| 48 | /// Check that a golden file we created earlier can still be read by the current model by |
| 49 | /// comparing to a debug string (which should at least be readable enough to show what changed). |