Skip to content

Commit

Permalink
Add try_from
Browse files Browse the repository at this point in the history
  • Loading branch information
theory committed Jul 31, 2024
1 parent d6a09c0 commit 9affbc9
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/valid/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,17 @@ impl Validator {
}
}

impl TryFrom<&str> for Validator {
type Error = Box<dyn Error>;
/// try_from creates and returns a new Validator with the schema loaded
/// from `str`.
fn try_from(str: &str) -> Result<Self, Self::Error> {
let compiler = super::compiler::from_str(str)?;
let schemas = Schemas::new();
Ok(Validator { compiler, schemas })
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -109,6 +120,29 @@ mod tests {
Ok(())
}

#[test]
fn test_from() -> Result<(), Box<dyn Error>> {
let schema_v1 = include_str!(concat!(env!("OUT_DIR"), "/pgxn-meta-v1.schema.json"));
let schema_v2 = include_str!(concat!(env!("OUT_DIR"), "/pgxn-meta-v2.schema.json"));

for tc in [
("v1", "widget.json", schema_v1),
("v2", "typical-sql.json", schema_v2),
] {
// Test v1 schema.
let mut validator = Validator::try_from(tc.2)?;

let path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("corpus")
.join(tc.0)
.join(tc.1);
let meta: Value = serde_json::from_reader(File::open(path)?)?;
assert!(validator.validate(&meta).is_ok());
}

Ok(())
}
#[test]
fn test_errors() {
assert_eq!(
Expand Down

0 comments on commit 9affbc9

Please sign in to comment.