CodeSampleX

샘플

idna 3.11: encode

검증된 샘플 — pypi idna 3.11: encode. python 3.12 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: idna.encode(domain) converts internationalized domain names…

sha256:c0c67147b7c63059afeb65b6ec7f492f4c48a7bd95f1f854417dfb0494fca163

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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())

오리진 시더

익명