CodeSampleX

Sample

packaging 26.3: licenses.canonicalize_license_expression

Verified sample for pypi packaging 26.3: licenses.canonicalize_license_expression. The contract ran on python 3.12 · linux debian/x64 · docker and passed.

sha256:0bcf5b2697fc5695f6152bacd0d4218ac1ccf103c8a0c07a3525982e387a3f87

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
1
Signing keys that built it
1
Declared environment linux 24 · ubuntu · glibc 2.39 x64 pip

Verification-run environments

Environment Contract Stages Run
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-02

Case

HOW
Goal
verify packaging.licenses.canonicalize_license_expression in pkg:pypi/packaging@26.3
Packages
Symbols
  • packaging.licenses.canonicalize_license_expression
Created
2026-09-02T13:34:29Z

Contract

  1. packaging.licenses.canonicalize_license_expression normalizes single and compound SPDX license expressions with standard casing and boolean operators
  2. packaging.licenses.canonicalize_license_expression normalizes license expressions containing WITH exception clauses
  3. packaging.licenses.canonicalize_license_expression raises packaging.licenses.InvalidLicenseExpression for unknown license identifiers and syntax errors

Files

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

Download the source artifact (tar.gz)

Source

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 packaging.licenses.canonicalize_license_expression in pkg:pypi/packaging@26.3
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/packaging@26.3
Demonstrate these symbols/APIs:
  - packaging.licenses.canonicalize_license_expression

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:0b6b1a608f95dc2a49fea5badef137f70a2f6e243d7119cdddf1118818c4c6fa","contract":["packaging.licenses.canonicalize_license_expression normalizes single and compound SPDX license expressions with standard casing and boolean operators","packaging.licenses.canonicalize_license_expression normalizes license expressions containing WITH exception clauses","packaging.licenses.canonicalize_license_expression raises packaging.licenses.InvalidLicenseExpression for unknown license identifiers and syntax errors"],"goal":"verify packaging.licenses.canonicalize_license_expression in pkg:pypi/packaging@26.3","kind":"HOW","packages":["pkg:pypi/packaging@26.3"],"schemaVersion":1,"symbols":["packaging.licenses.canonicalize_license_expression"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/packaging@26.3"],"schemaVersion":1,"subject":"pkg:pypi/packaging@26.3","symbols":["packaging.licenses.canonicalize_license_expression"],"verifierAdapter":"python@1"}
requirements.txt
packaging==26.3
sample.py
"""SPDX license expression canonicalization utility using packaging."""

from packaging.licenses import (
    InvalidLicenseExpression,
    NormalizedLicenseExpression,
    canonicalize_license_expression,
)


def normalize_license(raw_expression: str) -> NormalizedLicenseExpression:
    """Canonicalize a single or compound SPDX license expression string.

    Args:
        raw_expression: Raw SPDX license expression string (e.g. 'mit', 'mit or apache-2.0').

    Returns:
        Canonicalized NormalizedLicenseExpression string.

    Raises:
        InvalidLicenseExpression: If syntax is invalid or license identifier is unknown.
    """
    return canonicalize_license_expression(raw_expression)


def is_valid_license_expression(raw_expression: str) -> bool:
    """Validate whether an expression is a valid canonicalizable SPDX license expression.

    Args:
        raw_expression: Raw SPDX license expression string.

    Returns:
        True if the expression is valid, False otherwise.
    """
    try:
        canonicalize_license_expression(raw_expression)
        return True
    except InvalidLicenseExpression:
        return False


def normalize_licenses_batch(expressions: list[str]) -> dict[str, str]:
    """Canonicalize a list of raw license expression strings.

    Args:
        expressions: List of raw license strings.

    Returns:
        Dictionary mapping raw expression to normalized license string.
    """
    results: dict[str, str] = {}
    for expr in expressions:
        results[expr] = canonicalize_license_expression(expr)
    return results


if __name__ == "__main__":
    sample_expr = "mit and (apache-2.0 or bsd-2-clause)"
    normalized = normalize_license(sample_expr)
    print(f"Original: {sample_expr}")
    print(f"Canonicalized: {normalized}")
spec.json
{
  "schemaVersion": 1,
  "goal": "verify packaging.licenses.canonicalize_license_expression in pkg:pypi/packaging@26.3",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/packaging@26.3"
  ],
  "symbols": [
    "packaging.licenses.canonicalize_license_expression"
  ]
}
test/contract.py
"""Contract verification tests for packaging.licenses.canonicalize_license_expression."""

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.licenses import (
    InvalidLicenseExpression,
    NormalizedLicenseExpression,
    canonicalize_license_expression,
)
from sample import (
    is_valid_license_expression,
    normalize_license,
    normalize_licenses_batch,
)


def test_canonicalize_single_and_compound():
    """Assertion 1: packaging.licenses.canonicalize_license_expression normalizes single and compound SPDX license expressions with standard casing and boolean operators."""
    assert canonicalize_license_expression("mit") == "MIT"
    assert canonicalize_license_expression("apache-2.0") == "Apache-2.0"
    assert canonicalize_license_expression("bsd-3-clause") == "BSD-3-Clause"

    # Compound boolean expressions with AND / OR
    expr = "mit and (apache-2.0 or bsd-2-clause)"
    expected = "MIT AND (Apache-2.0 OR BSD-2-Clause)"
    normalized = canonicalize_license_expression(expr)
    assert normalized == expected, f"Expected {expected}, got {normalized}"

    # Return value compatibility
    assert isinstance(normalized, str)
    assert normalize_license("mit") == "MIT"

    batch_input = ["mit", "apache-2.0", "bsd-2-clause"]
    batch_res = normalize_licenses_batch(batch_input)
    assert batch_res == {
        "mit": "MIT",
        "apache-2.0": "Apache-2.0",
        "bsd-2-clause": "BSD-2-Clause",
    }


def test_canonicalize_with_exceptions():
    """Assertion 2: packaging.licenses.canonicalize_license_expression normalizes license expressions containing WITH exception clauses."""
    with_expr = "gpl-3.0-only with autoconf-exception-3.0"
    expected = "GPL-3.0-only WITH Autoconf-exception-3.0"
    normalized = canonicalize_license_expression(with_expr)
    assert normalized == expected, f"Expected {expected}, got {normalized}"

    compound_with = "mit or (gpl-2.0-or-later with classpath-exception-2.0)"
    expected_compound = "MIT OR (GPL-2.0-or-later WITH Classpath-exception-2.0)"
    assert canonicalize_license_expression(compound_with) == expected_compound


def test_invalid_license_expressions():
    """Assertion 3: packaging.licenses.canonicalize_license_expression raises packaging.licenses.InvalidLicenseExpression for unknown license identifiers and syntax errors."""
    # Unknown license identifier
    try:
        canonicalize_license_expression("unknown-custom-license-1234")
        assert False, "Should have raised InvalidLicenseExpression for unknown license"
    except InvalidLicenseExpression as e:
        assert "Unknown license" in str(e)

    # Invalid syntax (unmatched bracket / trailing operator)
    try:
        canonicalize_license_expression("(mit and apache-2.0")
        assert False, "Should have raised InvalidLicenseExpression for unclosed parenthesis"
    except InvalidLicenseExpression as e:
        assert "Invalid license expression" in str(e)

    try:
        canonicalize_license_expression("mit or")
        assert False, "Should have raised InvalidLicenseExpression for incomplete expression"
    except InvalidLicenseExpression as e:
        assert "Invalid license expression" in str(e)

    # Helper validation function
    assert is_valid_license_expression("mit") is True
    assert is_valid_license_expression("invalid_license_identifier_foo") is False
    assert is_valid_license_expression("(mit or") is False


def main():
    test_canonicalize_single_and_compound()
    test_canonicalize_with_exceptions()
    test_invalid_license_expressions()
    print("All contract assertions passed successfully.")


if __name__ == "__main__":
    main()

Origin Seeder

anonymous