import pytest from models import execution from models.execution import Execution, ExecutionError from persistance import cluster def square(x): return int(x) ** 2 def fail_on_three(x): if x == 3: raise RuntimeError("three") return x @pytest.fixture(autouse=True) def env(monkeypatch): for name in ("EXECUTION_MODE", "DASK_SCHEDULERS"): monkeypatch.delenv(name, raising=False) def test_resolve_defaults_and_allow_list(monkeypatch): assert execution.resolve().mode == "local" monkeypatch.setenv("EXECUTION_MODE", "sync") assert execution.resolve().mode == "sync" with pytest.raises(ExecutionError): execution.resolve(Execution(mode="remote")) monkeypatch.setenv("DASK_SCHEDULERS", "a:8786,tcp://b:8786") assert execution.resolve(Execution(mode="remote")).scheduler == "tcp://a:8786" assert execution.resolve(Execution(mode="remote", scheduler="b:8786")).scheduler == ( "tcp://b:8786" ) assert execution.options().schedulers == ["tcp://a:8786", "tcp://b:8786"] def test_resolve_rejects_unlisted_scheduler_and_scheduler_in_local_mode(monkeypatch): monkeypatch.setenv("DASK_SCHEDULERS", "a:8786") with pytest.raises(ExecutionError, match="not in DASK_SCHEDULERS"): execution.resolve(Execution(mode="remote", scheduler="c:8786")) with pytest.raises(ExecutionError, match="only goes with remote"): execution.resolve(Execution(mode="local", scheduler="a:8786")) with pytest.raises(ExecutionError, match="not host:port"): cluster.normalize("http://a:1") def test_map_sync_keeps_input_order_and_reports_each_item(monkeypatch): monkeypatch.setenv("EXECUTION_MODE", "sync") lines = [] assert execution.map(square, range(5), log=lines.append) == [0, 1, 4, 9, 16] assert lines[0] == "working: 0/5" and lines[-1] == "working: 5/5" def test_map_on_error_converts_a_failed_item(monkeypatch): monkeypatch.setenv("EXECUTION_MODE", "sync") out = execution.map(fail_on_three, range(6), on_error=lambda item, e: -item, log=lambda s: None) assert out == [0, 1, 2, -3, 4, 5] def test_map_raises_without_on_error(monkeypatch): monkeypatch.setenv("EXECUTION_MODE", "sync") with pytest.raises(RuntimeError, match="three"): execution.map(fail_on_three, range(6), log=lambda s: None) def test_eta_smoothing_and_threshold(): eta = execution.Eta(alpha=0.3, min_done=3) eta.update(0.0, 0) eta.update(1.0, 2) assert eta.eta_s(10) is None eta.update(2.0, 4) assert eta.eta_s(10) == pytest.approx((10 - 4) / 2.0) eta.update(3.0, 8) assert eta.rate == pytest.approx(0.3 * 4 + 0.7 * 2.0) assert eta.eta_s(10) == pytest.approx(2 / eta.rate)