Exemplo
urllib3 2.7.0: HTTPHeaderDict, encode_multipart_formdata
Amostra verificada para pypi urllib3 2.7.0: HTTPHeaderDict, encode_multipart_formdata. O contrato rodou em python 3.12 · linux alpine/x64 · docker e passou.
sha256:872a88927c5ad0ea0b38fe16bc1328324e088c02c47034e472c4389f0c062f72
Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu.
Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas.
MIT-0
Evidência de execução
O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.
- Base da evidência
- Contrato assinado aprovado
- Recibos de verificação
- 1
- Chaves de assinatura que o compilaram
- 1
Ambiente declarado
python linux 24 · ubuntu · glibc 2.39 x64 python python pip
Ambientes das execuções de verificação
| Ambiente | Contrato | Etapas | Execução |
|---|---|---|---|
| python 3.12 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · python@1 |
2026-08-20 |
Caso
HOW- Objetivo
- verify pkg:pypi/urllib3@2.7.0
- Pacotes
- Símbolos
-
- urllib3.HTTPHeaderDict
- urllib3.encode_multipart_formdata
- Ambiente
- python
- Criado
- 2026-08-20T03:13:04Z
Contrato
- urllib3.HTTPHeaderDict provides case-insensitive header access while preserving header casing
- urllib3.HTTPHeaderDict.add supports repeated headers and getlist returns all values as a list
- urllib3.encode_multipart_formdata formats fields and file payloads into multipart form-data body and content-type header
Arquivos
- PROMPT.md
- csx.json
- requirements.txt
- sample.py
- spec.json
- test/contract.py
Código-fonte
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/urllib3@2.7.0
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:pypi/urllib3@2.7.0
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.
{"case":{"caseId":"case:sha256:fa449772050e9c9e0c8c5e979d9ae886abeb447c912e930536fcef4608ba2eb1","contract":["urllib3.HTTPHeaderDict provides case-insensitive header access while preserving header casing","urllib3.HTTPHeaderDict.add supports repeated headers and getlist returns all values as a list","urllib3.encode_multipart_formdata formats fields and file payloads into multipart form-data body and content-type header"],"goal":"verify pkg:pypi/urllib3@2.7.0","kind":"HOW","packages":["pkg:pypi/urllib3@2.7.0"],"schemaVersion":1,"symbols":["urllib3.HTTPHeaderDict","urllib3.encode_multipart_formdata"]},"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/urllib3@2.7.0"],"schemaVersion":1,"symbols":["urllib3.HTTPHeaderDict","urllib3.encode_multipart_formdata"],"verifierAdapter":"python@1"}
urllib3==2.7.0
"""Sample demonstrating HTTPHeaderDict header management and multipart form encoding with urllib3."""
from typing import Any, Dict, List, Optional, Tuple, Union
import urllib3
from urllib3 import HTTPHeaderDict, encode_multipart_formdata
def create_header_dict(initial_headers: Optional[Dict[str, str]] = None) -> HTTPHeaderDict:
"""Create a urllib3 HTTPHeaderDict instance with optional initial headers."""
return HTTPHeaderDict(initial_headers or {})
def add_header_entry(headers: HTTPHeaderDict, key: str, value: str) -> None:
"""Add a header entry without overwriting existing entries with the same key."""
headers.add(key, value)
def get_header_values(headers: HTTPHeaderDict, key: str) -> List[str]:
"""Retrieve all values associated with a header key."""
return headers.getlist(key)
def build_multipart_payload(
fields: Dict[str, Union[str, bytes, Tuple[str, Union[str, bytes], str]]],
) -> Tuple[bytes, str]:
"""Encode form fields and file data into a multipart body and Content-Type header."""
body, content_type = encode_multipart_formdata(fields)
return body, content_type
{
"schemaVersion": 1,
"goal": "verify pkg:pypi/urllib3@2.7.0",
"kind": "HOW",
"packages": [
"pkg:pypi/urllib3@2.7.0"
]
}
"""Contract verification test for urllib3 HTTPHeaderDict and multipart encoding."""
import os
import sys
# Ensure project root is on sys.path for local module imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import urllib3
from sample import (
add_header_entry,
build_multipart_payload,
create_header_dict,
get_header_values,
)
def test_header_dict_case_insensitivity():
"""Assertion 1: urllib3.HTTPHeaderDict provides case-insensitive header access while preserving header casing."""
headers = create_header_dict({"Content-Type": "application/json", "X-Custom-ID": "12345"})
# Check case-insensitive lookup
assert headers["content-type"] == "application/json"
assert headers["CONTENT-TYPE"] == "application/json"
assert headers["x-custom-id"] == "12345"
assert "content-type" in headers
assert "Content-Type" in headers
assert "X-CUSTOM-ID" in headers
# Keys preserve original casing when iterating
header_keys = list(headers.keys())
assert "Content-Type" in header_keys
assert "X-Custom-ID" in header_keys
def test_header_dict_multi_value_handling():
"""Assertion 2: urllib3.HTTPHeaderDict.add supports repeated headers and getlist returns all values as a list."""
headers = create_header_dict()
add_header_entry(headers, "Set-Cookie", "session=xyz987; Path=/; Secure")
add_header_entry(headers, "Set-Cookie", "theme=dark; Path=/")
values = get_header_values(headers, "set-cookie")
assert isinstance(values, list)
assert len(values) == 2
assert values[0] == "session=xyz987; Path=/; Secure"
assert values[1] == "theme=dark; Path=/"
# Accessing via dictionary lookup combines with comma separator per HTTP spec
combined = headers["set-cookie"]
assert "session=xyz987; Path=/; Secure" in combined
assert "theme=dark; Path=/" in combined
def test_multipart_payload_encoding():
"""Assertion 3: urllib3.encode_multipart_formdata formats fields and file payloads into multipart form-data body and content-type header."""
fields = {
"user_id": "usr_42",
"avatar": ("profile.png", b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR", "image/png"),
}
body, content_type = build_multipart_payload(fields)
assert isinstance(body, bytes)
assert content_type.startswith("multipart/form-data; boundary=")
# Verify field content and file header formatting in multipart body
assert b'name="user_id"' in body
assert b"usr_42" in body
assert b'name="avatar"; filename="profile.png"' in body
assert b"Content-Type: image/png" in body
assert b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR" in body
def main():
test_header_dict_case_insensitivity()
test_header_dict_multi_value_handling()
test_multipart_payload_encoding()
print("All contract assertions passed successfully.")
if __name__ == "__main__":
main()
Seeder de origem
anônimo