feat: impl Add for Price

This commit is contained in:
Aravinth Manivannan 2024-09-18 14:05:04 +05:30
parent dbbbb86a8c
commit 384dae69f5
Signed by: realaravinth
GPG key ID: F8F50389936984FF

View file

@ -2,7 +2,7 @@
// //
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
use std::str::FromStr; use std::{ops::Add, str::FromStr};
use async_trait::async_trait; use async_trait::async_trait;
use cqrs_es::Aggregate; use cqrs_es::Aggregate;
@ -62,6 +62,16 @@ impl Price {
} }
} }
impl Add for Price {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
let self_minor = self.major_as_minor() + self.minor;
let rhs_minor = rhs.major_as_minor() + rhs.minor;
Self::from_minor(self_minor + rhs_minor, self.currency)
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@ -110,4 +120,70 @@ mod tests {
} }
); );
} }
#[test]
fn test_price_add() {
let a = Price {
minor: 10,
major: 100,
currency: Currency::INR,
};
let b = Price {
minor: 1,
major: 200,
currency: Currency::INR,
};
assert_eq!(
a + b,
Price {
minor: 11,
major: 300,
currency: Currency::INR
}
);
}
#[test]
fn test_price_add_zero() {
let a = Price {
minor: 0,
major: 0,
currency: Currency::INR,
};
assert_eq!(
a.clone() + a,
Price {
minor: 0,
major: 0,
currency: Currency::INR
}
);
}
#[test]
fn test_price_add_overflow() {
let a = Price {
minor: 80,
major: 100,
currency: Currency::INR,
};
let b = Price {
minor: 80,
major: 200,
currency: Currency::INR,
};
assert_eq!(
a + b,
Price {
minor: 60,
major: 301,
currency: Currency::INR
}
);
}
} }