|
| 1 | +"""Tests for mine_global_lock: non-blocking cross-process lock semantics.""" |
| 2 | +import threading |
| 3 | + |
| 4 | +import pytest |
| 5 | + |
| 6 | +from mempalace.palace import MineAlreadyRunning, mine_global_lock |
| 7 | + |
| 8 | + |
| 9 | +def test_mine_global_lock_acquired(tmp_path, monkeypatch): |
| 10 | + """Lock is acquired and released without error.""" |
| 11 | + monkeypatch.setenv("HOME", str(tmp_path)) |
| 12 | + with mine_global_lock(): |
| 13 | + pass # should not raise |
| 14 | + |
| 15 | + |
| 16 | +def test_mine_global_lock_second_acquire_raises(tmp_path, monkeypatch): |
| 17 | + """Concurrent second acquire raises MineAlreadyRunning.""" |
| 18 | + monkeypatch.setenv("HOME", str(tmp_path)) |
| 19 | + results: list[str] = [] |
| 20 | + |
| 21 | + with mine_global_lock(): |
| 22 | + # While this lock is held, spawn a thread that tries to acquire. |
| 23 | + def try_acquire(): |
| 24 | + try: |
| 25 | + with mine_global_lock(): |
| 26 | + results.append("acquired") |
| 27 | + except MineAlreadyRunning: |
| 28 | + results.append("blocked") |
| 29 | + |
| 30 | + t = threading.Thread(target=try_acquire) |
| 31 | + t.start() |
| 32 | + t.join(timeout=5) |
| 33 | + |
| 34 | + assert results == ["blocked"] |
| 35 | + |
| 36 | + |
| 37 | +def test_mine_global_lock_reusable_after_release(tmp_path, monkeypatch): |
| 38 | + """Lock can be re-acquired after the context manager exits.""" |
| 39 | + monkeypatch.setenv("HOME", str(tmp_path)) |
| 40 | + |
| 41 | + with mine_global_lock(): |
| 42 | + pass # first acquire + release |
| 43 | + |
| 44 | + # Second acquire must succeed; MineAlreadyRunning would propagate as failure. |
| 45 | + with mine_global_lock(): |
| 46 | + pass |
| 47 | + |
| 48 | + |
| 49 | +def test_mine_global_lock_exception_still_releases(tmp_path, monkeypatch): |
| 50 | + """Lock is released even when the body raises.""" |
| 51 | + monkeypatch.setenv("HOME", str(tmp_path)) |
| 52 | + |
| 53 | + with pytest.raises(ValueError): |
| 54 | + with mine_global_lock(): |
| 55 | + raise ValueError("boom") |
| 56 | + |
| 57 | + # Must be acquirable again after the exception. |
| 58 | + with mine_global_lock(): |
| 59 | + pass |
0 commit comments