CodeSampleX

Ejemplo

packaging 26.2: version.Version, specifiers.SpecifierSet, requirements.Requirement

Muestra verificada para pypi packaging 26.2: version.Version, specifiers.SpecifierSet, requirements.Requirement. El contrato se ejecutó en python 3.12 …

sha256:429645c8f49885bcc40eaf8d385090fdce1fce1b1dd15e1cc5fd92adc8d858bb

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado python linux 24 · ubuntu · glibc 2.39 x64 python python pip

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
python 3.12 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-20

Caso

HOW
Objetivo
verify pkg:pypi/packaging@26.2
Paquetes
Símbolos
  • packaging.version.Version
  • packaging.specifiers.SpecifierSet
  • packaging.requirements.Requirement
Entorno
python
Creado
2026-08-20T02:39:45Z

Contrato

  1. packaging.version.Version parses semantic version strings and correctly evaluates version ordering precedence
  2. packaging.specifiers.SpecifierSet matches version instances against version specifier constraints and filters candidate lists
  3. packaging.requirements.Requirement parses package dependency requirements with extras and environment markers

Archivos

  • PROMPT.md
  • csx.json
  • requirements.txt
  • sample.py
  • spec.json
  • test/contract.py

Descargar el artefacto de código fuente (tar.gz)

Código fuente

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify pkg:pypi/packaging@26.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/packaging@26.2

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:b5c906f8e6ced1808568414b5d9bef49d69838554530b1e8b5148564fbfaf789","contract":["packaging.version.Version parses semantic version strings and correctly evaluates version ordering precedence","packaging.specifiers.SpecifierSet matches version instances against version specifier constraints and filters candidate lists","packaging.requirements.Requirement parses package dependency requirements with extras and environment markers"],"goal":"verify pkg:pypi/packaging@26.2","kind":"HOW","packages":["pkg:pypi/packaging@26.2"],"schemaVersion":1,"symbols":["packaging.version.Version","packaging.specifiers.SpecifierSet","packaging.requirements.Requirement"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","language":"python","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/packaging@26.2"],"schemaVersion":1,"symbols":["packaging.version.Version","packaging.specifiers.SpecifierSet","packaging.requirements.Requirement"],"verifierAdapter":"python@1"}
requirements.txt
packaging==26.2
sample.py
"""Package versioning and dependency specification utility using packaging."""

from typing import Any
from packaging.version import Version
from packaging.specifiers import SpecifierSet
from packaging.requirements import Requirement


def parse_and_compare_versions(v1: str, v2: str) -> int:
    """Compare two version strings according to PEP 440 ordering.

    Returns:
        -1 if v1 < v2, 0 if v1 == v2, 1 if v1 > v2.
    """
    ver1 = Version(v1)
    ver2 = Version(v2)
    if ver1 < ver2:
        return -1
    elif ver1 > ver2:
        return 1
    return 0


def filter_compatible_versions(specifier_str: str, candidate_versions: list[str]) -> list[str]:
    """Filter and return candidate versions that satisfy the given specifier expression."""
    spec = SpecifierSet(specifier_str)
    matching = list(spec.filter(candidate_versions))
    return sorted(matching, key=Version)


def evaluate_dependency(
    requirement_str: str,
    installed_version_str: str,
    environment_markers: dict[str, Any] | None = None,
) -> bool:
    """Check if an installed package version satisfies a requirement and its environment markers.

    Returns:
        True if markers match (or no markers) and the version satisfies the specifier;
        False otherwise.
    """
    req = Requirement(requirement_str)
    if req.marker is not None and environment_markers is not None:
        if not req.marker.evaluate(environment_markers):
            return False
    return req.specifier.contains(installed_version_str)


if __name__ == "__main__":
    is_valid = evaluate_dependency(
        "example-pkg>=1.0,<2.0; python_version >= '3.8'",
        "1.5.0",
        {"python_version": "3.11"},
    )
    print(f"Dependency valid: {is_valid}")
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:pypi/packaging@26.2",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/packaging@26.2"
  ]
}
test/contract.py
"""Contract verification test for packaging library functionality."""

import os
import sys

# Ensure sample module can be imported from root directory
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from packaging.version import Version
from packaging.specifiers import SpecifierSet
from packaging.requirements import Requirement
from sample import parse_and_compare_versions, filter_compatible_versions, evaluate_dependency


def test_version_parsing_and_ordering():
    """Assertion 1: packaging.version.Version parses semantic version strings and correctly evaluates version ordering precedence."""
    v_base = Version("1.0.0")
    v_pre = Version("1.0.0a1")
    v_post = Version("1.0.0.post1")
    v_dev = Version("1.0.0.dev1")
    v_next = Version("1.0.1")

    assert v_dev < v_pre < v_base < v_post < v_next, "PEP 440 version ordering failed"
    assert v_base.major == 1 and v_base.minor == 0 and v_base.micro == 0
    assert v_pre.is_prerelease is True
    assert v_post.is_postrelease is True
    assert v_dev.is_devrelease is True

    assert parse_and_compare_versions("2.1.0", "2.0.9") == 1
    assert parse_and_compare_versions("1.5.0", "1.5.0") == 0
    assert parse_and_compare_versions("1.0.0b1", "1.0.0") == -1


def test_specifier_matching_and_filtering():
    """Assertion 2: packaging.specifiers.SpecifierSet matches version instances against version specifier constraints and filters candidate lists."""
    spec = SpecifierSet(">=1.5.0, <3.0.0, !=2.0.1")

    assert spec.contains("1.5.0") is True
    assert spec.contains("2.0.0") is True
    assert spec.contains("2.0.1") is False
    assert spec.contains("1.4.9") is False
    assert spec.contains("3.0.0") is False

    candidates = ["1.0.0", "1.5.0", "2.0.0", "2.0.1", "2.5.0", "3.0.0", "3.1.0"]
    compatible = filter_compatible_versions(">=1.5.0, <3.0.0, !=2.0.1", candidates)
    assert compatible == ["1.5.0", "2.0.0", "2.5.0"], f"Filtered versions mismatch: {compatible}"


def test_requirement_parsing_and_marker_evaluation():
    """Assertion 3: packaging.requirements.Requirement parses package dependency requirements with extras and environment markers."""
    req_text = "requests[security,tests]>=2.28.0,<3.0.0; python_version >= '3.8'"
    req = Requirement(req_text)

    assert req.name == "requests"
    assert req.extras == {"security", "tests"}
    assert req.specifier.contains("2.28.1") is True
    assert req.specifier.contains("3.0.0") is False
    assert req.marker is not None

    # Test evaluate_dependency wrapper
    assert evaluate_dependency(req_text, "2.28.1", {"python_version": "3.10"}) is True
    assert evaluate_dependency(req_text, "2.28.1", {"python_version": "3.7"}) is False
    assert evaluate_dependency(req_text, "1.9.0", {"python_version": "3.10"}) is False


def main():
    test_version_parsing_and_ordering()
    test_specifier_matching_and_filtering()
    test_requirement_parsing_and_marker_evaluation()
    print("All contract assertions passed successfully.")


if __name__ == "__main__":
    main()

Seeder de origen

anónimo