Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

9.0 KB
Raw Blame
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations

import time
from types import SimpleNamespace
from typing import TYPE_CHECKING, Any
from unittest.mock import Mock, patch

import pytest

from marimo._plugins.stateless.status._progress import (
    _Progress,
    progress_bar,
    spinner,
)
from marimo._runtime.context.types import runtime_context_installed
from marimo._types.ids import CellId_t
from tests.conftest import MockedKernel

if TYPE_CHECKING:
    from collections.abc import AsyncIterator


@pytest.fixture
def frozen_progress_time(monkeypatch: pytest.MonkeyPatch) -> None:
    now = time.time()
    clock = SimpleNamespace(time=lambda: now)
    monkeypatch.setattr(
        "marimo._plugins.stateless.status._progress.time", clock
    )
    monkeypatch.setattr("marimo._utils.debounce.time", clock)


# Test initialization
def test_progress_init() -> None:
    progress = _Progress(
        title="Test",
        subtitle="Running",
        total=100,
        show_rate=True,
        show_eta=True,
    )
    assert progress.title == "Test"
    assert progress.subtitle == "Running"
    assert progress.total == 100
    assert progress.current == 0
    assert progress.closed is False
    assert progress.loading_spinner is False
    assert progress.show_rate is True
    assert progress.show_eta is True
    # sleep 10ms
    time.sleep(0.01)
    rate = progress._get_rate()
    assert rate == 0.0
    eta = progress._get_eta()
    assert eta is None


# Test update_progress method
@patch("marimo._runtime.output._output.flush")
def test_update_progress(mock_flush: Any) -> None:
    progress = _Progress(
        title="Test",
        subtitle="Running",
        total=10000000,
        show_rate=True,
        show_eta=True,
    )
    # sleep 100ms
    time.sleep(0.1)
    progress.update_progress(
        increment=10, title="Updated", subtitle="Still Running"
    )
    assert progress.current == 10
    assert progress.title == "Updated"
    assert progress.subtitle == "Still Running"
    rate = progress._get_rate()
    assert rate is not None
    assert rate > 0.0
    eta = progress._get_eta()
    assert eta is not None
    assert eta > 0.0
    mock_flush.assert_called_once()


# Test update_progress method slow
@patch("marimo._runtime.output._output.flush")
def test_update_progress_slowly(mock_flush: Any) -> None:
    progress = _Progress(
        title="Test",
        subtitle="Running Slowly",
        total=5,
        show_rate=True,
        show_eta=True,
    )

    # Mock sleep 120 seconds
    with patch(
        "marimo._plugins.stateless.status._progress.time",
        Mock(time=Mock(return_value=progress.start_time + 120)),
    ):
        progress.update_progress(
            increment=1, title="Updated", subtitle="Still Running Slowly"
        )

        rate = progress._get_rate()
        eta = progress._get_eta()

    assert progress.current == 1
    assert progress.title == "Updated"
    assert progress.subtitle == "Still Running Slowly"
    assert rate is not None
    assert rate > 0.0
    assert eta is not None
    assert eta > 0.0
    mock_flush.assert_called_once()


# Test update_progress without arguments
@patch("marimo._runtime.output._output.flush")
def test_update_progress_no_args(mock_flush: Any) -> None:
    del mock_flush
    progress = _Progress(
        title="Test",
        subtitle="Running",
        total=100,
        show_rate=False,
        show_eta=False,
    )
    # sleep 100ms
    time.sleep(0.1)
    progress.update_progress()
    assert progress.current == 1
    assert progress.title == "Test"
    assert progress.subtitle == "Running"
    rate = progress._get_rate()
    assert rate is None
    eta = progress._get_eta()
    assert eta is None


# Test update_progress with closed progress
@patch("marimo._runtime.output._output.flush")
def test_update_progress_closed(mock_flush: Any) -> None:
    progress = _Progress(
        title="Test",
        subtitle="Running",
        total=100,
        show_rate=True,
        show_eta=True,
    )
    progress.close()
    assert progress.closed is True
    with pytest.raises(RuntimeError):
        progress.update_progress()
    mock_flush.assert_called_once()


@pytest.mark.usefixtures("frozen_progress_time")
@pytest.mark.parametrize("kind", ["progress_bar", "spinner"])
@pytest.mark.parametrize("field", ["title", "subtitle"])
def test_rapid_text_updates(
    mocked_kernel: MockedKernel, kind: str, field: str
) -> None:
    with mocked_kernel.k._install_execution_context(cell_id=CellId_t("0")):
        indicator: progress_bar[int] | spinner = (
            progress_bar(total=5) if kind == "progress_bar" else spinner()
        )
        with indicator as status:
            for text in ["first", "second", "third"]:
                status.update(
                    title=text if field == "title" else None,
                    subtitle=text if field == "subtitle" else None,
                )
            outputs = [
                msg.output.data
                for msg in mocked_kernel.stream.cell_notifications
                if msg.output is not None
            ]
            assert f"data-{field}='"third"'" in outputs[-1]


@pytest.mark.usefixtures("frozen_progress_time")
@pytest.mark.parametrize(
    ("title", "subtitle"), [(None, None), ("fixed", None), (None, "fixed")]
)
@patch("marimo._runtime.output._output.flush")
def test_numeric_updates_remain_rate_limited(
    mock_flush: Mock,
    title: str | None,
    subtitle: str | None,
) -> None:
    with progress_bar(total=100, title=title, subtitle=subtitle) as bar:
        bar.update(title=title, subtitle=subtitle)
        mock_flush.reset_mock()
        bar.update(title=title, subtitle=subtitle)
        mock_flush.assert_not_called()


def test_spinner_without_context():
    assert runtime_context_installed() is False

    with spinner("Test"):
        assert True

    with spinner(subtitle="Loading data ...") as _spinner:
        assert spinner
        _spinner.update(subtitle="Crunching numbers ...")


def test_progress_without_context():
    assert runtime_context_installed() is False

    for i in progress_bar(range(10)):
        assert i is not None

    with progress_bar(total=10) as bar:
        for _ in range(10):
            assert bar
            bar.update()

    # iterator (no len()) with total
    assert progress_bar(iter(range(1000)), total=1000)

    with pytest.raises(RuntimeError):
        for _ in progress_bar(total=10):
            pass


def test_progress_with_stepped_range_without_total() -> None:
    assert runtime_context_installed() is False

    progress = progress_bar(range(0, 10, 2))
    assert list(progress) == [0, 2, 4, 6, 8]
    assert (progress.progress.current, progress.progress.total) == (5, 5)


def test_progress_with_stepped_range_and_total() -> None:
    assert runtime_context_installed() is False

    progress = progress_bar(range(0, 10, 2), total=10)
    assert list(progress) == [0, 2, 4, 6, 8]
    assert (progress.progress.current, progress.progress.total) == (10, 10)


async def async_items(items: list[int]) -> AsyncIterator[int]:
    import asyncio

    for item in items:
        await asyncio.sleep(0)
        yield item


async def test_progress_async():
    assert runtime_context_installed() is False

    progress = progress_bar(async_items([1, 2, 3]), total=3)
    result = [item async for item in progress]

    assert result == [1, 2, 3]
    assert progress.progress.current == 3


def test_progress_no_total_error():
    assert runtime_context_installed() is False

    def sync_generator():
        yield 1
        yield 2
        yield 3

    with pytest.raises(
        TypeError,
        match=r"Cannot determine the length of a collection\. A `total` must be provided\.",
    ):
        progress_bar(sync_generator())


def test_progress_async_no_total_error():
    assert runtime_context_installed() is False

    async def async_generator():
        yield 1
        yield 2
        yield 3

    with pytest.raises(
        TypeError,
        match=r"Cannot determine the length of a collection\. A `total` must be provided\.",
    ):
        progress_bar(async_generator())


def test_progress_for_loop_error():
    assert runtime_context_installed() is False

    async def async_generator():
        yield 1

    with pytest.raises(
        RuntimeError,
        match=r"Cannot iterate over an async collection with `for`\. Use `async for` instead\.",
    ):
        for _ in progress_bar(async_generator(), total=1):
            pass


async def test_progress_async_for_loop_error():
    assert runtime_context_installed() is False

    with pytest.raises(
        RuntimeError,
        match=r"Cannot iterate over a sync collection with `async for`\. Use `for` instead\.",
    ):
        async for _ in progress_bar([1, 2, 3]):
            pass


async def test_progress_async_for_loop_without_collection_error():
    assert runtime_context_installed() is False

    with pytest.raises(
        RuntimeError,
        match="progress_bar can only be iterated over if a collection is provided",
    ):
        async for _ in progress_bar(total=1):
            pass