use super::Quota;
use super::QuotaPolicy;
use super::RefillRate;
use std::time::Duration;

#[test]
fn policy_refills_quota_on_tick() {
    let policy = QuotaPolicy::new()
        .set_capacity(10.0)
        .set_refill_rate(RefillRate::per_micro(100.0));

    let quota = Quota::with_initial_tokens(10);

    let mut results = vec![];
    for _ in 0..100 {
        policy.tick(1, &quota);
        results.push(quota.consume(1));
    }

    assert_eq!(results.iter().filter(|r| r.is_ok()).count(), 19);
    assert_eq!(results.iter().filter(|r| r.is_err()).count(), 81);
}

#[test]
fn policy_skips_refill_before_interval() {
    let policy = QuotaPolicy::new()
        .set_capacity(10.0)
        .set_refill_rate(RefillRate::per_sec(10))
        .set_refill_interval(Duration::from_secs(1));
    let quota = Quota::new();

    let did_refill = policy.tick_with_interval(500_000_000, &quota, 500_000_000);

    assert!(!did_refill);
    assert!(quota.consume(1).is_err());
}

#[test]
fn policy_refills_after_interval() {
    let policy = QuotaPolicy::new()
        .set_capacity(10.0)
        .set_refill_rate(RefillRate::per_sec(10))
        .set_refill_interval(Duration::from_secs(1));
    let quota = Quota::new();

    let did_refill = policy.tick_with_interval(500_000_000, &quota, 1_000_000_000);
    let result = quota.consume(1).expect("interval refill should add tokens");

    assert!(did_refill);
    assert_eq!(result.available(), 4.0);
}
