import pytest

from retryxpy import RetryError, retry


def test_result_based_retry_eventually_succeeds():
    state = {"count": 0}

    @retry(max_attempts=4, delay=0, retry_if_result=lambda result: result is None)
    def flaky():
        state["count"] += 1
        if state["count"] < 3:
            return None
        return "ok"

    result = flaky()
    assert result == "ok"
    assert state["count"] == 3


def test_result_based_retry_raises_when_result_never_changes():
    state = {"count": 0}

    @retry(max_attempts=3, delay=0, retry_if_result=lambda result: result == "")
    def always_empty():
        state["count"] += 1
        return ""

    with pytest.raises(RetryError):
        always_empty()

    assert state["count"] == 3
