flexpool-rules 0.2.1

flexpool market rules: dated entries with registered sources, embedded at compile time. No I/O.
Documentation
//! Rule pack tests (002 US-4).

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

use flexpool_rules::{RuleBook, SourceStatus};
use time::macros::{date, datetime};

const SOURCES: &str = r#"
[[source]]
id = "s"
title = "T"
publisher = "P"
url = "https://example.org"
date = "2025-01-01"
status = "checked"
"#;

#[test]
fn bundled_packs_load() {
    let book = RuleBook::bundled().unwrap();
    assert!(book.entries().count() >= 10);
}

#[test]
fn day_ahead_time_unit_changes_with_the_delivery_day() {
    let book = RuleBook::bundled().unwrap();
    let (before, e1) = book.da_mtu(date!(2025 - 09 - 30)).unwrap();
    let (after, e2) = book.da_mtu(date!(2025 - 10 - 01)).unwrap();
    assert_eq!((before, after), (60, 15));
    assert_eq!(book.source_of(e2).unwrap().status, SourceStatus::Checked);
    assert_ne!(e1.source, e2.source);
}

#[test]
fn gates_are_berlin_local_times_across_dst() {
    let book = RuleBook::bundled().unwrap();
    // Winter: 12:00 CET = 11:00 UTC on D-1.
    assert_eq!(
        book.gate("da.gate", date!(2026 - 01 - 15)).unwrap().0,
        datetime!(2026-01-14 11:00 UTC)
    );
    // Summer: 12:00 CEST = 10:00 UTC on D-1.
    assert_eq!(
        book.gate("da.gate", date!(2026 - 07 - 15)).unwrap().0,
        datetime!(2026-07-14 10:00 UTC)
    );
    // Delivery on the autumn switch day: the gate on D-1 is still summer time.
    assert_eq!(
        book.gate("da.gate", date!(2026 - 10 - 25)).unwrap().0,
        datetime!(2026-10-24 10:00 UTC)
    );
    // IDA3 is on the delivery day itself.
    assert_eq!(
        book.gate("ida3.gate", date!(2026 - 01 - 15)).unwrap().0,
        datetime!(2026-01-15 09:00 UTC)
    );
}

/// market-replay/SR-004: a rule citing an unregistered source is refused.
#[test]
fn sr_004_unregistered_source_is_refused() {
    let pack = r#"
[[rule]]
id = "x.y"
valid_from = "2025-01-01"
source = "nope"
clause = "c"
minutes = 15
"#;
    let problems = RuleBook::parse(SOURCES, &[("p.toml", pack)]).unwrap_err();
    assert!(
        problems[0].to_string().contains("x.y") && problems[0].to_string().contains("nope"),
        "{problems:?}"
    );
}

/// market-replay/SR-004: two entries of one rule with overlapping validity are refused, naming both.
#[test]
fn sr_004_overlapping_entries_are_refused_naming_both() {
    let pack = r#"
[[rule]]
id = "da.mtu"
valid_from = "2025-01-01"
source = "s"
clause = "a"
minutes = 60

[[rule]]
id = "da.mtu"
valid_from = "2025-10-01"
source = "s"
clause = "b"
minutes = 15
"#;
    let problems = RuleBook::parse(SOURCES, &[("p.toml", pack)]).unwrap_err();
    let text = problems[0].to_string();
    assert!(
        text.contains("2025-01-01") && text.contains("2025-10-01") && text.contains("overlap"),
        "{text}"
    );
}

#[test]
fn incomplete_sources_and_bad_values_are_all_reported() {
    let sources = SOURCES
        .replace("https://example.org", "http://example.org")
        .replace("\"T\"", "\"\"");
    let pack = "[[rule]]\nid = \"a\"\nvalid_from = \"2025-01-01\"\nsource = \"s\"\nclause = \"c\"\nminutes = 7\n";
    let problems = RuleBook::parse(&sources, &[("p.toml", pack)]).unwrap_err();
    assert_eq!(problems.len(), 3, "{problems:?}");
}

#[test]
fn lookups_outside_validity_are_missing() {
    let book = RuleBook::bundled().unwrap();
    assert!(book.gate("ida1.gate", date!(2020 - 01 - 01)).is_err());
    assert!(book.entry("no.such.rule", date!(2026 - 01 - 01)).is_err());
}

#[test]
fn every_bundled_rule_id_has_a_test_naming_it() {
    let book = RuleBook::bundled().unwrap();
    let ids: std::collections::BTreeSet<_> = book.entries().map(|e| e.id.clone()).collect();
    let this = include_str!("main.rs");
    for id in ids {
        assert!(
            this.contains(&format!("\"{id}\"")),
            "no test names rule {id}"
        );
    }
}

#[test]
fn da_publication_and_ida_gates_in_force() {
    let book = RuleBook::bundled().unwrap();
    assert_eq!(
        book.gate("da.publication", date!(2026 - 01 - 15))
            .unwrap()
            .0,
        datetime!(2026-01-14 11:57 UTC)
    );
    assert_eq!(
        book.gate("ida1.gate", date!(2026 - 01 - 15)).unwrap().0,
        datetime!(2026-01-14 14:00 UTC)
    );
    assert_eq!(
        book.gate("ida2.gate", date!(2026 - 01 - 15)).unwrap().0,
        datetime!(2026-01-14 21:00 UTC)
    );
}

#[test]
fn da_price_limits_and_granularity_in_force() {
    let book = RuleBook::bundled().unwrap();
    let (min, max, entry) = book.da_price_limits(date!(2026 - 01 - 15)).unwrap();
    assert_eq!(
        entry,
        book.entry("da.price-limits", date!(2026 - 01 - 15))
            .unwrap()
    );
    assert_eq!(
        (min.value().to_string(), max.value().to_string()),
        ("-500".to_owned(), "4000".to_owned())
    );
    let (vol, _) = book
        .granularity("da.volume-granularity", date!(2026 - 01 - 15))
        .unwrap();
    assert_eq!(vol.direction(), flexpool_core::RoundDirection::TowardZero);
    let (price, _) = book
        .granularity("da.price-granularity", date!(2026 - 01 - 15))
        .unwrap();
    assert_eq!(price.step().to_string(), "0.01");
    let (mtu, _) = book.da_mtu(date!(2025 - 06 - 01)).unwrap();
    assert_eq!(mtu, 60, "\"da.mtu\" hourly before the go-live");
}

/// Days before the sources hold are refused, not guessed (review M12).
#[test]
fn days_before_the_sources_are_refused() {
    let book = RuleBook::bundled().unwrap();
    assert!(book.da_price_limits(date!(2021 - 06 - 01)).is_err());
    assert!(book.gate("da.gate", date!(2024 - 12 - 31)).is_err());
}

#[test]
fn stray_value_fields_are_refused() {
    let pack = "[[rule]]\nid = \"x\"\nvalid_from = \"2025-01-01\"\nsource = \"s\"\nclause = \"c\"\nminutes = 15\ndirection = \"toward-zero\"\n";
    let problems = RuleBook::parse(SOURCES, &[("p.toml", pack)]).unwrap_err();
    assert!(problems[0].message.contains("direction"), "{problems:?}");
}

#[test]
fn a_gate_inside_the_skipped_spring_hour_is_refused() {
    let pack = "[[rule]]\nid = \"odd.gate\"\nvalid_from = \"2025-01-01\"\nsource = \"s\"\nclause = \"c\"\nlocal_time = \"02:30\"\nday_offset = 0\n";
    let book = RuleBook::parse(SOURCES, &[("p.toml", pack)]).unwrap();
    assert!(book.gate("odd.gate", date!(2026 - 03 - 29)).is_err());
    assert!(book.gate("odd.gate", date!(2026 - 03 - 30)).is_ok());
}

#[test]
fn the_alarm_philosophy_and_types_are_rules() {
    let book = RuleBook::bundled().unwrap();
    let day = date!(2026 - 01 - 15);
    assert_eq!(book.rate("alarm.target-rate", day).unwrap().0..=1, 1..=1);
    let (count, window, _) = book.rate("alarm.flood", day).unwrap();
    assert_eq!((count, window), (10, 600));
    assert_eq!(book.rate("alarm.chattering", day).unwrap().0, 3);
    assert_eq!(book.seconds("alarm.standing", day).unwrap().0, 86_400);
    assert_eq!(book.seconds("alarm.shelve-max", day).unwrap().0, 8 * 3600);
    let expected = [
        ("alarm.pool-availability", 1, 120),
        ("alarm.connection-down", 2, 30),
        ("alarm.asset-implausible", 2, 60),
        ("alarm.asset-offline", 3, 300),
        ("alarm.asset-stale", 3, 300),
        ("alarm.delivery-deviation", 2, 0),
    ];
    for (rule, priority, on_delay) in expected {
        let (a, _) = book.alarm(rule, day).unwrap();
        assert_eq!(
            (a.priority, a.on_delay_secs),
            (priority, on_delay),
            "{rule}"
        );
        assert!(
            a.title.de.contains("{subject}") && !a.action.en.is_empty(),
            "{rule}"
        );
    }
    let (pool, _) = book.alarm("alarm.pool-availability", day).unwrap();
    assert_eq!(pool.threshold.map(|t| t.to_string()), Some("0.9".into()));
    assert!(
        book.alarm("alarm.flood", day).is_err(),
        "a rate is not an alarm"
    );
}

#[test]
fn alarm_rules_are_validated() {
    let sources = r#"[[source]]
id = "s"
title = "t"
publisher = "p"
url = "https://example.org"
date = "2025-01-01"
status = "checked"
"#;
    let alarm = |extra: &str| {
        format!(
            "[[rule]]\nid = \"alarm.x\"\nvalid_from = \"2025-01-01\"\nsource = \"s\"\nclause = \"c\"\n{extra}[rule.alarm]\npriority = 4\nrespond_minutes = 1\non_delay_secs = 1\noff_delay_secs = 1\nthreshold = \"1.5\"\ntitle_de = \"ohne Subjekt\"\ntitle_en = \"t {{subject}}\"\ncause_de = \"c\"\ncause_en = \"c\"\nconsequence_de = \"c\"\nconsequence_en = \"c\"\naction_de = \"a\"\naction_en = \"\"\n"
        )
    };
    let problems = |pack: String| {
        RuleBook::parse(sources, &[("p.toml", pack.as_str())])
            .unwrap_err()
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join("\n")
    };
    assert!(problems(alarm("")).contains("priority 4 must be 1, 2 or 3"));
    assert!(problems(alarm("seconds = 5\n")).contains("exactly one of"));
    let rate = "[[rule]]\nid = \"r\"\nvalid_from = \"2025-01-01\"\nsource = \"s\"\nclause = \"c\"\nwindow_secs = 60\n".to_owned();
    assert!(problems(rate).contains("window_secs"));
}