from contextvars import ContextVar

import pytest

from ucam_faas.contexts import contextvar_activator

EXAMPLE_CONTEXT: ContextVar[int] = ContextVar("EXAMPLE_CONTEXT")


def test_contextvar_activator() -> None:
    activate_example_context = contextvar_activator(EXAMPLE_CONTEXT)

    @activate_example_context(value=100)
    def func_with_context_active() -> None:
        assert EXAMPLE_CONTEXT.get() == 100

    # The context holds no value yet
    with pytest.raises(LookupError):
        assert EXAMPLE_CONTEXT.get()

    with activate_example_context(value=42) as activate_context_value:
        assert activate_context_value == 42
        assert EXAMPLE_CONTEXT.get() == 42

        # Contexts can be nested
        with activate_example_context(value=3) as inner_context_value:
            assert inner_context_value == 3
            assert EXAMPLE_CONTEXT.get() == 3

            func_with_context_active()

        # The old value is restored after the inner block ends
        assert EXAMPLE_CONTEXT.get() == 42

    # The context holds no value after execution leaves the with block.
    with pytest.raises(LookupError):
        assert EXAMPLE_CONTEXT.get()
