CodeSampleX

Exemple

zipp 4.1.0: Navigate and traverse implied directories in zip archives with zipp.Path without missing entries or failing iterdir

Échantillon vérifié pour pypi zipp 4.1.0: Navigate and traverse implied directories in zip archives with zipp.Path without missing entries or failing…

sha256:00f9926ea635cabde911806dda15b6abecbe1fda1872ea2a51887544b21c4b03

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
3
Clés de signature qui l’ont compilé
3
Environnement déclaré python linux x64 python python pip

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
python 3.12 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-16
python 3.12 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-18
python 3.12 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-slim@sha256:09f7da3bc104…
2026-09-08

Cas

HOW
Objectif
Navigate and traverse implied directories in zip archives with zipp.Path without missing entries or failing iterdir
Paquets
Symboles
  • zipp.Path
  • zipp.CompleteDirs
  • zipp.FastLookup
Environnement
python
Créé
2026-08-16T12:21:55Z

Contrat

  1. assert not Path(zf, 'sub').exists() and not Path(zf, 'sub').is_dir() and (Path(zf) / 'sub').exists() and (Path(zf) / 'sub').is_dir()
  2. assert list((Path(zf) / 'sub').iterdir()) == [Path(zf.filename, 'sub/nested/')] and attempting iterdir on Path(zf, 'sub') raises NotADirectoryError
  3. assert not Path(zf).exists() and Path(zf).is_dir() at the archive root
  4. assert isinstance((Path(zf) / 'sub').parent, zipp.Path) while Path(zf).parent returns a pathlib.Path
  5. assert isinstance(zf, zipp.FastLookup) after constructing Path(zf) in read mode

Fichiers

  • NOTES.md
  • csx.json
  • requirements.txt
  • src/__init__.py
  • src/archive_nav.py
  • test/contract.py

Télécharger l’artefact source (tar.gz)

Code source

NOTES.md
# zipp Implied Directory Resolution and Traversal Traps

## Prior Solution Search Result
`search_known_solution` returned COMPATIBLE sample `sha256:beb8b3121c3cddc83a0038650f092bd1609123c82e31e1209dc60f07e688d56f` (`importlib-metadata` version resolution mapping distribution names to top-level import names). That sample addresses metadata discovery rather than `zipp.Path` archive navigation and directory resolution.

## What a Model Would Have Written Instead
A model navigating archive subdirectories would construct `zipp.Path(zf, "sub")` directly or assume `Path(zf).exists()` returns `True` for an open archive root, expecting direct instantiation of directory paths to behave identically to path division (`root / "sub"`).

## How the Wrong Version Fails
It fails loudly with `NotADirectoryError: Can't listdir a file` when calling `.iterdir()` on directly constructed directory paths because `.at` lacks a trailing slash, and returns `exists() == False` and `is_dir() == False` silently despite child files existing within that directory.
csx.json
{"case":{"believed":"Directly instantiating zipp.Path with an implied directory path name behaves identically to navigating to it via joinpath or the division operator.","caseId":"case:sha256:8c5ed9e207f35d482556c07c6ef86aacac2310fbf4637591c3096fac38bfc2b3","contract":["assert not Path(zf, 'sub').exists() and not Path(zf, 'sub').is_dir() and (Path(zf) / 'sub').exists() and (Path(zf) / 'sub').is_dir()","assert list((Path(zf) / 'sub').iterdir()) == [Path(zf.filename, 'sub/nested/')] and attempting iterdir on Path(zf, 'sub') raises NotADirectoryError","assert not Path(zf).exists() and Path(zf).is_dir() at the archive root","assert isinstance((Path(zf) / 'sub').parent, zipp.Path) while Path(zf).parent returns a pathlib.Path","assert isinstance(zf, zipp.FastLookup) after constructing Path(zf) in read mode"],"goal":"Navigate and traverse implied directories in zip archives with zipp.Path without missing entries or failing iterdir","kind":"HOW","packages":["pkg:pypi/zipp@4.1.0"],"schemaVersion":1,"symbols":["zipp.Path","zipp.CompleteDirs","zipp.FastLookup"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","os":"linux","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/zipp@4.1.0"],"schemaVersion":1,"symbols":["zipp.Path","zipp.CompleteDirs","zipp.FastLookup"],"verifierAdapter":"python@1"}
requirements.txt
zipp==4.1.0
src/__init__.py
"""Package initialization."""
src/archive_nav.py
"""Archive navigation and path resolution utilities using zipp."""

from typing import List, Union
import pathlib
import zipfile
import zipp


def safe_resolve_subpath(root_path: zipp.Path, relative_subpath: str) -> zipp.Path:
    """Resolve a subpath within an archive using joinpath to ensure implied directory resolution.

    Directly constructing zipp.Path(zf, relative_subpath) fails to normalize implied
    directories with trailing slashes, causing .exists() and .is_dir() to return False.
    Navigating via joinpath (or the / operator) properly resolves implied directories.
    """
    parts = [p for p in relative_subpath.replace("\\", "/").strip("/").split("/") if p]
    current = root_path
    for part in parts:
        current = current / part
    return current


def list_directory_children(dir_path: zipp.Path) -> List[str]:
    """List child entry names inside an archive directory.

    Raises NotADirectoryError if dir_path is not recognized as a directory.
    """
    if not dir_path.is_dir():
        raise NotADirectoryError(f"Cannot list non-directory path: {dir_path.at}")
    return [child.name for child in dir_path.iterdir()]


def is_archive_internal_parent(path: zipp.Path) -> bool:
    """Determine whether the parent of the given path is within the archive itself.

    For subpaths inside the archive, .parent returns a zipp.Path.
    For the root archive path (at=""), .parent resolves to a pathlib.Path representing
    the host filesystem parent of the zipfile.
    """
    return bool(path.at) and isinstance(path.parent, zipp.Path)


def get_parent_location(path: zipp.Path) -> Union[zipp.Path, pathlib.Path]:
    """Retrieve the parent path of an archive entry or the archive file itself."""
    return path.parent
test/contract.py
import io
import os
import pathlib
import sys
import zipfile

# Ensure project root is on sys.path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import zipp
from src.archive_nav import (
    safe_resolve_subpath,
    list_directory_children,
    is_archive_internal_parent,
    get_parent_location,
)


def build_test_zip_buffer() -> io.BytesIO:
    """Construct an in-memory zip archive with implied directories."""
    buffer = io.BytesIO()
    with zipfile.ZipFile(buffer, "w") as zf_w:
        # Write files under nested paths without creating explicit directory records
        zf_w.writestr("sub/nested/file.txt", "hello world")
        zf_w.writestr("root_file.txt", "root content")
    buffer.seek(0)
    return buffer


def main() -> None:
    buf = build_test_zip_buffer()
    zf = zipfile.ZipFile(buf, "r")
    zf.filename = "archive.zip"
    root = zipp.Path(zf)

    # -----------------------------------------------------------------------------
    # 1. Implied Directory Resolution Trap
    # Naive model expectation: Directly instantiating Path(zf, 'sub') yields an
    # existing directory path equivalent to navigating via (root / 'sub').
    # zipp reality: Path(zf, 'sub') sets at='sub' directly without trailing slash.
    # Because CompleteDirs._name_set() contains implied dirs with trailing slashes ('sub/'),
    # direct.exists() and direct.is_dir() both evaluate to False.
    # In contrast, (root / 'sub') routes through resolve_dir(), appending the trailing slash.
    # -----------------------------------------------------------------------------
    direct = zipp.Path(zf, "sub")
    joined = root / "sub"
    safe_resolved = safe_resolve_subpath(root, "sub")

    assert not direct.exists(), "Direct Path(zf, 'sub') must not report exists=True without resolve_dir"
    assert not direct.is_dir(), "Direct Path(zf, 'sub') must not report is_dir=True without trailing slash"
    assert joined.exists(), "Navigating with / operator must resolve implied directory in _name_set"
    assert joined.is_dir(), "Navigating with / operator must recognize implied directory"
    assert safe_resolved.exists() and safe_resolved.is_dir()

    assert direct.at == "sub"
    assert joined.at == "sub/"
    assert joined.name == "sub"

    # -----------------------------------------------------------------------------
    # 2. Directory Iteration Trap
    # Naive model expectation: Calling .iterdir() on direct Path(zf, 'sub') works.
    # zipp reality: Because direct.is_dir() is False, direct.iterdir() raises
    # NotADirectoryError ("Can't listdir a file"). iterdir() on joined path succeeds.
    # -----------------------------------------------------------------------------
    direct_iterdir_failed = False
    try:
        list(direct.iterdir())
    except NotADirectoryError:
        direct_iterdir_failed = True
    assert direct_iterdir_failed, "iterdir() on un-resolved directory path must raise NotADirectoryError"

    child_names = list_directory_children(joined)
    assert child_names == ["nested"]

    nested_dir = joined / "nested"
    assert nested_dir.exists() and nested_dir.is_dir()
    assert list_directory_children(nested_dir) == ["file.txt"]

    # -----------------------------------------------------------------------------
    # 3. Root Path Existence vs Directory Trap
    # Naive model expectation: The root Path(zf) object has exists() == True.
    # zipp reality: root.at is "", which is not in _name_set() (contains only archive entries).
    # Therefore root.exists() is False, yet root.is_dir() is True.
    # -----------------------------------------------------------------------------
    assert not root.exists(), "Root zipp.Path has at='' which is not in _name_set(), so exists() is False"
    assert root.is_dir(), "Root zipp.Path must report is_dir() as True"
    assert not root.is_file(), "Root zipp.Path is a directory container, not a file"
    assert sorted(list_directory_children(root)) == ["root_file.txt", "sub"]

    # -----------------------------------------------------------------------------
    # 4. Parent Path Type Asymmetry Trap
    # Naive model expectation: .parent always returns a zipp.Path instance.
    # zipp reality: For subpaths, .parent returns a zipp.Path pointing to the parent
    # archive directory. For the root archive path, .parent returns a pathlib.Path
    # pointing to the parent folder of the zipfile on the host filesystem.
    # -----------------------------------------------------------------------------
    assert isinstance(joined.parent, zipp.Path)
    assert joined.parent == root
    assert is_archive_internal_parent(joined)

    root_parent = get_parent_location(root)
    assert isinstance(root_parent, pathlib.Path)
    assert not isinstance(root_parent, zipp.Path)
    assert not is_archive_internal_parent(root)

    # -----------------------------------------------------------------------------
    # 5. In-Place ZipFile Class Mutation Trap
    # Naive model expectation: Constructing zipp.Path(zf) leaves zf.__class__ as zipfile.ZipFile.
    # zipp reality: FastLookup.make(zf) mutates zf.__class__ in-place to zipp.FastLookup
    # for read-only archives (or zipp.CompleteDirs for writable archives).
    # -----------------------------------------------------------------------------
    assert isinstance(zf, zipp.FastLookup)
    assert zf.__class__ is zipp.FastLookup

    # -----------------------------------------------------------------------------
    # 6. Reading File vs Directory Content
    # Naive model expectation: Calling read_text() on a directory returns empty or raises KeyError.
    # zipp reality: open() and read_text() on a directory path raise IsADirectoryError.
    # -----------------------------------------------------------------------------
    file_entry = nested_dir / "file.txt"
    assert file_entry.is_file() and file_entry.exists()
    assert file_entry.read_text(encoding="utf-8") == "hello world"
    assert file_entry.read_bytes() == b"hello world"

    dir_read_failed = False
    try:
        joined.read_text()
    except IsADirectoryError:
        dir_read_failed = True
    assert dir_read_failed, "read_text() on a directory entry must raise IsADirectoryError"

    print("CONTRACT PASS: zipp.Path implied directory resolution and traversal verified")


if __name__ == "__main__":
    main()

Seeder d'origine

csx-seed