Пример
click 8.4.2: click
Проверенный пример — pypi click 8.4.2: click. Контракт выполнен на python 3.12 · linux debian/x64 · docker и пройден: click.command decorates a function into…
sha256:69005cfea999520c579fc1c469a5de5dd5baafb1bc6077ac4c98f9a067599dcf
Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла.
Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди.
MIT-0
Свидетельства выполнения
Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.
- Основа свидетельства
- Подписанный контракт пройден
- Квитанции проверки
- 1
- Ключи подписи, собравшие его
- 1
Заявленная среда
python linux 24 · ubuntu · glibc 2.39 x64 python python pip
Среды запусков проверки
| Окружение | Контракт | Этапы | Запуск |
|---|---|---|---|
| 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-06 |
Кейс
HOW- Цель
- verify click in pkg:pypi/click@8.4.2
- Пакеты
- Символы
-
- click
- Окружение
- python
- Создан
- 2026-09-06T09:39:58Z
Контракт
- click.command decorates a function into a Command object that parses options and arguments.
- click.option configures named CLI flags and option parameters with default values and type validation.
- click.argument configures positional arguments and parses them into function parameters.
- click.echo prints message strings to the output stream safely handling unicode and byte representations.
- click.BadParameter and click.UsageError raise structured CLI errors with expected exit status codes.
Файлы
- NOTES.md
- PROMPT.md
- csx.json
- requirements.txt
- sample.py
- spec.json
- test/contract.py
Исходный код
# Click CLI command and parameter handling
This sample pins `click` 8.4.2 and verifies `click` core command definition, option and argument handling, output stream writing, and error types.
The contract verifies:
- `click.command` decorates a Python function into a Command object that parses options and arguments.
- `click.option` configures named CLI flags and option parameters with default values and type validation.
- `click.argument` configures positional arguments and parses them into function parameters.
- `click.echo` prints message strings to the output stream safely handling unicode and byte representations.
- `click.BadParameter` and `click.UsageError` raise structured CLI errors with expected exit status codes.
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 click in pkg:pypi/click@8.4.2
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:pypi/click@8.4.2
Demonstrate these symbols/APIs:
- click
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:018df7f0ac0308967d6daa30f1d8105c2afbeeea8737c7be263dcebf0ed66545","contract":["click.command decorates a function into a Command object that parses options and arguments.","click.option configures named CLI flags and option parameters with default values and type validation.","click.argument configures positional arguments and parses them into function parameters.","click.echo prints message strings to the output stream safely handling unicode and byte representations.","click.BadParameter and click.UsageError raise structured CLI errors with expected exit status codes."],"goal":"verify click in pkg:pypi/click@8.4.2","kind":"HOW","packages":["pkg:pypi/click@8.4.2"],"schemaVersion":1,"symbols":["click"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","executionContext":"python","language":"python","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/click@8.4.2"],"schemaVersion":1,"subject":"pkg:pypi/click@8.4.2","symbols":["click"],"verifierAdapter":"python@1"}
click==8.4.2
"""Sample demonstrating core Click command-line interface patterns."""
import click
@click.command()
@click.argument("name", type=str)
@click.option("--count", "-c", default=1, type=click.IntRange(1, 100), help="Number of greetings.")
@click.option("--shout/--no-shout", default=False, help="Whether to shout greeting.")
def greet(name: str, count: int, shout: bool) -> str:
"""Generate a greeting message for a user."""
greeting = f"Hello, {name}!"
if shout:
greeting = greeting.upper()
for _ in range(count):
click.echo(greeting)
return greeting
def format_message(text: str, err: bool = False) -> None:
"""Print message via click.echo with optional error stream destination."""
click.echo(text, err=err)
def validate_positive_number(ctx: click.Context, param: click.Parameter, value: int) -> int:
"""Custom parameter callback raising BadParameter on non-positive input."""
if value <= 0:
raise click.BadParameter("value must be strictly positive", ctx=ctx, param=param)
return value
{
"schemaVersion": 1,
"goal": "verify click in pkg:pypi/click@8.4.2",
"kind": "HOW",
"packages": [
"pkg:pypi/click@8.4.2"
],
"symbols": [
"click"
]
}
"""Contract verification test for click in pkg:pypi/click@8.4.2."""
import io
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 click
from click.testing import CliRunner
from sample import greet, format_message, validate_positive_number
def test_command_decoration() -> None:
# 1. click.command decorates a function into a Command object that parses options and arguments.
assert isinstance(greet, click.Command), f"Expected click.Command, got {type(greet)}"
assert greet.name == "greet"
runner = CliRunner()
result = runner.invoke(greet, ["Alice"])
assert result.exit_code == 0
assert "Hello, Alice!" in result.output
def test_option_parsing_and_types() -> None:
# 2. click.option configures named CLI flags and option parameters with default values and type validation.
runner = CliRunner()
result = runner.invoke(greet, ["Bob", "--count", "3", "--shout"])
assert result.exit_code == 0
lines = [line.strip() for line in result.output.strip().splitlines()]
assert len(lines) == 3
assert all(line == "HELLO, BOB!" for line in lines)
# Validate type validation out of range error
invalid_result = runner.invoke(greet, ["Bob", "--count", "0"])
assert invalid_result.exit_code != 0
assert "Invalid value for '--count' / '-c'" in invalid_result.output or "Invalid value" in invalid_result.output
def test_argument_handling() -> None:
# 3. click.argument configures positional arguments and parses them into function parameters.
runner = CliRunner()
# Missing required positional argument 'name'
missing_result = runner.invoke(greet, [])
assert missing_result.exit_code != 0
assert "Missing argument" in missing_result.output
def test_click_echo_output() -> None:
# 4. click.echo prints message strings to the output stream safely handling unicode and byte representations.
stream = io.StringIO()
click.echo("Offline verification check", file=stream)
assert stream.getvalue() == "Offline verification check\n"
err_stream = io.StringIO()
click.echo("Offline error check", file=err_stream, err=True)
assert err_stream.getvalue() == "Offline error check\n"
def test_exception_types_and_codes() -> None:
# 5. click.BadParameter and click.UsageError raise structured CLI errors with expected exit status codes.
assert issubclass(click.BadParameter, click.UsageError)
assert issubclass(click.UsageError, click.ClickException)
err = click.UsageError("custom usage problem")
assert err.exit_code == 2
assert "custom usage problem" in err.format_message()
bad_param = click.BadParameter("invalid input value")
assert bad_param.exit_code == 2
assert "invalid input value" in bad_param.format_message()
def main() -> None:
test_command_decoration()
test_option_parsing_and_types()
test_argument_handling()
test_click_echo_output()
test_exception_types_and_codes()
print("CONTRACT PASS: click verified offline")
if __name__ == "__main__":
main()
Исходный сидер
аноним