flexpool-core 0.5.0

flexpool domain core: exact energy and money units, the Europe/Berlin quarter-hour calendar, portfolio identities and the single quantisation boundary. No I/O, no clock.
Documentation
//! Integration tests for flexpool-core.

#![allow(clippy::unwrap_used, reason = "tests fail loudly")]

use flexpool_core::calendar::QUARTER;
use flexpool_core::*;
use rust_decimal::Decimal;
use std::str::FromStr;
use time::macros::{date, datetime};
use time::{Duration, Month};

fn d(s: &str) -> Decimal {
    Decimal::from_str(s).unwrap()
}

// ── calendar ──────────────────────────────────────────────────────────────

#[test]
fn spring_switch_day_has_92_quarters() {
    assert_eq!(BusinessDay::new(date!(2026 - 03 - 29)).unwrap().len(), 92);
}

#[test]
fn autumn_switch_day_has_100_quarters() {
    assert_eq!(BusinessDay::new(date!(2026 - 10 - 25)).unwrap().len(), 100);
}

#[test]
fn ordinary_day_has_96_quarters() {
    let day = BusinessDay::new(date!(2026 - 11 - 26)).unwrap();
    assert_eq!(day.len(), 96);
    assert_eq!(day.quarters().count(), 96);
    assert_eq!(day.start(), datetime!(2026-11-25 23:00 UTC));
}

#[test]
fn every_dst_transition_2025_to_2030_is_92_or_100() {
    let mut switches = Vec::new();
    for year in 2025..=2030 {
        for month in [Month::March, Month::October] {
            let mut date = time::Date::from_calendar_date(year, month, 1).unwrap();
            while date.month() == month {
                let n = BusinessDay::new(date).unwrap().len();
                if n != 96 {
                    switches.push((date, n));
                }
                date = date.next_day().unwrap();
            }
        }
    }
    assert_eq!(switches.len(), 12, "{switches:?}");
    for (date, n) in switches {
        let expected = if date.month() == Month::March {
            92
        } else {
            100
        };
        assert_eq!(n, expected, "{date}");
    }
}

#[test]
fn repeated_autumn_hour_yields_distinct_ordered_quarters() {
    let day = BusinessDay::new(date!(2026 - 10 - 25)).unwrap();
    let qs: Vec<_> = day.quarters().collect();
    assert!(
        qs.windows(2)
            .all(|w| w[0] < w[1] && w[0].end() == w[1].start())
    );
    // 02:00 CEST = 00:00 UTC and 02:00 CET = 01:00 UTC are both quarters of the day.
    let first = Quarter::starting_at(datetime!(2026-10-25 00:00 UTC)).unwrap();
    let second = Quarter::starting_at(datetime!(2026-10-25 01:00 UTC)).unwrap();
    assert_eq!((first.index(), second.index()), (8, 12));
    assert_eq!(first.date(), second.date());
}

#[test]
fn quarter_containing_and_next_cross_the_day() {
    let q = Quarter::containing(datetime!(2026-11-26 22:59:59 UTC)).unwrap();
    assert_eq!(q.index(), 95);
    let next = q.next().unwrap();
    assert_eq!((next.date(), next.index()), (date!(2026 - 11 - 27), 0));
    assert!(Quarter::starting_at(datetime!(2026-11-26 10:07 UTC)).is_err());
}

// ── units ─────────────────────────────────────────────────────────────────

#[test]
fn power_times_duration_is_energy_and_energy_times_price_is_money() {
    let p = Kw::from_mw(d("2")).unwrap();
    let e = p.energy_over(QUARTER).unwrap();
    assert_eq!(e, Kwh::new(d("500")));
    let money = e.priced_at(EurPerMwh::new(d("80.50"))).unwrap();
    assert_eq!(money, Eur::new(d("40.25")));
    assert_eq!(e.mean_power_over(QUARTER).unwrap(), p);
}

#[test]
fn capacity_price_times_power_times_duration_is_money() {
    let money = EurPerMwPerH::new(d("12.5"))
        .for_capacity(Kw::from_mw(d("10")).unwrap(), Duration::hours(4))
        .unwrap();
    assert_eq!(money, Eur::new(d("500")));
}

#[test]
fn overflow_is_refused_not_wrapped() {
    assert_eq!(
        Eur::new(Decimal::MAX).checked_add(Eur::new(Decimal::ONE)),
        None
    );
    assert_eq!(Kw::from_mw(Decimal::MAX), None);
}

#[test]
fn money_rounds_half_even_to_cents_and_serialises_as_string() {
    assert_eq!(Eur::new(d("1.005")).round_cents(), Eur::new(d("1.00")));
    assert_eq!(Eur::new(d("1.015")).round_cents(), Eur::new(d("1.02")));
    assert_eq!(
        serde_json::to_string(&Kw::new(d("1.50"))).unwrap(),
        "\"1.50\""
    );
}

// ── quantize ──────────────────────────────────────────────────────────────

fn mw(direction: RoundDirection) -> Granularity {
    Granularity::new(Decimal::ONE, direction).unwrap()
}

#[test]
fn quantize_rounds_down_to_one_mw_and_reports_the_rule() {
    let q = quantize(12.3456, mw(RoundDirection::TowardZero)).unwrap();
    assert_eq!(q.value, d("12"));
    assert_eq!(q.granularity.direction(), RoundDirection::TowardZero);
    assert_eq!(q.input, 12.3456);
}

#[test]
fn quantize_uses_the_shortest_decimal_not_binary_noise() {
    let cent = Granularity::new(d("0.01"), RoundDirection::NearestHalfEven).unwrap();
    assert_eq!(quantize(0.1, cent).unwrap().value, d("0.1"));
    assert_eq!(quantize(0.1 + 0.2, cent).unwrap().value, d("0.3"));
    // Toward zero never promises more — also for feed-in (negative).
    assert_eq!(
        quantize(-12.3456, mw(RoundDirection::TowardZero))
            .unwrap()
            .value,
        d("-12")
    );
    assert_eq!(
        quantize(-12.3456, mw(RoundDirection::AwayFromZero))
            .unwrap()
            .value,
        d("-13")
    );
    let tenth = Granularity::new(d("0.1"), RoundDirection::TowardZero).unwrap();
    assert_eq!(quantize(-1.25, tenth).unwrap().value, d("-1.2"));
    // Below Decimal precision: away from zero is still one step.
    let up = Granularity::new(d("0.01"), RoundDirection::AwayFromZero).unwrap();
    assert_eq!(quantize(1e-30, up).unwrap().value, d("0.01"));
    assert_eq!(quantize(-1e-30, up).unwrap().value, d("-0.01"));
    assert_eq!(quantize(2.0, up).unwrap().value, d("2"));
    assert_eq!(
        quantize(12.0001, mw(RoundDirection::AwayFromZero))
            .unwrap()
            .value,
        d("13")
    );
    assert_eq!(quantize(1e-20, cent).unwrap().value, Decimal::ZERO);
}

#[test]
fn quantize_refuses_non_finite_and_out_of_range() {
    let g = mw(RoundDirection::TowardZero);
    assert!(matches!(
        quantize(f64::NAN, g),
        Err(QuantizeError::NonFinite(_))
    ));
    assert!(matches!(
        quantize(f64::INFINITY, g),
        Err(QuantizeError::NonFinite(_))
    ));
    assert!(matches!(
        quantize(1e40, g),
        Err(QuantizeError::OutOfRange(_))
    ));
    assert!(Granularity::new(Decimal::ZERO, RoundDirection::TowardZero).is_err());
}

// ── portfolio ─────────────────────────────────────────────────────────────

#[test]
fn ids_are_slugs() {
    assert!(PoolId::parse("pool-nord").is_ok());
    assert!(PoolId::parse("Pool Nord").is_err());
    assert!(PoolId::parse("").is_err());
    assert!(PoolId::parse("a".repeat(65)).is_err());
}

#[test]
fn plain_decimals_refuse_spreadsheet_surprises() {
    assert_eq!(parse_plain("10.5"), Some(d("10.5")));
    assert_eq!(parse_plain("-0.25"), Some(d("-0.25")));
    for bad in ["1_0.5", "1e3", "+5", " 5", "5.", ".5", "", "-", "1.2.3"] {
        assert_eq!(parse_plain(bad), None, "{bad:?}");
    }
}