CodeSampleX

샘플

pydantic-settings 2.14.2: CliApp

검증된 샘플 — pypi pydantic-settings 2.14.2: CliApp. python 3.12 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: assert CliApp.run executes cli_cmd on a…

sha256:6850064ed58b6cdd88b9ea41e49ae60a6b4baf46eb3b8be01dacec47432caeb9

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

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 python 3.12 linux 24 · ubuntu · glibc 2.39 x64 python 3.12 python pip 24

검증 실행 환경

환경 컨트랙트 단계 실행일
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-30

케이스

HOW
목표
verify CliApp in pkg:pypi/pydantic-settings@2.14.2
패키지
심벌
  • CliApp
환경
python 3.12
생성일
2026-08-30T19:26:07Z

컨트랙트

  1. assert CliApp.run executes cli_cmd on a BaseSettings class with parsed command-line arguments
  2. assert CliApp.run supports asynchronous cli_cmd entrypoints on BaseModel classes
  3. assert CliApp.format_help returns formatted CLI help string describing model options
  4. assert CliApp.serialize converts model instance fields into command-line argument lists
  5. assert CliApp.run_subcommand dispatches CLI execution to nested subcommands defined with CliSubCommand
  6. assert CliApp.run raises SettingsError when encountering unknown arguments if cli_exit_on_error is False

파일

  • PROMPT.md
  • csx.json
  • pyproject.toml
  • requirements.txt
  • spec.json
  • 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 CliApp in pkg:pypi/pydantic-settings@2.14.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/pydantic-settings@2.14.2
Demonstrate these symbols/APIs:
  - CliApp
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:533c1d7468c141079c40309d901ddf43c38bfb945f6f2826c533f5c7a555714a","constraints":{"executionContext":"python"},"contract":["assert CliApp.run executes cli_cmd on a BaseSettings class with parsed command-line arguments","assert CliApp.run supports asynchronous cli_cmd entrypoints on BaseModel classes","assert CliApp.format_help returns formatted CLI help string describing model options","assert CliApp.serialize converts model instance fields into command-line argument lists","assert CliApp.run_subcommand dispatches CLI execution to nested subcommands defined with CliSubCommand","assert CliApp.run raises SettingsError when encountering unknown arguments if cli_exit_on_error is False"],"goal":"verify CliApp in pkg:pypi/pydantic-settings@2.14.2","kind":"HOW","packages":["pkg:pypi/pydantic-settings@2.14.2"],"schemaVersion":1,"symbols":["CliApp"]},"contractCommand":["python3","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","executionContext":"python","language":"python","libc":"glibc","libcVersion":"2.39","moduleSystem":"standard","os":"linux","osVersionBucket":"24","packageManager":"pip","packageManagerVersion":"24.0","runtime":"python","runtimeVersion":"3.12","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/pydantic-settings@2.14.2"],"schemaVersion":1,"subject":"pkg:pypi/pydantic-settings@2.14.2","symbols":["CliApp"],"verifierAdapter":"python@1"}
pyproject.toml
[project]
name = "verify-pydantic-settings-cliapp"
version = "0.1.0"
dependencies = [
    "pydantic-settings==2.14.2",
]
requirements.txt
annotated-types==0.8.0
pydantic==2.13.5
pydantic-core==2.46.5
pydantic-settings==2.14.2
python-dotenv==1.2.3
typing-extensions==4.16.0
typing-inspection==0.4.4
spec.json
{
  "schemaVersion": 1,
  "goal": "verify CliApp in pkg:pypi/pydantic-settings@2.14.2",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/pydantic-settings@2.14.2"
  ],
  "symbols": [
    "CliApp"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.py
import asyncio
from typing import List, Union
from pydantic import BaseModel, Field
from pydantic_settings import (
    BaseSettings,
    CliApp,
    CliSubCommand,
    SettingsConfigDict,
    SettingsError,
)


class AppSettings(BaseSettings):
    model_config = SettingsConfigDict(cli_implicit_flags=True)

    host: str = "127.0.0.1"
    port: int = 8080
    debug: bool = False
    tags: List[str] = Field(default_factory=list)

    def cli_cmd(self) -> None:
        self._ran = True


class AsyncApp(BaseModel):
    name: str = "service"
    retries: int = 3

    async def cli_cmd(self) -> None:
        await asyncio.sleep(0.001)
        self._async_ran = True


def test_cli_app_run_basic():
    app = CliApp.run(
        AppSettings,
        cli_args=["--host", "0.0.0.0", "--port", "9000", "--debug", "--tags", '["alpha", "beta"]'],
        cli_exit_on_error=False,
    )
    assert app.host == "0.0.0.0"
    assert app.port == 9000
    assert app.debug is True
    assert app.tags == ["alpha", "beta"]
    assert getattr(app, "_ran", False) is True


def test_cli_app_run_async():
    app = CliApp.run(
        AsyncApp,
        cli_args=["--name", "custom-service", "--retries", "5"],
        cli_exit_on_error=False,
    )
    assert app.name == "custom-service"
    assert app.retries == 5
    assert getattr(app, "_async_ran", False) is True


def test_cli_app_format_help():
    help_text = CliApp.format_help(AppSettings, strip_ansi_color=True)
    assert "--host" in help_text
    assert "--port" in help_text
    assert "--debug" in help_text


def test_cli_app_serialize():
    app = AppSettings(host="192.168.1.1", port=3000, debug=True, tags=["web", "api"])
    serialized = CliApp.serialize(app, list_style="argparse")
    assert "--host" in serialized
    assert "192.168.1.1" in serialized
    assert "--port" in serialized
    assert "3000" in serialized
    assert "--tags" in serialized


class SubCommandA(BaseModel):
    alpha: str = "default_a"

    def cli_cmd(self) -> None:
        self._sub_a_ran = True


class SubCommandB(BaseModel):
    beta: int = 42

    def cli_cmd(self) -> None:
        self._sub_b_ran = True


class RootApp(BaseSettings):
    model_config = SettingsConfigDict(cli_implicit_flags=True)
    cmd: CliSubCommand[Union[SubCommandA, SubCommandB]]

    def cli_cmd(self) -> None:
        CliApp.run_subcommand(self)


def test_cli_app_subcommand():
    root = CliApp.run(
        RootApp,
        cli_args=["SubCommandA", "--alpha", "custom_val"],
        cli_exit_on_error=False,
    )
    assert isinstance(root.cmd, SubCommandA)
    assert root.cmd.alpha == "custom_val"
    assert getattr(root.cmd, "_sub_a_ran", False) is True


def test_cli_app_invalid_args_raises():
    try:
        CliApp.run(
            AppSettings,
            cli_args=["--unknown-flag", "value"],
            cli_exit_on_error=False,
        )
        assert False, "Expected SettingsError"
    except SettingsError:
        pass


def main():
    test_cli_app_run_basic()
    test_cli_app_run_async()
    test_cli_app_format_help()
    test_cli_app_serialize()
    test_cli_app_subcommand()
    test_cli_app_invalid_args_raises()
    print("All CliApp contract assertions passed.")


if __name__ == "__main__":
    main()

오리진 시더

익명