| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from typing import TYPE_CHECKING |
| 4 |
|
| 5 |
import pytest |
| 6 |
|
| 7 |
from filelock import SoftFileLease, SoftFileLock, StrictSoftFileLock |
| 8 |
from filelock._identity import host_name |
| 9 |
|
| 10 |
if TYPE_CHECKING: |
| 11 |
from pathlib import Path |
| 12 |
|
| 13 |
from pytest_mock import MockerFixture |
| 14 |
|
| 15 |
|
| 16 |
@pytest.fixture( |
| 17 |
params=[ |
| 18 |
pytest.param("host with space", id="space"), |
| 19 |
pytest.param("host\nname", id="newline"), |
| 20 |
pytest.param("wörks", id="non-ascii"), |
| 21 |
pytest.param("b\udcffd", id="undecodable-byte"), |
| 22 |
] |
| 23 |
) |
| 24 |
def out_of_grammar_host(request: pytest.FixtureRequest, mocker: MockerFixture) -> None: |
| 25 |
# Kernel hostnames that every marker format used to publish verbatim and then read back as malformed. The |
| 26 |
# surrogate is how Python surfaces a hostname that is not valid UTF-8. |
| 27 |
mocker.patch("filelock._identity.socket.gethostname", return_value=request.param) |
| 28 |
|
| 29 |
|
| 30 |
@pytest.mark.usefixtures("out_of_grammar_host") |
| 31 |
def test_soft_file_lock_recognizes_its_own_marker(tmp_path: Path) -> None: |
| 32 |
with SoftFileLock(tmp_path / "resource.lock", timeout=2) as lock: |
| 33 |
assert lock.is_lock_held_by_us is True |
| 34 |
|
| 35 |
|
| 36 |
@pytest.mark.requires_hard_links |
| 37 |
@pytest.mark.usefixtures("out_of_grammar_host") |
| 38 |
def test_strict_soft_file_lock_reads_back_its_own_claim(tmp_path: Path) -> None: # pragma: needs hard-link |
| 39 |
with StrictSoftFileLock(tmp_path / "resource.lock", timeout=2) as lock: |
| 40 |
assert {claim.hostname for claim in lock.claims} == {host_name()} |
| 41 |
|
| 42 |
|
| 43 |
@pytest.mark.usefixtures("out_of_grammar_host") |
| 44 |
def test_soft_file_lease_reads_back_its_own_owner(tmp_path: Path) -> None: |
| 45 |
lease = SoftFileLease(str(tmp_path / "resource.lock"), timeout=2, lease_duration=30, heartbeat_interval=1) |
| 46 |
with lease: |
| 47 |
owner = lease.owner |
| 48 |
assert owner is not None |
| 49 |
assert owner.hostname == host_name() |