From 5322417aeb9e9cdf99817581072230c326b8c689 Mon Sep 17 00:00:00 2001 From: Ruchir Chawdhry Date: Wed, 25 Nov 2026 15:22:28 +0530 Subject: [PATCH 1/7] Enable PR-only template validation and fix B008 defaults --- .github/workflows/template-ci.yml | 16 +++++++++++++ README.md | 24 ++++++++++++-------- template/AGENTS.md.jinja | 2 +- template/src/{{ package_name }}/cli.py.jinja | 22 +++++++++++------- tests/test_template.py | 17 ++++++++++++-- 5 files changed, 61 insertions(+), 20 deletions(-) create mode 100644 .github/workflows/template-ci.yml diff --git a/.github/workflows/template-ci.yml b/.github/workflows/template-ci.yml new file mode 100644 index 0000000..ff42fb0 --- /dev/null +++ b/.github/workflows/template-ci.yml @@ -0,0 +1,16 @@ +name: Template CI + +on: + pull_request: + types: [opened, synchronize, reopened] + +permissions: + contents: read + +concurrency: + group: template-ci-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + validate: + uses: RuchirChawdhry/ci-workflows/.github/workflows/copier-ci.yml@main diff --git a/README.md b/README.md index 4350ea4..19a507a 100644 --- a/README.md +++ b/README.md @@ -32,13 +32,19 @@ Commit the generated `uv.lock` for reproducible development and CI. - PR-only GitHub Actions callers for the central **python-cli** and **python-build** workflows. - MIT license, `.gitignore`, Copier answers for future `copier update`. -## Why the template repo never runs these workflows +## Continuous integration -The workflow source lives in `template/.github/workflows/ci.yml.jinja`, **not** -`.github/workflows/` at this repository's root. GitHub only detects workflows in the -root `.github/workflows/`, so nothing is activated here. Copier emits the normal -`.github/workflows/ci.yml` only into generated projects. Generated workflows run on -**pull requests only**, never `push`, `schedule`, or manual dispatch. +This repository has a root workflow, `.github/workflows/template-ci.yml`, +which calls the central [Copier validation workflow](https://github.com/RuchirChawdhry/ci-workflows/blob/main/.github/workflows/copier-ci.yml). +It runs when a pull request is opened, updated or reopened. It tests the template +contracts, renders the current revision, runs Ruff and pytest on the generated +project, builds and checks distributions, and installs the wheel for a CLI help +smoke test on Ubuntu 24.04. New commits cancel older runs for the same PR. + +The generated application's independent workflow lives under +`template/.github/workflows/ci.yml.jinja`. Copier renders it into the generated +project; it is not run in this template repository. Generated workflows remain +PR-only. The CI jobs reference: @@ -51,12 +57,12 @@ reproducibility is required; the user-managed central workflows remain the sourc ## Test this template itself ```sh -uv run --no-project --with copier --with pytest pytest tests -q +uv run --no-project --with copier==9.14.1 --with pytest --with PyYAML pytest tests -q ``` The tests generate a sample application and assert package metadata, imports, -Copier update context, and isolated PR-only workflow placement. No GitHub Actions -workflows are registered in this template repository. +Copier update context, and separation of the template-validation and generated-project +PR-only workflows. ## Philosophy diff --git a/template/AGENTS.md.jinja b/template/AGENTS.md.jinja index f375b21..12e16c4 100644 --- a/template/AGENTS.md.jinja +++ b/template/AGENTS.md.jinja @@ -19,7 +19,7 @@ installation, other project virtual environments, or shared CI workflow reposito - Logging: initialize `LoggingConfig` in business commands; use Loguru for diagnostics and Rich for user-facing output. Keep logs off stdout and do not log secrets. Optional synchronous @log_call in logging_utils.py traces entry, timing and failure type; native @logger.catch(reraise=True) logs exceptions. Never swallow failures; do not stack both decorators on the same function. - Persistence: use database.py and parameterized sqlite3 queries with WAL enabled by default; expose project-specific commands rather than generic database setters/getters. Keep YAML for settings, SQLite for application data. - Diagnostics: extend doctor.py with read-only checks; never dump configuration or create files; preserve full parser diagnostics. -- Output: accept shared OutputOptions on every subcommand, emit data via Output.emit() without wrapping commands in repeated error handlers, and use Output.progress()/track() for progress. Keep stdout machine-readable; JSON/JSONL use orjson exclusively for serialization and automatically disable color and progress. Do not introduce parallel JSON output implementations. Do not add redundant color flags. Send diagnostics and errors to stderr. +- Output: accept shared OutputOptions on every subcommand with the immutable DEFAULT_OUTPUT_OPTIONS singleton (no constructor calls in argument defaults), emit data via Output.emit() without wrapping commands in repeated error handlers, and use Output.progress()/track() for progress. Keep stdout machine-readable; JSON/JSONL use orjson exclusively for serialization and automatically disable color and progress. Do not introduce parallel JSON output implementations. Do not add redundant color flags. Send diagnostics and errors to stderr. - Errors: let expected domain failures raise ApplicationError from errors.py. The cli.main entrypoint handles those, filesystem, SQLite and YAML failures once; Cyclopts owns parse errors and exit-code handling. Preserve original exception messages, including YAML parser diagnostics. Do not catch unexpected programming exceptions or duplicate the entrypoint handler in commands. - Development commands: use Taskfile.yml for setup, dev, test, test:all, lint, fix, build, install, clean, doctor and update. Test runner: pytest with pytest-testmon for changed-code selection; lint/format: Ruff. Use the full suite for subprocess or external-resource changes and final verification. Do not invent alternate task runners. - CI: PR-only callers of `RuchirChawdhry/ci-workflows`. Never duplicate shared workflow logic here. diff --git a/template/src/{{ package_name }}/cli.py.jinja b/template/src/{{ package_name }}/cli.py.jinja index 42bb448..445dc90 100644 --- a/template/src/{{ package_name }}/cli.py.jinja +++ b/template/src/{{ package_name }}/cli.py.jinja @@ -29,6 +29,7 @@ CONFIG_PATH_EXCLUSION = Group( "Configuration path restriction", show=False, validator=validators.MutuallyExclusive() ) Verbosity = Annotated[int | None, Parameter(validator=validators.Number(gte=0, lte=3))] +DEFAULT_OUTPUT_OPTIONS = OutputOptions() app = App( name="{{ cli_command }}", @@ -52,7 +53,7 @@ def hello( *, config: File | None = None, verbosity: Verbosity = None, - options: OutputOptions = OutputOptions(), + options: OutputOptions = DEFAULT_OUTPUT_OPTIONS, ) -> None: """Print a friendly greeting; demonstrate logging and structured results.""" output = Output(options) @@ -96,7 +97,7 @@ def configuration( config_path: Annotated[bool, Parameter(group=(CONFIG_ACTIONS, CONFIG_PATH_EXCLUSION))] = False, show_config: Annotated[bool, Parameter(group=CONFIG_ACTIONS)] = False, path: Annotated[File | None, Parameter(group=CONFIG_PATH_EXCLUSION)] = None, - options: OutputOptions = OutputOptions(), + options: OutputOptions = DEFAULT_OUTPUT_OPTIONS, ) -> None: """Manage the application configuration. @@ -117,15 +118,18 @@ def configuration( if action is not None: action() return - if path is not None or options != OutputOptions(): + if path is not None or options != DEFAULT_OUTPUT_OPTIONS: raise ApplicationError("Select a configuration flag or a subcommand") app.help_print([]) - @app.command def set_config( - key: str, value: str, *, path: File | None = None, options: OutputOptions = OutputOptions() + key: str, + value: str, + *, + path: File | None = None, + options: OutputOptions = DEFAULT_OUTPUT_OPTIONS, ) -> None: """Set a dotted configuration key to a YAML value.""" output = Output(options) @@ -135,7 +139,7 @@ def set_config( @app.command -def doctor(*, options: OutputOptions = OutputOptions()) -> int: +def doctor(*, options: OutputOptions = DEFAULT_OUTPUT_OPTIONS) -> int: """Diagnose Python, platform, configuration, paths and SQLite without writing.""" output = Output(options) output.note("Checking runtime and local storage") @@ -155,7 +159,7 @@ def doctor(*, options: OutputOptions = OutputOptions()) -> int: @app.command -def db_path(*, options: OutputOptions = OutputOptions()) -> None: +def db_path(*, options: OutputOptions = DEFAULT_OUTPUT_OPTIONS) -> None: """Print the default SQLite database path without initializing it.""" output = Output(options) path = str(database.default_database_path()) @@ -163,7 +167,9 @@ def db_path(*, options: OutputOptions = OutputOptions()) -> None: @app.command -def db_list(*, path: File | None = None, options: OutputOptions = OutputOptions()) -> None: +def db_list( + *, path: File | None = None, options: OutputOptions = DEFAULT_OUTPUT_OPTIONS +) -> None: """List records in deterministic key order.""" output = Output(options) output.note("Listing SQLite records") diff --git a/tests/test_template.py b/tests/test_template.py index 827beed..fae2f01 100644 --- a/tests/test_template.py +++ b/tests/test_template.py @@ -25,13 +25,25 @@ def generated(tmp_path: Path) -> Path: "author_name": "Example Person", }, defaults=True, + vcs_ref="HEAD", unsafe=False, ) return destination -def test_template_repo_workflows_are_inert() -> None: - assert not (ROOT / ".github" / "workflows").exists() +def test_template_repo_workflow_calls_central_validation_only_on_pr() -> None: + workflow = yaml.load( + (ROOT / ".github" / "workflows" / "template-ci.yml").read_text(encoding="utf-8"), + Loader=yaml.BaseLoader, + ) + assert set(workflow["on"]) == {"pull_request"} + assert set(workflow["on"]["pull_request"]["types"]) == { + "opened", "synchronize", "reopened", + } + assert workflow["permissions"] == {"contents": "read"} + assert workflow["jobs"]["validate"]["uses"] == ( + "RuchirChawdhry/ci-workflows/.github/workflows/copier-ci.yml@main" + ) assert (ROOT / "template" / ".github" / "workflows" / "ci.yml.jinja").exists() @@ -48,6 +60,7 @@ def test_generated_package_metadata(generated: Path) -> None: ) assert set(config["dependency-groups"]["dev"]) == {"pytest", "pytest-testmon", "ruff"} assert (generated / "src" / "sample_cli" / "cli.py").is_file() + assert not (generated / ".github" / "workflows" / "template-ci.yml").exists() config_source = generated / "src" / "sample_cli" / "config.py" assert config_source.is_file() assert 'APP_NAME = "sample-cli"' in config_source.read_text(encoding="utf-8") From 5583bbdec0cbbc5d1ebe5453744e72ac7d33e4a1 Mon Sep 17 00:00:00 2001 From: Ruchir Chawdhry Date: Wed, 25 Nov 2026 15:25:18 +0530 Subject: [PATCH 2/7] Fix CI lint failures and install automatic Ruff pre-commit hooks --- README.md | 3 ++- template/.pre-commit-config.yaml | 13 +++++++++++++ template/AGENTS.md.jinja | 1 + template/README.md.jinja | 15 +++++++++++++++ template/Taskfile.yml.jinja | 4 ++++ template/pyproject.toml.jinja | 2 +- template/src/{{ package_name }}/cli.py.jinja | 2 +- template/src/{{ package_name }}/output.py | 1 - template/tests/test_cli.py.jinja | 5 ++--- tests/test_template.py | 20 ++++++++++++++++++-- 10 files changed, 57 insertions(+), 9 deletions(-) create mode 100644 template/.pre-commit-config.yaml diff --git a/README.md b/README.md index 19a507a..b77adb6 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ A lean, reusable Copier template for agent-ready Python CLI applications. ⚡ -**Stack:** uv · Python 3.14.7 · Cyclopts · ruamel.yaml · Rich · platformdirs · Loguru · orjson · SQLite · Ruff · pytest · pytest-testmon · Go Task. +**Stack:** uv · Python 3.14.7 · Cyclopts · ruamel.yaml · Rich · platformdirs · Loguru · orjson · SQLite · Ruff · pytest · pytest-testmon · pre-commit · Go Task. ## Generate a project @@ -27,6 +27,7 @@ Commit the generated `uv.lock` for reproducible development and CI. - Read-only environment diagnostics, platform-aware SQLite persistence with WAL enabled by default and Rich progress reporting. - Shared agent-friendly flags on all application subcommands: --json, --jsonl, --quiet, --verbose; machine output is compact UTF-8 serialized with orjson. - Cross-platform Taskfile.yml with standardized development, focused/full testing, installation, cleanup and diagnostics tasks. +- Version-controlled pre-commit hooks for automatic Ruff lint fixes and formatting of staged Python files; installed by `task setup` after Git initialization. - Real pytest tests for logic and CLI, Ruff formatting/lint settings, `.python-version`. - `AGENTS.md` with repo-local TDD and agent-environment guidance. - PR-only GitHub Actions callers for the central **python-cli** and **python-build** workflows. diff --git a/template/.pre-commit-config.yaml b/template/.pre-commit-config.yaml new file mode 100644 index 0000000..5dbb6b5 --- /dev/null +++ b/template/.pre-commit-config.yaml @@ -0,0 +1,13 @@ +repos: + - repo: local + hooks: + - id: ruff-check + name: Ruff lint fixes + entry: uv run --no-sync ruff check --fix --force-exclude + language: system + types: [python] + - id: ruff-format + name: Ruff format + entry: uv run --no-sync ruff format --force-exclude + language: system + types: [python] diff --git a/template/AGENTS.md.jinja b/template/AGENTS.md.jinja index 12e16c4..588060c 100644 --- a/template/AGENTS.md.jinja +++ b/template/AGENTS.md.jinja @@ -22,6 +22,7 @@ installation, other project virtual environments, or shared CI workflow reposito - Output: accept shared OutputOptions on every subcommand with the immutable DEFAULT_OUTPUT_OPTIONS singleton (no constructor calls in argument defaults), emit data via Output.emit() without wrapping commands in repeated error handlers, and use Output.progress()/track() for progress. Keep stdout machine-readable; JSON/JSONL use orjson exclusively for serialization and automatically disable color and progress. Do not introduce parallel JSON output implementations. Do not add redundant color flags. Send diagnostics and errors to stderr. - Errors: let expected domain failures raise ApplicationError from errors.py. The cli.main entrypoint handles those, filesystem, SQLite and YAML failures once; Cyclopts owns parse errors and exit-code handling. Preserve original exception messages, including YAML parser diagnostics. Do not catch unexpected programming exceptions or duplicate the entrypoint handler in commands. - Development commands: use Taskfile.yml for setup, dev, test, test:all, lint, fix, build, install, clean, doctor and update. Test runner: pytest with pytest-testmon for changed-code selection; lint/format: Ruff. Use the full suite for subprocess or external-resource changes and final verification. Do not invent alternate task runners. +- Git hooks: initialize Git before task setup; setup installs pre-commit hooks using the project's Ruff. If formatting changes files, review and stage the fixes, then retry the commit. Do not bypass hooks. - CI: PR-only callers of `RuchirChawdhry/ci-workflows`. Never duplicate shared workflow logic here. Avoid fetching dependencies globally or modifying system configuration. diff --git a/template/README.md.jinja b/template/README.md.jinja index 23ba5c2..30c355c 100644 --- a/template/README.md.jinja +++ b/template/README.md.jinja @@ -267,3 +267,18 @@ The `.copier-answers.yml` tracks the source template and your answers: ```sh uvx copier update ``` + + +## Git hooks + +Initialize Git before running `task setup`. Setup installs the version-controlled +pre-commit hooks when run at the root of a Git working tree. For a project +generated before Git initialization, run `task setup` again after `git init`. + +On each commit, Ruff applies safe lint fixes and formats staged Python files. +Pre-commit protects unstaged edits, and if a hook changes a file, the commit +stops so you can review and stage the fixes before retrying. Hooks use the same +Ruff version and configuration as `task fix` and CI, without a second tool environment. + +To format all tracked Python files manually, run +`uv run pre-commit run --all-files`. diff --git a/template/Taskfile.yml.jinja b/template/Taskfile.yml.jinja index ed93a13..2dda816 100644 --- a/template/Taskfile.yml.jinja +++ b/template/Taskfile.yml.jinja @@ -5,6 +5,10 @@ tasks: desc: Initialize the development environment cmds: - uv sync --group dev + - | + if git rev-parse --show-toplevel >/dev/null 2>&1 && [ -z "$(git rev-parse --show-prefix)" ]; then + uv run --no-sync pre-commit install + fi dev: desc: Run the application from the development environment diff --git a/template/pyproject.toml.jinja b/template/pyproject.toml.jinja index 0d0ac04..730055b 100644 --- a/template/pyproject.toml.jinja +++ b/template/pyproject.toml.jinja @@ -23,7 +23,7 @@ dependencies = [ "{{ cli_command }}" = "{{ package_name }}.cli:main" [dependency-groups] -dev = ["pytest", "pytest-testmon", "ruff"] +dev = ["pre-commit", "pytest", "pytest-testmon", "ruff"] [tool.uv.build-backend] module-name = "{{ package_name }}" diff --git a/template/src/{{ package_name }}/cli.py.jinja b/template/src/{{ package_name }}/cli.py.jinja index 445dc90..663eb00 100644 --- a/template/src/{{ package_name }}/cli.py.jinja +++ b/template/src/{{ package_name }}/cli.py.jinja @@ -18,8 +18,8 @@ from rich.text import Text from ruamel.yaml import YAML from ruamel.yaml.error import YAMLError -from . import database from . import config as settings +from . import database from .doctor import CHECK_COUNT, run_checks from .errors import ApplicationError from .output import Output, OutputOptions diff --git a/template/src/{{ package_name }}/output.py b/template/src/{{ package_name }}/output.py index 17170ed..6a75928 100644 --- a/template/src/{{ package_name }}/output.py +++ b/template/src/{{ package_name }}/output.py @@ -12,7 +12,6 @@ from .errors import ApplicationError - FORMAT_GROUP = Group("Output format", validator=validators.MutuallyExclusive()) VERBOSITY_GROUP = Group("Output verbosity", validator=validators.MutuallyExclusive()) diff --git a/template/tests/test_cli.py.jinja b/template/tests/test_cli.py.jinja index dd2684c..5823d01 100644 --- a/template/tests/test_cli.py.jinja +++ b/template/tests/test_cli.py.jinja @@ -286,9 +286,8 @@ def test_missing_config_error(tmp_path: Path) -> None: def test_yaml_error_preserves_parser_diagnostics(tmp_path: Path) -> None: path = tmp_path / "config.yml" path.write_text("logging: [invalid-value\n", encoding="utf-8") - with pytest.raises(YAMLError) as error: - with path.open(encoding="utf-8") as stream: - YAML(typ="safe").load(stream) + with pytest.raises(YAMLError) as error, path.open(encoding="utf-8") as stream: + YAML(typ="safe").load(stream) result = subprocess.run( [sys.executable, "-m", "{{ package_name }}", "--show-config", "--path", str(path)], capture_output=True, diff --git a/tests/test_template.py b/tests/test_template.py index fae2f01..09af734 100644 --- a/tests/test_template.py +++ b/tests/test_template.py @@ -58,7 +58,7 @@ def test_generated_package_metadata(generated: Path) -> None: any(dependency.startswith(name) for dependency in config["project"]["dependencies"]) for name in ("cyclopts", "loguru", "orjson", "platformdirs", "rich", "ruamel.yaml") ) - assert set(config["dependency-groups"]["dev"]) == {"pytest", "pytest-testmon", "ruff"} + assert set(config["dependency-groups"]["dev"]) == {"pre-commit", "pytest", "pytest-testmon", "ruff"} assert (generated / "src" / "sample_cli" / "cli.py").is_file() assert not (generated / ".github" / "workflows" / "template-ci.yml").exists() config_source = generated / "src" / "sample_cli" / "config.py" @@ -111,7 +111,9 @@ def test_generated_taskfile(generated: Path) -> None: "doctor", "update", } - assert tasks["setup"]["cmds"] == ["uv sync --group dev"] + assert tasks["setup"]["cmds"][0] == "uv sync --group dev" + assert "uv run --no-sync pre-commit install" in tasks["setup"]["cmds"][1] + assert "git rev-parse --show-prefix" in tasks["setup"]["cmds"][1] assert tasks["dev"]["cmds"] == [ "uv run sample-cli {{if .CLI_ARGS}}{{.CLI_ARGS}}{{else}}--help{{end}}" ] @@ -122,3 +124,17 @@ def test_generated_taskfile(generated: Path) -> None: assert "uv tool install --reinstall --python 3.14.7 ." in install assert "uv tool update-shell" in install assert "pipx ensurepath" in install + + +def test_generated_pre_commit_hooks(generated: Path) -> None: + config = yaml.safe_load((generated / ".pre-commit-config.yaml").read_text(encoding="utf-8")) + assert len(config["repos"]) == 1 + repo = config["repos"][0] + assert repo["repo"] == "local" + hooks = repo["hooks"] + assert [hook["id"] for hook in hooks] == ["ruff-check", "ruff-format"] + assert [hook["entry"] for hook in hooks] == [ + "uv run --no-sync ruff check --fix --force-exclude", + "uv run --no-sync ruff format --force-exclude", + ] + assert all(hook["types"] == ["python"] for hook in hooks) From 5d5e5f1d99e52372335bd3493b837812171893fa Mon Sep 17 00:00:00 2001 From: Ruchir Chawdhry Date: Wed, 25 Nov 2026 15:34:45 +0530 Subject: [PATCH 3/7] Apply exact Ruff formatting changes reported by CI --- template/src/{{ package_name }}/cli.py.jinja | 4 +--- template/tests/test_cli.py.jinja | 12 +++++++----- template/tests/test_logging_utils.py.jinja | 3 +++ 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/template/src/{{ package_name }}/cli.py.jinja b/template/src/{{ package_name }}/cli.py.jinja index 663eb00..ceb5389 100644 --- a/template/src/{{ package_name }}/cli.py.jinja +++ b/template/src/{{ package_name }}/cli.py.jinja @@ -167,9 +167,7 @@ def db_path(*, options: OutputOptions = DEFAULT_OUTPUT_OPTIONS) -> None: @app.command -def db_list( - *, path: File | None = None, options: OutputOptions = DEFAULT_OUTPUT_OPTIONS -) -> None: +def db_list(*, path: File | None = None, options: OutputOptions = DEFAULT_OUTPUT_OPTIONS) -> None: """List records in deterministic key order.""" output = Output(options) output.note("Listing SQLite records") diff --git a/template/tests/test_cli.py.jinja b/template/tests/test_cli.py.jinja index 5823d01..92d6306 100644 --- a/template/tests/test_cli.py.jinja +++ b/template/tests/test_cli.py.jinja @@ -166,8 +166,7 @@ def test_native_validation(args: list[str], monkeypatch, tmp_path: Path) -> None def test_yaml_command_defaults_and_overrides(tmp_path: Path) -> None: path = tmp_path / "settings.yml" path.write_text( - "logging:\n file_enabled: false\n" - "cli:\n hello:\n name: Ada\n verbosity: 1\n", + "logging:\n file_enabled: false\ncli:\n hello:\n name: Ada\n verbosity: 1\n", encoding="utf-8", ) result = run_cli("hello", "--config", str(path), "--json") @@ -187,9 +186,12 @@ def test_invalid_yaml_cli_default_is_rejected(tmp_path: Path) -> None: app.parse_args(["hello", "--config", str(path)], exit_on_error=False, print_error=False) # Config-management commands do not parse command defaults and can repair them. run_cli("set-config", "cli.hello.verbosity", "1", "--path", str(path)) - assert json.loads(run_cli("--show-config", "--path", str(path), "--json").stdout)[ - "cli" - ]["hello"]["verbosity"] == 1 + assert ( + json.loads(run_cli("--show-config", "--path", str(path), "--json").stdout)["cli"]["hello"][ + "verbosity" + ] + == 1 + ) def test_platform_yaml_defaults(monkeypatch, tmp_path: Path) -> None: diff --git a/template/tests/test_logging_utils.py.jinja b/template/tests/test_logging_utils.py.jinja index 0bbe991..4cf6edb 100644 --- a/template/tests/test_logging_utils.py.jinja +++ b/template/tests/test_logging_utils.py.jinja @@ -11,6 +11,7 @@ def test_log_call_preserves_result_signature_and_privacy() -> None: output = StringIO() sink = logger.add(output, level="DEBUG", diagnose=False) try: + @log_call def example(value: str) -> str: """Return the value unchanged.""" @@ -30,6 +31,7 @@ def test_log_call_preserves_failure() -> None: output = StringIO() sink = logger.add(output, level="ERROR", diagnose=False) try: + @log_call def fail() -> None: raise ValueError("private-error") @@ -47,6 +49,7 @@ def test_native_catch_reraises() -> None: output = StringIO() sink = logger.add(output, level="ERROR", diagnose=False, backtrace=False) try: + @logger.catch(reraise=True) def fail() -> None: raise RuntimeError("native failure") From 5c9a05de057cde576962adb43456a835ddeec508 Mon Sep 17 00:00:00 2001 From: Ruchir Chawdhry Date: Wed, 25 Nov 2026 15:44:32 +0530 Subject: [PATCH 4/7] Add installed-wheel functional smoke tests required by shared Copier CI --- README.md | 6 ++- tests/smoke_installed.py | 99 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 103 insertions(+), 2 deletions(-) create mode 100644 tests/smoke_installed.py diff --git a/README.md b/README.md index b77adb6..9c2068c 100644 --- a/README.md +++ b/README.md @@ -39,8 +39,10 @@ This repository has a root workflow, `.github/workflows/template-ci.yml`, which calls the central [Copier validation workflow](https://github.com/RuchirChawdhry/ci-workflows/blob/main/.github/workflows/copier-ci.yml). It runs when a pull request is opened, updated or reopened. It tests the template contracts, renders the current revision, runs Ruff and pytest on the generated -project, builds and checks distributions, and installs the wheel for a CLI help -smoke test on Ubuntu 24.04. New commits cancel older runs for the same PR. +project, builds and checks distributions, and installs the wheel for functional smoke tests on Ubuntu 24.04. +The central workflow explicitly runs `tests/smoke_installed.py` against the +installed console script via `CLI_EXECUTABLE`, outside the generated project. +The tests cover machine output, configuration, SQLite WAL and doctor diagnostics. New commits cancel older runs for the same PR. The generated application's independent workflow lives under `template/.github/workflows/ci.yml.jinja`. Copier renders it into the generated diff --git a/tests/smoke_installed.py b/tests/smoke_installed.py new file mode 100644 index 0000000..f2ac783 --- /dev/null +++ b/tests/smoke_installed.py @@ -0,0 +1,99 @@ +"""Exercise the installed wheel outside the generated source tree.""" + +import json +import os +import sqlite3 +import subprocess +from pathlib import Path + +import pytest + + +@pytest.fixture +def run_cli(tmp_path, monkeypatch): + for name, directory in ( + ("HOME", "home"), + ("XDG_CONFIG_HOME", "config"), + ("XDG_DATA_HOME", "data"), + ("XDG_STATE_HOME", "state"), + ("XDG_CACHE_HOME", "cache"), + ): + path = tmp_path / directory + path.mkdir() + monkeypatch.setenv(name, str(path)) + monkeypatch.setenv("FORCE_COLOR", "1") + executable = os.environ["CLI_EXECUTABLE"] + + def run(*args, check=True): + return subprocess.run( + [executable, *args], + cwd=tmp_path, + capture_output=True, + text=True, + check=check, + timeout=30, + ) + + return run + + +def test_installed_machine_output(run_cli): + result = run_cli("hello", "--name", "Agent", "--json", "--verbose") + assert json.loads(result.stdout) == {"message": "Hello, Agent!"} + assert "Greeting requested" in result.stderr + assert "\x1b" not in result.stdout + result.stderr + + result = run_cli("hello", "--jsonl", "--quiet") + assert len(result.stdout.splitlines()) == 1 + assert json.loads(result.stdout) == {"message": "Hello, world!"} + assert result.stderr == "" + + +def test_installed_configuration(run_cli, tmp_path): + path = Path(json.loads(run_cli("--config-path", "--json").stdout)["path"]) + assert path.is_relative_to(tmp_path / "config") + assert not path.exists() + assert json.loads(run_cli("--init-config", "--json").stdout) == {"path": str(path)} + original = path.read_bytes() + result = run_cli("--init-config", "--json", check=False) + assert result.returncode != 0 + assert result.stdout == "" + assert path.read_bytes() == original + + run_cli("set-config", "logging.file_enabled", "false", "--json") + run_cli("set-config", "cli.hello.name", "Ada", "--json") + settings = json.loads(run_cli("--show-config", "--json").stdout) + assert settings["logging"]["file_enabled"] is False + assert settings["cli"]["hello"]["name"] == "Ada" + assert json.loads(run_cli("hello", "--json").stdout) == {"message": "Hello, Ada!"} + assert json.loads(run_cli("hello", "--name", "Grace", "--json").stdout) == { + "message": "Hello, Grace!" + } + + path.write_text("logging: [invalid-value\n", encoding="utf-8") + result = run_cli("--show-config", "--json", check=False) + assert result.returncode != 0 + assert result.stdout == "" + assert "line 1" in result.stderr + assert "column" in result.stderr + + +def test_installed_database_and_doctor(run_cli, tmp_path): + path = Path(json.loads(run_cli("db-path", "--json").stdout)["path"]) + assert path.is_relative_to(tmp_path / "data") + assert not path.exists() + checks = json.loads(run_cli("doctor", "--json").stdout) + assert checks and all(check["ok"] for check in checks) + assert not path.exists() + + result = run_cli("db-list", "--json", "--jsonl", check=False) + assert result.returncode != 0 + assert not path.exists() + assert json.loads(run_cli("db-list", "--json").stdout) == [] + with sqlite3.connect(path) as db: + assert db.execute("PRAGMA journal_mode").fetchone()[0] == "wal" + db.execute("INSERT INTO records (key, value) VALUES (?, ?)", ("example", "value")) + assert json.loads(run_cli("db-list", "--jsonl").stdout) == { + "key": "example", + "value": "value", + } From f22548a56b616b258a84c0060e81528ddd810c7f Mon Sep 17 00:00:00 2001 From: Ruchir Chawdhry Date: Wed, 25 Nov 2026 15:51:13 +0530 Subject: [PATCH 5/7] Expose installed CLI stderr on smoke test failure --- tests/smoke_installed.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/tests/smoke_installed.py b/tests/smoke_installed.py index f2ac783..c578370 100644 --- a/tests/smoke_installed.py +++ b/tests/smoke_installed.py @@ -25,14 +25,20 @@ def run_cli(tmp_path, monkeypatch): executable = os.environ["CLI_EXECUTABLE"] def run(*args, check=True): - return subprocess.run( + result = subprocess.run( [executable, *args], cwd=tmp_path, capture_output=True, text=True, - check=check, + check=False, timeout=30, ) + if check: + assert result.returncode == 0, ( + f"{result.args!r} exited {result.returncode}\n" + f"stdout: {result.stdout}\nstderr: {result.stderr}" + ) + return result return run From 654211349252e56ff0c058ca4607c35d251561de Mon Sep 17 00:00:00 2001 From: Ruchir Chawdhry Date: Wed, 25 Nov 2026 15:52:01 +0530 Subject: [PATCH 6/7] Accept YAML integer subclasses for valid logging verbosity --- template/src/{{ package_name }}/config.py.jinja | 6 +++++- template/tests/test_config.py.jinja | 11 +++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/template/src/{{ package_name }}/config.py.jinja b/template/src/{{ package_name }}/config.py.jinja index b4b03b5..075ddaa 100644 --- a/template/src/{{ package_name }}/config.py.jinja +++ b/template/src/{{ package_name }}/config.py.jinja @@ -39,7 +39,11 @@ class LoggingConfig: if not isinstance(self.level, str) or self.level.upper() not in LOG_LEVELS: raise ApplicationError(f"Logging level must be one of: {', '.join(LOG_LEVELS)}") self.level = self.level.upper() - if type(self.verbosity) is not int or self.verbosity not in range(len(CONSOLE_LEVELS)): + if ( + not isinstance(self.verbosity, int) + or isinstance(self.verbosity, bool) + or self.verbosity not in range(len(CONSOLE_LEVELS)) + ): raise ApplicationError("Logging verbosity must be an integer from 0 to 3") if type(self.file_enabled) is not bool: raise ApplicationError("logging.file_enabled must be a boolean") diff --git a/template/tests/test_config.py.jinja b/template/tests/test_config.py.jinja index 97f0060..a4a49bc 100644 --- a/template/tests/test_config.py.jinja +++ b/template/tests/test_config.py.jinja @@ -115,3 +115,14 @@ def test_config_path_uses_local_non_roaming_directory(monkeypatch, tmp_path: Pat monkeypatch.setattr(config, "user_config_path", user_config_path) assert config.default_config_path() == tmp_path / config.APP_NAME / "config.yml" assert not config.default_config_path().exists() + + +def test_update_preserves_default_zero_verbosity(monkeypatch, tmp_path: Path) -> None: + path = tmp_path / "config.yml" + monkeypatch.setattr(config, "default_config_path", lambda: path) + init_config() + update_setting("logging.file_enabled", "false") + update_setting("cli.hello.name", "Ada") + settings = read_settings() + assert settings["logging"] == {"level": "INFO", "verbosity": 0, "file_enabled": False} + assert settings["cli"]["hello"]["name"] == "Ada" From e3284fca60f2167008c66d51445f2542aa35e863 Mon Sep 17 00:00:00 2001 From: Ruchir Chawdhry Date: Wed, 25 Nov 2026 16:06:59 +0530 Subject: [PATCH 7/7] Simplify logging to native named levels and shared CLI overrides --- template/AGENTS.md.jinja | 2 +- template/README.md.jinja | 31 ++++++----- template/config.example.yml | 6 +- template/src/{{ package_name }}/cli.py.jinja | 6 +- .../src/{{ package_name }}/config.py.jinja | 42 +++++++------- template/tests/test_cli.py.jinja | 43 +++++++-------- template/tests/test_config.py.jinja | 55 +++++++++++++++---- tests/smoke_installed.py | 11 +++- 8 files changed, 118 insertions(+), 78 deletions(-) diff --git a/template/AGENTS.md.jinja b/template/AGENTS.md.jinja index 588060c..e829f16 100644 --- a/template/AGENTS.md.jinja +++ b/template/AGENTS.md.jinja @@ -16,7 +16,7 @@ installation, other project virtual environments, or shared CI workflow reposito - Dependencies: `uv sync --group dev` (commit `uv.lock`). - CLI: Cyclopts; prefer existing cyclopts.types aliases (File, ExistingFile, Directory, ExistingDirectory, PositiveInt, NonNegativeInt, Port) when their semantics match; use native Parameter/Group validators for custom constraints; do not duplicate CLI validation in command bodies. Use dispatch tables for mutually exclusive action selection after Cyclopts validates the arguments. Terminal output: Rich; YAML: ruamel.yaml with safe loading. - Configuration: use `config.py`, platformdirs and persistent `config.yml`; do not create alternate settings systems. Use native Cyclopts Yaml loading for argument defaults under cli.; do not merge arguments manually. Use root flags --init-config, --config-path, --show-config; retain set-config as a subcommand. -- Logging: initialize `LoggingConfig` in business commands; use Loguru for diagnostics and Rich for user-facing output. Keep logs off stdout and do not log secrets. Optional synchronous @log_call in logging_utils.py traces entry, timing and failure type; native @logger.catch(reraise=True) logs exceptions. Never swallow failures; do not stack both decorators on the same function. +- Logging: initialize `LoggingConfig` in business commands; use named `file_level` and `console_level` settings, with shared `--verbose` (DEBUG) and `--quiet` overrides; never add numeric logging levels; use Loguru for diagnostics and Rich for user-facing output. Keep logs off stdout and do not log secrets. Optional synchronous @log_call in logging_utils.py traces entry, timing and failure type; native @logger.catch(reraise=True) logs exceptions. Never swallow failures; do not stack both decorators on the same function. - Persistence: use database.py and parameterized sqlite3 queries with WAL enabled by default; expose project-specific commands rather than generic database setters/getters. Keep YAML for settings, SQLite for application data. - Diagnostics: extend doctor.py with read-only checks; never dump configuration or create files; preserve full parser diagnostics. - Output: accept shared OutputOptions on every subcommand with the immutable DEFAULT_OUTPUT_OPTIONS singleton (no constructor calls in argument defaults), emit data via Output.emit() without wrapping commands in repeated error handlers, and use Output.progress()/track() for progress. Keep stdout machine-readable; JSON/JSONL use orjson exclusively for serialization and automatically disable color and progress. Do not introduce parallel JSON output implementations. Do not add redundant color flags. Send diagnostics and errors to stderr. diff --git a/template/README.md.jinja b/template/README.md.jinja index 30c355c..3a28e58 100644 --- a/template/README.md.jinja +++ b/template/README.md.jinja @@ -21,9 +21,9 @@ Commit the generated `uv.lock` for repeatable dependency resolution and CI runs. uv run {{ cli_command }} --config-path uv run {{ cli_command }} --init-config uv run {{ cli_command }} --show-config -uv run {{ cli_command }} set-config logging.level DEBUG -uv run {{ cli_command }} set-config logging.verbosity 2 -uv run {{ cli_command }} hello --verbosity 1 +uv run {{ cli_command }} set-config logging.file_level DEBUG +uv run {{ cli_command }} set-config logging.console_level DEBUG +uv run {{ cli_command }} hello --verbose ``` Settings live in the platform-specific user configuration directory as `config.yml`. @@ -46,13 +46,13 @@ on the sample `hello` command to select a different file. ```yaml logging: - level: INFO - verbosity: 0 + file_level: INFO + console_level: WARNING file_enabled: true ``` -`LoggingConfig` in `config.py` controls logging. Console verbosity is 0=WARNING, -1=INFO, 2=DEBUG, 3=TRACE. The file level is independent. File logs rotate at 5 MB +`LoggingConfig` in `config.py` validates named levels using Loguru. The console +and file levels are independent. File logs rotate at 5 MB and old logs are retained for 7 days; disable file logging with `file_enabled: false`. Logs go to stderr and the platform-specific log directory (`app.log`), not stdout. The example `hello` command initializes logging at command execution; use the same @@ -69,8 +69,7 @@ both `.yml` and `.yaml` as well as SQLite filenames. Use `ExistingFile` or `ExistingDirectory` when the target must already exist, `NonExistentFile` for a new output target, `Directory` for a directory that may need creation, and `PositiveInt`, `NonNegativeInt` or `Port` for matching numeric -constraints. Use custom validators only for project-specific restrictions, such -as logging verbosity from 0 through 3. +constraints. Use custom validators only for project-specific restrictions. See [Cyclopts types](https://cyclopts.readthedocs.io/en/stable/types.html). @@ -83,7 +82,6 @@ defaults in the same YAML file, under the `cli` namespace: cli: hello: name: Ada - verbosity: 1 ``` ```sh @@ -177,11 +175,11 @@ JSON/JSONL automatically disable progress and ANSI styling, including when FORCE is set; they are mutually exclusive. No separate color flag is needed. Human-readable results use Rich's automatic terminal and color detection. Quiet and verbose are mutually exclusive. Cyclopts group validators reject conflicting -flags before command execution, and its numeric validator constrains CLI verbosity. +flags before command execution. Logs, progress and errors go to stderr; commands exit nonzero on errors. Cyclopts help and parse errors remain textual. -The legacy numeric `hello --verbosity` option is retained. Verbose raises the -console level to at least DEBUG; quiet suppresses console logs, not file logs. +Verbose selects DEBUG for the console; quiet suppresses console logs, not file logs. +For TRACE or another named level, set `logging.console_level` in YAML. Machine output contains no Rich formatting. Both formats use orjson to write compact UTF-8 bytes directly to stdout, with one newline per document or record. Dates use ISO 8601, unsupported object values fall back to str, and supported non-string keys @@ -262,7 +260,12 @@ It runs for pull requests, not pushes or schedules. No PyPI publishing is enable ## Updating from the Copier template -The `.copier-answers.yml` tracks the source template and your answers: +The `.copier-answers.yml` tracks the source template and your answers. +If updating an older generated project, migrate the user configuration: rename +`logging.level` to `logging.file_level`, replace `logging.verbosity` with +`logging.console_level` (0=WARNING, 1=INFO, 2=DEBUG, 3=TRACE), and remove any +numeric `verbosity` defaults under `cli`. No automatic configuration migration is performed. + ```sh uvx copier update diff --git a/template/config.example.yml b/template/config.example.yml index 8246266..f6b1e73 100644 --- a/template/config.example.yml +++ b/template/config.example.yml @@ -1,7 +1,7 @@ -# File logging level and independent console verbosity. +# Independent named Loguru levels for file and console logging. logging: - level: INFO - verbosity: 0 # 0=WARNING, 1=INFO, 2=DEBUG, 3=TRACE + file_level: INFO + console_level: WARNING file_enabled: true # Optional defaults for command arguments; explicit CLI arguments take priority. diff --git a/template/src/{{ package_name }}/cli.py.jinja b/template/src/{{ package_name }}/cli.py.jinja index ceb5389..602dba0 100644 --- a/template/src/{{ package_name }}/cli.py.jinja +++ b/template/src/{{ package_name }}/cli.py.jinja @@ -28,7 +28,6 @@ CONFIG_ACTIONS = Group("Configuration actions", validator=validators.MutuallyExc CONFIG_PATH_EXCLUSION = Group( "Configuration path restriction", show=False, validator=validators.MutuallyExclusive() ) -Verbosity = Annotated[int | None, Parameter(validator=validators.Number(gte=0, lte=3))] DEFAULT_OUTPUT_OPTIONS = OutputOptions() app = App( @@ -52,16 +51,13 @@ def hello( name: str = "world", *, config: File | None = None, - verbosity: Verbosity = None, options: OutputOptions = DEFAULT_OUTPUT_OPTIONS, ) -> None: """Print a friendly greeting; demonstrate logging and structured results.""" output = Output(options) logging = settings.LoggingConfig.from_config(settings.read_settings(config)) - if output.options.verbose: - verbosity = max(2, logging.verbosity if verbosity is None else verbosity) logging.configure( - verbosity, + verbose=output.options.verbose, quiet=output.options.quiet, no_color=output.machine, ) diff --git a/template/src/{{ package_name }}/config.py.jinja b/template/src/{{ package_name }}/config.py.jinja index 075ddaa..e3d6b6b 100644 --- a/template/src/{{ package_name }}/config.py.jinja +++ b/template/src/{{ package_name }}/config.py.jinja @@ -3,7 +3,7 @@ from __future__ import annotations import sys -from dataclasses import asdict, dataclass, replace +from dataclasses import asdict, dataclass from pathlib import Path from tempfile import NamedTemporaryFile from typing import Any @@ -15,8 +15,6 @@ from ruamel.yaml import YAML from .errors import ApplicationError APP_NAME = "{{ project_slug }}" -CONSOLE_LEVELS = ("WARNING", "INFO", "DEBUG", "TRACE") -LOG_LEVELS = ("TRACE", "DEBUG", "INFO", "SUCCESS", "WARNING", "ERROR", "CRITICAL") def default_config_path() -> Path: @@ -27,24 +25,27 @@ def default_log_path() -> Path: return user_log_path(APP_NAME, appauthor=False) / "app.log" +def logging_level(value: str, field: str) -> str: + """Validate a named level using Loguru's own level registry.""" + if not isinstance(value, str): + raise ApplicationError(f"logging.{field} must be a named Loguru level") + try: + return logger.level(value.upper()).name + except ValueError as error: + raise ApplicationError(f"Invalid logging.{field}: {value}") from error + + @dataclass class LoggingConfig: - """Set file logging level and terminal verbosity independently.""" + """Set independent named file and console logging levels.""" - level: str = "INFO" - verbosity: int = 0 + file_level: str = "INFO" + console_level: str = "WARNING" file_enabled: bool = True def __post_init__(self) -> None: - if not isinstance(self.level, str) or self.level.upper() not in LOG_LEVELS: - raise ApplicationError(f"Logging level must be one of: {', '.join(LOG_LEVELS)}") - self.level = self.level.upper() - if ( - not isinstance(self.verbosity, int) - or isinstance(self.verbosity, bool) - or self.verbosity not in range(len(CONSOLE_LEVELS)) - ): - raise ApplicationError("Logging verbosity must be an integer from 0 to 3") + self.file_level = logging_level(self.file_level, "file_level") + self.console_level = logging_level(self.console_level, "console_level") if type(self.file_enabled) is not bool: raise ApplicationError("logging.file_enabled must be a boolean") @@ -53,34 +54,33 @@ class LoggingConfig: settings = config.get("logging", {}) if not isinstance(settings, dict): raise ApplicationError("logging must be a YAML mapping") - unknown = settings.keys() - {"level", "verbosity", "file_enabled"} + unknown = settings.keys() - {"file_level", "console_level", "file_enabled"} if unknown: raise ApplicationError("Unknown logging configuration keys") return cls(**settings) def configure( self, - verbosity: int | None = None, *, + verbose: bool = False, quiet: bool = False, no_color: bool = False, ) -> None: """Replace Loguru's default sink; never write logs to stdout.""" - settings = self if verbosity is None else replace(self, verbosity=verbosity) logger.remove() if not quiet: logger.add( sys.stderr, - level=CONSOLE_LEVELS[settings.verbosity], + level="DEBUG" if verbose else self.console_level, format="{level}: {message}", colorize=False if no_color else None, backtrace=False, diagnose=False, ) - if settings.file_enabled: + if self.file_enabled: logger.add( default_log_path(), - level=settings.level, + level=self.file_level, rotation="5 MB", retention="7 days", encoding="utf-8", diff --git a/template/tests/test_cli.py.jinja b/template/tests/test_cli.py.jinja index 92d6306..e72ecf7 100644 --- a/template/tests/test_cli.py.jinja +++ b/template/tests/test_cli.py.jinja @@ -48,18 +48,20 @@ def test_module_help() -> None: assert "db-set" not in result.stdout assert "db-get" not in result.stdout assert "--no-color" not in result.stdout - assert "--no-color" not in run_cli("hello", "--help").stdout + help_text = run_cli("hello", "--help").stdout + assert "--no-color" not in help_text + assert "--verbosity" not in help_text def test_config_commands(tmp_path: Path) -> None: path = str(tmp_path / "settings.yml") run_cli("--init-config", "--path", path) - run_cli("set-config", "logging.verbosity", "2", "--path", path) + run_cli("set-config", "logging.console_level", "INFO", "--path", path) run_cli("set-config", "logging.file_enabled", "false", "--path", path) result = run_cli("--show-config", "--path", path) - assert "verbosity: 2" in result.stdout + assert "console_level: INFO" in result.stdout assert "file_enabled: false" in result.stdout - result = run_cli("hello", "--config", path, "--verbosity", "1") + result = run_cli("hello", "--config", path) assert "Hello, world!" in result.stdout assert "Greeting requested" in result.stderr @@ -115,7 +117,7 @@ def test_root_config_flags(tmp_path: Path) -> None: result = run_cli("--init-config", "--path", str(path), "--json") assert json.loads(result.stdout) == {"path": str(path)} result = run_cli("--show-config", "--path", str(path), "--jsonl") - assert json.loads(result.stdout)["logging"]["verbosity"] == 0 + assert json.loads(result.stdout)["logging"]["console_level"] == "WARNING" result = run_cli("--config-path", "--json") assert Path(json.loads(result.stdout)["path"]).name == "config.yml" assert not run_cli().stderr @@ -151,8 +153,6 @@ def test_root_conflict_does_not_write(tmp_path: Path) -> None: ["--show-config", "--init-config"], ["--config-path", "--show-config"], ["--config-path", "--path", "custom.yml"], - ["hello", "--verbosity", "4"], - ["hello", "--verbosity", "-1"], ["--show-config", "--json", "--jsonl"], ["--show-config", "--quiet", "--verbose"], ], @@ -166,32 +166,31 @@ def test_native_validation(args: list[str], monkeypatch, tmp_path: Path) -> None def test_yaml_command_defaults_and_overrides(tmp_path: Path) -> None: path = tmp_path / "settings.yml" path.write_text( - "logging:\n file_enabled: false\ncli:\n hello:\n name: Ada\n verbosity: 1\n", + "logging:\n file_enabled: false\n console_level: INFO\ncli:\n hello:\n name: Ada\n", encoding="utf-8", ) result = run_cli("hello", "--config", str(path), "--json") assert json.loads(result.stdout) == {"message": "Hello, Ada!"} assert "Greeting requested" in result.stderr - result = run_cli( - "hello", "--config", str(path), "--name", "Grace", "--verbosity", "0", "--json" - ) + result = run_cli("hello", "--config", str(path), "--name", "Grace", "--quiet", "--json") assert json.loads(result.stdout) == {"message": "Hello, Grace!"} assert result.stderr == "" -def test_invalid_yaml_cli_default_is_rejected(tmp_path: Path) -> None: +def test_invalid_named_logging_level_is_rejected(tmp_path: Path) -> None: path = tmp_path / "settings.yml" - path.write_text("cli:\n hello:\n verbosity: 9\n", encoding="utf-8") - with pytest.raises(ValidationError): - app.parse_args(["hello", "--config", str(path)], exit_on_error=False, print_error=False) - # Config-management commands do not parse command defaults and can repair them. - run_cli("set-config", "cli.hello.verbosity", "1", "--path", str(path)) - assert ( - json.loads(run_cli("--show-config", "--path", str(path), "--json").stdout)["cli"]["hello"][ - "verbosity" - ] - == 1 + path.write_text("logging:\n console_level: INVALID\n", encoding="utf-8") + result = subprocess.run( + [sys.executable, "-m", "{{ package_name }}", "hello", "--config", str(path)], + capture_output=True, + text=True, + check=False, ) + assert result.returncode == 1 + assert "Invalid logging.console_level: INVALID" in result.stderr + run_cli("set-config", "logging.console_level", "INFO", "--path", str(path)) + settings_data = json.loads(run_cli("--show-config", "--path", str(path), "--json").stdout) + assert settings_data["logging"]["console_level"] == "INFO" def test_platform_yaml_defaults(monkeypatch, tmp_path: Path) -> None: diff --git a/template/tests/test_config.py.jinja b/template/tests/test_config.py.jinja index a4a49bc..896aa76 100644 --- a/template/tests/test_config.py.jinja +++ b/template/tests/test_config.py.jinja @@ -50,16 +50,16 @@ def test_init_and_update(tmp_path: Path) -> None: with pytest.raises(FileExistsError): init_config(path) path.write_text(path.read_text(encoding="utf-8") + "# Keep this comment\n", encoding="utf-8") - update_setting("logging.verbosity", "2", path) + update_setting("logging.console_level", "DEBUG", path) update_setting("application.retries", "3", path) update_setting("application.enabled", "true", path) settings = load_config(path) - assert settings["logging"]["verbosity"] == 2 + assert settings["logging"]["console_level"] == "DEBUG" assert settings["application"] == {"retries": 3, "enabled": True} assert "# Keep this comment" in path.read_text(encoding="utf-8") original = path.read_bytes() - with pytest.raises(ValueError, match="verbosity"): - update_setting("logging.verbosity", "9", path) + with pytest.raises(ValueError, match="console_level"): + update_setting("logging.console_level", "INVALID", path) assert path.read_bytes() == original @@ -72,7 +72,13 @@ def test_update_creates_missing_file(tmp_path: Path) -> None: @pytest.mark.parametrize( "settings", - [{"level": "invalid"}, {"verbosity": -1}, {"verbosity": True}, {"file_enabled": "false"}], + [ + {"file_level": "invalid"}, + {"console_level": "invalid"}, + {"console_level": 2}, + {"console_level": True}, + {"file_enabled": "false"}, + ], ) def test_invalid_logging(settings: dict) -> None: with pytest.raises(ValueError): @@ -85,13 +91,13 @@ def test_logging_sinks(monkeypatch, tmp_path: Path) -> None: monkeypatch.setattr(config.sys, "stderr", output) monkeypatch.setattr(config, "default_log_path", lambda: path) try: - settings = LoggingConfig(level="INFO", verbosity=0) - settings.configure(verbosity=2) + settings = LoggingConfig(file_level="INFO", console_level="WARNING") + settings.configure(verbose=True) logger.debug("console only") logger.info("both sinks") assert "console only" in output.getvalue() assert "both sinks" in output.getvalue() - assert settings.verbosity == 0 + assert settings.console_level == "WARNING" assert "both sinks" in path.read_text(encoding="utf-8") assert "console only" not in path.read_text(encoding="utf-8") output.truncate(0) @@ -117,12 +123,41 @@ def test_config_path_uses_local_non_roaming_directory(monkeypatch, tmp_path: Pat assert not config.default_config_path().exists() -def test_update_preserves_default_zero_verbosity(monkeypatch, tmp_path: Path) -> None: +def test_update_preserves_default_logging_levels(monkeypatch, tmp_path: Path) -> None: path = tmp_path / "config.yml" monkeypatch.setattr(config, "default_config_path", lambda: path) init_config() update_setting("logging.file_enabled", "false") update_setting("cli.hello.name", "Ada") settings = read_settings() - assert settings["logging"] == {"level": "INFO", "verbosity": 0, "file_enabled": False} + assert settings["logging"] == { + "file_level": "INFO", + "console_level": "WARNING", + "file_enabled": False, + } assert settings["cli"]["hello"]["name"] == "Ada" + + +def test_named_levels_and_console_overrides(monkeypatch, tmp_path: Path) -> None: + output = io.StringIO() + path = tmp_path / "app.log" + monkeypatch.setattr(config.sys, "stderr", output) + monkeypatch.setattr(config, "default_log_path", lambda: path) + settings = LoggingConfig(file_level="debug", console_level="trace") + assert settings.file_level == "DEBUG" + assert settings.console_level == "TRACE" + try: + settings.configure() + logger.trace("configured trace") + assert "configured trace" in output.getvalue() + settings.configure(verbose=True) + logger.trace("hidden trace") + logger.debug("verbose debug") + assert "hidden trace" not in output.getvalue() + assert "verbose debug" in output.getvalue() + settings.configure(quiet=True) + logger.error("file only") + assert "file only" not in output.getvalue() + assert "file only" in path.read_text(encoding="utf-8") + finally: + logger.remove() diff --git a/tests/smoke_installed.py b/tests/smoke_installed.py index c578370..a8b3c3e 100644 --- a/tests/smoke_installed.py +++ b/tests/smoke_installed.py @@ -67,11 +67,18 @@ def test_installed_configuration(run_cli, tmp_path): assert path.read_bytes() == original run_cli("set-config", "logging.file_enabled", "false", "--json") + run_cli("set-config", "logging.console_level", "INFO", "--json") run_cli("set-config", "cli.hello.name", "Ada", "--json") settings = json.loads(run_cli("--show-config", "--json").stdout) - assert settings["logging"]["file_enabled"] is False + assert settings["logging"] == { + "file_level": "INFO", + "console_level": "INFO", + "file_enabled": False, + } assert settings["cli"]["hello"]["name"] == "Ada" - assert json.loads(run_cli("hello", "--json").stdout) == {"message": "Hello, Ada!"} + result = run_cli("hello", "--json") + assert json.loads(result.stdout) == {"message": "Hello, Ada!"} + assert "Greeting requested" in result.stderr assert json.loads(run_cli("hello", "--name", "Grace", "--json").stdout) == { "message": "Hello, Grace!" }