MCPcopy Create free account
hub / github.com/consensus-shipyard/ipc / read_or_create

Function read_or_create

fendermint/testing/src/golden.rs:20–46  ·  view source on GitHub ↗

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,
)

Source from the content-addressed store, hash-verified

18
19/// Read the contents of an existing golden file, or create it by turning `fallback` into string first.
20fn 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).

Callers 2

test_txtFunction · 0.85
test_cidFunction · 0.85

Calls 5

pathFunction · 0.85
create_dir_allFunction · 0.85
openFunction · 0.85
existsMethod · 0.80
parentMethod · 0.45

Tested by 2

test_txtFunction · 0.68
test_cidFunction · 0.68