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;
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)]
23    pub sub_status: String,
24    #[serde(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    pub error: String,
78    pub email_address: String,
79}
80
81
82#[derive(Clone, Debug, Deserialize)]
83pub struct ZBBatchValidation {
84    pub email_batch: Vec<ZBValidation>,
85    pub errors: Vec<ZBBatchError>,
86}
87
88#[cfg(test)]
89mod test {
90    use serde_json::{Result as SerdeResult, from_str};
91
92    use super::*;
93    use crate::utility::mock_constants::VALIDATION_RESPONSE_VALID;
94    use crate::utility::mock_constants::VALIDATION_RESPONSE_INVALID;
95    use crate::utility::mock_constants::VALIDATION_RESPONSE_NULL_FIELDS;
96    use crate::utility::mock_constants::BATCH_VALIDATION_WITH_ERROR;
97    use crate::utility::mock_constants::BATCH_VALIDATION_ERROR_ONLY;
98    use crate::utility::mock_constants::BATCH_VALIDATION_NO_ERROR;
99
100    #[test]
101    fn test_validation_invalid_json() {
102        let validation_res: SerdeResult<ZBValidation> = from_str("");
103        assert!(validation_res.is_err());
104    }
105
106    #[test]
107    fn test_validation_missing_expected_fields() {
108        let validation_res: SerdeResult<ZBValidation> = from_str(VALIDATION_RESPONSE_NULL_FIELDS);
109        assert!(validation_res.is_ok());
110
111        let validation = validation_res.unwrap();
112        assert_eq!(validation.did_you_mean, None);
113        assert_eq!(validation.domain_age_days, Some("".to_string()));
114    }
115
116    #[test]
117    fn test_validation_invalid_email_status() {
118        let validation_res: SerdeResult<ZBValidation> = from_str(VALIDATION_RESPONSE_INVALID);
119        assert!(validation_res.is_ok());
120
121        let validation = validation_res.unwrap();
122        assert_eq!(validation.status, "invalid".to_string());
123        assert_eq!(validation.sub_status, "mailbox_not_found".to_string());
124        assert_eq!(validation.did_you_mean, None);
125        assert_eq!(validation.smtp_provider, Some("example".to_string()));
126        assert!(!validation.free_email);
127
128        let expected_date = NaiveDateTime::new(
129            chrono::NaiveDate::from_ymd_opt(2023, 3, 23).unwrap(),
130            chrono::NaiveTime::from_hms_milli_opt(12, 30, 28, 3).unwrap(),
131        );
132        assert_eq!(validation.processed_at, expected_date);
133    }
134
135    #[test]
136    fn test_validation_valid_email_status() {
137        let validation_res: SerdeResult<ZBValidation> = from_str(VALIDATION_RESPONSE_VALID);
138        assert!(validation_res.is_ok());
139
140        let validation = validation_res.unwrap();
141        assert_eq!(validation.status, "valid".to_string());
142        assert_eq!(validation.sub_status, "".to_string());
143        assert_eq!(validation.did_you_mean, None);
144        assert_eq!(validation.smtp_provider, Some("example".to_string()));
145        assert_eq!(validation.catchall_domain, Some(false));
146        assert!(!validation.free_email);
147
148        let expected_date = NaiveDateTime::new(
149            chrono::NaiveDate::from_ymd_opt(2023, 3, 23).unwrap(),
150            chrono::NaiveTime::from_hms_milli_opt(13, 30, 28, 105).unwrap(),
151        );
152        assert_eq!(validation.processed_at, expected_date);
153    }
154
155    #[test]
156    fn test_batch_error_only_content() {
157        let batch: SerdeResult<ZBBatchValidation> = from_str(BATCH_VALIDATION_ERROR_ONLY);
158        assert!(batch.is_ok());
159
160        let batch_object = batch.unwrap();
161        assert_eq!(batch_object.email_batch.len(), 0);
162        assert_eq!(batch_object.errors.len(), 1);
163    }
164
165    #[test]
166    fn test_batch_validation_and_error_content() {
167        let batch: SerdeResult<ZBBatchValidation> = from_str(BATCH_VALIDATION_WITH_ERROR);
168        assert!(batch.is_ok());
169
170        let batch_object = batch.unwrap();
171        assert_eq!(batch_object.email_batch.len(), 1);
172        assert_eq!(batch_object.errors.len(), 1);
173    }
174
175    #[test]
176    fn test_batch_validation_only_content() {
177        let batch: SerdeResult<ZBBatchValidation> = from_str(BATCH_VALIDATION_NO_ERROR);
178        assert!(batch.is_ok());
179
180        let batch_object = batch.unwrap();
181        assert_eq!(batch_object.email_batch.len(), 1);
182        assert_eq!(batch_object.errors.len(), 0);
183    }
184
185}