Skip to main content

zero_bounce/utility/structures/
validation.rs

1use chrono::NaiveDateTime;
2use serde::Deserialize;
3
4use crate::utility::structures::custom_deserialize::{deserialize_naive_date, null_as_default};
5use crate::utility::structures::validate_enums::{ZBValidateStatus, ZBValidateSubStatus};
6
7
8/// One validation result.
9///
10/// `#[non_exhaustive]`: the API adds response fields over time, and a field
11/// added later is not a breaking change. Values come from the API (or from
12/// `serde_json` in tests); there is no struct literal outside this crate.
13#[derive(Clone, Debug, Deserialize)]
14#[non_exhaustive]
15pub struct ZBValidation {
16    // These default rather than fail: a repeated greylist_processing request
17    // answers with nothing but "Message" (see `message`).
18    #[serde(default)]
19    pub address: String,
20    #[serde(default)]
21    pub status: String,
22    #[serde(default, deserialize_with = "null_as_default")]
23    pub sub_status: String,
24    #[serde(default, deserialize_with = "null_as_default")]
25    pub free_email: bool,
26    pub did_you_mean: Option<String>,
27    pub account: Option<String>,
28    pub domain: Option<String>,
29    pub domain_age_days: Option<String>,
30    pub active_in_days: Option<String>,
31    pub active_first_seen: Option<String>,
32    pub smtp_provider: Option<String>,
33    pub catchall_domain: Option<bool>,
34    pub mx_record: Option<String>,
35    pub mx_found: Option<String>,
36    pub firstname: Option<String>,
37    pub lastname: Option<String>,
38    pub gender: Option<String>,
39    pub country: Option<String>,
40    pub region: Option<String>,
41    pub city: Option<String>,
42    pub zipcode: Option<String>,
43
44    /// With `domain_info`: whether the domain has a website ("True", "False" or "unchecked").
45    pub domain_website_exists: Option<String>,
46
47    /// With `domain_info`: the WHOIS registrant company, "Registrant info not found"
48    /// or "unchecked".
49    pub domain_registrant_company_name: Option<String>,
50
51    /// Set instead of a result while greylist processing is still running; validate
52    /// again later to pick it up. The API spells this key "Message".
53    #[serde(rename = "Message")]
54    pub message: Option<String>,
55
56    /// A greylist pickup that is still running carries no timestamp, so this
57    /// defaults rather than failing the whole response.
58    #[serde(default, deserialize_with="deserialize_naive_date")]
59    pub processed_at: NaiveDateTime,
60}
61
62impl ZBValidation {
63    /// Parse `status` string into typed enum (unknown API values become `ZBValidateStatus::UnknownValue`).
64    pub fn status_enum(&self) -> ZBValidateStatus {
65        self.status.parse().unwrap_or_else(|_| ZBValidateStatus::UnknownValue(self.status.clone()))
66    }
67
68    /// Parse `sub_status` string into typed enum (unknown API values become `ZBValidateSubStatus::UnknownValue`).
69    pub fn sub_status_enum(&self) -> ZBValidateSubStatus {
70        self.sub_status.parse().unwrap_or_else(|_| ZBValidateSubStatus::UnknownValue(self.sub_status.clone()))
71    }
72}
73
74
75#[derive(Clone, Debug, Deserialize)]
76pub struct ZBBatchError {
77    #[serde(deserialize_with = "null_as_default")]
78    pub error: String,
79    #[serde(deserialize_with = "null_as_default")]
80    pub email_address: String,
81}
82
83
84#[derive(Clone, Debug, Deserialize)]
85pub struct ZBBatchValidation {
86    #[serde(deserialize_with = "null_as_default")]
87    pub email_batch: Vec<ZBValidation>,
88    #[serde(deserialize_with = "null_as_default")]
89    pub errors: Vec<ZBBatchError>,
90}
91
92#[cfg(test)]
93mod test {
94    use serde_json::{Result as SerdeResult, from_str};
95
96    use super::*;
97    use crate::utility::mock_constants::VALIDATION_RESPONSE_VALID;
98    use crate::utility::mock_constants::VALIDATION_RESPONSE_INVALID;
99    use crate::utility::mock_constants::VALIDATION_RESPONSE_NULL_FIELDS;
100    use crate::utility::mock_constants::BATCH_VALIDATION_WITH_ERROR;
101    use crate::utility::mock_constants::BATCH_VALIDATION_ERROR_ONLY;
102    use crate::utility::mock_constants::BATCH_VALIDATION_NO_ERROR;
103
104    #[test]
105    fn test_validation_invalid_json() {
106        let validation_res: SerdeResult<ZBValidation> = from_str("");
107        assert!(validation_res.is_err());
108    }
109
110    #[test]
111    fn test_validation_missing_expected_fields() {
112        let validation_res: SerdeResult<ZBValidation> = from_str(VALIDATION_RESPONSE_NULL_FIELDS);
113        assert!(validation_res.is_ok());
114
115        let validation = validation_res.unwrap();
116        assert_eq!(validation.did_you_mean, None);
117        assert_eq!(validation.domain_age_days, Some("".to_string()));
118    }
119
120    #[test]
121    fn test_validation_invalid_email_status() {
122        let validation_res: SerdeResult<ZBValidation> = from_str(VALIDATION_RESPONSE_INVALID);
123        assert!(validation_res.is_ok());
124
125        let validation = validation_res.unwrap();
126        assert_eq!(validation.status, "invalid".to_string());
127        assert_eq!(validation.sub_status, "mailbox_not_found".to_string());
128        assert_eq!(validation.did_you_mean, None);
129        assert_eq!(validation.smtp_provider, Some("example".to_string()));
130        assert!(!validation.free_email);
131
132        let expected_date = NaiveDateTime::new(
133            chrono::NaiveDate::from_ymd_opt(2023, 3, 23).unwrap(),
134            chrono::NaiveTime::from_hms_milli_opt(12, 30, 28, 3).unwrap(),
135        );
136        assert_eq!(validation.processed_at, expected_date);
137    }
138
139    #[test]
140    fn test_validation_valid_email_status() {
141        let validation_res: SerdeResult<ZBValidation> = from_str(VALIDATION_RESPONSE_VALID);
142        assert!(validation_res.is_ok());
143
144        let validation = validation_res.unwrap();
145        assert_eq!(validation.status, "valid".to_string());
146        assert_eq!(validation.sub_status, "".to_string());
147        assert_eq!(validation.did_you_mean, None);
148        assert_eq!(validation.smtp_provider, Some("example".to_string()));
149        assert_eq!(validation.catchall_domain, Some(false));
150        assert!(!validation.free_email);
151
152        let expected_date = NaiveDateTime::new(
153            chrono::NaiveDate::from_ymd_opt(2023, 3, 23).unwrap(),
154            chrono::NaiveTime::from_hms_milli_opt(13, 30, 28, 105).unwrap(),
155        );
156        assert_eq!(validation.processed_at, expected_date);
157    }
158
159    #[test]
160    fn test_batch_error_only_content() {
161        let batch: SerdeResult<ZBBatchValidation> = from_str(BATCH_VALIDATION_ERROR_ONLY);
162        assert!(batch.is_ok());
163
164        let batch_object = batch.unwrap();
165        assert_eq!(batch_object.email_batch.len(), 0);
166        assert_eq!(batch_object.errors.len(), 1);
167    }
168
169    #[test]
170    fn test_batch_validation_and_error_content() {
171        let batch: SerdeResult<ZBBatchValidation> = from_str(BATCH_VALIDATION_WITH_ERROR);
172        assert!(batch.is_ok());
173
174        let batch_object = batch.unwrap();
175        assert_eq!(batch_object.email_batch.len(), 1);
176        assert_eq!(batch_object.errors.len(), 1);
177    }
178
179    #[test]
180    fn test_batch_validation_only_content() {
181        let batch: SerdeResult<ZBBatchValidation> = from_str(BATCH_VALIDATION_NO_ERROR);
182        assert!(batch.is_ok());
183
184        let batch_object = batch.unwrap();
185        assert_eq!(batch_object.email_batch.len(), 1);
186        assert_eq!(batch_object.errors.len(), 0);
187    }
188
189}