Files
unshackle/tests/downloaders/test_speed_limit.py
T

91 lines
2.6 KiB
Python

import importlib
from types import SimpleNamespace
import pytest
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.downloaders.requests import TokenBucket, parse_speed_limit
requests_downloader = importlib.import_module("unshackle.core.downloaders.requests")
@pytest.fixture(autouse=True)
def clean_cancel():
# a failing batch sets the process-global cancel, which TokenBucket.consume waits on;
# keep tests independent
DOWNLOAD_CANCELLED.clear()
yield
DOWNLOAD_CANCELLED.clear()
@pytest.mark.parametrize(
("value", "expected"),
[
("500k", 500_000),
("5M", 5_000_000),
("10MB", 10_000_000),
("10mb/s", 10_000_000),
("1.5G", 1_500_000_000),
("1048576", 1_048_576),
(5_000_000, 5_000_000.0),
(None, None),
("off", None),
("none", None),
("unlimited", None),
("0", None),
(0, None),
],
)
def test_parse_speed_limit(value, expected):
assert parse_speed_limit(value) == expected
@pytest.mark.parametrize(
"value",
[
"fast",
"10TB",
"10MiB",
"-5M",
"M",
"1..5M",
".",
"1.2.3",
float("inf"),
float("nan"),
-5,
-1.5,
pytest.param("9" * 400 + "k", id="400-digits-k"),
pytest.param("9" * 400, id="400-digits"),
pytest.param("9" * 308 + "g", id="308-digits-g"),
pytest.param(10**400, id="int-10e400"),
],
)
def test_parse_speed_limit_rejects(value):
with pytest.raises(ValueError):
parse_speed_limit(value)
def test_bucket_refills_at_the_rate(monkeypatch):
"""On a simulated clock the throughput is exact, so a slow refill fails like a fast one."""
clock = [0.0]
monkeypatch.setattr(requests_downloader, "time", SimpleNamespace(monotonic=lambda: clock[0]))
monkeypatch.setattr(
requests_downloader, "DOWNLOAD_CANCELLED", SimpleNamespace(wait=lambda s: clock.__setitem__(0, clock[0] + s))
)
bucket = TokenBucket(1_000)
for _ in range(50):
bucket.consume(100)
assert clock[0] == pytest.approx(5.0)
def test_bucket_chunk_larger_than_capacity_does_not_deadlock(monkeypatch):
# capture the debt sleep instead of timing it: Event.wait can wake early spuriously,
# so a wall-clock lower bound flakes
waits: list[float] = []
monkeypatch.setattr(requests_downloader, "DOWNLOAD_CANCELLED", SimpleNamespace(wait=waits.append))
bucket = TokenBucket(1_000_000)
bucket.consume(1_100_000)
assert len(waits) == 1
assert 1.0 < waits[0] < 2.0