|
| 1 | +extern crate measurements; |
| 2 | + |
| 3 | +use measurements::{mass::Mass, test_utils::assert_almost_eq, Measurement}; |
| 4 | + |
| 5 | +// Macro for testing `get_appropriate_units()`. |
| 6 | +// Specify the name of the test, the initial value (in kg) to be |
| 7 | +// passed in and the units that should be returned when |
| 8 | +// `get_appropriate_units()` is called. |
| 9 | +// An additional factor term may be given for cases when a |
| 10 | +// unit conversion takes place. |
| 11 | +macro_rules! test_from_kg { |
| 12 | + ($name:ident, $value:expr, $unit:expr) => { |
| 13 | + #[test] |
| 14 | + fn $name() { |
| 15 | + let mass = Mass::from_kilograms($value); |
| 16 | + let (unit, v) = mass.get_appropriate_units(); |
| 17 | + assert_eq!(unit, $unit); |
| 18 | + assert_almost_eq($value, v); |
| 19 | + } |
| 20 | + }; |
| 21 | + ($name:ident, $value:expr, $unit:expr, $factor:expr) => { |
| 22 | + #[test] |
| 23 | + fn $name() { |
| 24 | + let mass = Mass::from_kilograms($value); |
| 25 | + let (unit, v) = mass.get_appropriate_units(); |
| 26 | + assert_eq!(unit, $unit); |
| 27 | + assert_almost_eq($value * $factor, v); |
| 28 | + } |
| 29 | + }; |
| 30 | +} |
| 31 | + |
| 32 | +test_from_kg!(one_kg_keeps_unit, 1.0, "kg"); |
| 33 | +test_from_kg!(minus_one_kg_keeps_unit, -1.0, "kg"); |
| 34 | +test_from_kg!(more_than_one_kg_keeps_unit, 1.0 + 0.001, "kg"); |
| 35 | +test_from_kg!( |
| 36 | + less_than_one_kg_changes_unit_to_grams, |
| 37 | + 1.0 - 0.001, |
| 38 | + "g", |
| 39 | + 1000.0 |
| 40 | +); |
| 41 | +test_from_kg!( |
| 42 | + one_thousand_kg_changes_unit_to_tonnes, |
| 43 | + 1000.0, |
| 44 | + "tonnes", |
| 45 | + 0.001 |
| 46 | +); |
| 47 | +test_from_kg!( |
| 48 | + one_thousandth_of_kg_changes_unit_to_grams, |
| 49 | + 0.001, |
| 50 | + "g", |
| 51 | + 1000.0 |
| 52 | +); |
0 commit comments