74 lines
1.8 KiB
Rust
Raw Normal View History

2023-01-30 11:11:19 +08:00
use crate::errors::UserErrorCode;
use validator::validate_email;
#[derive(Debug)]
2021-07-05 16:54:41 +08:00
pub struct UserEmail(pub String);
impl UserEmail {
2023-01-30 11:11:19 +08:00
pub fn parse(s: String) -> Result<UserEmail, UserErrorCode> {
2021-07-06 14:14:47 +08:00
if s.trim().is_empty() {
2023-01-30 11:11:19 +08:00
return Err(UserErrorCode::EmailIsEmpty);
2021-07-06 14:14:47 +08:00
}
if validate_email(&s) {
Ok(Self(s))
} else {
2023-01-30 11:11:19 +08:00
Err(UserErrorCode::EmailFormatInvalid)
}
}
}
impl AsRef<str> for UserEmail {
2022-01-23 12:14:00 +08:00
fn as_ref(&self) -> &str {
&self.0
}
}
#[cfg(test)]
mod tests {
use super::*;
use claim::assert_err;
use fake::{faker::internet::en::SafeEmail, Fake};
2022-04-29 09:23:36 +08:00
use rand::prelude::StdRng;
use rand_core::SeedableRng;
#[test]
fn empty_string_is_rejected() {
let email = "".to_string();
assert_err!(UserEmail::parse(email));
}
#[test]
fn email_missing_at_symbol_is_rejected() {
let email = "helloworld.com".to_string();
assert_err!(UserEmail::parse(email));
}
#[test]
fn email_missing_subject_is_rejected() {
let email = "@domain.com".to_string();
assert_err!(UserEmail::parse(email));
}
#[derive(Debug, Clone)]
struct ValidEmailFixture(pub String);
impl quickcheck::Arbitrary for ValidEmailFixture {
2022-04-29 09:23:36 +08:00
fn arbitrary(g: &mut quickcheck::Gen) -> Self {
let mut rand_slice: [u8; 32] = [0; 32];
2022-05-11 11:34:13 +08:00
#[allow(clippy::needless_range_loop)]
2022-04-29 09:23:36 +08:00
for i in 0..32 {
rand_slice[i] = u8::arbitrary(g);
}
let mut seed = StdRng::from_seed(rand_slice);
let email = SafeEmail().fake_with_rng(&mut seed);
Self(email)
}
}
#[quickcheck_macros::quickcheck]
fn valid_emails_are_parsed_successfully(valid_email: ValidEmailFixture) -> bool {
UserEmail::parse(valid_email.0).is_ok()
}
}