Skip to main content

rain_metadata/cli/
validate.rs

1use clap::Parser;
2use std::path::PathBuf;
3use crate::meta::KnownMeta;
4
5/// command for validating a meta
6#[derive(Parser)]
7pub struct Validate {
8    /// The known meta to validate against.
9    #[arg(short, long)]
10    meta: KnownMeta,
11    /// The input path to the json serialized metadata to validate against the
12    /// known schema.
13    #[arg(short, long)]
14    input_path: PathBuf,
15}
16
17pub fn validate(v: Validate) -> anyhow::Result<()> {
18    let data: Vec<u8> = std::fs::read(v.input_path)?;
19    // If we can normalize the input data then it is valid.
20    let _normalized = v.meta.normalize(&data)?;
21    Ok(())
22}
23
24#[cfg(all(test, not(target_family = "wasm")))]
25mod tests {
26    use super::*;
27    use std::io::Write;
28
29    /// A meta that normalizes is valid.
30    #[test]
31    fn test_validate_ok_for_valid_meta() {
32        let mut file = tempfile::NamedTempFile::new().unwrap();
33        file.write_all(b"[]").unwrap();
34        let v = Validate {
35            meta: KnownMeta::SolidityAbiV2,
36            input_path: file.path().to_path_buf(),
37        };
38        assert!(validate(v).is_ok());
39    }
40
41    /// A meta that does not normalize is invalid: validity IS
42    /// normalizability.
43    #[test]
44    fn test_validate_err_for_invalid_meta() {
45        let mut file = tempfile::NamedTempFile::new().unwrap();
46        file.write_all(b"{\"not\": \"an abi\"}").unwrap();
47        let v = Validate {
48            meta: KnownMeta::SolidityAbiV2,
49            input_path: file.path().to_path_buf(),
50        };
51        assert!(validate(v).is_err());
52    }
53
54    /// Arbitrary bytes are not a valid authoring-meta-v2.
55    #[test]
56    fn test_validate_err_for_arbitrary_authoring_meta_v2() {
57        let mut file = tempfile::NamedTempFile::new().unwrap();
58        file.write_all(&[0xde, 0xad]).unwrap();
59        let v = Validate {
60            meta: KnownMeta::AuthoringMetaV2,
61            input_path: file.path().to_path_buf(),
62        };
63        assert!(validate(v).is_err());
64    }
65}