CodeSampleX

示例

click 8.4.2: click

已验证示例 — pypi click 8.4.2: click. contract 在 python 3.12 · linux debian/x64 · docker 上运行并通过: click.command decorates a function into a Command object that…

sha256:69005cfea999520c579fc1c469a5de5dd5baafb1bc6077ac4c98f9a067599dcf

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

契约

  1. click.command decorates a function into a Command object that parses options and arguments.
  2. click.option configures named CLI flags and option parameters with default values and type validation.
  3. click.argument configures positional arguments and parses them into function parameters.
  4. click.echo prints message strings to the output stream safely handling unicode and byte representations.
  5. 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

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

源代码

NOTES.md
# 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.
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 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.
csx.json
{"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"}
requirements.txt
click==8.4.2
sample.py
"""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
spec.json
{
  "schemaVersion": 1,
  "goal": "verify click in pkg:pypi/click@8.4.2",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/click@8.4.2"
  ],
  "symbols": [
    "click"
  ]
}
test/contract.py
"""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()

原始种子者

匿名