waves_rust/model/
validation.rs1use crate::error::{Error, Result};
2use crate::util::JsonDeserializer;
3use serde_json::Value;
4
5#[derive(Clone, Eq, PartialEq, Debug)]
6pub struct Validation {
7 valid: bool,
8 validation_time: u64,
9 error: Option<String>,
10}
11
12impl Validation {
13 pub fn new(valid: bool, validation_time: u64, error: Option<String>) -> Self {
14 Self {
15 valid,
16 validation_time,
17 error,
18 }
19 }
20
21 pub fn valid(&self) -> bool {
22 self.valid
23 }
24
25 pub fn validation_time(&self) -> u64 {
26 self.validation_time
27 }
28
29 pub fn error(&self) -> Option<String> {
30 self.error.clone()
31 }
32}
33
34impl TryFrom<&Value> for Validation {
35 type Error = Error;
36
37 fn try_from(value: &Value) -> Result<Self> {
38 let valid = JsonDeserializer::safe_to_boolean_from_field(value, "valid")?;
39 let validation_time = JsonDeserializer::safe_to_int_from_field(value, "validationTime")?;
40 let error = value["error"].as_str().map(|it| it.to_owned());
41 Ok(Validation {
42 valid,
43 validation_time: validation_time as u64,
44 error,
45 })
46 }
47}
48
49#[cfg(test)]
50mod tests {
51 use crate::error::Result;
52 use crate::model::Validation;
53
54 use serde_json::Value;
55 use std::borrow::Borrow;
56 use std::fs;
57
58 #[test]
59 fn test_json_to_validation() -> Result<()> {
60 let data = fs::read_to_string("./tests/resources/validation_rs.json")
61 .expect("Unable to read file");
62 let json: Value = serde_json::from_str(&data).expect("failed to generate json from str");
63
64 let validation: Validation = json.borrow().try_into()?;
65
66 assert_eq!(validation.valid(), true);
67 assert_eq!(validation.validation_time(), 3);
68 assert_eq!(validation.error().unwrap(), "some error");
69 Ok(())
70 }
71}