import sys

import pytest
from clarabot_nano_common.utility.path.error import (
    attempt_share_locked_operation,
    NtOSError,
    NtOSErrorCodes,
    SharedLockError,
)


@pytest.mark.skipif(not sys.platform.startswith("win"), reason="for windows only")
@pytest.mark.asyncio
async def test_attempt_share_locked_operation_nt():
    o = object()
    c = 0

    async def _f(e_for):
        nonlocal c
        c += 1
        if c < e_for:
            e = NtOSError()
            e.winerror = NtOSErrorCodes.ERROR_SHARING_VIOLATION
            raise e
        return o

    assert await attempt_share_locked_operation(3, 0.1, _f, 2) is o
    c = 0
    with pytest.raises(SharedLockError):
        await attempt_share_locked_operation(3, 0.1, _f, 8)


@pytest.mark.skipif(sys.platform.startswith("win"), reason="for posix only")
@pytest.mark.asyncio
async def test_attempt_share_locked_operation_posix():

    o = object()

    async def _f():
        return o

    assert await attempt_share_locked_operation(3, 0.1, _f) is o
