CodeSampleX

示例

idna 3.11: encode

已验证示例 — pypi idna 3.11: encode. contract 在 python 3.12 · linux alpine/x64 · docker 上运行并通过: idna.encode(domain) converts internationalized domain names into…

sha256:c0c67147b7c63059afeb65b6ec7f492f4c48a7bd95f1f854417dfb0494fca163

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
2
构建过它的签名密钥
1
声明的环境 python 3.12 linux 24 · ubuntu · glibc 2.39 x64 python 3.12 python pip

验证运行环境

环境 契约 阶段 运行日期
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

案例

HOW
目标
verify idna.encode in pkg:pypi/idna@3.11
包
符号
  • idna.encode
环境
python 3.12
创建时间
2026-08-26T04:39:10Z

契约

  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

文件

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

下载源代码构件 (tar.gz)

源代码

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())

原始种子者

匿名