CodeSampleX

Exemple

idna 3.11: encode

Échantillon vérifié pour pypi idna 3.11: encode. Le contrat s'est exécuté sur python 3.12 · linux alpine/x64 · docker et a réussi.

sha256:c0c67147b7c63059afeb65b6ec7f492f4c48a7bd95f1f854417dfb0494fca163

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
2
Clés de signature qui l’ont compilé
1
Environnement déclaré python 3.12 linux 24 · ubuntu · glibc 2.39 x64 python 3.12 python pip

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
python 3.12 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-alpine@sha256:d09d15e60962…
2026-08-26
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-07

Cas

HOW
Objectif
verify idna.encode in pkg:pypi/idna@3.11
Paquets
Symboles
  • idna.encode
Environnement
python 3.12
Créé
2026-08-26T04:39:10Z

Contrat

  1. idna.encode(domain) converts internationalized domain names into Punycode ASCII-compatible encoding (ACE) bytes
  2. idna.encode(domain) preserves ASCII domain names and trailing dots in returned bytes
  3. idna.encode(domain, uts46=True) normalizes and case-folds uppercase characters before encoding
  4. idna.encode(domain) raises idna.core.InvalidCodepoint for uppercase codepoints under strict IDNA2008
  5. idna.encode(domain) raises idna.core.IDNAError when domain contains empty labels
  6. idna.encode(domain) raises TypeError when passed unsupported input types

Fichiers

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

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

Code 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 idna.encode in pkg:pypi/idna@3.11
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/idna@3.11
Demonstrate these symbols/APIs:
  - idna.encode

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:a7d4b8f888172c33742ac32bdf477793a330e95bf9e750e75aa6cfdf415afdc3","contract":["idna.encode(domain) converts internationalized domain names into Punycode ASCII-compatible encoding (ACE) bytes","idna.encode(domain) preserves ASCII domain names and trailing dots in returned bytes","idna.encode(domain, uts46=True) normalizes and case-folds uppercase characters before encoding","idna.encode(domain) raises idna.core.InvalidCodepoint for uppercase codepoints under strict IDNA2008","idna.encode(domain) raises idna.core.IDNAError when domain contains empty labels","idna.encode(domain) raises TypeError when passed unsupported input types"],"goal":"verify idna.encode in pkg:pypi/idna@3.11","kind":"HOW","packages":["pkg:pypi/idna@3.11"],"schemaVersion":1,"symbols":["idna.encode"]},"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","runtimeVersion":"3.12","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/idna@3.11"],"schemaVersion":1,"subject":"pkg:pypi/idna@3.11","symbols":["idna.encode"],"verifierAdapter":"python@1"}
requirements.txt
idna==3.11
spec.json
{
  "schemaVersion": 1,
  "goal": "verify idna.encode in pkg:pypi/idna@3.11",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/idna@3.11"
  ],
  "symbols": [
    "idna.encode"
  ]
}
src/encoder.py
"""Domain name encoder using idna.encode."""

import idna


def encode_domain(domain: str, *, uts46: bool = False, std3_rules: bool = False) -> bytes:
    """Encode an internationalized domain name (IDN) to Punycode ASCII-compatible encoding.

    Args:
        domain: Domain name string to encode.
        uts46: Whether to apply Unicode Technical Standard #46 processing and case folding.
        std3_rules: Whether to apply strict STD3 ASCII rules.

    Returns:
        bytes: The ACE (ASCII Compatible Encoding) representation of the domain.

    Raises:
        idna.core.IDNAError: If the domain contains invalid codepoints or empty labels.
        TypeError: If domain is not a str or bytes.
    """
    if not isinstance(domain, (str, bytes, bytearray)):
        raise TypeError(f"Expected str or bytes-like object, got: {type(domain).__name__}")

    return idna.encode(domain, uts46=uts46, std3_rules=std3_rules)
test/contract.py
"""Contract verification test for idna.encode."""

import os
import sys

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

import idna
from src.encoder import encode_domain


def test_encode_ascii_domain():
    """Verify ASCII domain encoding preserves ASCII labels and returns bytes."""
    domain = "example.com"
    result = idna.encode(domain)
    assert isinstance(result, bytes), f"Expected bytes, got {type(result)}"
    assert result == b"example.com"

    # Trailing dot preserved
    trailing_dot_result = idna.encode("example.com.")
    assert trailing_dot_result == b"example.com."

    # Via helper wrapper
    helper_result = encode_domain("example.com")
    assert helper_result == b"example.com"


def test_encode_internationalized_domain():
    """Verify IDN domains are converted to Punycode A-labels."""
    # German umlaut
    res1 = idna.encode("königen.example")
    assert isinstance(res1, bytes)
    assert res1 == b"xn--knigen-wxa.example"

    # Multiple internationalized labels
    res2 = idna.encode("bücher.münchen.de")
    assert res2 == b"xn--bcher-kva.xn--mnchen-3ya.de"

    # Preserving trailing dot on IDN
    res3 = idna.encode("königen.example.")
    assert res3 == b"xn--knigen-wxa.example."

    # Via helper wrapper
    helper_res = encode_domain("königen.example")
    assert helper_res == b"xn--knigen-wxa.example"


def test_encode_uts46_case_folding():
    """Verify uts46=True normalizes uppercase characters to lowercase before encoding."""
    res_uts46 = idna.encode("KÖNIGEN.example", uts46=True)
    assert res_uts46 == b"xn--knigen-wxa.example"

    helper_uts46 = encode_domain("KÖNIGEN.example", uts46=True)
    assert helper_uts46 == b"xn--knigen-wxa.example"


def test_encode_strict_idna2008_disallows_uppercase():
    """Verify IDNA2008 without UTS46 raises InvalidCodepoint on uppercase ASCII."""
    try:
        idna.encode("KÖNIGEN.example", uts46=False)
        assert False, "Expected idna.core.InvalidCodepoint for uppercase under IDNA2008"
    except idna.core.InvalidCodepoint:
        pass


def test_encode_empty_label_error():
    """Verify empty labels (such as leading/double dots) raise IDNAError."""
    for invalid_domain in [".example.com", "example..com"]:
        try:
            idna.encode(invalid_domain)
            assert False, f"Expected IDNAError for '{invalid_domain}'"
        except idna.core.IDNAError:
            pass


def test_encode_type_error():
    """Verify non-string / non-bytes inputs raise TypeError."""
    for invalid_input in [12345, None, ["example.com"], {}]:
        try:
            encode_domain(invalid_input)
            assert False, f"Expected TypeError for {type(invalid_input)}"
        except TypeError:
            pass


def main():
    test_encode_ascii_domain()
    test_encode_internationalized_domain()
    test_encode_uts46_case_folding()
    test_encode_strict_idna2008_disallows_uppercase()
    test_encode_empty_label_error()
    test_encode_type_error()
    print("Contract tests for idna.encode passed successfully.")
    return 0


if __name__ == "__main__":
    sys.exit(main())

Seeder d'origine

anonyme