CodeSampleX

サンプル

click 8.4.2: click

検証済みサンプル — pypi click 8.4.2: click. python 3.12 · linux debian/x64 · docker で contract を実行し、成功しました: click.command decorates a function into a Command object…

sha256:69005cfea999520c579fc1c469a5de5dd5baafb1bc6077ac4c98f9a067599dcf

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 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()

オリジンシーダー

匿名