diff --git a/dokimi/changelog.d/20261204_100000_repo-eval-readers-unlistable.md b/dokimi/changelog.d/20261204_100000_repo-eval-readers-unlistable.md new file mode 100644 index 0000000000..2b46c878b2 --- /dev/null +++ b/dokimi/changelog.d/20261204_100000_repo-eval-readers-unlistable.md @@ -0,0 +1,3 @@ +### Fixed + +- **Four repo-eval readers refuse a directory they cannot list instead of reading it as empty** — an eval `tasks` directory at mode `0o111` gave `no task under eval/tasks`, `repo report` and `repo compare` of a batch directory reported no missing cell and no unsupported one, the check of a batch against another execution found none and let `repo run` resume or report with the cells of two executions mixed, and `eval tasks generate --from prs` or `--from history` did not see the tasks already in `--out-dir` and authored the pull request again. Each now stops with `cannot list : Permission denied`: `repo report` and `repo compare` exit 2, `repo run` and `eval tasks generate` refuse and exit 1 as they do for their other unusable inputs. A missing directory still has no entries. diff --git a/dokimi/docs/repo-evaluation-contract.md b/dokimi/docs/repo-evaluation-contract.md index b376635a78..1d4f054543 100644 --- a/dokimi/docs/repo-evaluation-contract.md +++ b/dokimi/docs/repo-evaluation-contract.md @@ -1439,7 +1439,8 @@ malformed source, an unpinned remote, a local source that is not a directory, a a repository that is not its root (`/sub@`: give the root), or a `--cache-dir` that is not a usable directory. It exits 1 when the pull request file cannot be read or holds no pull request, when no pull request gave a task (written, or kept from before), and on an error that is not one pull request's own: a malformed pull request (a `number` that is not -an integer), a source it cannot open, a manifest that is missing or malformed, the prompt file (unreadable or empty), or a task it +an integer), a source it cannot open, a manifest that is missing or malformed, the prompt file (unreadable or empty), an `--out-dir` that cannot be listed (its tasks cannot be told from none, so a pull request +would be authored again), or a task it cannot write. Each prints `✗` and the reason; a `--manifest` path that leaves the source tree exits 2 instead, pinned or not. Grading a task needs the manifest's `entry_points.test` (§2). @@ -2618,7 +2619,10 @@ python cli.py repo compare repo-runs/authoring --baseline guidance:none --metric - Each cell holds the §4 inputs plus `agent.stdout` (the raw trace) and `result.json`, the framework's verdict. A cell with `result.json` is skipped on a rerun unless `--force`; a cell without one is reported as missing, not - failed, and the next run of the batch fills it. `meta.json` and + failed, and the next run of the batch fills it. A batch directory that cannot be listed is refused + (`repo run`: it cannot tell whether the cells of another execution are in it; `repo report`, + `repo compare`: exit 2), not read as one with no cell; so is an eval `tasks` directory that cannot be listed + (`no task under ...` would blame a missing task). `meta.json` and `result.json` record `execution`: the tool mode, the delegation mode (the one whose arguments ran; a skill with `context: fork` can still start a subagent under `none`) and an diff --git a/dokimi/dokimi/digest_entries.py b/dokimi/dokimi/digest_entries.py index b5b4fddb92..5fa6442dfa 100644 --- a/dokimi/dokimi/digest_entries.py +++ b/dokimi/dokimi/digest_entries.py @@ -3,7 +3,7 @@ """The digest of one entry a repo config subject walks: a file by its content and executable bit, a link by its target text. ``repo_config._digest_files`` digests each entry with these. :func:`listed_entries` lists the entries -a digest of a tree walks; :func:`children_matching` and :func:`pack_files` list one directory.""" +a digest of a tree walks; :func:`children_matching`, :func:`children_holding` and :func:`pack_files` list one directory.""" import errno import fnmatch @@ -43,6 +43,24 @@ def pack_files(directory: Path, filename: str) -> list[Path]: return [path for path in (child / filename for child in children_matching(directory, "*")) if _is_regular(path)] +def children_holding(directory: Path, pattern: str, filename: str) -> list[Path]: + """``directory//filename`` for each child whose name ``pattern`` matches and that holds ``filename`` as any + kind of entry, sorted: ``directory.glob(pattern + "/" + filename)`` where a directory that cannot be listed, or a + child that cannot be searched, raises its OSError. An absent ``filename`` or a child that is no directory is no hit.""" + hits = [] + for path in (child / filename for child in children_matching(directory, pattern)): + try: + path.lstat() + except (FileNotFoundError, NotADirectoryError): + continue + except OSError as exc: + if exc.errno == errno.ELOOP: + continue + raise + hits.append(path) + return hits + + def _is_regular(path: Path) -> bool: """True when ``path`` is a regular file (a link is followed); an absent path, a parent that is no directory or a link loop is not, and any other OSError (a parent that cannot be searched) is raised.""" diff --git a/dokimi/dokimi/repos/batch_ledger.py b/dokimi/dokimi/repos/batch_ledger.py index 43a188511d..f282e119d5 100644 --- a/dokimi/dokimi/repos/batch_ledger.py +++ b/dokimi/dokimi/repos/batch_ledger.py @@ -34,6 +34,7 @@ from typing import Any from dokimi.atomic_write import write_text_atomic +from dokimi.digest_entries import children_holding from .arms import resolve_skills, slug, tree_sha256 from .bases import NOT_UTF8 from .errors import PrepError @@ -164,7 +165,12 @@ def check_batch_executions(batch_dir: Path, wanted: set[str], replacing: set[str which would stay in the report next to the new ones. A cell whose result cannot be read has no execution to compare; a cell of this run's plan reports it when it runs, so it is not an error here.""" found: set[str] = set() - for path in sorted(batch_dir.glob("*/result.json")): + try: + results = children_holding(batch_dir, "*", "result.json") + except OSError as exc: # its cells cannot be told from none: the batch could be resumed with another execution's + raise ExecutionMismatch(f"cannot list {batch_dir}: {exc.strerror or exc}; its cells cannot be checked " + "against this run's execution") from exc + for path in results: if replacing is not None and path.parent.name in replacing: continue try: diff --git a/dokimi/dokimi/repos/replay/authoring.py b/dokimi/dokimi/repos/replay/authoring.py index 181b81b9f1..81fd44f3f7 100644 --- a/dokimi/dokimi/repos/replay/authoring.py +++ b/dokimi/dokimi/repos/replay/authoring.py @@ -24,7 +24,9 @@ from typing import Any from dokimi.atomic_write import write_json_atomic +from dokimi.digest_entries import children_holding from ...provenance import generated_by +from ..errors import PrepError from ..graders.hidden_tests import HIDDEN_DIR from ..graders.typecheck import REFERENCE_DIR from ..manifest import RepoManifest @@ -103,7 +105,11 @@ def kept(opts: Options, number: int | None, task_id: str) -> Outcome | None: def tasks_by_pr(out: Path) -> dict[int, str]: """Index existing authoring tasks once per batch, by their source pull request.""" found: dict[int, str] = {} - for path in sorted(out.glob("authoring_*/task.json")): + try: + paths = children_holding(out, "authoring_*", "task.json") + except OSError as exc: # its tasks cannot be told from none: a pull request would be authored again + raise PrepError(f"cannot list {out}: {exc.strerror or exc}") from exc + for path in paths: suffix = path.parent.name.removeprefix("authoring_pr") if suffix.isascii() and suffix.isdecimal(): found[int(suffix)] = path.parent.name # the direct PR task takes precedence diff --git a/dokimi/dokimi/repos/report.py b/dokimi/dokimi/repos/report.py index b61e77e6ef..f0345f35c3 100644 --- a/dokimi/dokimi/repos/report.py +++ b/dokimi/dokimi/repos/report.py @@ -58,6 +58,7 @@ from pathlib import Path from typing import Any +from dokimi.digest_entries import children_holding from dokimi.eval.sign_flip import round_off_zero from dokimi.measure import as_float, is_number from dokimi.provenance import STATUSES, UNKNOWN @@ -201,13 +202,22 @@ def _check_cell(path: Path, rec: dict[str, Any]) -> None: raise CellFileError(f"{path} has no usable `batch`") +def _cell_files(batch_dir: Path, name: str) -> list[Path]: + """``batch_dir//name`` for each cell that has it, sorted; a :class:`CellFileError` naming ``batch_dir`` when + it cannot be listed (a missing one has no cell).""" + try: + return children_holding(batch_dir, "*", name) + except OSError as exc: + raise CellFileError(f"cannot list {batch_dir}: {exc.strerror or exc}") from exc + + def load_cells(batch_dir: Path) -> tuple[list[dict[str, Any]], list[str]]: """Finished cells (their ``result.json``) and the names of missing ones.""" + started = {p.parent.name for p in _cell_files(batch_dir, "meta.json")} # first: it names a directory that cannot be listed plan_path = batch_dir / "_eval" / "plan.json" planned = _planned_cells(plan_path) if plan_path.is_file() else set() - started = {p.parent.name for p in batch_dir.glob("*/meta.json")} finished = [] - for path in sorted(batch_dir.glob("*/result.json")): + for path in _cell_files(batch_dir, "result.json"): rec = _read_object(path) _fail_unmeasurable_score(rec) _check_cell(path, rec) @@ -218,7 +228,7 @@ def load_cells(batch_dir: Path) -> tuple[list[dict[str, Any]], list[str]]: rec["score_task"] = bool(rec["score_task"] if "score_task" in rec else rec["grade"]["score_only"]) finished.append(rec) done = {r["cell"] for r in finished} - unsupported = {p.parent.name for p in batch_dir.glob(f"*/{UNSUPPORTED_FILE}")} + unsupported = {p.parent.name for p in _cell_files(batch_dir, UNSUPPORTED_FILE)} return finished, sorted((planned | started) - done - unsupported) @@ -252,7 +262,7 @@ def refuse_mixed_executions(cells: list[dict[str, Any]], where: str) -> None: def load_unsupported(batch_dir: Path) -> list[dict[str, Any]]: """Cells the runner did not run on a host that missed their task's ``host`` requirements.""" out = [] - for path in sorted(batch_dir.glob(f"*/{UNSUPPORTED_FILE}")): + for path in _cell_files(batch_dir, UNSUPPORTED_FILE): if (path.parent / "result.json").is_file(): continue rec = _read_object(path) diff --git a/dokimi/dokimi/repos/workspace.py b/dokimi/dokimi/repos/workspace.py index 81ba0e4a4e..0600fbe9b2 100644 --- a/dokimi/dokimi/repos/workspace.py +++ b/dokimi/dokimi/repos/workspace.py @@ -49,6 +49,7 @@ from typing import Any from dokimi import process +from dokimi.digest_entries import children_holding from dokimi.process_io import exact_path_text from .arms import ArmError, Skill, resolve_skills, tree_sha256 @@ -264,7 +265,10 @@ def load_tasks(content_dir: Path, manifest: RepoManifest, ids: list[str] | None No task at all is refused: a check or run over none would report 0/0 as a pass.""" eval_dir, tasks = manifest.run_paths() tasks_dir = content_dir / PurePosixPath(tasks).relative_to(eval_dir) - found = {p.parent.name: p for p in sorted(tasks_dir.glob("*/task.json"))} + try: + found = {p.parent.name: p for p in children_holding(tasks_dir, "*", "task.json")} + except OSError as exc: # a directory that cannot be listed is not one with no task + raise PrepError(f"cannot list {tasks_dir}: {exc.strerror or exc}") from exc if not found: raise PrepError(f"no task under {manifest.tasks} (no */task.json): nothing to check or run") wanted = ids or sorted(found) diff --git a/dokimi/tests/cli_faults.py b/dokimi/tests/cli_faults.py index 15fe083222..ad26bf6829 100644 --- a/dokimi/tests/cli_faults.py +++ b/dokimi/tests/cli_faults.py @@ -87,8 +87,8 @@ } # The allowlist only shrinks: any row added, deleted or swapped changes this count or digest (#1294), so review sees it. -ALLOWLIST_ROWS = 48 -ALLOWLIST_DIGEST = "98d781d77eb6" +ALLOWLIST_ROWS = 45 +ALLOWLIST_DIGEST = "17c76f7f9a04" # Commands whose input refusals are not all exit 2 (docs/quickstart.md, "Exit codes"): they may also exit 1. OWN_CODES: dict[str, frozenset[int]] = { diff --git a/dokimi/tests/data/cli_fault_allowlist.txt b/dokimi/tests/data/cli_fault_allowlist.txt index 6a64e77257..3f34c987ec 100644 --- a/dokimi/tests/data/cli_fault_allowlist.txt +++ b/dokimi/tests/data/cli_fault_allowlist.txt @@ -29,7 +29,6 @@ eval native-import | log | dangling-link | exit 5 with a traceback (FileNotFound eval tasks list | --tasks-root | unreadable | exit 5 with a traceback (PermissionError) explore run | --out-md | directory | exit 2 but leaves a results directory behind in the working directory explore run | --out-md | unwritable-parent | exit 2 but leaves a results directory behind in the working directory -repo compare | batch_dirs | unreadable | python <3.14: exit 5 with a traceback (PermissionError) repo hits judge | --labels | missing | exit 2 but leaves the batch's _eval directory behind repo hits judge | --labels | directory | exit 2 but leaves the batch's _eval directory behind repo hits judge | --labels | unreadable | exit 2 but leaves the batch's _eval directory behind @@ -37,8 +36,6 @@ repo hits judge | --labels | dangling-link | exit 2 but leaves the batch's _eval repo hits judge | --labels | link-out-of-root | exit 2 but leaves the batch's _eval directory behind repo hits judge | --labels | dotdot | exit 2 but leaves the batch's _eval directory behind repo hits judge | --labels | absolute | exit 2 but leaves the batch's _eval directory behind -repo hits sheet | batch_dir | unreadable | python <3.14: exit 5 with a traceback (PermissionError) -repo report | batch_dir | unreadable | exit 5 with a traceback (PermissionError) repo skill-reach | --work-dir | unreadable | exit 5 with a traceback (PermissionError) report opportunities | inputs | empty | exit 0, nothing on stderr report summary | inputs | unreadable | exit 0, nothing on stderr diff --git a/dokimi/tests/test_children_holding.py b/dokimi/tests/test_children_holding.py new file mode 100644 index 0000000000..48b0abbca2 --- /dev/null +++ b/dokimi/tests/test_children_holding.py @@ -0,0 +1,91 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""#1507: ``children_holding`` lists ``/`` as ``glob`` did, a link included, and raises what it cannot look up.""" + +from __future__ import annotations + +import os + +import pytest + +from dokimi.cli import build_parser +from dokimi.digest_entries import children_holding +from tests.cli_refusal import refusal + + +def _names(root, hits): + return [str(p.relative_to(root)) for p in hits] + + +def test_a_dangling_or_looping_leaf_link_is_a_hit_like_the_glob_found_it(tmp_path): + for child in ("dangling", "loop", "file", "dir"): + (tmp_path / child).mkdir() + os.symlink("nowhere", tmp_path / "dangling" / "result.json") + os.symlink("result.json", tmp_path / "loop" / "result.json") + (tmp_path / "file" / "result.json").write_text("{}") + (tmp_path / "dir" / "result.json").mkdir() + assert _names(tmp_path, children_holding(tmp_path, "*", "result.json")) == [ + "dangling/result.json", "dir/result.json", "file/result.json", "loop/result.json"] + assert _names(tmp_path, children_holding(tmp_path, "*", "result.json")) == sorted( + str(p.relative_to(tmp_path)) for p in tmp_path.glob("*/result.json")) + + +def test_an_absent_name_a_child_that_is_no_directory_and_a_missing_root_are_no_hit(tmp_path): + (tmp_path / "empty").mkdir() + (tmp_path / "plain").write_text("not a directory") + assert children_holding(tmp_path, "*", "result.json") == [] + assert children_holding(tmp_path / "missing", "*", "result.json") == [] + + +def test_a_child_that_is_a_link_loop_is_no_hit_as_for_the_glob(tmp_path): + os.symlink("loop", tmp_path / "loop") + assert children_holding(tmp_path, "*", "result.json") == [] + assert list(tmp_path.glob("*/result.json")) == [] + + +def test_a_child_that_cannot_be_searched_raises(tmp_path): + child = tmp_path / "cell1" + child.mkdir() + (child / "result.json").write_text("{}") + child.chmod(0) + try: + try: + os.stat(child / "result.json") + except PermissionError: + with pytest.raises(PermissionError): + children_holding(tmp_path, "*", "result.json") + else: + pytest.skip("this process searches a mode 0 directory (root)") + finally: + child.chmod(0o700) + + +def test_a_batch_directory_that_cannot_be_searched_is_refused_naming_it_on_every_python(tmp_path): + from dokimi.repos.report import CellFileError, load_cells + + batch = tmp_path / "b1" + batch.mkdir() + batch.chmod(0) + try: + try: + os.stat(batch / "_eval") + except PermissionError: + with pytest.raises(CellFileError, match=f"cannot list {batch}: Permission denied"): + load_cells(batch) + else: + pytest.skip("this process searches a mode 0 directory (root)") + finally: + batch.chmod(0o700) + + +@pytest.mark.parametrize("link",["nowhere", "result.json"], ids=["dangling", "looping"]) +def test_report_reads_a_leaf_link_it_cannot_follow_and_refuses_it_naming_the_file(tmp_path, capsys, link): + cell = tmp_path / "b1" / "t__a__m__r1" + cell.mkdir(parents=True) + os.symlink(link, cell / "result.json") + with refusal() as exc: + args = build_parser().parse_args(["repo", "report", str(tmp_path / "b1")]) + args.func(args) + assert exc.code == 2 + assert f"cannot read {cell / 'result.json'}" in capsys.readouterr().err diff --git a/dokimi/tests/test_repo_authoring.py b/dokimi/tests/test_repo_authoring.py index b82f9ae2cb..23db60aa3f 100644 --- a/dokimi/tests/test_repo_authoring.py +++ b/dokimi/tests/test_repo_authoring.py @@ -387,6 +387,28 @@ def test_an_existing_task_is_kept_unless_forced(toy, tmp_path, capsys): assert _task(out, 1)["family"] == "feature" and not (out / "authoring_pr1/reference/stale.txt").exists() +def test_an_out_directory_that_cannot_be_listed_exits_1_naming_it_and_authors_nothing_again(toy, tmp_path, capsys): + """#1507: the tasks index of `--out` at mode 111 is a refusal, not `{}` (which authors PR 1 a second time).""" + from dokimi.repos.errors import PrepError + from dokimi.repos.replay.authoring import task_of_pr, tasks_by_pr + from tests.unlistable_dir import unlistable + + out = tmp_path / "tasks" + _authoring(toy["root"], [_pr1(toy)], out) + capsys.readouterr() + (out / "notes").mkdir() + (out / "notes" / "task.json").write_text(json.dumps({"source_pr": 9}), encoding="utf-8") # not an authoring_ directory + assert tasks_by_pr(out) == {1: "authoring_pr1"} and task_of_pr(out, 1) == "authoring_pr1" + assert tasks_by_pr(tmp_path / "missing") == {} + with unlistable(out): + with pytest.raises(PrepError, match=f"cannot list {out}: Permission denied"): + task_of_pr(out, 1) + with pytest.raises(SystemExit) as exc: + _authoring(toy["root"], [_pr1(toy)], out) + err = capsys.readouterr().err + assert exc.value.code == 1 and err.startswith("✗ ") and f"cannot list {out}: Permission denied" in err + + @pytest.mark.parametrize(("raw", "message"), [ (None, "cannot read the pull request file"), ("", "cannot read the pull request file"), diff --git a/dokimi/tests/test_repo_overlay.py b/dokimi/tests/test_repo_overlay.py index f9270b31eb..918e576d38 100644 --- a/dokimi/tests/test_repo_overlay.py +++ b/dokimi/tests/test_repo_overlay.py @@ -896,6 +896,22 @@ def cell_id(profile, arm): check_batch_executions(batch, [options(claude)]) # a plain cell beside an overlay cell of one profile +def test_a_batch_directory_that_cannot_be_listed_is_refused_not_read_as_holding_no_cell(tmp_path): + """#1507: the cells of another execution are not hidden by a batch directory at mode 111.""" + from dokimi.repos.batch_ledger import ExecutionMismatch, check_batch_executions + from tests.unlistable_dir import unlistable + + batch = tmp_path / "batch" + (batch / "cell1").mkdir(parents=True) + (batch / "cell1" / "result.json").write_text(json.dumps({"execution": {"id": "other"}}), encoding="utf-8") + with pytest.raises(ExecutionMismatch, match="holds cells of another execution"): + check_batch_executions(batch, {"mine"}) + with unlistable(batch), pytest.raises(ExecutionMismatch) as err: + check_batch_executions(batch, {"mine"}) + assert f"cannot list {batch}: Permission denied" in str(err.value) and "holds cells" not in str(err.value) + check_batch_executions(tmp_path / "missing", {"mine"}) # no directory, no cell + + def test_overlay_report_leaves_a_load_of_a_foreign_target_with_an_own_alias_unattributed(): records = [{"file": "AGENTS.codex.md", "scenario": "cwd=.", "class": "loaded"}] report = overlay_report(records, "claude", {"AGENTS.codex.md": ("AGENTS.claude.md",)}) diff --git a/dokimi/tests/test_repo_report_unreadable_cell.py b/dokimi/tests/test_repo_report_unreadable_cell.py index 79317d0a67..3e17685e5c 100644 --- a/dokimi/tests/test_repo_report_unreadable_cell.py +++ b/dokimi/tests/test_repo_report_unreadable_cell.py @@ -461,6 +461,24 @@ def test_a_result_file_with_a_batch_that_is_not_a_string_exits_2(tmp_path, capsy assert "Traceback" not in err +def test_a_batch_directory_that_cannot_be_listed_exits_2_naming_it_not_reading_as_empty(tmp_path, capsys): + """#1507: `repo report` of a batch at mode 111 does not report the started cell as nothing.""" + from dokimi.repos.report import load_cells, load_unsupported + from tests.unlistable_dir import unlistable + + batch = _batch(tmp_path, "b1", {"cell1/meta.json": b"{}", "cell2/unsupported.json": b"{}"}) + assert load_cells(batch) == ([], ["cell1"]) + assert [c["cell"] for c in load_unsupported(batch)] == ["cell2"] + assert load_cells(tmp_path / "missing") == ([], []) and load_unsupported(tmp_path / "missing") == [] + with unlistable(batch): + for load in (load_cells, load_unsupported): + with pytest.raises(CellFileError, match=f"cannot list {batch}: Permission denied"): + load(batch) + with refusal() as exc: + _run("report", str(batch)) + assert exc.code == 2 and f"cannot list {batch}: Permission denied" in capsys.readouterr().err + + @pytest.mark.parametrize("batch, starts", [("b7", "b7: the cells of arm a, model m ran with"), ("", "WHERE: the cells of arm a, model m ran with")]) def test_the_mixed_execution_refusal_starts_with_the_batch_name_or_else_where(batch, starts): diff --git a/dokimi/tests/test_repo_task_required_keys.py b/dokimi/tests/test_repo_task_required_keys.py index 94ebffe066..91c1378659 100644 --- a/dokimi/tests/test_repo_task_required_keys.py +++ b/dokimi/tests/test_repo_task_required_keys.py @@ -118,3 +118,17 @@ def test_load_tasks_refuses_bad_task_unless_keys_unchecked(tmp_path, body): with pytest.raises(PrepError, match="task.json"): load_tasks(content, manifest) assert [t.id for t in load_tasks(content, manifest, check_keys=False)] == ["t"] + + +def test_load_tasks_names_a_tasks_directory_it_cannot_list_and_keeps_no_task_for_a_missing_one(tmp_path): + """#1507: a tasks directory at mode 111 is a PrepError naming it, not `no task under ...`; a missing one has none.""" + from dokimi.repos.workspace import PrepError, load_tasks + from tests.unlistable_dir import unlistable + + content, manifest = _tasks_dir(tmp_path, "{}") + assert [t.id for t in load_tasks(content, manifest, check_keys=False)] == ["t"] + with unlistable(tmp_path / "tasks"), pytest.raises(PrepError) as err: + load_tasks(content, manifest, check_keys=False) + assert f"cannot list {tmp_path / 'tasks'}: Permission denied" in str(err.value) and "no task under" not in str(err.value) + with pytest.raises(PrepError, match=r"no task under ev/tasks \(no \*/task.json\)"): + load_tasks(tmp_path / "elsewhere", manifest) diff --git a/dokimi/tests/unlistable_dir.py b/dokimi/tests/unlistable_dir.py new file mode 100644 index 0000000000..230409d1bb --- /dev/null +++ b/dokimi/tests/unlistable_dir.py @@ -0,0 +1,28 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""A directory a process that is not root cannot list, for the tests of the readers that must refuse one.""" + +from __future__ import annotations + +import os +from contextlib import contextmanager +from pathlib import Path +from typing import Iterator + +import pytest + + +@contextmanager +def unlistable(path: Path) -> Iterator[None]: + """``path`` at mode 111 for the block; the test is skipped when this process can still list it (root).""" + path.chmod(0o111) + try: + try: + os.listdir(path) + except PermissionError: + yield + else: + pytest.skip("this process lists a mode 111 directory (root)") + finally: + path.chmod(0o700)