1
use num_rational::Rational64;
2
use sqlx::types::Uuid;
3

            
4
use crate::transaction::{Conversion, balances};
5

            
6
const EUR: Uuid = Uuid::from_u128(1);
7
const JPY: Uuid = Uuid::from_u128(2);
8

            
9
23
fn id(n: u128) -> Uuid {
10
23
    Uuid::from_u128(100 + n)
11
23
}
12

            
13
22
fn value(n: i64) -> Rational64 {
14
22
    Rational64::from_integer(n)
15
22
}
16

            
17
4
fn converted_pair() -> Vec<(Uuid, Uuid, Rational64)> {
18
4
    vec![(id(1), EUR, value(-10)), (id(2), JPY, value(1600))]
19
4
}
20

            
21
4
fn eur_to_jpy(split: Uuid) -> Conversion {
22
4
    Conversion {
23
4
        split,
24
4
        into: JPY,
25
4
        rate: value(160),
26
4
    }
27
4
}
28

            
29
#[test]
30
1
fn a_converted_pair_balances_in_either_order_beside_a_plain_pair() {
31
1
    let mut legs = converted_pair();
32
1
    legs.extend([(id(3), JPY, value(-199)), (id(4), JPY, value(199))]);
33
1
    assert!(balances(&legs, &[eur_to_jpy(id(1))]));
34
1
    legs.reverse();
35
1
    assert!(balances(&legs, &[eur_to_jpy(id(1))]));
36
1
}
37

            
38
#[test]
39
1
fn a_plain_pair_off_by_one_does_not_balance() {
40
1
    let mut legs = converted_pair();
41
1
    legs.extend([(id(3), JPY, value(-199)), (id(4), JPY, value(198))]);
42
1
    assert!(!balances(&legs, &[eur_to_jpy(id(1))]));
43
1
}
44

            
45
#[test]
46
1
fn a_currency_side_conversion_uses_the_inverse_rate() {
47
1
    let inverse = Conversion {
48
1
        split: id(2),
49
1
        into: EUR,
50
1
        rate: Rational64::new(1, 160),
51
1
    };
52
1
    assert!(balances(&converted_pair(), &[inverse]));
53
1
}
54

            
55
#[test]
56
1
fn an_unconverted_foreign_split_does_not_balance() {
57
1
    assert!(!balances(&converted_pair(), &[]));
58
1
}
59

            
60
#[test]
61
1
fn an_overflowing_conversion_does_not_balance() {
62
1
    let legs = vec![(id(1), EUR, value(i64::MAX)), (id(2), JPY, value(1))];
63
1
    assert!(!balances(&legs, &[eur_to_jpy(id(1))]));
64
1
}
65

            
66
#[test]
67
1
fn plain_pairs_in_two_commodities_balance_without_a_price() {
68
1
    let legs = vec![
69
1
        (id(1), EUR, value(-20)),
70
1
        (id(2), EUR, value(20)),
71
1
        (id(3), JPY, value(-199)),
72
1
        (id(4), JPY, value(199)),
73
    ];
74
1
    assert!(balances(&legs, &[]));
75
1
}