Harbor format: 871 coding_baseline tasks (part 48)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/tests/trusted-inventory.jsonAdded+167
- tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/tests/trusted/tests/typing/typing_progressbar.pyAdded+24
- tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/tests/trusted/tests/typing/typing_simple_example.pyAdded+17
- tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/tests/trusted/tests/typing/typing_version_option.pyAdded+16
- tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/tests/trusted/tox.iniAdded+55
- tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/validation/canaries/first-hunk-only.shAdded+35
- tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/validation/canaries/original-bug.shAdded+3
- tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/validation/openenv.jsonAdded+27
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/LICENSE.sourceAdded+28
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/adapter.jsonAdded+127
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/dependency-setup.shAdded+8
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/environment/DockerfileAdded+3
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/instruction.mdAdded+46
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/metadata.jsonAdded+744
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/provenance.jsonAdded+88
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/provided-gold.diffAdded+95
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/solution/solve.shAdded+101
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/task.tomlAdded+23
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/check_pytest.pyAdded+91
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/expected-panels.jsonAdded+485
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/grade.pyAdded+128
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/panel-config.jsonAdded+23
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/test.shAdded+6
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted-inventory.jsonAdded+167
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/pyproject.tomlAdded+102
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/conftest.pyAdded+8
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_arguments.pyAdded+436
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_basic.pyAdded+575
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_chain.pyAdded+245
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_command_decorators.pyAdded+92
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_commands.pyAdded+407
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_compat.pyAdded+10
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_context.pyAdded+545
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_custom_classes.pyAdded+112
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_defaults.pyAdded+86
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_formatting.pyAdded+368
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_imports.pyAdded+69
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_info_dict.pyAdded+275
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_normalization.pyAdded+38
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_options.pyAdded+1017
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_parser.pyAdded+32
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_shell_completion.pyAdded+442
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_termui.pyAdded+487
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_testing.pyAdded+430
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_types.pyAdded+252
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_utils.pyAdded+653
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_aliased_group.pyAdded+46
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_confirmation_option.pyAdded+14
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_group_kw_options.pyAdded+11
- tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_help_option.pyAdded+13
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167{ "directory_roots": [ "tests" ], "files": { "pyproject.toml": { "bytes": 2059, "mode": 420, "sha256": "9613cb0037dd9c13abedfa097793fd78f78560ac605a995852caa3be5cb1d6ae" }, "tests/conftest.py": { "bytes": 131, "mode": 420, "sha256": "192be82444d6048fd222e2d73cd5c3bec768d65c6e10c0ffc230f307f363590b" }, "tests/test_arguments.py": { "bytes": 11929, "mode": 420, "sha256": "f8ebd354ffba0e644bf3516d379955ff4894d63137a8fd2b491f2478c48382bd" }, "tests/test_basic.py": { "bytes": 15452, "mode": 420, "sha256": "a22bb35be13097b31e48a9f352019c0319d88dc8e5c62bf8031f9a92d8408bb3" }, "tests/test_chain.py": { "bytes": 5786, "mode": 420, "sha256": "32247d8a208c84e571a89e87cbce389cc9aac08e98ece741c7d53fca0c63d881" }, "tests/test_command_decorators.py": { "bytes": 1880, "mode": 420, "sha256": "234ede359da2839923af2436056680bab68bdba622bf596452bbfbe1e1cfd6fa" }, "tests/test_commands.py": { "bytes": 11043, "mode": 420, "sha256": "9775d56ac9b373b3c6a1e92705b13f4ed5fc43a0bf984becd988437e815d2119" }, "tests/test_compat.py": { "bytes": 307, "mode": 420, "sha256": "5373454ca4b0718b079d1f49f1d153b0535686d6cf1f25291253b2dff1b5e748" }, "tests/test_context.py": { "bytes": 14294, "mode": 420, "sha256": "e7ab67acb6d3d413b8ecc1ad6d1ef64ac4ce49173b805b2f7d5851c81d680e54" }, "tests/test_custom_classes.py": { "bytes": 3022, "mode": 420, "sha256": "9d403c3b960ca927170645dcb144db33eb42c705208b6fa3b235c54889eee8e0" }, "tests/test_defaults.py": { "bytes": 2531, "mode": 420, "sha256": "1f835d0531beaaaa0fe99dcfa57635fa5e2cc9edd85d279a3f854a85551c8e45" }, "tests/test_formatting.py": { "bytes": 9413, "mode": 420, "sha256": "79c8ed50dd4507ef491a49dc7a69f2db65ee740f07fad31a09ff03b568141192" }, "tests/test_imports.py": { "bytes": 1414, "mode": 420, "sha256": "60310370edf02e88a94bb7f63c5a73eee7386b0b7adf6aa3e52633c073d7f929" }, "tests/test_info_dict.py": { "bytes": 7932, "mode": 420, "sha256": "544256b586fb50143e795b2f8023f5799e84ffdb57e34dcef31e386e6537098c" }, "tests/test_normalization.py": { "bytes": 955, "mode": 420, "sha256": "fab82963f1fe5a747429e324186e7fd34f7ef08a7ac20092c1899db3263f2376" }, "tests/test_options.py": { "bytes": 31807, "mode": 420, "sha256": "e18616e6a0a2e6f2bd9d8cb612c6ab0b36eafb1b6b3ac28fd374ffde3b4bfad3" }, "tests/test_parser.py": { "bytes": 915, "mode": 420, "sha256": "9e3a95fb896166e23bb8070de55a7d81a72a95c0b4909da659e54274b1615069" }, "tests/test_shell_completion.py": { "bytes": 14917, "mode": 420, "sha256": "faec10970de514a4a78abafb81573876f4ff383754969ef75954a6b850bf0f9e" }, "tests/test_termui.py": { "bytes": 15248, "mode": 420, "sha256": "14788f5acdeb49f9d3f8fefe2144bfad501a4519a2b42eec246c95746256fcf6" }, "tests/test_testing.py": { "bytes": 11102, "mode": 420, "sha256": "c63512960c836d493f11c143df8e35d43aa94b8b34af3516f97ca68bf348e369" }, "tests/test_types.py": { "bytes": 7807, "mode": 420, "sha256": "1d48de1f111b92b78153377db2286f6f37c306ded4b6b8c76111037743d7c8a1" }, "tests/test_utils.py": { "bytes": 21175, "mode": 420, "sha256": "424dee62b698503934682408d9aa28fe5be890f27ae4c92c7ab666ea9d2060f1" }, "tests/typing/typing_aliased_group.py": { "bytes": 1191, "mode": 420, "sha256": "0908243a61416433ff835ad517abf2a0f95275686dbb2fdb965579115a1f3189" }, "tests/typing/typing_confirmation_option.py": { "bytes": 326, "mode": 420, "sha256": "b25f68dfcef2a29c707aba78b722e46abe53a8e384e925f051e90e9e1e9d97c5" }, "tests/typing/typing_group_kw_options.py": { "bytes": 156, "mode": 420, "sha256": "53cb7ef7d78a9bbb1cd82e2e841a2b43efd1bf6b235ae002398eaf3272ecc87e" }, "tests/typing/typing_help_option.py": { "bytes": 262, "mode": 420, "sha256": "5dc1e21f7d8f4328f9c050294e1fc5964dd6b5ec01964b0f371fc2750721e545" }, "tests/typing/typing_options.py": { "bytes": 390, "mode": 420, "sha256": "a6579a3777cd63a27b030be925dcc1f38acbb46daf22f4092a3aee50b18ba043" }, "tests/typing/typing_password_option.py": { "bytes": 255, "mode": 420, "sha256": "71b7ae0e53bdde145628cbcb5f7a06a21e88ae58b438abfe99a8f0685549f4b6" }, "tests/typing/typing_progressbar.py": { "bytes": 559, "mode": 420, "sha256": "ba0529f20aa25016ffe36176db14437030b1fc7805a083b11742c5e03b3ba59c" }, "tests/typing/typing_simple_example.py": { "bytes": 508, "mode": 420, "sha256": "82c6a9d71dad51af7ce9f3c3cba5a9f9fc89184592d17d9385c14f330b81c64f" }, "tests/typing/typing_version_option.py": { "bytes": 287, "mode": 420, "sha256": "668cfdf7b197f178e519034ac8bce9f3901786ba6a9db0d1f2a9ef3c4b2d1ada" }, "tox.ini": { "bytes": 1203, "mode": 420, "sha256": "34183c21fb749d74f9a8299feaf931dcf01679634e3e9367923770cf83bb2838" } }}123456789101112131415161718192021222324from __future__ import annotations
from typing_extensions import assert_type
from click import progressbarfrom click._termui_impl import ProgressBar
def test_length_is_int() -> None: with progressbar(length=5) as bar: assert_type(bar, ProgressBar[int]) for i in bar: assert_type(i, int)
def it() -> tuple[str, ...]: return ("hello", "world")
def test_generic_on_iterable() -> None: with progressbar(it()) as bar: assert_type(bar, ProgressBar[str]) for s in bar: assert_type(s, str)1234567891011121314151617"""The simple example from https://github.com/pallets/click#a-simple-example."""
from typing_extensions import assert_type
import click
@click.command()@click.option("--count", default=1, help="Number of greetings.")@click.option("--name", prompt="Your name", help="The person to greet.")def hello(count: int, name: str) -> None: """Simple program that greets NAME for a total of COUNT times.""" for _ in range(count): click.echo(f"Hello, {name}!")
assert_type(hello, click.Command)12345678910111213141516"""From https://click.palletsprojects.com/en/8.1.x/options/#callbacks-and-eager-options."""
from typing_extensions import assert_type
import click
@click.command()@click.version_option("0.1")def hello() -> None: click.echo("Hello World!")
assert_type(hello, click.Command)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455[tox]envlist = py3{13,12,11,10,9,8} pypy310 style typing docsskip_missing_interpreters = true
[testenv]package = wheelwheel_build_env = .pkgconstrain_package_deps = trueuse_frozen_constraints = truedeps = -r requirements/tests.txtcommands = pytest -v --tb=short --basetemp={envtmpdir} {posargs}
[testenv:style]deps = pre-commitskip_install = truecommands = pre-commit run --all-files
[testenv:typing]deps = -r requirements/typing.txtcommands = mypy pyright tests/typing pyright --verifytypes click --ignoreexternal
[testenv:docs]deps = -r requirements/docs.txtcommands = sphinx-build -E -W -b dirhtml docs docs/_build/dirhtml
[testenv:update-actions]labels = updatedeps = gha-updatecommands = gha-update
[testenv:update-pre_commit]labels = updatedeps = pre-commitskip_install = truecommands = pre-commit autoupdate -j4
[testenv:update-requirements]labels = updatedeps = pip-toolsskip_install = truechange_dir = requirementscommands = pip-compile build.in -q {posargs:-U} pip-compile docs.in -q {posargs:-U} pip-compile tests.in -q {posargs:-U} pip-compile typing.in -q {posargs:-U} pip-compile dev.in -q {posargs:-U}1234567891011121314151617181920212223242526272829303132333435#!/bin/bashset -Eeuo pipefailcd /testbed/repocat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL'diff --git a/src/click/_termui_impl.py b/src/click/_termui_impl.pyindex fafd58d0a6786e5e2e7df260be5c825ae230e6bc..a6c7e6b3661f3e0b9cf719bbe3f93e3ff2235aed 100644--- a/src/click/_termui_impl.py+++ b/src/click/_termui_impl.py@@ -189,18 +189,18 @@ if self.length is not None: bar_length = int(self.pct * self.width) bar = self.fill_char * bar_length- bar += self.empty_char * (self.width - bar_length + 1)+ bar += self.empty_char * (self.width - bar_length) elif self.finished:- bar = self.empty_char * self.width- else:- chars = list(self.fill_char * (self.width or 1))+ bar = self.fill_char * self.width+ else:+ chars = list(self.empty_char * (self.width or 1)) if self.time_per_iteration != 0: chars[ int(- (math.sin(self.pos * self.time_per_iteration) / 2.0 + 0.5)+ (math.cos(self.pos * self.time_per_iteration) / 2.0 + 0.5) * self.width )- ] = self.empty_char+ ] = self.fill_char bar = "".join(chars) return bar OPENENV_PARTIAL/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff123#!/bin/bashset -Eeuo pipefail:123456789101112131415161718192021222324252627{ "canaries": "validation/canaries", "profile": "harbor-semantic-v1", "requires_credentials": false, "resources": { "cpu": 2, "disk_mb": 16384, "episode_timeout_s": 1800, "memory_mb": 8192 }, "reward": { "floor_margin": 0.1, "oracle_tolerance": 0, "range": [ 0, 1 ] }, "reward_key": "reward", "types": { "tags": [ "swe", "python", "mutation-repair" ] }}12345678910111213141516171819202122232425262728Copyright 2014 Pallets
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions aremet:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOTLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR APARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHTHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITEDTO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, ORPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OFLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDINGNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THISSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127{ "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", "collector_sha256": "352e555112f2de8a1393f939903e4971c9ace0e944843762b707a725c5c72481", "dependency_installation_pinned": false, "dependency_setup_sha256": "3a63d6a3502a27f06313581dcecb335018a18a55a2d1b5f0db2805ea49cc2052", "gold_patch_sha256": "c777bf7b2212fa53743824eb181b46a4a13093227be84a27928afed54cc3812a", "hostile_code_isolation_established": false, "known_wrong_semantic_implementations": 0, "native_inventory_sha256": "ddc55ffa2d50d767d810017108572caeae1294cba017721329f7178459610cb0", "new_files_deletions_and_executable_modes_supported": true, "official_profile": { "eval_sets": [], "profile_class": "ClickFde47b4b4", "profile_lines": [ 229, 232 ], "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", "profile_source_path": "swesmith/profiles/python.py", "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", "upstream_commit": "fde47b4b4f978f179b9dff34583cb2b99021f482", "upstream_repo": "pallets/click" }, "original_bug_canary_nop_equivalent": true, "original_bug_runtime_wrongness_established": false, "partial_repair_canary": true, "partial_repair_sha256": "b69df9d02a20849dbf931e97860ad3f78b55bc106bab458d78a4753727c0dc62", "partial_repair_wrongness_established": false, "provided_original_bug_control": true, "repo_url": "https://github.com/swesmith/pallets__click.fde47b4b.git", "runtime_image": null, "runtime_ready": false, "runtime_recipe": { "dependency_installation_pinned": false, "official_install_cmds": [ "python -m pip install -e ." ], "official_pytest_argv": [ "pytest", "--disable-warnings", "--color=no", "--tb=no", "--verbose" ], "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", "python_version": "3.10", "source_bound_test_dependency_cmds": [ "python -m pip install -r requirements/tests.txt" ], "test_dependency_source_sha256": { "requirements/tests.txt": "35f217825acd2a107dfb2c7b848d8a963e8d2eba6d7bd50e9fb34f3912e68658", "tox.ini": "34183c21fb749d74f9a8299feaf931dcf01679634e3e9367923770cf83bb2838" } }, "runtime_resource_review_required": false, "schema": "python-git-patch-jobs-v1", "source_base_commit": "0452dae4dbf9634371b6bdf30ada275d95e599ea", "source_completion_sha256": "342065db8f9dfa4aa2e1a8233184267e6b8fff93cb3a7ef9439c64eae9841254", "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", "source_pr_url": null, "source_record": { "anti_training_canary": false, "anti_training_reviewed": true, "candidate_id": "swesmith-py:pallets__click.fde47b4b.combine_file__3hfoaaic", "cloud_launch_ready": false, "eligibility": { "reasons": [], "semantic_nonoverlap_established": false, "status": "eligible_for_controls", "training_admissible": false, "warnings": [] }, "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", "instruction_sha256": "45367013c7477f15a1a1e66bbcd21bb281c15c0eab16640646ad4997c1262169", "is_fork": true, "learner_path": "tasks/012bd400c7ad13fa808fde1c/learner", "license_evidence": { "source_code": { "actual_upstream_commit": "fde47b4b4f978f179b9dff34583cb2b99021f482", "actual_upstream_url": "https://raw.githubusercontent.com/pallets/click/fde47b4b4f978f179b9dff34583cb2b99021f482/LICENSE.txt", "reviewed": true, "sha256": "9a8ad106a394e853bfe21f42f4e72d592819a22805d991b5f3275029292b658d", "spdx": "BSD-3-Clause", "training_allowed": true, "url": "https://raw.githubusercontent.com/swesmith/pallets__click.fde47b4b/0452dae4dbf9634371b6bdf30ada275d95e599ea/LICENSE.txt" }, "task_bundle": { "reviewed": true, "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", "spdx": "MIT", "training_allowed": true, "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" } }, "original_source_commit": "fde47b4b4f978f179b9dff34583cb2b99021f482", "patch_sha256": "3314835b6acae3bcd146678a99dd26d7b1956dad88ce9e296cc7edbe22fd9c1f", "provenance_path": "tasks/012bd400c7ad13fa808fde1c/source-proof.json", "repository_lineage": [ "swesmith/pallets__click.fde47b4b", "pallets/click" ], "rfc008_complete": false, "runtime_qualified": false, "semantic_nonoverlap_established": false, "source_commit": "0452dae4dbf9634371b6bdf30ada275d95e599ea", "source_dataset": "SWE-bench/SWE-smith-py", "source_head_commit": "3097ec466315f1f9ad82fbd894dfb9235b6bc1cf", "source_kind": "mutation", "source_repo": "swesmith/pallets__click.fde47b4b", "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", "source_split": "train", "target_model_calibrated": false, "task_id": "pallets__click.fde47b4b.combine_file__3hfoaaic", "task_sha256": "7b537833ef61b3cda2b29a6f983e61d078e2be53b30c3945ce1063a0f10fb426", "training_admissible": false, "upstream_identity_reviewed": true, "upstream_repo": "pallets/click", "usage": "quarantine_only" }, "source_repo": "swesmith/pallets__click.fde47b4b", "symlink_submodule_changes_supported": false, "task_id": "pallets__click.fde47b4b.combine_file__3hfoaaic", "transfer": "index-independent-worktree-to-Git-binary-patch", "transfer_path": "/testbed/submission.patch", "upstream_repo": "pallets/click"}12345678#!/bin/bashset -Eeuo pipefailsource /opt/miniconda3/bin/activateconda activate testbedcd /testbed/repopython -c 'import sys; assert sys.version_info[:2] == (3, 10)'python -m pip install -e .python -m pip install -r requirements/tests.txt123# Runtime is selected only by an independently qualified immutable amd64 receipt.FROM ubuntu:22.04RUN false12345678910111213141516171819202122232425262728293031323334353637383940414243444546Click decorators broken after recent changes
I'm encountering issues with Click decorators that seem to have broken functionality. When trying to use basic Click commands with decorators like `@click.pass_context` and `@click.pass_obj`, I'm getting unexpected errors.
#### Steps/Code to Reproduce
```pythonimport click
@click.group()@click.pass_contextdef cli(ctx): ctx.obj = 'test'
@cli.command()@click.pass_objdef test(obj): click.echo(obj)
if __name__ == '__main__': cli()```
Running this simple example throws a `TypeError: Attempted to convert a callback into a command twice.`
Also having issues with basic option decorators:
```pythonimport click
@click.command()@click.option('--name', default='World')def hello(name): click.echo(f'Hello {name}!')
if __name__ == '__main__': hello()```
This also fails with similar errors. The decorators seem to be malfunctioning and not properly wrapping the functions as expected.
The issue appears to affect multiple decorator types including `@click.pass_context`, `@click.pass_obj`, `@click.option`, and others. Basic Click functionality that was working before is now completely broken.
## Environment
The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest <tests>`. Don't install packages: the tests need nothing else, and the sandbox may have no network access.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744{ "all_runtime_and_training_flags": false, "official_profile": { "eval_sets": [], "profile_class": "ClickFde47b4b4", "profile_lines": [ 229, 232 ], "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", "profile_source_path": "swesmith/profiles/python.py", "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", "upstream_commit": "fde47b4b4f978f179b9dff34583cb2b99021f482", "upstream_repo": "pallets/click" }, "source_healthy_reference_proof": { "FAIL_TO_PASS": [ "tests/test_arguments.py::test_nargs_star", "tests/test_arguments.py::test_nargs_tup", "tests/test_arguments.py::test_nargs_tup_composite[opts0]", "tests/test_arguments.py::test_nargs_tup_composite[opts1]", "tests/test_arguments.py::test_nargs_tup_composite[opts2]", "tests/test_arguments.py::test_nargs_tup_composite[opts3]", "tests/test_arguments.py::test_nargs_err", "tests/test_arguments.py::test_bytes_args", "tests/test_arguments.py::test_file_args", "tests/test_arguments.py::test_path_allow_dash", "tests/test_arguments.py::test_file_atomics", "tests/test_arguments.py::test_stdout_default", "tests/test_arguments.py::test_nargs_envvar[2--None]", "tests/test_arguments.py::test_nargs_envvar[-1--expect5]", "tests/test_arguments.py::test_envvar_flag_value", "tests/test_arguments.py::test_nargs_envvar_only_if_values_empty", "tests/test_arguments.py::test_empty_nargs", "tests/test_arguments.py::test_missing_arg", "tests/test_arguments.py::test_implicit_non_required", "tests/test_arguments.py::test_eat_options", "tests/test_arguments.py::test_nargs_star_ordering", "tests/test_arguments.py::test_nargs_specified_plus_star_ordering", "tests/test_arguments.py::test_defaults_for_nargs", "tests/test_arguments.py::test_subcommand_help", "tests/test_arguments.py::test_nested_subcommand_help", "tests/test_arguments.py::test_when_argument_decorator_is_used_multiple_times_cls_is_preserved", "tests/test_arguments.py::test_duplicate_names_warning[args_one0-args_two0]", "tests/test_basic.py::test_basic_functionality", "tests/test_basic.py::test_repr", "tests/test_basic.py::test_return_values", "tests/test_basic.py::test_basic_group", "tests/test_basic.py::test_group_commands_dict", "tests/test_basic.py::test_group_from_list", "tests/test_basic.py::test_string_option[args1-S:[42]]", "tests/test_basic.py::test_string_option[args3-S:[]]", "tests/test_basic.py::test_string_option[args4-S:[\\u2603]]", "tests/test_basic.py::test_int_option[args0-I:[84]]", "tests/test_basic.py::test_int_option[args1-I:[46]]", "tests/test_basic.py::test_uuid_option[args0-U:[ba122011-349f-423b-873b-9d6a79c688ab]]", "tests/test_basic.py::test_uuid_option[args1-U:[821592c1-c50e-4971-9cd6-e89dc6832f86]]", "tests/test_basic.py::test_float_option[args0-F:[42.0]]", "tests/test_basic.py::test_float_option[--f=23.5-F:[23.5]]", "tests/test_basic.py::test_boolean_switch[args0-True-True]", "tests/test_basic.py::test_boolean_switch[args0-True-False]", "tests/test_basic.py::test_boolean_switch[args1-False-True]", "tests/test_basic.py::test_boolean_switch[args1-False-False]", "tests/test_basic.py::test_boolean_switch[args2-None-True]", "tests/test_basic.py::test_boolean_switch[args2-None-False]", "tests/test_basic.py::test_boolean_flag[args0-True-True]", "tests/test_basic.py::test_boolean_flag[args0-True-False]", "tests/test_basic.py::test_boolean_flag[args1-False-True]", "tests/test_basic.py::test_boolean_flag[args1-False-False]", "tests/test_basic.py::test_boolean_conversion[1-True]", "tests/test_basic.py::test_boolean_conversion[true-True]", "tests/test_basic.py::test_boolean_conversion[t-True]", "tests/test_basic.py::test_boolean_conversion[yes-True]", "tests/test_basic.py::test_boolean_conversion[y-True]", "tests/test_basic.py::test_boolean_conversion[on-True]", "tests/test_basic.py::test_boolean_conversion[0-False]", "tests/test_basic.py::test_boolean_conversion[false-False]", "tests/test_basic.py::test_boolean_conversion[f-False]", "tests/test_basic.py::test_boolean_conversion[no-False]", "tests/test_basic.py::test_boolean_conversion[n-False]", "tests/test_basic.py::test_boolean_conversion[off-False]", "tests/test_basic.py::test_file_option", "tests/test_basic.py::test_file_lazy_mode", "tests/test_basic.py::test_path_option", "tests/test_basic.py::test_choice_option", "tests/test_basic.py::test_choice_argument", "tests/test_basic.py::test_datetime_option_default", "tests/test_basic.py::test_datetime_option_custom", "tests/test_basic.py::test_required_option", "tests/test_basic.py::test_evaluation_order", "tests/test_basic.py::test_hidden_option", "tests/test_basic.py::test_hidden_command", "tests/test_basic.py::test_hidden_group", "tests/test_basic.py::test_summary_line", "tests/test_chain.py::test_basic_chaining", "tests/test_chain.py::test_chaining_with_options", "tests/test_chain.py::test_no_command_result_callback[False-1]", "tests/test_chain.py::test_no_command_result_callback[True-[]]", "tests/test_chain.py::test_chaining_with_arguments", "tests/test_chain.py::test_pipeline[args0-foo\\nbar-expect0]", "tests/test_chain.py::test_args_and_chain", "tests/test_chain.py::test_group_arg_behavior", "tests/test_command_decorators.py::test_command_no_parens", "tests/test_command_decorators.py::test_custom_command_no_parens", "tests/test_command_decorators.py::test_group_no_parens", "tests/test_command_decorators.py::test_params_argument", "tests/test_command_decorators.py::test_generate_name[init_data]", "tests/test_command_decorators.py::test_generate_name[init_data_command]", "tests/test_command_decorators.py::test_generate_name[init_data_cmd]", "tests/test_command_decorators.py::test_generate_name[init_data_group]", "tests/test_command_decorators.py::test_generate_name[init_data_grp]", "tests/test_commands.py::test_other_command_invoke", "tests/test_commands.py::test_other_command_forward", "tests/test_commands.py::test_forwarded_params_consistency", "tests/test_commands.py::test_auto_shorthelp", "tests/test_commands.py::test_default_maps", "tests/test_commands.py::test_group_with_args[args2-0-obj=obj1\\nmove\\n]", "tests/test_commands.py::test_custom_parser", "tests/test_commands.py::test_object_propagation", "tests/test_commands.py::test_other_command_invoke_with_defaults", "tests/test_commands.py::test_invoked_subcommand", "tests/test_commands.py::test_aliased_command_canonical_name", "tests/test_commands.py::test_unprocessed_options", "tests/test_commands.py::test_deprecated_in_help_messages[None]", "tests/test_commands.py::test_deprecated_in_invocation", "tests/test_commands.py::test_command_parse_args_collects_option_prefixes", "tests/test_commands.py::test_group_parse_args_collects_base_option_prefixes", "tests/test_commands.py::test_group_invoke_collects_used_option_prefixes", "tests/test_commands.py::test_abort_exceptions_with_disabled_standalone_mode[EOFError]", "tests/test_commands.py::test_abort_exceptions_with_disabled_standalone_mode[KeyboardInterrupt]", "tests/test_context.py::test_ensure_context_objects", "tests/test_context.py::test_get_context_objects", "tests/test_context.py::test_get_context_objects_no_ensuring", "tests/test_context.py::test_get_context_objects_missing", "tests/test_context.py::test_multi_enter", "tests/test_context.py::test_global_context_object", "tests/test_context.py::test_context_meta", "tests/test_context.py::test_make_pass_meta_decorator", "tests/test_context.py::test_context_pushing", "tests/test_context.py::test_pass_obj", "tests/test_context.py::test_close_before_pop", "tests/test_context.py::test_close_before_exit", "tests/test_context.py::test_multiple_eager_callbacks[natural_order]", "tests/test_context.py::test_multiple_eager_callbacks[eagerness_precedence]", "tests/test_context.py::test_no_state_leaks", "tests/test_context.py::test_make_pass_decorator_args", "tests/test_context.py::test_exit_not_standalone", "tests/test_context.py::test_parameter_source[default]", "tests/test_context.py::test_parameter_source[default_map]", "tests/test_custom_classes.py::test_context_invoke_type", "tests/test_custom_classes.py::test_group_command_class", "tests/test_custom_classes.py::test_group_group_class", "tests/test_custom_classes.py::test_group_group_class_self", "tests/test_defaults.py::test_basic_defaults", "tests/test_defaults.py::test_multiple_defaults", "tests/test_defaults.py::test_nargs_plus_multiple", "tests/test_defaults.py::test_multiple_flag_default", "tests/test_defaults.py::test_flag_default_map", "tests/test_formatting.py::test_basic_functionality", "tests/test_formatting.py::test_wrapping_long_options_strings", "tests/test_formatting.py::test_wrapping_long_command_name", "tests/test_formatting.py::test_formatting_empty_help_lines", "tests/test_formatting.py::test_formatting_usage_error", "tests/test_formatting.py::test_formatting_usage_error_metavar_missing_arg", "tests/test_formatting.py::test_formatting_usage_error_metavar_bad_arg", "tests/test_formatting.py::test_formatting_usage_error_nested", "tests/test_formatting.py::test_formatting_usage_error_no_help", "tests/test_formatting.py::test_formatting_usage_custom_help", "tests/test_formatting.py::test_formatting_custom_type_metavar", "tests/test_formatting.py::test_truncating_docstring", "tests/test_formatting.py::test_truncating_docstring_no_help", "tests/test_formatting.py::test_removing_multiline_marker", "tests/test_formatting.py::test_global_show_default", "tests/test_normalization.py::test_option_normalization", "tests/test_normalization.py::test_choice_normalization", "tests/test_normalization.py::test_command_normalization", "tests/test_options.py::test_prefixes", "tests/test_options.py::test_nargs_tup_composite_mult", "tests/test_options.py::test_counting", "tests/test_options.py::test_unknown_options[--foo]", "tests/test_options.py::test_unknown_options[-f]", "tests/test_options.py::test_multiple_required", "tests/test_options.py::test_empty_envvar[MYPATH]", "tests/test_options.py::test_empty_envvar[AUTO_MYPATH]", "tests/test_options.py::test_multiple_envvar", "tests/test_options.py::test_trailing_blanks_boolean_envvar", "tests/test_options.py::test_multiple_default_help", "tests/test_options.py::test_show_default_default_map", "tests/test_options.py::test_parse_multiple_default_composite_type", "tests/test_options.py::test_dynamic_default_help_unset", "tests/test_options.py::test_dynamic_default_help_text", "tests/test_options.py::test_toupper_envvar_prefix", "tests/test_options.py::test_nargs_envvar", "tests/test_options.py::test_show_envvar", "tests/test_options.py::test_show_envvar_auto_prefix", "tests/test_options.py::test_show_envvar_auto_prefix_dash_in_command", "tests/test_options.py::test_custom_validation", "tests/test_options.py::test_callback_validates_prompt", "tests/test_options.py::test_winstyle_options", "tests/test_options.py::test_legacy_options", "tests/test_options.py::test_missing_choice", "tests/test_options.py::test_case_insensitive_choice", "tests/test_options.py::test_case_insensitive_choice_returned_exactly", "tests/test_options.py::test_option_help_preserve_paragraphs", "tests/test_options.py::test_argument_custom_class", "tests/test_options.py::test_option_custom_class", "tests/test_options.py::test_option_custom_class_reusable", "tests/test_options.py::test_bool_flag_with_type", "tests/test_options.py::test_aliases_for_flags", "tests/test_options.py::test_option_names[option_args0-aggressive]", "tests/test_options.py::test_option_names[option_args1-first]", "tests/test_options.py::test_option_names[option_args2-apple]", "tests/test_options.py::test_option_names[option_args3-cantaloupe]", "tests/test_options.py::test_option_names[option_args4-a]", "tests/test_options.py::test_option_names[option_args5-c]", "tests/test_options.py::test_option_names[option_args6-apple]", "tests/test_options.py::test_option_names[option_args7-cantaloupe]", "tests/test_options.py::test_option_names[option_args8-_from]", "tests/test_options.py::test_option_names[option_args9-_ret]", "tests/test_options.py::test_option_with_optional_value[None-expect0]", "tests/test_options.py::test_option_with_optional_value[args1-expect1]", "tests/test_options.py::test_option_with_optional_value[args2-expect2]", "tests/test_options.py::test_option_with_optional_value[args3-expect3]", "tests/test_options.py::test_option_with_optional_value[args4-expect4]", "tests/test_options.py::test_option_with_optional_value[args5-expect5]", "tests/test_options.py::test_option_with_optional_value[args6-expect6]", "tests/test_options.py::test_option_with_optional_value[args7-expect7]", "tests/test_options.py::test_option_with_optional_value[args8-expect8]", "tests/test_options.py::test_option_with_optional_value[args9-expect9]", "tests/test_options.py::test_option_with_optional_value[args10-expect10]", "tests/test_options.py::test_option_with_optional_value[args11-expect11]", "tests/test_options.py::test_option_with_optional_value[args12-expect12]", "tests/test_options.py::test_option_with_optional_value[args13-expect13]", "tests/test_options.py::test_duplicate_names_warning[opts_one0-opts_two0]", "tests/test_options.py::test_duplicate_names_warning[opts_one1-opts_two1]", "tests/test_shell_completion.py::test_files_closed", "tests/test_termui.py::test_progressbar_strip_regression", "tests/test_termui.py::test_progressbar_length_hint", "tests/test_termui.py::test_progressbar_no_tty", "tests/test_termui.py::test_progressbar_hidden_manual", "tests/test_termui.py::test_progressbar_is_iterator", "tests/test_termui.py::test_choices_list_in_prompt", "tests/test_termui.py::test_file_prompt_default_format[file_kwargs0]", "tests/test_termui.py::test_file_prompt_default_format[file_kwargs1]", "tests/test_termui.py::test_file_prompt_default_format[file_kwargs2]", "tests/test_termui.py::test_progressbar_update", "tests/test_termui.py::test_progressbar_item_show_func", "tests/test_termui.py::test_progressbar_update_with_item_show_func", "tests/test_termui.py::test_prompt_required_with_required[True-False-None-prompt]", "tests/test_termui.py::test_prompt_required_with_required[False-True-None-prompt]", "tests/test_termui.py::test_prompt_required_with_required[False-True-args3-prompt]", "tests/test_termui.py::test_confirmation_prompt[True-password\\npassword-None-password]", "tests/test_termui.py::test_confirmation_prompt[True---]", "tests/test_termui.py::test_confirmation_prompt[False-None-None-None]", "tests/test_termui.py::test_false_show_default_cause_no_default_display_in_prompt", "tests/test_testing.py::test_runner", "tests/test_testing.py::test_echo_stdin_stream", "tests/test_testing.py::test_echo_stdin_prompts", "tests/test_testing.py::test_runner_with_stream", "tests/test_testing.py::test_prompts", "tests/test_testing.py::test_getchar", "tests/test_testing.py::test_catch_exceptions", "tests/test_testing.py::test_with_color", "tests/test_testing.py::test_with_color_errors", "tests/test_testing.py::test_with_color_but_pause_not_blocking", "tests/test_testing.py::test_exit_code_and_output_from_sys_exit", "tests/test_testing.py::test_env", "tests/test_testing.py::test_stderr", "tests/test_testing.py::test_args[None-bar\\n]", "tests/test_testing.py::test_args[args1-bar\\n]", "tests/test_testing.py::test_args[-bar\\n]", "tests/test_testing.py::test_setting_prog_name_in_extra", "tests/test_testing.py::test_command_standalone_mode_returns_value", "tests/test_testing.py::test_file_stdin_attrs", "tests/test_utils.py::test_echo", "tests/test_utils.py::test_prompts", "tests/test_utils.py::test_open_file", "tests/test_utils.py::test_open_file_pathlib_dash", "tests/test_utils.py::test_open_file_ignore_errors_stdin", "tests/test_utils.py::test_open_file_atomic_permissions_existing_file[256]", "tests/test_utils.py::test_open_file_atomic_permissions_existing_file[292]", "tests/test_utils.py::test_open_file_atomic_permissions_existing_file[384]", "tests/test_utils.py::test_open_file_atomic_permissions_existing_file[420]", "tests/test_utils.py::test_open_file_atomic_permissions_new_file" ], "PASS_TO_PASS": [ "tests/test_arguments.py::test_argument_unbounded_nargs_cant_have_default", "tests/test_arguments.py::test_missing_argument_string_cast", "tests/test_arguments.py::test_multiple_param_decls_not_allowed", "tests/test_arguments.py::test_multiple_not_allowed", "tests/test_arguments.py::test_nargs_bad_default[value0]", "tests/test_arguments.py::test_nargs_bad_default[value1]", "tests/test_arguments.py::test_nargs_bad_default[value2]", "tests/test_basic.py::test_help_invalid_default", "tests/test_commands.py::test_command_no_args_is_help", "tests/test_commands.py::test_group_add_command_name", "tests/test_compat.py::test_is_jupyter_kernel_output", "tests/test_context.py::test_make_pass_meta_decorator_doc", "tests/test_context.py::test_with_resource", "tests/test_context.py::test_propagate_show_default_setting", "tests/test_context.py::test_propagate_opt_prefixes", "tests/test_custom_classes.py::test_command_context_class", "tests/test_custom_classes.py::test_context_formatter_class", "tests/test_formatting.py::test_formatting_with_options_metavar_empty", "tests/test_formatting.py::test_help_formatter_write_text", "tests/test_imports.py::test_light_imports", "tests/test_info_dict.py::test_parameter[Option]", "tests/test_info_dict.py::test_parameter[Argument]", "tests/test_info_dict.py::test_command[Command]", "tests/test_info_dict.py::test_command[Group]", "tests/test_info_dict.py::test_context", "tests/test_info_dict.py::test_paramtype_no_name", "tests/test_options.py::test_invalid_option", "tests/test_options.py::test_invalid_nargs", "tests/test_options.py::test_init_good_default_list[True-1-default0]", "tests/test_options.py::test_init_good_default_list[True-1-default1]", "tests/test_options.py::test_init_good_default_list[False-2-default2]", "tests/test_options.py::test_init_good_default_list[True-2-default3]", "tests/test_options.py::test_init_good_default_list[True-2-default4]", "tests/test_options.py::test_init_bad_default_list[True-1-1]", "tests/test_options.py::test_init_bad_default_list[False-2-default1]", "tests/test_options.py::test_init_bad_default_list[True-2-default2]", "tests/test_options.py::test_multiple_default_type", "tests/test_options.py::test_multiple_default_composite_type", "tests/test_options.py::test_dynamic_default_help_special_method", "tests/test_options.py::test_intrange_default_help_text[type0-1<=x<=32]", "tests/test_options.py::test_intrange_default_help_text[type1-1<x<32]", "tests/test_options.py::test_intrange_default_help_text[type2-x>=1]", "tests/test_options.py::test_intrange_default_help_text[type3-x<=32]", "tests/test_options.py::test_count_default_type_help", "tests/test_options.py::test_file_type_help_default", "tests/test_options.py::test_missing_option_string_cast", "tests/test_options.py::test_missing_required_flag", "tests/test_options.py::test_missing_envvar", "tests/test_options.py::test_flag_duplicate_names", "tests/test_options.py::test_show_default_boolean_flag_name[False-no-cache]", "tests/test_options.py::test_show_default_boolean_flag_name[True-cache]", "tests/test_options.py::test_show_true_default_boolean_flag_value", "tests/test_options.py::test_hide_false_default_boolean_flag_value[False]", "tests/test_options.py::test_hide_false_default_boolean_flag_value[None]", "tests/test_options.py::test_show_default_string", "tests/test_options.py::test_show_default_with_empty_string", "tests/test_options.py::test_do_not_show_no_default", "tests/test_options.py::test_do_not_show_default_empty_multiple", "tests/test_options.py::test_show_default_precedence[None-None-extra_value0-False]", "tests/test_options.py::test_show_default_precedence[None-False-extra_value1-False]", "tests/test_options.py::test_show_default_precedence[None-True-extra_value2-True]", "tests/test_options.py::test_show_default_precedence[False-None-extra_value3-False]", "tests/test_options.py::test_show_default_precedence[False-False-extra_value4-False]", "tests/test_options.py::test_show_default_precedence[False-True-extra_value5-True]", "tests/test_options.py::test_show_default_precedence[True-None-extra_value6-True]", "tests/test_options.py::test_show_default_precedence[True-False-extra_value7-False]", "tests/test_options.py::test_show_default_precedence[True-True-extra_value8-True]", "tests/test_options.py::test_show_default_precedence[False-one-extra_value9-True]", "tests/test_options.py::test_multiple_option_with_optional_value", "tests/test_options.py::test_type_from_flag_value", "tests/test_options.py::test_is_bool_flag_is_correctly_set[is_flag=True]", "tests/test_parser.py::test_parser_default_prefixes", "tests/test_parser.py::test_parser_collects_prefixes", "tests/test_shell_completion.py::test_command", "tests/test_shell_completion.py::test_group", "tests/test_shell_completion.py::test_group_command_same_option", "tests/test_shell_completion.py::test_chained", "tests/test_shell_completion.py::test_help_option", "tests/test_shell_completion.py::test_argument_order", "tests/test_shell_completion.py::test_argument_default", "tests/test_shell_completion.py::test_type_choice", "tests/test_shell_completion.py::test_choice_special_characters", "tests/test_shell_completion.py::test_choice_conflicting_prefix", "tests/test_shell_completion.py::test_option_count", "tests/test_shell_completion.py::test_option_optional", "tests/test_shell_completion.py::test_path_types[type0-file]", "tests/test_shell_completion.py::test_path_types[type1-file]", "tests/test_shell_completion.py::test_path_types[type2-dir]", "tests/test_shell_completion.py::test_absolute_path", "tests/test_shell_completion.py::test_option_flag", "tests/test_shell_completion.py::test_option_custom", "tests/test_shell_completion.py::test_option_multiple", "tests/test_shell_completion.py::test_option_nargs", "tests/test_shell_completion.py::test_argument_nargs", "tests/test_shell_completion.py::test_double_dash", "tests/test_shell_completion.py::test_hidden", "tests/test_shell_completion.py::test_add_different_name", "tests/test_shell_completion.py::test_completion_item_data", "tests/test_shell_completion.py::test_full_source[bash]", "tests/test_shell_completion.py::test_full_source[zsh]", "tests/test_shell_completion.py::test_full_source[fish]", "tests/test_shell_completion.py::test_full_complete[bash-env0-plain,a\\nplain,b\\n]", "tests/test_shell_completion.py::test_full_complete[bash-env1-plain,b\\n]", "tests/test_shell_completion.py::test_full_complete[zsh-env2-plain\\na\\n_\\nplain\\nb\\nbee\\n]", "tests/test_shell_completion.py::test_full_complete[zsh-env3-plain\\nb\\nbee\\n]", "tests/test_shell_completion.py::test_full_complete[fish-env4-plain,a\\nplain,b\\tbee\\n]", "tests/test_shell_completion.py::test_full_complete[fish-env5-plain,b\\tbee\\n]", "tests/test_shell_completion.py::test_context_settings", "tests/test_shell_completion.py::test_choice_case_sensitive[False-expect0]", "tests/test_shell_completion.py::test_choice_case_sensitive[True-expect1]", "tests/test_shell_completion.py::test_add_completion_class", "tests/test_shell_completion.py::test_add_completion_class_with_name", "tests/test_shell_completion.py::test_add_completion_class_decorator", "tests/test_termui.py::test_progressbar_time_per_iteration[avg0-0.0]", "tests/test_termui.py::test_progressbar_time_per_iteration[avg1-2.5]", "tests/test_termui.py::test_progressbar_eta[False-5]", "tests/test_termui.py::test_progressbar_eta[True-0]", "tests/test_termui.py::test_progressbar_format_eta[0-00:00:00]", "tests/test_termui.py::test_progressbar_format_eta[30-00:00:30]", "tests/test_termui.py::test_progressbar_format_eta[90-00:01:30]", "tests/test_termui.py::test_progressbar_format_eta[900-00:15:00]", "tests/test_termui.py::test_progressbar_format_eta[9000-02:30:00]", "tests/test_termui.py::test_progressbar_format_eta[None-]", "tests/test_termui.py::test_progressbar_format_pos[0-5]", "tests/test_termui.py::test_progressbar_format_pos[-1-1]", "tests/test_termui.py::test_progressbar_format_pos[5-5]", "tests/test_termui.py::test_progressbar_format_pos[6-5]", "tests/test_termui.py::test_progressbar_format_pos[4-0]", "tests/test_termui.py::test_progressbar_format_bar[8-False-7-0-#######-]", "tests/test_termui.py::test_progressbar_format_bar[0-True-8-0-########]", "tests/test_termui.py::test_progressbar_format_progress_line_with_show_func[test]", "tests/test_termui.py::test_progressbar_format_progress_line_with_show_func[None]", "tests/test_termui.py::test_progressbar_init_exceptions", "tests/test_termui.py::test_progressbar_iter_outside_with_exceptions", "tests/test_termui.py::test_secho", "tests/test_termui.py::test_secho_non_text[123-\\x1b[45m123\\x1b[0m]", "tests/test_termui.py::test_secho_non_text[test-test]", "tests/test_termui.py::test_progressbar_yields_all_items", "tests/test_termui.py::test_progress_bar_update_min_steps", "tests/test_termui.py::test_fast_edit", "tests/test_termui.py::test_edit", "tests/test_testing.py::test_isolated_runner", "tests/test_testing.py::test_isolated_runner_custom_tempdir", "tests/test_testing.py::test_isolation_stderr_errors", "tests/test_types.py::test_range[type0-3-3]", "tests/test_types.py::test_range[type1-5-5]", "tests/test_types.py::test_range[type2-100-100]", "tests/test_types.py::test_range[type3-5-5]", "tests/test_types.py::test_range[type4--100--100]", "tests/test_types.py::test_range[type5--1-0]", "tests/test_types.py::test_range[type6-6-5]", "tests/test_types.py::test_range[type7-0-1]", "tests/test_types.py::test_range[type8-5-4]", "tests/test_types.py::test_range[type9-1.2-1.2]", "tests/test_types.py::test_range[type10-0.51-0.51]", "tests/test_types.py::test_range[type11-1.49-1.49]", "tests/test_types.py::test_range[type12--0.0-0.5]", "tests/test_types.py::test_range[type13-inf-1.5]", "tests/test_types.py::test_range_fail[type3-0-0<x<=5]", "tests/test_types.py::test_range_fail[type4-5-0<=x<5]", "tests/test_types.py::test_range_fail[type5-0.5-x>0.5]", "tests/test_types.py::test_range_fail[type6-1.5-x<1.5]", "tests/test_types.py::test_float_range_no_clamp_open", "tests/test_types.py::test_cast_multi_default[2-False-None-None]", "tests/test_types.py::test_cast_multi_default[2-False-default1-expect1]", "tests/test_types.py::test_cast_multi_default[None-True-None-expect2]", "tests/test_types.py::test_cast_multi_default[None-True-default3-expect3]", "tests/test_types.py::test_cast_multi_default[2-True-None-expect4]", "tests/test_types.py::test_cast_multi_default[2-True-default5-expect5]", "tests/test_types.py::test_cast_multi_default[-1-None-None-expect6]", "tests/test_types.py::test_path_type[None-a/b/c.txt]", "tests/test_types.py::test_path_type[str-a/b/c.txt]", "tests/test_types.py::test_path_type[bytes-a/b/c.txt]", "tests/test_types.py::test_path_type[Path-expect3]", "tests/test_types.py::test_path_resolve_symlink", "tests/test_types.py::test_path_surrogates", "tests/test_types.py::test_file_surrogates[type0]", "tests/test_types.py::test_file_surrogates[type1]", "tests/test_types.py::test_file_error_surrogates", "tests/test_types.py::test_invalid_path_with_esc_sequence", "tests/test_types.py::test_choice_get_invalid_choice_message", "tests/test_utils.py::test_echo_custom_file", "tests/test_utils.py::test_echo_no_streams", "tests/test_utils.py::test_filename_formatting", "tests/test_utils.py::test_confirm_repeat", "tests/test_utils.py::test_prompts_abort", "tests/test_utils.py::test_echo_via_pager[test0]", "tests/test_utils.py::test_echo_via_pager[test1]", "tests/test_utils.py::test_echo_via_pager[test2]", "tests/test_utils.py::test_echo_via_pager[test3]", "tests/test_utils.py::test_echo_via_pager[test4]", "tests/test_utils.py::test_echo_via_pager[test5]", "tests/test_utils.py::test_echo_via_pager[test6]", "tests/test_utils.py::test_echo_via_pager[test7]", "tests/test_utils.py::test_echo_via_pager[test8]", "tests/test_utils.py::test_echo_via_pager[test9]", "tests/test_utils.py::test_echo_color_flag", "tests/test_utils.py::test_prompt_cast_default", "tests/test_utils.py::test_echo_writing_to_standard_error", "tests/test_utils.py::test_echo_with_capsys", "tests/test_utils.py::test_open_file_respects_ignore", "tests/test_utils.py::test_open_file_ignore_invalid_utf8", "tests/test_utils.py::test_open_file_ignore_no_encoding", "tests/test_utils.py::test_iter_keepopenfile", "tests/test_utils.py::test_iter_lazyfile", "tests/test_utils.py::test_detect_program_name[example.py-None-example.py]", "tests/test_utils.py::test_detect_program_name[/foo/bar/example.py-None-example.py]", "tests/test_utils.py::test_detect_program_name[example-None-example]", "tests/test_utils.py::test_detect_program_name[example--example]", "tests/test_utils.py::test_expand_args", "tests/test_utils.py::test_make_default_short_help[-empty]", "tests/test_utils.py::test_make_default_short_help[-truncate]" ], "all_git_blobs_modes_verified": true, "cloud_launch_ready": false, "commits": { "bug": "3097ec466315f1f9ad82fbd894dfb9235b6bc1cf", "healthy": "642a0737fd895f3adba643e7502081ce98f5abbb", "learner": "0452dae4dbf9634371b6bdf30ada275d95e599ea" }, "existing_squirrel_snapshot_reused": false, "full_transfer_allowlist": [ "/testbed/.devcontainer/devcontainer.json", "/testbed/.devcontainer/on-create-command.sh", "/testbed/.editorconfig", "/testbed/.github/ISSUE_TEMPLATE/bug-report.md", "/testbed/.github/ISSUE_TEMPLATE/config.yml", "/testbed/.github/ISSUE_TEMPLATE/feature-request.md", "/testbed/.github/pull_request_template.md", "/testbed/.gitignore", "/testbed/.pre-commit-config.yaml", "/testbed/.readthedocs.yaml", "/testbed/CHANGES.rst", "/testbed/CONTRIBUTING.rst", "/testbed/LICENSE.txt", "/testbed/README.md", "/testbed/artwork/logo.svg", "/testbed/docs/Makefile", "/testbed/docs/_static/click-icon.png", "/testbed/docs/_static/click-logo-sidebar.png", "/testbed/docs/_static/click-logo.png", "/testbed/docs/advanced.rst", "/testbed/docs/api.rst", "/testbed/docs/arguments.rst", "/testbed/docs/changes.rst", "/testbed/docs/commands.rst", "/testbed/docs/complex.rst", "/testbed/docs/conf.py", "/testbed/docs/contrib.rst", "/testbed/docs/documentation.rst", "/testbed/docs/entry-points.rst", "/testbed/docs/exceptions.rst", "/testbed/docs/index.rst", "/testbed/docs/license.rst", "/testbed/docs/make.bat", "/testbed/docs/options.rst", "/testbed/docs/parameters.rst", "/testbed/docs/prompts.rst", "/testbed/docs/quickstart.rst", "/testbed/docs/setuptools.rst", "/testbed/docs/shell-completion.rst", "/testbed/docs/testing.rst", "/testbed/docs/unicode-support.rst", "/testbed/docs/utils.rst", "/testbed/docs/virtualenv.rst", "/testbed/docs/why.rst", "/testbed/docs/wincmd.rst", "/testbed/examples/README", "/testbed/examples/aliases/README", "/testbed/examples/aliases/aliases.ini", "/testbed/examples/aliases/aliases.py", "/testbed/examples/aliases/pyproject.toml", "/testbed/examples/colors/README", "/testbed/examples/colors/colors.py", "/testbed/examples/colors/pyproject.toml", "/testbed/examples/completion/README", "/testbed/examples/completion/completion.py", "/testbed/examples/completion/pyproject.toml", "/testbed/examples/complex/README", "/testbed/examples/complex/complex/__init__.py", "/testbed/examples/complex/complex/cli.py", "/testbed/examples/complex/complex/commands/__init__.py", "/testbed/examples/complex/complex/commands/cmd_init.py", "/testbed/examples/complex/complex/commands/cmd_status.py", "/testbed/examples/complex/pyproject.toml", "/testbed/examples/imagepipe/.gitignore", "/testbed/examples/imagepipe/README", "/testbed/examples/imagepipe/example01.jpg", "/testbed/examples/imagepipe/example02.jpg", "/testbed/examples/imagepipe/imagepipe.py", "/testbed/examples/imagepipe/pyproject.toml", "/testbed/examples/inout/README", "/testbed/examples/inout/inout.py", "/testbed/examples/inout/pyproject.toml", "/testbed/examples/naval/README", "/testbed/examples/naval/naval.py", "/testbed/examples/naval/pyproject.toml", "/testbed/examples/repo/README", "/testbed/examples/repo/pyproject.toml", "/testbed/examples/repo/repo.py", "/testbed/examples/termui/README", "/testbed/examples/termui/pyproject.toml", "/testbed/examples/termui/termui.py", "/testbed/examples/validation/README", "/testbed/examples/validation/pyproject.toml", "/testbed/examples/validation/validation.py", "/testbed/pyproject.toml", "/testbed/requirements/build.in", "/testbed/requirements/build.txt", "/testbed/requirements/dev.in", "/testbed/requirements/dev.txt", "/testbed/requirements/docs.in", "/testbed/requirements/docs.txt", "/testbed/requirements/tests.in", "/testbed/requirements/tests.txt", "/testbed/requirements/typing.in", "/testbed/requirements/typing.txt", "/testbed/src/click/__init__.py", "/testbed/src/click/_compat.py", "/testbed/src/click/_termui_impl.py", "/testbed/src/click/_textwrap.py", "/testbed/src/click/_winconsole.py", "/testbed/src/click/core.py", "/testbed/src/click/decorators.py", "/testbed/src/click/exceptions.py", "/testbed/src/click/formatting.py", "/testbed/src/click/globals.py", "/testbed/src/click/parser.py", "/testbed/src/click/py.typed", "/testbed/src/click/shell_completion.py", "/testbed/src/click/termui.py", "/testbed/src/click/testing.py", "/testbed/src/click/types.py", "/testbed/src/click/utils.py", "/testbed/tests/conftest.py", "/testbed/tests/test_compat.py", "/testbed/tests/test_imports.py", "/testbed/tests/test_info_dict.py", "/testbed/tests/test_parser.py", "/testbed/tests/test_types.py", "/testbed/tests/typing/typing_aliased_group.py", "/testbed/tests/typing/typing_confirmation_option.py", "/testbed/tests/typing/typing_group_kw_options.py", "/testbed/tests/typing/typing_help_option.py", "/testbed/tests/typing/typing_options.py", "/testbed/tests/typing/typing_password_option.py", "/testbed/tests/typing/typing_progressbar.py", "/testbed/tests/typing/typing_simple_example.py", "/testbed/tests/typing/typing_version_option.py", "/testbed/tox.ini" ], "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", "mutation_matches_dataset_and_git_blobs": true, "official_profile": { "eval_sets": [], "profile_class": "ClickFde47b4b4", "profile_lines": [ 229, 232 ], "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", "profile_source_path": "swesmith/profiles/python.py", "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", "upstream_commit": "fde47b4b4f978f179b9dff34583cb2b99021f482", "upstream_repo": "pallets/click" }, "original_source_commit": "fde47b4b4f978f179b9dff34583cb2b99021f482", "private_test_paths": [ "tests/test_arguments.py", "tests/test_basic.py", "tests/test_chain.py", "tests/test_command_decorators.py", "tests/test_commands.py", "tests/test_context.py", "tests/test_custom_classes.py", "tests/test_defaults.py", "tests/test_formatting.py", "tests/test_normalization.py", "tests/test_options.py", "tests/test_shell_completion.py", "tests/test_termui.py", "tests/test_testing.py", "tests/test_utils.py" ], "private_tests_unchanged": true, "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", "qwen_calibrated": false, "runtime_qualified": false, "source_paths": [ "src/click/decorators.py" ], "source_repo": "swesmith/pallets__click.fde47b4b", "source_stages_bytes": 2675299, "task_id": "pallets__click.fde47b4b.combine_file__3hfoaaic", "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", "upstream_repo": "pallets/click" }, "source_record": { "anti_training_canary": false, "anti_training_reviewed": true, "candidate_id": "swesmith-py:pallets__click.fde47b4b.combine_file__3hfoaaic", "cloud_launch_ready": false, "eligibility": { "reasons": [], "semantic_nonoverlap_established": false, "status": "eligible_for_controls", "training_admissible": false, "warnings": [] }, "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", "instruction_sha256": "45367013c7477f15a1a1e66bbcd21bb281c15c0eab16640646ad4997c1262169", "is_fork": true, "learner_path": "tasks/012bd400c7ad13fa808fde1c/learner", "license_evidence": { "source_code": { "actual_upstream_commit": "fde47b4b4f978f179b9dff34583cb2b99021f482", "actual_upstream_url": "https://raw.githubusercontent.com/pallets/click/fde47b4b4f978f179b9dff34583cb2b99021f482/LICENSE.txt", "reviewed": true, "sha256": "9a8ad106a394e853bfe21f42f4e72d592819a22805d991b5f3275029292b658d", "spdx": "BSD-3-Clause", "training_allowed": true, "url": "https://raw.githubusercontent.com/swesmith/pallets__click.fde47b4b/0452dae4dbf9634371b6bdf30ada275d95e599ea/LICENSE.txt" }, "task_bundle": { "reviewed": true, "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", "spdx": "MIT", "training_allowed": true, "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" } }, "original_source_commit": "fde47b4b4f978f179b9dff34583cb2b99021f482", "patch_sha256": "3314835b6acae3bcd146678a99dd26d7b1956dad88ce9e296cc7edbe22fd9c1f", "provenance_path": "tasks/012bd400c7ad13fa808fde1c/source-proof.json", "repository_lineage": [ "swesmith/pallets__click.fde47b4b", "pallets/click" ], "rfc008_complete": false, "runtime_qualified": false, "semantic_nonoverlap_established": false, "source_commit": "0452dae4dbf9634371b6bdf30ada275d95e599ea", "source_dataset": "SWE-bench/SWE-smith-py", "source_head_commit": "3097ec466315f1f9ad82fbd894dfb9235b6bc1cf", "source_kind": "mutation", "source_repo": "swesmith/pallets__click.fde47b4b", "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", "source_split": "train", "target_model_calibrated": false, "task_id": "pallets__click.fde47b4b.combine_file__3hfoaaic", "task_sha256": "7b537833ef61b3cda2b29a6f983e61d078e2be53b30c3945ce1063a0f10fb426", "training_admissible": false, "upstream_identity_reviewed": true, "upstream_repo": "pallets/click", "usage": "quarantine_only" }, "task_kind": "original-source-mutation"}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788{ "generated_reference": false, "healthy_reference_delta_sha256": "c777bf7b2212fa53743824eb181b46a4a13093227be84a27928afed54cc3812a", "native_pytest_ids_preserved": true, "original_source_code_license": { "actual_upstream_commit": "fde47b4b4f978f179b9dff34583cb2b99021f482", "actual_upstream_url": "https://raw.githubusercontent.com/pallets/click/fde47b4b4f978f179b9dff34583cb2b99021f482/LICENSE.txt", "reviewed": true, "sha256": "9a8ad106a394e853bfe21f42f4e72d592819a22805d991b5f3275029292b658d", "spdx": "BSD-3-Clause", "training_allowed": true, "url": "https://raw.githubusercontent.com/swesmith/pallets__click.fde47b4b/0452dae4dbf9634371b6bdf30ada275d95e599ea/LICENSE.txt" }, "provided_reference": true, "qwen_calibrated": false, "runtime_qualified": false, "source_completion_sha256": "342065db8f9dfa4aa2e1a8233184267e6b8fff93cb3a7ef9439c64eae9841254", "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", "source_proof_sha256": "f40177e2dbf2563bac918905153bf63cb7ef57b65e66f9bd7448b689997ab5d4", "source_record": { "anti_training_canary": false, "anti_training_reviewed": true, "candidate_id": "swesmith-py:pallets__click.fde47b4b.combine_file__3hfoaaic", "cloud_launch_ready": false, "eligibility": { "reasons": [], "semantic_nonoverlap_established": false, "status": "eligible_for_controls", "training_admissible": false, "warnings": [] }, "healthy_mirror_commit": "642a0737fd895f3adba643e7502081ce98f5abbb", "instruction_sha256": "45367013c7477f15a1a1e66bbcd21bb281c15c0eab16640646ad4997c1262169", "is_fork": true, "learner_path": "tasks/012bd400c7ad13fa808fde1c/learner", "license_evidence": { "source_code": { "actual_upstream_commit": "fde47b4b4f978f179b9dff34583cb2b99021f482", "actual_upstream_url": "https://raw.githubusercontent.com/pallets/click/fde47b4b4f978f179b9dff34583cb2b99021f482/LICENSE.txt", "reviewed": true, "sha256": "9a8ad106a394e853bfe21f42f4e72d592819a22805d991b5f3275029292b658d", "spdx": "BSD-3-Clause", "training_allowed": true, "url": "https://raw.githubusercontent.com/swesmith/pallets__click.fde47b4b/0452dae4dbf9634371b6bdf30ada275d95e599ea/LICENSE.txt" }, "task_bundle": { "reviewed": true, "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", "spdx": "MIT", "training_allowed": true, "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" } }, "original_source_commit": "fde47b4b4f978f179b9dff34583cb2b99021f482", "patch_sha256": "3314835b6acae3bcd146678a99dd26d7b1956dad88ce9e296cc7edbe22fd9c1f", "provenance_path": "tasks/012bd400c7ad13fa808fde1c/source-proof.json", "repository_lineage": [ "swesmith/pallets__click.fde47b4b", "pallets/click" ], "rfc008_complete": false, "runtime_qualified": false, "semantic_nonoverlap_established": false, "source_commit": "0452dae4dbf9634371b6bdf30ada275d95e599ea", "source_dataset": "SWE-bench/SWE-smith-py", "source_head_commit": "3097ec466315f1f9ad82fbd894dfb9235b6bc1cf", "source_kind": "mutation", "source_repo": "swesmith/pallets__click.fde47b4b", "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", "source_split": "train", "target_model_calibrated": false, "task_id": "pallets__click.fde47b4b.combine_file__3hfoaaic", "task_sha256": "7b537833ef61b3cda2b29a6f983e61d078e2be53b30c3945ce1063a0f10fb426", "training_admissible": false, "upstream_identity_reviewed": true, "upstream_repo": "pallets/click", "usage": "quarantine_only" }, "task_bundle_license": { "reviewed": true, "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", "spdx": "MIT", "training_allowed": true, "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" }, "training_admissible": false, "trusted_tests_sha256": "03ded6ee8f725e98d55ac189e3afc15b2f769e811afe4ad8b802a828785f4b93"}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495diff --git a/src/click/decorators.py b/src/click/decorators.pyindex 61f8e0622f790bace26608f40a90af7c59952d20..901f831ad9c4ceb584e4af277eca6a36d1336a2d 100644--- a/src/click/decorators.py+++ b/src/click/decorators.py@@ -79,7 +79,7 @@ ctx = get_current_context() obj: T | None- if not ensure: # Logical condition inverted+ if ensure: obj = ctx.ensure_object(object_type) else: obj = ctx.find_object(object_type)@@ -91,7 +91,7 @@ " existing." ) - return ctx.invoke(f, ctx, *args, **kwargs) # Pass ctx instead of obj+ return ctx.invoke(f, obj, *args, **kwargs) return update_wrapper(new_func, f) @@ -116,10 +116,10 @@ def decorator(f: t.Callable[te.Concatenate[T, P], R]) -> t.Callable[P, R]: def new_func(*args: P.args, **kwargs: P.kwargs) -> R: ctx = get_current_context()- obj = None # Incorrectly assign None instead of fetching the object from ctx.meta- return ctx.invoke(f, obj, *args, **kwargs) # Pass the wrong object (None) to f- - return update_wrapper(f, new_func) # Swap the arguments in the update_wrapper call+ obj = ctx.meta[key]+ return ctx.invoke(f, obj, *args, **kwargs)++ return update_wrapper(new_func, f) if doc_description is None: doc_description = f"the {key!r} key from :attr:`click.Context.meta`"@@ -216,7 +216,7 @@ cls = t.cast("type[CmdType]", Command) def decorator(f: _AnyCallable) -> CmdType:- if not isinstance(f, Command):+ if isinstance(f, Command): raise TypeError("Attempted to convert a callback into a command twice.") attr_params = attrs.pop("params", None)@@ -225,29 +225,29 @@ try: decorator_params = f.__click_params__ # type: ignore except AttributeError:- params.append("default_param")+ pass else: del f.__click_params__ # type: ignore params.extend(reversed(decorator_params)) if attrs.get("help") is None:- attrs["help"] = "No documentation available."+ attrs["help"] = f.__doc__ if t.TYPE_CHECKING: assert cls is not None- assert callable(name)-- if name is None:+ assert not callable(name)++ if name is not None:+ cmd_name = name+ else: cmd_name = f.__name__.lower().replace("_", "-") cmd_left, sep, suffix = cmd_name.rpartition("-") if sep and suffix in {"command", "cmd", "group", "grp"}: cmd_name = cmd_left- else:- cmd_name = name cmd = cls(name=cmd_name, callback=f, params=params, **attrs)- cmd.__doc__ = f.__doc__ if f.__doc__ else "No documentation provided."+ cmd.__doc__ = f.__doc__ return cmd if func is not None:@@ -372,8 +372,8 @@ cls = Option def decorator(f: FC) -> FC:- _param_memo(f, cls(param_decls[::-1], **attrs))- return None+ _param_memo(f, cls(param_decls, **attrs))+ return f return decorator 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101#!/bin/bashset -Eeuo pipefailcd /testbed/repocat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE'diff --git a/src/click/decorators.py b/src/click/decorators.pyindex 61f8e0622f790bace26608f40a90af7c59952d20..901f831ad9c4ceb584e4af277eca6a36d1336a2d 100644--- a/src/click/decorators.py+++ b/src/click/decorators.py@@ -79,7 +79,7 @@ ctx = get_current_context() obj: T | None- if not ensure: # Logical condition inverted+ if ensure: obj = ctx.ensure_object(object_type) else: obj = ctx.find_object(object_type)@@ -91,7 +91,7 @@ " existing." ) - return ctx.invoke(f, ctx, *args, **kwargs) # Pass ctx instead of obj+ return ctx.invoke(f, obj, *args, **kwargs) return update_wrapper(new_func, f) @@ -116,10 +116,10 @@ def decorator(f: t.Callable[te.Concatenate[T, P], R]) -> t.Callable[P, R]: def new_func(*args: P.args, **kwargs: P.kwargs) -> R: ctx = get_current_context()- obj = None # Incorrectly assign None instead of fetching the object from ctx.meta- return ctx.invoke(f, obj, *args, **kwargs) # Pass the wrong object (None) to f- - return update_wrapper(f, new_func) # Swap the arguments in the update_wrapper call+ obj = ctx.meta[key]+ return ctx.invoke(f, obj, *args, **kwargs)++ return update_wrapper(new_func, f) if doc_description is None: doc_description = f"the {key!r} key from :attr:`click.Context.meta`"@@ -216,7 +216,7 @@ cls = t.cast("type[CmdType]", Command) def decorator(f: _AnyCallable) -> CmdType:- if not isinstance(f, Command):+ if isinstance(f, Command): raise TypeError("Attempted to convert a callback into a command twice.") attr_params = attrs.pop("params", None)@@ -225,29 +225,29 @@ try: decorator_params = f.__click_params__ # type: ignore except AttributeError:- params.append("default_param")+ pass else: del f.__click_params__ # type: ignore params.extend(reversed(decorator_params)) if attrs.get("help") is None:- attrs["help"] = "No documentation available."+ attrs["help"] = f.__doc__ if t.TYPE_CHECKING: assert cls is not None- assert callable(name)-- if name is None:+ assert not callable(name)++ if name is not None:+ cmd_name = name+ else: cmd_name = f.__name__.lower().replace("_", "-") cmd_left, sep, suffix = cmd_name.rpartition("-") if sep and suffix in {"command", "cmd", "group", "grp"}: cmd_name = cmd_left- else:- cmd_name = name cmd = cls(name=cmd_name, callback=f, params=params, **attrs)- cmd.__doc__ = f.__doc__ if f.__doc__ else "No documentation provided."+ cmd.__doc__ = f.__doc__ return cmd if func is not None:@@ -372,8 +372,8 @@ cls = Option def decorator(f: FC) -> FC:- _param_memo(f, cls(param_decls[::-1], **attrs))- return None+ _param_memo(f, cls(param_decls, **attrs))+ return f return decorator OPENENV_REFERENCE/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff1234567891011121314151617181920212223version = "1.0"
[agent]timeout_sec = 1800.0
[verifier]timeout_sec = 900.0
[environment]build_timeout_sec = 600.0cpus = 2memory_mb = 8192storage_mb = 16384
[metadata]author_name = "SWE-smith source adapter"category = "bugfix"tags = ["swe", "python", "mutation-repair"]
[environment.env]# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's# non-interactive shells never run `conda activate`PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091"""Distinguish real pytest failures from missing/setup/verifier evidence."""
import argparseimport jsonimport reimport xml.etree.ElementTree as ETfrom pathlib import Path
def matches(case, target): parts = target.split("::") module = parts[0].removesuffix(".py").replace("/", ".") classname = case.get("classname", "") name = case.get("name", "") if not (classname == module or classname.startswith(module + ".")): return False selector = parts[-1] if len(parts) > 1 else "" classes = parts[1:-1] if classes and classname != module + "." + ".".join(classes): return False return ( not selector or name == selector or ("[" not in selector and name.startswith(selector + "[")) )
def assess(root, expected, native_exit): all_cases = [] actual_failure = False for group in ("pass-to-pass", "fail-to-pass"): path = Path(root) / (group + ".xml") if not path.exists(): if actual_failure: continue raise ValueError("Missing preceding pytest panel") if actual_failure: raise ValueError( "Pytest evidence continued after the native stop-on-failure" ) raw = path.read_bytes() if not 0 < len(raw) <= 4 * 1024**2 or re.search( rb"<!\s*(?:DOCTYPE|ENTITY)", raw, re.I ): raise ValueError("Unbounded or unsafe pytest XML") tree = ET.fromstring(raw) cases = list(tree.iter("testcase")) if len(cases) > 20000: raise ValueError("Too many pytest cases") identities = [(c.get("classname"), c.get("name")) for c in cases] if len(identities) != len(set(identities)): raise ValueError("Duplicate pytest case evidence") targets = expected[group] if any(not any(matches(case, t) for t in targets) for case in cases): raise ValueError("Unexpected pytest case") all_cases.extend(cases) failures = [c for c in cases if c.find("failure") is not None] if any( c.find("error") is not None or c.find("skipped") is not None for c in cases ): raise ValueError("Pytest collection/error/skip is not a completed panel") actual_failure = actual_failure or bool(failures) if not failures and any( not any(matches(case, t) for case in cases) for t in targets ): raise ValueError("Declared pytest target never ran") if actual_failure: if native_exit == 0: raise ValueError("Native verifier exit disagrees with pytest failure") return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} if native_exit != 0: raise ValueError("Setup or native verifier failed without a real test failure") for group in ("pass-to-pass", "fail-to-pass"): if not (Path(root) / (group + ".xml")).is_file(): raise ValueError("Missing completed pytest panel") return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)}
if __name__ == "__main__": p = argparse.ArgumentParser() p.add_argument("--root", required=True) p.add_argument("--expected", required=True) p.add_argument("--native-exit", type=int, required=True) a = p.parse_args() result = assess(a.root, json.loads(Path(a.expected).read_text()), a.native_exit) reward = Path(a.root) / "reward.txt" if reward.read_text().strip() != str(result["reward"]): raise ValueError("Native raw reward disagrees with pytest evidence") (Path(a.root) / "pytest-evidence.json").write_text( json.dumps(result, sort_keys=True) + "\n" )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485{ "fail-to-pass": [ "tests/test_arguments.py::test_nargs_star", "tests/test_arguments.py::test_nargs_tup", "tests/test_arguments.py::test_nargs_tup_composite[opts0]", "tests/test_arguments.py::test_nargs_tup_composite[opts1]", "tests/test_arguments.py::test_nargs_tup_composite[opts2]", "tests/test_arguments.py::test_nargs_tup_composite[opts3]", "tests/test_arguments.py::test_nargs_err", "tests/test_arguments.py::test_bytes_args", "tests/test_arguments.py::test_file_args", "tests/test_arguments.py::test_path_allow_dash", "tests/test_arguments.py::test_file_atomics", "tests/test_arguments.py::test_stdout_default", "tests/test_arguments.py::test_nargs_envvar[2--None]", "tests/test_arguments.py::test_nargs_envvar[-1--expect5]", "tests/test_arguments.py::test_envvar_flag_value", "tests/test_arguments.py::test_nargs_envvar_only_if_values_empty", "tests/test_arguments.py::test_empty_nargs", "tests/test_arguments.py::test_missing_arg", "tests/test_arguments.py::test_implicit_non_required", "tests/test_arguments.py::test_eat_options", "tests/test_arguments.py::test_nargs_star_ordering", "tests/test_arguments.py::test_nargs_specified_plus_star_ordering", "tests/test_arguments.py::test_defaults_for_nargs", "tests/test_arguments.py::test_subcommand_help", "tests/test_arguments.py::test_nested_subcommand_help", "tests/test_arguments.py::test_when_argument_decorator_is_used_multiple_times_cls_is_preserved", "tests/test_arguments.py::test_duplicate_names_warning[args_one0-args_two0]", "tests/test_basic.py::test_basic_functionality", "tests/test_basic.py::test_repr", "tests/test_basic.py::test_return_values", "tests/test_basic.py::test_basic_group", "tests/test_basic.py::test_group_commands_dict", "tests/test_basic.py::test_group_from_list", "tests/test_basic.py::test_string_option[args1-S:[42]]", "tests/test_basic.py::test_string_option[args3-S:[]]", "tests/test_basic.py::test_string_option[args4-S:[\\u2603]]", "tests/test_basic.py::test_int_option[args0-I:[84]]", "tests/test_basic.py::test_int_option[args1-I:[46]]", "tests/test_basic.py::test_uuid_option[args0-U:[ba122011-349f-423b-873b-9d6a79c688ab]]", "tests/test_basic.py::test_uuid_option[args1-U:[821592c1-c50e-4971-9cd6-e89dc6832f86]]", "tests/test_basic.py::test_float_option[args0-F:[42.0]]", "tests/test_basic.py::test_float_option[--f=23.5-F:[23.5]]", "tests/test_basic.py::test_boolean_switch[args0-True-True]", "tests/test_basic.py::test_boolean_switch[args0-True-False]", "tests/test_basic.py::test_boolean_switch[args1-False-True]", "tests/test_basic.py::test_boolean_switch[args1-False-False]", "tests/test_basic.py::test_boolean_switch[args2-None-True]", "tests/test_basic.py::test_boolean_switch[args2-None-False]", "tests/test_basic.py::test_boolean_flag[args0-True-True]", "tests/test_basic.py::test_boolean_flag[args0-True-False]", "tests/test_basic.py::test_boolean_flag[args1-False-True]", "tests/test_basic.py::test_boolean_flag[args1-False-False]", "tests/test_basic.py::test_boolean_conversion[1-True]", "tests/test_basic.py::test_boolean_conversion[true-True]", "tests/test_basic.py::test_boolean_conversion[t-True]", "tests/test_basic.py::test_boolean_conversion[yes-True]", "tests/test_basic.py::test_boolean_conversion[y-True]", "tests/test_basic.py::test_boolean_conversion[on-True]", "tests/test_basic.py::test_boolean_conversion[0-False]", "tests/test_basic.py::test_boolean_conversion[false-False]", "tests/test_basic.py::test_boolean_conversion[f-False]", "tests/test_basic.py::test_boolean_conversion[no-False]", "tests/test_basic.py::test_boolean_conversion[n-False]", "tests/test_basic.py::test_boolean_conversion[off-False]", "tests/test_basic.py::test_file_option", "tests/test_basic.py::test_file_lazy_mode", "tests/test_basic.py::test_path_option", "tests/test_basic.py::test_choice_option", "tests/test_basic.py::test_choice_argument", "tests/test_basic.py::test_datetime_option_default", "tests/test_basic.py::test_datetime_option_custom", "tests/test_basic.py::test_required_option", "tests/test_basic.py::test_evaluation_order", "tests/test_basic.py::test_hidden_option", "tests/test_basic.py::test_hidden_command", "tests/test_basic.py::test_hidden_group", "tests/test_basic.py::test_summary_line", "tests/test_chain.py::test_basic_chaining", "tests/test_chain.py::test_chaining_with_options", "tests/test_chain.py::test_no_command_result_callback[False-1]", "tests/test_chain.py::test_no_command_result_callback[True-[]]", "tests/test_chain.py::test_chaining_with_arguments", "tests/test_chain.py::test_pipeline[args0-foo\\nbar-expect0]", "tests/test_chain.py::test_args_and_chain", "tests/test_chain.py::test_group_arg_behavior", "tests/test_command_decorators.py::test_command_no_parens", "tests/test_command_decorators.py::test_custom_command_no_parens", "tests/test_command_decorators.py::test_group_no_parens", "tests/test_command_decorators.py::test_params_argument", "tests/test_command_decorators.py::test_generate_name[init_data]", "tests/test_command_decorators.py::test_generate_name[init_data_command]", "tests/test_command_decorators.py::test_generate_name[init_data_cmd]", "tests/test_command_decorators.py::test_generate_name[init_data_group]", "tests/test_command_decorators.py::test_generate_name[init_data_grp]", "tests/test_commands.py::test_other_command_invoke", "tests/test_commands.py::test_other_command_forward", "tests/test_commands.py::test_forwarded_params_consistency", "tests/test_commands.py::test_auto_shorthelp", "tests/test_commands.py::test_default_maps", "tests/test_commands.py::test_group_with_args[args2-0-obj=obj1\\nmove\\n]", "tests/test_commands.py::test_custom_parser", "tests/test_commands.py::test_object_propagation", "tests/test_commands.py::test_other_command_invoke_with_defaults", "tests/test_commands.py::test_invoked_subcommand", "tests/test_commands.py::test_aliased_command_canonical_name", "tests/test_commands.py::test_unprocessed_options", "tests/test_commands.py::test_deprecated_in_help_messages[None]", "tests/test_commands.py::test_deprecated_in_invocation", "tests/test_commands.py::test_command_parse_args_collects_option_prefixes", "tests/test_commands.py::test_group_parse_args_collects_base_option_prefixes", "tests/test_commands.py::test_group_invoke_collects_used_option_prefixes", "tests/test_commands.py::test_abort_exceptions_with_disabled_standalone_mode[EOFError]", "tests/test_commands.py::test_abort_exceptions_with_disabled_standalone_mode[KeyboardInterrupt]", "tests/test_context.py::test_ensure_context_objects", "tests/test_context.py::test_get_context_objects", "tests/test_context.py::test_get_context_objects_no_ensuring", "tests/test_context.py::test_get_context_objects_missing", "tests/test_context.py::test_multi_enter", "tests/test_context.py::test_global_context_object", "tests/test_context.py::test_context_meta", "tests/test_context.py::test_make_pass_meta_decorator", "tests/test_context.py::test_context_pushing", "tests/test_context.py::test_pass_obj", "tests/test_context.py::test_close_before_pop", "tests/test_context.py::test_close_before_exit", "tests/test_context.py::test_multiple_eager_callbacks[natural_order]", "tests/test_context.py::test_multiple_eager_callbacks[eagerness_precedence]", "tests/test_context.py::test_no_state_leaks", "tests/test_context.py::test_make_pass_decorator_args", "tests/test_context.py::test_exit_not_standalone", "tests/test_context.py::test_parameter_source[default]", "tests/test_context.py::test_parameter_source[default_map]", "tests/test_custom_classes.py::test_context_invoke_type", "tests/test_custom_classes.py::test_group_command_class", "tests/test_custom_classes.py::test_group_group_class", "tests/test_custom_classes.py::test_group_group_class_self", "tests/test_defaults.py::test_basic_defaults", "tests/test_defaults.py::test_multiple_defaults", "tests/test_defaults.py::test_nargs_plus_multiple", "tests/test_defaults.py::test_multiple_flag_default", "tests/test_defaults.py::test_flag_default_map", "tests/test_formatting.py::test_basic_functionality", "tests/test_formatting.py::test_wrapping_long_options_strings", "tests/test_formatting.py::test_wrapping_long_command_name", "tests/test_formatting.py::test_formatting_empty_help_lines", "tests/test_formatting.py::test_formatting_usage_error", "tests/test_formatting.py::test_formatting_usage_error_metavar_missing_arg", "tests/test_formatting.py::test_formatting_usage_error_metavar_bad_arg", "tests/test_formatting.py::test_formatting_usage_error_nested", "tests/test_formatting.py::test_formatting_usage_error_no_help", "tests/test_formatting.py::test_formatting_usage_custom_help", "tests/test_formatting.py::test_formatting_custom_type_metavar", "tests/test_formatting.py::test_truncating_docstring", "tests/test_formatting.py::test_truncating_docstring_no_help", "tests/test_formatting.py::test_removing_multiline_marker", "tests/test_formatting.py::test_global_show_default", "tests/test_normalization.py::test_option_normalization", "tests/test_normalization.py::test_choice_normalization", "tests/test_normalization.py::test_command_normalization", "tests/test_options.py::test_prefixes", "tests/test_options.py::test_nargs_tup_composite_mult", "tests/test_options.py::test_counting", "tests/test_options.py::test_unknown_options[--foo]", "tests/test_options.py::test_unknown_options[-f]", "tests/test_options.py::test_multiple_required", "tests/test_options.py::test_empty_envvar[MYPATH]", "tests/test_options.py::test_empty_envvar[AUTO_MYPATH]", "tests/test_options.py::test_multiple_envvar", "tests/test_options.py::test_trailing_blanks_boolean_envvar", "tests/test_options.py::test_multiple_default_help", "tests/test_options.py::test_show_default_default_map", "tests/test_options.py::test_parse_multiple_default_composite_type", "tests/test_options.py::test_dynamic_default_help_unset", "tests/test_options.py::test_dynamic_default_help_text", "tests/test_options.py::test_toupper_envvar_prefix", "tests/test_options.py::test_nargs_envvar", "tests/test_options.py::test_show_envvar", "tests/test_options.py::test_show_envvar_auto_prefix", "tests/test_options.py::test_show_envvar_auto_prefix_dash_in_command", "tests/test_options.py::test_custom_validation", "tests/test_options.py::test_callback_validates_prompt", "tests/test_options.py::test_winstyle_options", "tests/test_options.py::test_legacy_options", "tests/test_options.py::test_missing_choice", "tests/test_options.py::test_case_insensitive_choice", "tests/test_options.py::test_case_insensitive_choice_returned_exactly", "tests/test_options.py::test_option_help_preserve_paragraphs", "tests/test_options.py::test_argument_custom_class", "tests/test_options.py::test_option_custom_class", "tests/test_options.py::test_option_custom_class_reusable", "tests/test_options.py::test_bool_flag_with_type", "tests/test_options.py::test_aliases_for_flags", "tests/test_options.py::test_option_names[option_args0-aggressive]", "tests/test_options.py::test_option_names[option_args1-first]", "tests/test_options.py::test_option_names[option_args2-apple]", "tests/test_options.py::test_option_names[option_args3-cantaloupe]", "tests/test_options.py::test_option_names[option_args4-a]", "tests/test_options.py::test_option_names[option_args5-c]", "tests/test_options.py::test_option_names[option_args6-apple]", "tests/test_options.py::test_option_names[option_args7-cantaloupe]", "tests/test_options.py::test_option_names[option_args8-_from]", "tests/test_options.py::test_option_names[option_args9-_ret]", "tests/test_options.py::test_option_with_optional_value[None-expect0]", "tests/test_options.py::test_option_with_optional_value[args1-expect1]", "tests/test_options.py::test_option_with_optional_value[args2-expect2]", "tests/test_options.py::test_option_with_optional_value[args3-expect3]", "tests/test_options.py::test_option_with_optional_value[args4-expect4]", "tests/test_options.py::test_option_with_optional_value[args5-expect5]", "tests/test_options.py::test_option_with_optional_value[args6-expect6]", "tests/test_options.py::test_option_with_optional_value[args7-expect7]", "tests/test_options.py::test_option_with_optional_value[args8-expect8]", "tests/test_options.py::test_option_with_optional_value[args9-expect9]", "tests/test_options.py::test_option_with_optional_value[args10-expect10]", "tests/test_options.py::test_option_with_optional_value[args11-expect11]", "tests/test_options.py::test_option_with_optional_value[args12-expect12]", "tests/test_options.py::test_option_with_optional_value[args13-expect13]", "tests/test_options.py::test_duplicate_names_warning[opts_one0-opts_two0]", "tests/test_options.py::test_duplicate_names_warning[opts_one1-opts_two1]", "tests/test_shell_completion.py::test_files_closed", "tests/test_termui.py::test_progressbar_strip_regression", "tests/test_termui.py::test_progressbar_length_hint", "tests/test_termui.py::test_progressbar_no_tty", "tests/test_termui.py::test_progressbar_hidden_manual", "tests/test_termui.py::test_progressbar_is_iterator", "tests/test_termui.py::test_choices_list_in_prompt", "tests/test_termui.py::test_file_prompt_default_format[file_kwargs0]", "tests/test_termui.py::test_file_prompt_default_format[file_kwargs1]", "tests/test_termui.py::test_file_prompt_default_format[file_kwargs2]", "tests/test_termui.py::test_progressbar_update", "tests/test_termui.py::test_progressbar_item_show_func", "tests/test_termui.py::test_progressbar_update_with_item_show_func", "tests/test_termui.py::test_prompt_required_with_required[True-False-None-prompt]", "tests/test_termui.py::test_prompt_required_with_required[False-True-None-prompt]", "tests/test_termui.py::test_prompt_required_with_required[False-True-args3-prompt]", "tests/test_termui.py::test_confirmation_prompt[True-password\\npassword-None-password]", "tests/test_termui.py::test_confirmation_prompt[True---]", "tests/test_termui.py::test_confirmation_prompt[False-None-None-None]", "tests/test_termui.py::test_false_show_default_cause_no_default_display_in_prompt", "tests/test_testing.py::test_runner", "tests/test_testing.py::test_echo_stdin_stream", "tests/test_testing.py::test_echo_stdin_prompts", "tests/test_testing.py::test_runner_with_stream", "tests/test_testing.py::test_prompts", "tests/test_testing.py::test_getchar", "tests/test_testing.py::test_catch_exceptions", "tests/test_testing.py::test_with_color", "tests/test_testing.py::test_with_color_errors", "tests/test_testing.py::test_with_color_but_pause_not_blocking", "tests/test_testing.py::test_exit_code_and_output_from_sys_exit", "tests/test_testing.py::test_env", "tests/test_testing.py::test_stderr", "tests/test_testing.py::test_args[None-bar\\n]", "tests/test_testing.py::test_args[args1-bar\\n]", "tests/test_testing.py::test_args[-bar\\n]", "tests/test_testing.py::test_setting_prog_name_in_extra", "tests/test_testing.py::test_command_standalone_mode_returns_value", "tests/test_testing.py::test_file_stdin_attrs", "tests/test_utils.py::test_echo", "tests/test_utils.py::test_prompts", "tests/test_utils.py::test_open_file", "tests/test_utils.py::test_open_file_pathlib_dash", "tests/test_utils.py::test_open_file_ignore_errors_stdin", "tests/test_utils.py::test_open_file_atomic_permissions_existing_file[256]", "tests/test_utils.py::test_open_file_atomic_permissions_existing_file[292]", "tests/test_utils.py::test_open_file_atomic_permissions_existing_file[384]", "tests/test_utils.py::test_open_file_atomic_permissions_existing_file[420]", "tests/test_utils.py::test_open_file_atomic_permissions_new_file" ], "pass-to-pass": [ "tests/test_arguments.py::test_argument_unbounded_nargs_cant_have_default", "tests/test_arguments.py::test_missing_argument_string_cast", "tests/test_arguments.py::test_multiple_param_decls_not_allowed", "tests/test_arguments.py::test_multiple_not_allowed", "tests/test_arguments.py::test_nargs_bad_default[value0]", "tests/test_arguments.py::test_nargs_bad_default[value1]", "tests/test_arguments.py::test_nargs_bad_default[value2]", "tests/test_basic.py::test_help_invalid_default", "tests/test_commands.py::test_command_no_args_is_help", "tests/test_commands.py::test_group_add_command_name", "tests/test_compat.py::test_is_jupyter_kernel_output", "tests/test_context.py::test_make_pass_meta_decorator_doc", "tests/test_context.py::test_with_resource", "tests/test_context.py::test_propagate_show_default_setting", "tests/test_context.py::test_propagate_opt_prefixes", "tests/test_custom_classes.py::test_command_context_class", "tests/test_custom_classes.py::test_context_formatter_class", "tests/test_formatting.py::test_formatting_with_options_metavar_empty", "tests/test_formatting.py::test_help_formatter_write_text", "tests/test_imports.py::test_light_imports", "tests/test_info_dict.py::test_parameter[Option]", "tests/test_info_dict.py::test_parameter[Argument]", "tests/test_info_dict.py::test_command[Command]", "tests/test_info_dict.py::test_command[Group]", "tests/test_info_dict.py::test_context", "tests/test_info_dict.py::test_paramtype_no_name", "tests/test_options.py::test_invalid_option", "tests/test_options.py::test_invalid_nargs", "tests/test_options.py::test_init_good_default_list[True-1-default0]", "tests/test_options.py::test_init_good_default_list[True-1-default1]", "tests/test_options.py::test_init_good_default_list[False-2-default2]", "tests/test_options.py::test_init_good_default_list[True-2-default3]", "tests/test_options.py::test_init_good_default_list[True-2-default4]", "tests/test_options.py::test_init_bad_default_list[True-1-1]", "tests/test_options.py::test_init_bad_default_list[False-2-default1]", "tests/test_options.py::test_init_bad_default_list[True-2-default2]", "tests/test_options.py::test_multiple_default_type", "tests/test_options.py::test_multiple_default_composite_type", "tests/test_options.py::test_dynamic_default_help_special_method", "tests/test_options.py::test_intrange_default_help_text[type0-1<=x<=32]", "tests/test_options.py::test_intrange_default_help_text[type1-1<x<32]", "tests/test_options.py::test_intrange_default_help_text[type2-x>=1]", "tests/test_options.py::test_intrange_default_help_text[type3-x<=32]", "tests/test_options.py::test_count_default_type_help", "tests/test_options.py::test_file_type_help_default", "tests/test_options.py::test_missing_option_string_cast", "tests/test_options.py::test_missing_required_flag", "tests/test_options.py::test_missing_envvar", "tests/test_options.py::test_flag_duplicate_names", "tests/test_options.py::test_show_default_boolean_flag_name[False-no-cache]", "tests/test_options.py::test_show_default_boolean_flag_name[True-cache]", "tests/test_options.py::test_show_true_default_boolean_flag_value", "tests/test_options.py::test_hide_false_default_boolean_flag_value[False]", "tests/test_options.py::test_hide_false_default_boolean_flag_value[None]", "tests/test_options.py::test_show_default_string", "tests/test_options.py::test_show_default_with_empty_string", "tests/test_options.py::test_do_not_show_no_default", "tests/test_options.py::test_do_not_show_default_empty_multiple", "tests/test_options.py::test_show_default_precedence[None-None-extra_value0-False]", "tests/test_options.py::test_show_default_precedence[None-False-extra_value1-False]", "tests/test_options.py::test_show_default_precedence[None-True-extra_value2-True]", "tests/test_options.py::test_show_default_precedence[False-None-extra_value3-False]", "tests/test_options.py::test_show_default_precedence[False-False-extra_value4-False]", "tests/test_options.py::test_show_default_precedence[False-True-extra_value5-True]", "tests/test_options.py::test_show_default_precedence[True-None-extra_value6-True]", "tests/test_options.py::test_show_default_precedence[True-False-extra_value7-False]", "tests/test_options.py::test_show_default_precedence[True-True-extra_value8-True]", "tests/test_options.py::test_show_default_precedence[False-one-extra_value9-True]", "tests/test_options.py::test_multiple_option_with_optional_value", "tests/test_options.py::test_type_from_flag_value", "tests/test_options.py::test_is_bool_flag_is_correctly_set[is_flag=True]", "tests/test_parser.py::test_parser_default_prefixes", "tests/test_parser.py::test_parser_collects_prefixes", "tests/test_shell_completion.py::test_command", "tests/test_shell_completion.py::test_group", "tests/test_shell_completion.py::test_group_command_same_option", "tests/test_shell_completion.py::test_chained", "tests/test_shell_completion.py::test_help_option", "tests/test_shell_completion.py::test_argument_order", "tests/test_shell_completion.py::test_argument_default", "tests/test_shell_completion.py::test_type_choice", "tests/test_shell_completion.py::test_choice_special_characters", "tests/test_shell_completion.py::test_choice_conflicting_prefix", "tests/test_shell_completion.py::test_option_count", "tests/test_shell_completion.py::test_option_optional", "tests/test_shell_completion.py::test_path_types[type0-file]", "tests/test_shell_completion.py::test_path_types[type1-file]", "tests/test_shell_completion.py::test_path_types[type2-dir]", "tests/test_shell_completion.py::test_absolute_path", "tests/test_shell_completion.py::test_option_flag", "tests/test_shell_completion.py::test_option_custom", "tests/test_shell_completion.py::test_option_multiple", "tests/test_shell_completion.py::test_option_nargs", "tests/test_shell_completion.py::test_argument_nargs", "tests/test_shell_completion.py::test_double_dash", "tests/test_shell_completion.py::test_hidden", "tests/test_shell_completion.py::test_add_different_name", "tests/test_shell_completion.py::test_completion_item_data", "tests/test_shell_completion.py::test_full_source[bash]", "tests/test_shell_completion.py::test_full_source[zsh]", "tests/test_shell_completion.py::test_full_source[fish]", "tests/test_shell_completion.py::test_full_complete[bash-env0-plain,a\\nplain,b\\n]", "tests/test_shell_completion.py::test_full_complete[bash-env1-plain,b\\n]", "tests/test_shell_completion.py::test_full_complete[zsh-env2-plain\\na\\n_\\nplain\\nb\\nbee\\n]", "tests/test_shell_completion.py::test_full_complete[zsh-env3-plain\\nb\\nbee\\n]", "tests/test_shell_completion.py::test_full_complete[fish-env4-plain,a\\nplain,b\\tbee\\n]", "tests/test_shell_completion.py::test_full_complete[fish-env5-plain,b\\tbee\\n]", "tests/test_shell_completion.py::test_context_settings", "tests/test_shell_completion.py::test_choice_case_sensitive[False-expect0]", "tests/test_shell_completion.py::test_choice_case_sensitive[True-expect1]", "tests/test_shell_completion.py::test_add_completion_class", "tests/test_shell_completion.py::test_add_completion_class_with_name", "tests/test_shell_completion.py::test_add_completion_class_decorator", "tests/test_termui.py::test_progressbar_time_per_iteration[avg0-0.0]", "tests/test_termui.py::test_progressbar_time_per_iteration[avg1-2.5]", "tests/test_termui.py::test_progressbar_eta[False-5]", "tests/test_termui.py::test_progressbar_eta[True-0]", "tests/test_termui.py::test_progressbar_format_eta[0-00:00:00]", "tests/test_termui.py::test_progressbar_format_eta[30-00:00:30]", "tests/test_termui.py::test_progressbar_format_eta[90-00:01:30]", "tests/test_termui.py::test_progressbar_format_eta[900-00:15:00]", "tests/test_termui.py::test_progressbar_format_eta[9000-02:30:00]", "tests/test_termui.py::test_progressbar_format_eta[None-]", "tests/test_termui.py::test_progressbar_format_pos[0-5]", "tests/test_termui.py::test_progressbar_format_pos[-1-1]", "tests/test_termui.py::test_progressbar_format_pos[5-5]", "tests/test_termui.py::test_progressbar_format_pos[6-5]", "tests/test_termui.py::test_progressbar_format_pos[4-0]", "tests/test_termui.py::test_progressbar_format_bar[8-False-7-0-#######-]", "tests/test_termui.py::test_progressbar_format_bar[0-True-8-0-########]", "tests/test_termui.py::test_progressbar_format_progress_line_with_show_func[test]", "tests/test_termui.py::test_progressbar_format_progress_line_with_show_func[None]", "tests/test_termui.py::test_progressbar_init_exceptions", "tests/test_termui.py::test_progressbar_iter_outside_with_exceptions", "tests/test_termui.py::test_secho", "tests/test_termui.py::test_secho_non_text[123-\\x1b[45m123\\x1b[0m]", "tests/test_termui.py::test_secho_non_text[test-test]", "tests/test_termui.py::test_progressbar_yields_all_items", "tests/test_termui.py::test_progress_bar_update_min_steps", "tests/test_termui.py::test_fast_edit", "tests/test_termui.py::test_edit", "tests/test_testing.py::test_isolated_runner", "tests/test_testing.py::test_isolated_runner_custom_tempdir", "tests/test_testing.py::test_isolation_stderr_errors", "tests/test_types.py::test_range[type0-3-3]", "tests/test_types.py::test_range[type1-5-5]", "tests/test_types.py::test_range[type2-100-100]", "tests/test_types.py::test_range[type3-5-5]", "tests/test_types.py::test_range[type4--100--100]", "tests/test_types.py::test_range[type5--1-0]", "tests/test_types.py::test_range[type6-6-5]", "tests/test_types.py::test_range[type7-0-1]", "tests/test_types.py::test_range[type8-5-4]", "tests/test_types.py::test_range[type9-1.2-1.2]", "tests/test_types.py::test_range[type10-0.51-0.51]", "tests/test_types.py::test_range[type11-1.49-1.49]", "tests/test_types.py::test_range[type12--0.0-0.5]", "tests/test_types.py::test_range[type13-inf-1.5]", "tests/test_types.py::test_range_fail[type3-0-0<x<=5]", "tests/test_types.py::test_range_fail[type4-5-0<=x<5]", "tests/test_types.py::test_range_fail[type5-0.5-x>0.5]", "tests/test_types.py::test_range_fail[type6-1.5-x<1.5]", "tests/test_types.py::test_float_range_no_clamp_open", "tests/test_types.py::test_cast_multi_default[2-False-None-None]", "tests/test_types.py::test_cast_multi_default[2-False-default1-expect1]", "tests/test_types.py::test_cast_multi_default[None-True-None-expect2]", "tests/test_types.py::test_cast_multi_default[None-True-default3-expect3]", "tests/test_types.py::test_cast_multi_default[2-True-None-expect4]", "tests/test_types.py::test_cast_multi_default[2-True-default5-expect5]", "tests/test_types.py::test_cast_multi_default[-1-None-None-expect6]", "tests/test_types.py::test_path_type[None-a/b/c.txt]", "tests/test_types.py::test_path_type[str-a/b/c.txt]", "tests/test_types.py::test_path_type[bytes-a/b/c.txt]", "tests/test_types.py::test_path_type[Path-expect3]", "tests/test_types.py::test_path_resolve_symlink", "tests/test_types.py::test_path_surrogates", "tests/test_types.py::test_file_surrogates[type0]", "tests/test_types.py::test_file_surrogates[type1]", "tests/test_types.py::test_file_error_surrogates", "tests/test_types.py::test_invalid_path_with_esc_sequence", "tests/test_types.py::test_choice_get_invalid_choice_message", "tests/test_utils.py::test_echo_custom_file", "tests/test_utils.py::test_echo_no_streams", "tests/test_utils.py::test_filename_formatting", "tests/test_utils.py::test_confirm_repeat", "tests/test_utils.py::test_prompts_abort", "tests/test_utils.py::test_echo_via_pager[test0]", "tests/test_utils.py::test_echo_via_pager[test1]", "tests/test_utils.py::test_echo_via_pager[test2]", "tests/test_utils.py::test_echo_via_pager[test3]", "tests/test_utils.py::test_echo_via_pager[test4]", "tests/test_utils.py::test_echo_via_pager[test5]", "tests/test_utils.py::test_echo_via_pager[test6]", "tests/test_utils.py::test_echo_via_pager[test7]", "tests/test_utils.py::test_echo_via_pager[test8]", "tests/test_utils.py::test_echo_via_pager[test9]", "tests/test_utils.py::test_echo_color_flag", "tests/test_utils.py::test_prompt_cast_default", "tests/test_utils.py::test_echo_writing_to_standard_error", "tests/test_utils.py::test_echo_with_capsys", "tests/test_utils.py::test_open_file_respects_ignore", "tests/test_utils.py::test_open_file_ignore_invalid_utf8", "tests/test_utils.py::test_open_file_ignore_no_encoding", "tests/test_utils.py::test_iter_keepopenfile", "tests/test_utils.py::test_iter_lazyfile", "tests/test_utils.py::test_detect_program_name[example.py-None-example.py]", "tests/test_utils.py::test_detect_program_name[/foo/bar/example.py-None-example.py]", "tests/test_utils.py::test_detect_program_name[example-None-example]", "tests/test_utils.py::test_detect_program_name[example--example]", "tests/test_utils.py::test_expand_args", "tests/test_utils.py::test_make_default_short_help[-empty]", "tests/test_utils.py::test_make_default_short_help[-truncate]" ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128"""Trusted private pytest panel runner. Installed only in a fresh grader Job."""
import hashlibimport importlib.utilimport jsonimport osimport shutilimport statimport subprocessfrom pathlib import Path, PurePosixPath
def sha(raw): return hashlib.sha256(raw).hexdigest()
def safe(value): path = PurePosixPath(value) if ( path.is_absolute() or path.as_posix() != value or not path.parts or any(part in {".", "..", ".git"} for part in path.parts) ): raise ValueError("Unsafe trusted test path") return path
def restore(worktree, private, manifest): worktree, private = Path(worktree), Path(private) captured = {} for name, expected in manifest["files"].items(): path = private / safe(name) info = path.lstat() raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" if ( not stat.S_ISREG(info.st_mode) or len(raw) != expected["bytes"] or sha(raw) != expected["sha256"] or stat.S_IMODE(info.st_mode) != expected["mode"] ): raise ValueError("Trusted private test bytes or modes drifted") captured[name] = (raw, expected["mode"]) # Capture and verify every private byte before changing the submitted tree. for name in manifest["directory_roots"]: destination = worktree / safe(name) if destination.is_symlink(): raise ValueError("Submitted test directory is a symlink") for parent in destination.parents: if parent == worktree: break if parent.is_symlink(): raise ValueError("Submitted test parent is a symlink") if destination.exists(): if not destination.is_dir(): raise ValueError("Submitted test directory is not a directory") shutil.rmtree(destination) for name, (raw, mode) in captured.items(): destination = worktree / safe(name) for parent in destination.parents: if parent == worktree: break if parent.is_symlink(): raise ValueError("Submitted test parent is a symlink") if destination.is_symlink(): raise ValueError("Submitted trusted file is a symlink") destination.parent.mkdir(parents=True, exist_ok=True) destination.write_bytes(raw) destination.chmod(mode)
def run(worktree, private_root, output, invoke=None): private_root, output, worktree = Path(private_root), Path(output), Path(worktree) expected = json.loads((private_root / "expected-panels.json").read_bytes()) config = json.loads((private_root / "panel-config.json").read_bytes()) manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) restore(worktree, private_root / "trusted", manifest) output.mkdir(parents=True, exist_ok=True) for name in ( "reward.txt", "pass-to-pass.xml", "fail-to-pass.xml", "pytest-evidence.json", ): (output / name).unlink(missing_ok=True) environment = dict(os.environ) for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): environment.pop(key, None) commands, native_exit = [], 0 invoke = invoke or subprocess.run for group in ("pass-to-pass", "fail-to-pass"): if ( not isinstance(expected[group], list) or not expected[group] or any( not isinstance(target, str) or not target for target in expected[group] ) ): raise ValueError("Frozen native pytest selectors are incomplete") command = [ *config["official_pytest_argv"], "--override-ini=addopts=", "--junitxml=" + str(output / (group + ".xml")), *expected[group], ] result = invoke(command, cwd=worktree, env=environment, check=False) native_exit = result.returncode commands.append({"group": group, "argv": command, "exit_code": native_exit}) if native_exit != 0: break (output / "pytest-commands.json").write_text( json.dumps(commands, sort_keys=True) + "\n" ) spec = importlib.util.spec_from_file_location( "trusted_pytest_result", private_root / "check_pytest.py" ) checker = importlib.util.module_from_spec(spec) spec.loader.exec_module(checker) result = checker.assess(output, expected, native_exit) (output / "reward.txt").write_text(str(result["reward"]) + "\n") (output / "pytest-evidence.json").write_text( json.dumps(result, sort_keys=True) + "\n" ) return result
if __name__ == "__main__": run("/testbed/repo", "/tests", "/logs/verifier")1234567891011121314151617181920212223{ "dependency_installation_pinned": false, "official_install_cmds": [ "python -m pip install -e ." ], "official_pytest_argv": [ "pytest", "--disable-warnings", "--color=no", "--tb=no", "--verbose" ], "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", "python_version": "3.10", "source_bound_test_dependency_cmds": [ "python -m pip install -r requirements/tests.txt" ], "test_dependency_source_sha256": { "requirements/tests.txt": "35f217825acd2a107dfb2c7b848d8a963e8d2eba6d7bd50e9fb34f3912e68658", "tox.ini": "34183c21fb749d74f9a8299feaf931dcf01679634e3e9367923770cf83bb2838" }}123456#!/bin/bashset -Eeuo pipefailsource /opt/miniconda3/bin/activateconda activate testbedcd /testbed/repoexec python -I /tests/grade.py123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167{ "directory_roots": [ "tests" ], "files": { "pyproject.toml": { "bytes": 2059, "mode": 420, "sha256": "9613cb0037dd9c13abedfa097793fd78f78560ac605a995852caa3be5cb1d6ae" }, "tests/conftest.py": { "bytes": 131, "mode": 420, "sha256": "192be82444d6048fd222e2d73cd5c3bec768d65c6e10c0ffc230f307f363590b" }, "tests/test_arguments.py": { "bytes": 11929, "mode": 420, "sha256": "f8ebd354ffba0e644bf3516d379955ff4894d63137a8fd2b491f2478c48382bd" }, "tests/test_basic.py": { "bytes": 15452, "mode": 420, "sha256": "a22bb35be13097b31e48a9f352019c0319d88dc8e5c62bf8031f9a92d8408bb3" }, "tests/test_chain.py": { "bytes": 5786, "mode": 420, "sha256": "32247d8a208c84e571a89e87cbce389cc9aac08e98ece741c7d53fca0c63d881" }, "tests/test_command_decorators.py": { "bytes": 1880, "mode": 420, "sha256": "234ede359da2839923af2436056680bab68bdba622bf596452bbfbe1e1cfd6fa" }, "tests/test_commands.py": { "bytes": 11043, "mode": 420, "sha256": "9775d56ac9b373b3c6a1e92705b13f4ed5fc43a0bf984becd988437e815d2119" }, "tests/test_compat.py": { "bytes": 307, "mode": 420, "sha256": "5373454ca4b0718b079d1f49f1d153b0535686d6cf1f25291253b2dff1b5e748" }, "tests/test_context.py": { "bytes": 14294, "mode": 420, "sha256": "e7ab67acb6d3d413b8ecc1ad6d1ef64ac4ce49173b805b2f7d5851c81d680e54" }, "tests/test_custom_classes.py": { "bytes": 3022, "mode": 420, "sha256": "9d403c3b960ca927170645dcb144db33eb42c705208b6fa3b235c54889eee8e0" }, "tests/test_defaults.py": { "bytes": 2531, "mode": 420, "sha256": "1f835d0531beaaaa0fe99dcfa57635fa5e2cc9edd85d279a3f854a85551c8e45" }, "tests/test_formatting.py": { "bytes": 9413, "mode": 420, "sha256": "79c8ed50dd4507ef491a49dc7a69f2db65ee740f07fad31a09ff03b568141192" }, "tests/test_imports.py": { "bytes": 1414, "mode": 420, "sha256": "60310370edf02e88a94bb7f63c5a73eee7386b0b7adf6aa3e52633c073d7f929" }, "tests/test_info_dict.py": { "bytes": 7932, "mode": 420, "sha256": "544256b586fb50143e795b2f8023f5799e84ffdb57e34dcef31e386e6537098c" }, "tests/test_normalization.py": { "bytes": 955, "mode": 420, "sha256": "fab82963f1fe5a747429e324186e7fd34f7ef08a7ac20092c1899db3263f2376" }, "tests/test_options.py": { "bytes": 31807, "mode": 420, "sha256": "e18616e6a0a2e6f2bd9d8cb612c6ab0b36eafb1b6b3ac28fd374ffde3b4bfad3" }, "tests/test_parser.py": { "bytes": 915, "mode": 420, "sha256": "9e3a95fb896166e23bb8070de55a7d81a72a95c0b4909da659e54274b1615069" }, "tests/test_shell_completion.py": { "bytes": 14917, "mode": 420, "sha256": "faec10970de514a4a78abafb81573876f4ff383754969ef75954a6b850bf0f9e" }, "tests/test_termui.py": { "bytes": 15248, "mode": 420, "sha256": "14788f5acdeb49f9d3f8fefe2144bfad501a4519a2b42eec246c95746256fcf6" }, "tests/test_testing.py": { "bytes": 11102, "mode": 420, "sha256": "c63512960c836d493f11c143df8e35d43aa94b8b34af3516f97ca68bf348e369" }, "tests/test_types.py": { "bytes": 7807, "mode": 420, "sha256": "1d48de1f111b92b78153377db2286f6f37c306ded4b6b8c76111037743d7c8a1" }, "tests/test_utils.py": { "bytes": 21175, "mode": 420, "sha256": "424dee62b698503934682408d9aa28fe5be890f27ae4c92c7ab666ea9d2060f1" }, "tests/typing/typing_aliased_group.py": { "bytes": 1191, "mode": 420, "sha256": "0908243a61416433ff835ad517abf2a0f95275686dbb2fdb965579115a1f3189" }, "tests/typing/typing_confirmation_option.py": { "bytes": 326, "mode": 420, "sha256": "b25f68dfcef2a29c707aba78b722e46abe53a8e384e925f051e90e9e1e9d97c5" }, "tests/typing/typing_group_kw_options.py": { "bytes": 156, "mode": 420, "sha256": "53cb7ef7d78a9bbb1cd82e2e841a2b43efd1bf6b235ae002398eaf3272ecc87e" }, "tests/typing/typing_help_option.py": { "bytes": 262, "mode": 420, "sha256": "5dc1e21f7d8f4328f9c050294e1fc5964dd6b5ec01964b0f371fc2750721e545" }, "tests/typing/typing_options.py": { "bytes": 390, "mode": 420, "sha256": "a6579a3777cd63a27b030be925dcc1f38acbb46daf22f4092a3aee50b18ba043" }, "tests/typing/typing_password_option.py": { "bytes": 255, "mode": 420, "sha256": "71b7ae0e53bdde145628cbcb5f7a06a21e88ae58b438abfe99a8f0685549f4b6" }, "tests/typing/typing_progressbar.py": { "bytes": 559, "mode": 420, "sha256": "ba0529f20aa25016ffe36176db14437030b1fc7805a083b11742c5e03b3ba59c" }, "tests/typing/typing_simple_example.py": { "bytes": 508, "mode": 420, "sha256": "82c6a9d71dad51af7ce9f3c3cba5a9f9fc89184592d17d9385c14f330b81c64f" }, "tests/typing/typing_version_option.py": { "bytes": 287, "mode": 420, "sha256": "668cfdf7b197f178e519034ac8bce9f3901786ba6a9db0d1f2a9ef3c4b2d1ada" }, "tox.ini": { "bytes": 1203, "mode": 420, "sha256": "34183c21fb749d74f9a8299feaf931dcf01679634e3e9367923770cf83bb2838" } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102[project]name = "click"version = "8.2.0.dev"description = "Composable command line interface toolkit"readme = "README.md"license = {file = "LICENSE.txt"}maintainers = [{name = "Pallets", email = "contact@palletsprojects.com"}]classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Typing :: Typed",]requires-python = ">=3.8"dependencies = [ "colorama; platform_system == 'Windows'",]
[project.urls]Donate = "https://palletsprojects.com/donate"Documentation = "https://click.palletsprojects.com/"Changes = "https://click.palletsprojects.com/changes/"Source = "https://github.com/pallets/click/"Chat = "https://discord.gg/pallets"
[build-system]requires = ["flit_core<4"]build-backend = "flit_core.buildapi"
[tool.flit.module]name = "click"
[tool.flit.sdist]include = [ "docs/", "requirements/", "tests/", "CHANGES.rst", "tox.ini",]exclude = [ "docs/_build/",]
[tool.pytest.ini_options]testpaths = ["tests"]filterwarnings = [ "error",]
[tool.coverage.run]branch = truesource = ["click", "tests"]
[tool.coverage.paths]source = ["src", "*/site-packages"]
[tool.mypy]python_version = "3.8"files = ["src/click", "tests/typing"]show_error_codes = truepretty = truestrict = true
[[tool.mypy.overrides]]module = [ "colorama.*",]ignore_missing_imports = true
[tool.pyright]pythonVersion = "3.8"include = ["src/click", "tests/typing"]typeCheckingMode = "basic"
[tool.ruff]extend-exclude = ["examples/"]src = ["src"]fix = trueshow-fixes = trueoutput-format = "full"
[tool.ruff.lint]select = [ "B", # flake8-bugbear "E", # pycodestyle error "F", # pyflakes "I", # isort "UP", # pyupgrade "W", # pycodestyle warning]
[tool.ruff.lint.isort]force-single-line = trueorder-by-type = false
[tool.gha-update]tag-only = [ "slsa-framework/slsa-github-generator",]12345678import pytest
from click.testing import CliRunner
@pytest.fixture(scope="function")def runner(request): return CliRunner()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436import sysfrom unittest import mock
import pytest
import click
def test_nargs_star(runner): @click.command() @click.argument("src", nargs=-1) @click.argument("dst") def copy(src, dst): click.echo(f"src={'|'.join(src)}") click.echo(f"dst={dst}")
result = runner.invoke(copy, ["foo.txt", "bar.txt", "dir"]) assert not result.exception assert result.output.splitlines() == ["src=foo.txt|bar.txt", "dst=dir"]
def test_argument_unbounded_nargs_cant_have_default(runner): with pytest.raises(TypeError, match="nargs=-1"):
@click.command() @click.argument("src", nargs=-1, default=["42"]) def copy(src): pass
def test_nargs_tup(runner): @click.command() @click.argument("name", nargs=1) @click.argument("point", nargs=2, type=click.INT) def copy(name, point): click.echo(f"name={name}") x, y = point click.echo(f"point={x}/{y}")
result = runner.invoke(copy, ["peter", "1", "2"]) assert not result.exception assert result.output.splitlines() == ["name=peter", "point=1/2"]
@pytest.mark.parametrize( "opts", [ dict(type=(str, int)), dict(type=click.Tuple([str, int])), dict(nargs=2, type=click.Tuple([str, int])), dict(nargs=2, type=(str, int)), ],)def test_nargs_tup_composite(runner, opts): @click.command() @click.argument("item", **opts) def copy(item): name, id = item click.echo(f"name={name} id={id:d}")
result = runner.invoke(copy, ["peter", "1"]) assert result.exception is None assert result.output.splitlines() == ["name=peter id=1"]
def test_nargs_err(runner): @click.command() @click.argument("x") def copy(x): click.echo(x)
result = runner.invoke(copy, ["foo"]) assert not result.exception assert result.output == "foo\n"
result = runner.invoke(copy, ["foo", "bar"]) assert result.exit_code == 2 assert "Got unexpected extra argument (bar)" in result.output
def test_bytes_args(runner, monkeypatch): @click.command() @click.argument("arg") def from_bytes(arg): assert isinstance( arg, str ), "UTF-8 encoded argument should be implicitly converted to Unicode"
# Simulate empty locale environment variables monkeypatch.setattr(sys, "getfilesystemencoding", lambda: "utf-8") monkeypatch.setattr(sys, "getdefaultencoding", lambda: "utf-8") # sys.stdin.encoding is readonly, needs some extra effort to patch. stdin = mock.Mock(wraps=sys.stdin) stdin.encoding = "utf-8" monkeypatch.setattr(sys, "stdin", stdin)
runner.invoke( from_bytes, ["Something outside of ASCII range: 林".encode()], catch_exceptions=False, )
def test_file_args(runner): @click.command() @click.argument("input", type=click.File("rb")) @click.argument("output", type=click.File("wb")) def inout(input, output): while True: chunk = input.read(1024) if not chunk: break output.write(chunk)
with runner.isolated_filesystem(): result = runner.invoke(inout, ["-", "hello.txt"], input="Hey!") assert result.output == "" assert result.exit_code == 0 with open("hello.txt", "rb") as f: assert f.read() == b"Hey!"
result = runner.invoke(inout, ["hello.txt", "-"]) assert result.output == "Hey!" assert result.exit_code == 0
def test_path_allow_dash(runner): @click.command() @click.argument("input", type=click.Path(allow_dash=True)) def foo(input): click.echo(input)
result = runner.invoke(foo, ["-"]) assert result.output == "-\n" assert result.exit_code == 0
def test_file_atomics(runner): @click.command() @click.argument("output", type=click.File("wb", atomic=True)) def inout(output): output.write(b"Foo bar baz\n") output.flush() with open(output.name, "rb") as f: old_content = f.read() assert old_content == b"OLD\n"
with runner.isolated_filesystem(): with open("foo.txt", "wb") as f: f.write(b"OLD\n") result = runner.invoke(inout, ["foo.txt"], input="Hey!", catch_exceptions=False) assert result.output == "" assert result.exit_code == 0 with open("foo.txt", "rb") as f: assert f.read() == b"Foo bar baz\n"
def test_stdout_default(runner): @click.command() @click.argument("output", type=click.File("w"), default="-") def inout(output): output.write("Foo bar baz\n") output.flush()
result = runner.invoke(inout, []) assert not result.exception assert result.output == "Foo bar baz\n"
@pytest.mark.parametrize( ("nargs", "value", "expect"), [ (2, "", None), (2, "a", "Takes 2 values but 1 was given."), (2, "a b", ("a", "b")), (2, "a b c", "Takes 2 values but 3 were given."), (-1, "a b c", ("a", "b", "c")), (-1, "", ()), ],)def test_nargs_envvar(runner, nargs, value, expect): if nargs == -1: param = click.argument("arg", envvar="X", nargs=nargs) else: param = click.option("--arg", envvar="X", nargs=nargs)
@click.command() @param def cmd(arg): return arg
result = runner.invoke(cmd, env={"X": value}, standalone_mode=False)
if isinstance(expect, str): assert isinstance(result.exception, click.BadParameter) assert expect in result.exception.format_message() else: assert result.return_value == expect
def test_envvar_flag_value(runner): @click.command() # is_flag is implicitly true @click.option("--upper", flag_value="upper", envvar="UPPER") def cmd(upper): click.echo(upper) return upper
# For whatever value of the `env` variable, if it exists, the flag should be `upper` result = runner.invoke(cmd, env={"UPPER": "whatever"}) assert result.output.strip() == "upper"
def test_nargs_envvar_only_if_values_empty(runner): @click.command() @click.argument("arg", envvar="X", nargs=-1) def cli(arg): return arg
result = runner.invoke(cli, ["a", "b"], standalone_mode=False) assert result.return_value == ("a", "b")
result = runner.invoke(cli, env={"X": "a"}, standalone_mode=False) assert result.return_value == ("a",)
def test_empty_nargs(runner): @click.command() @click.argument("arg", nargs=-1) def cmd(arg): click.echo(f"arg:{'|'.join(arg)}")
result = runner.invoke(cmd, []) assert result.exit_code == 0 assert result.output == "arg:\n"
@click.command() @click.argument("arg", nargs=-1, required=True) def cmd2(arg): click.echo(f"arg:{'|'.join(arg)}")
result = runner.invoke(cmd2, []) assert result.exit_code == 2 assert "Missing argument 'ARG...'" in result.output
def test_missing_arg(runner): @click.command() @click.argument("arg") def cmd(arg): click.echo(f"arg:{arg}")
result = runner.invoke(cmd, []) assert result.exit_code == 2 assert "Missing argument 'ARG'." in result.output
def test_missing_argument_string_cast(): ctx = click.Context(click.Command(""))
with pytest.raises(click.MissingParameter) as excinfo: click.Argument(["a"], required=True).process_value(ctx, None)
assert str(excinfo.value) == "Missing parameter: a"
def test_implicit_non_required(runner): @click.command() @click.argument("f", default="test") def cli(f): click.echo(f)
result = runner.invoke(cli, []) assert result.exit_code == 0 assert result.output == "test\n"
def test_eat_options(runner): @click.command() @click.option("-f") @click.argument("files", nargs=-1) def cmd(f, files): for filename in files: click.echo(filename) click.echo(f)
result = runner.invoke(cmd, ["--", "-foo", "bar"]) assert result.output.splitlines() == ["-foo", "bar", ""]
result = runner.invoke(cmd, ["-f", "-x", "--", "-foo", "bar"]) assert result.output.splitlines() == ["-foo", "bar", "-x"]
def test_nargs_star_ordering(runner): @click.command() @click.argument("a", nargs=-1) @click.argument("b") @click.argument("c") def cmd(a, b, c): for arg in (a, b, c): click.echo(arg)
result = runner.invoke(cmd, ["a", "b", "c"]) assert result.output.splitlines() == ["('a',)", "b", "c"]
def test_nargs_specified_plus_star_ordering(runner): @click.command() @click.argument("a", nargs=-1) @click.argument("b") @click.argument("c", nargs=2) def cmd(a, b, c): for arg in (a, b, c): click.echo(arg)
result = runner.invoke(cmd, ["a", "b", "c", "d", "e", "f"]) assert result.output.splitlines() == ["('a', 'b', 'c')", "d", "('e', 'f')"]
def test_defaults_for_nargs(runner): @click.command() @click.argument("a", nargs=2, type=int, default=(1, 2)) def cmd(a): x, y = a click.echo(x + y)
result = runner.invoke(cmd, []) assert result.output.strip() == "3"
result = runner.invoke(cmd, ["3", "4"]) assert result.output.strip() == "7"
result = runner.invoke(cmd, ["3"]) assert result.exception is not None assert "Argument 'a' takes 2 values." in result.output
def test_multiple_param_decls_not_allowed(runner): with pytest.raises(TypeError):
@click.command() @click.argument("x", click.Choice(["a", "b"])) def copy(x): click.echo(x)
def test_multiple_not_allowed(): with pytest.raises(TypeError, match="multiple"): click.Argument(["a"], multiple=True)
@pytest.mark.parametrize("value", [(), ("a",), ("a", "b", "c")])def test_nargs_bad_default(runner, value): with pytest.raises(ValueError, match="nargs=2"): click.Argument(["a"], nargs=2, default=value)
def test_subcommand_help(runner): @click.group() @click.argument("name") @click.argument("val") @click.option("--opt") @click.pass_context def cli(ctx, name, val, opt): ctx.obj = dict(name=name, val=val)
@cli.command() @click.pass_obj def cmd(obj): click.echo(f"CMD for {obj['name']} with value {obj['val']}")
result = runner.invoke(cli, ["foo", "bar", "cmd", "--help"]) assert not result.exception assert "Usage: cli NAME VAL cmd [OPTIONS]" in result.output
def test_nested_subcommand_help(runner): @click.group() @click.argument("arg1") @click.option("--opt1") def cli(arg1, opt1): pass
@cli.group() @click.argument("arg2") @click.option("--opt2") def cmd(arg2, opt2): pass
@cmd.command() def subcmd(): click.echo("subcommand")
result = runner.invoke(cli, ["arg1", "cmd", "arg2", "subcmd", "--help"]) assert not result.exception assert "Usage: cli ARG1 cmd ARG2 subcmd [OPTIONS]" in result.output
def test_when_argument_decorator_is_used_multiple_times_cls_is_preserved(): class CustomArgument(click.Argument): pass
reusable_argument = click.argument("art", cls=CustomArgument)
@click.command() @reusable_argument def foo(arg): pass
@click.command() @reusable_argument def bar(arg): pass
assert isinstance(foo.params[0], CustomArgument) assert isinstance(bar.params[0], CustomArgument)
@pytest.mark.parametrize( "args_one,args_two", [ ( ("aardvark",), ("aardvark",), ), ],)def test_duplicate_names_warning(runner, args_one, args_two): @click.command() @click.argument(*args_one) @click.argument(*args_two) def cli(one, two): pass
with pytest.warns(UserWarning): runner.invoke(cli, [])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575import osfrom itertools import chain
import pytest
import click
def test_basic_functionality(runner): @click.command() def cli(): """Hello World!""" click.echo("I EXECUTED")
result = runner.invoke(cli, ["--help"]) assert not result.exception assert "Hello World!" in result.output assert "Show this message and exit." in result.output assert result.exit_code == 0 assert "I EXECUTED" not in result.output
result = runner.invoke(cli, []) assert not result.exception assert "I EXECUTED" in result.output assert result.exit_code == 0
def test_repr(): @click.command() def command(): pass
@click.group() def group(): pass
@group.command() def subcommand(): pass
assert repr(command) == "<Command command>" assert repr(group) == "<Group group>" assert repr(subcommand) == "<Command subcommand>"
def test_return_values(): @click.command() def cli(): return 42
with cli.make_context("foo", []) as ctx: rv = cli.invoke(ctx) assert rv == 42
def test_basic_group(runner): @click.group() def cli(): """This is the root.""" click.echo("ROOT EXECUTED")
@cli.command() def subcommand(): """This is a subcommand.""" click.echo("SUBCOMMAND EXECUTED")
result = runner.invoke(cli, ["--help"]) assert not result.exception assert "COMMAND [ARGS]..." in result.output assert "This is the root" in result.output assert "This is a subcommand." in result.output assert result.exit_code == 0 assert "ROOT EXECUTED" not in result.output
result = runner.invoke(cli, ["subcommand"]) assert not result.exception assert result.exit_code == 0 assert "ROOT EXECUTED" in result.output assert "SUBCOMMAND EXECUTED" in result.output
def test_group_commands_dict(runner): """A Group can be built with a dict of commands."""
@click.command() def sub(): click.echo("sub", nl=False)
cli = click.Group(commands={"other": sub}) result = runner.invoke(cli, ["other"]) assert result.output == "sub"
def test_group_from_list(runner): """A Group can be built with a list of commands."""
@click.command() def sub(): click.echo("sub", nl=False)
cli = click.Group(commands=[sub]) result = runner.invoke(cli, ["sub"]) assert result.output == "sub"
@pytest.mark.parametrize( ("args", "expect"), [ ([], "S:[no value]"), (["--s=42"], "S:[42]"), (["--s"], "Error: Option '--s' requires an argument."), (["--s="], "S:[]"), (["--s=\N{SNOWMAN}"], "S:[\N{SNOWMAN}]"), ],)def test_string_option(runner, args, expect): @click.command() @click.option("--s", default="no value") def cli(s): click.echo(f"S:[{s}]")
result = runner.invoke(cli, args) assert expect in result.output
if expect.startswith("Error:"): assert result.exception is not None else: assert result.exception is None
@pytest.mark.parametrize( ("args", "expect"), [ ([], "I:[84]"), (["--i=23"], "I:[46]"), (["--i=x"], "Error: Invalid value for '--i': 'x' is not a valid integer."), ],)def test_int_option(runner, args, expect): @click.command() @click.option("--i", default=42) def cli(i): click.echo(f"I:[{i * 2}]")
result = runner.invoke(cli, args) assert expect in result.output
if expect.startswith("Error:"): assert result.exception is not None else: assert result.exception is None
@pytest.mark.parametrize( ("args", "expect"), [ ([], "U:[ba122011-349f-423b-873b-9d6a79c688ab]"), ( ["--u=821592c1-c50e-4971-9cd6-e89dc6832f86"], "U:[821592c1-c50e-4971-9cd6-e89dc6832f86]", ), (["--u=x"], "Error: Invalid value for '--u': 'x' is not a valid UUID."), ],)def test_uuid_option(runner, args, expect): @click.command() @click.option( "--u", default="ba122011-349f-423b-873b-9d6a79c688ab", type=click.UUID ) def cli(u): click.echo(f"U:[{u}]")
result = runner.invoke(cli, args) assert expect in result.output
if expect.startswith("Error:"): assert result.exception is not None else: assert result.exception is None
@pytest.mark.parametrize( ("args", "expect"), [ ([], "F:[42.0]"), ("--f=23.5", "F:[23.5]"), ("--f=x", "Error: Invalid value for '--f': 'x' is not a valid float."), ],)def test_float_option(runner, args, expect): @click.command() @click.option("--f", default=42.0) def cli(f): click.echo(f"F:[{f}]")
result = runner.invoke(cli, args) assert expect in result.output
if expect.startswith("Error:"): assert result.exception is not None else: assert result.exception is None
@pytest.mark.parametrize("default", [True, False])@pytest.mark.parametrize( ("args", "expect"), [(["--on"], True), (["--off"], False), ([], None)])def test_boolean_switch(runner, default, args, expect): @click.command() @click.option("--on/--off", default=default) def cli(on): return on
if expect is None: expect = default
result = runner.invoke(cli, args, standalone_mode=False) assert result.return_value is expect
@pytest.mark.parametrize("default", [True, False])@pytest.mark.parametrize(("args", "expect"), [(["--f"], True), ([], False)])def test_boolean_flag(runner, default, args, expect): @click.command() @click.option("--f", is_flag=True, default=default) def cli(f): return f
if default: expect = not expect
result = runner.invoke(cli, args, standalone_mode=False) assert result.return_value is expect
@pytest.mark.parametrize( ("value", "expect"), chain( ((x, "True") for x in ("1", "true", "t", "yes", "y", "on")), ((x, "False") for x in ("0", "false", "f", "no", "n", "off")), ),)def test_boolean_conversion(runner, value, expect): @click.command() @click.option("--flag", type=bool) def cli(flag): click.echo(flag, nl=False)
result = runner.invoke(cli, ["--flag", value]) assert result.output == expect
result = runner.invoke(cli, ["--flag", value.title()]) assert result.output == expect
def test_file_option(runner): @click.command() @click.option("--file", type=click.File("w")) def input(file): file.write("Hello World!\n")
@click.command() @click.option("--file", type=click.File("r")) def output(file): click.echo(file.read())
with runner.isolated_filesystem(): result_in = runner.invoke(input, ["--file=example.txt"]) result_out = runner.invoke(output, ["--file=example.txt"])
assert not result_in.exception assert result_in.output == "" assert not result_out.exception assert result_out.output == "Hello World!\n\n"
def test_file_lazy_mode(runner): do_io = False
@click.command() @click.option("--file", type=click.File("w")) def input(file): if do_io: file.write("Hello World!\n")
@click.command() @click.option("--file", type=click.File("r")) def output(file): pass
with runner.isolated_filesystem(): os.mkdir("example.txt")
do_io = True result_in = runner.invoke(input, ["--file=example.txt"]) assert result_in.exit_code == 1
do_io = False result_in = runner.invoke(input, ["--file=example.txt"]) assert result_in.exit_code == 0
result_out = runner.invoke(output, ["--file=example.txt"]) assert result_out.exception
@click.command() @click.option("--file", type=click.File("w", lazy=False)) def input_non_lazy(file): file.write("Hello World!\n")
with runner.isolated_filesystem(): os.mkdir("example.txt") result_in = runner.invoke(input_non_lazy, ["--file=example.txt"]) assert result_in.exit_code == 2 assert "Invalid value for '--file': 'example.txt'" in result_in.output
def test_path_option(runner): @click.command() @click.option("-O", type=click.Path(file_okay=False, exists=True, writable=True)) def write_to_dir(o): with open(os.path.join(o, "foo.txt"), "wb") as f: f.write(b"meh\n")
with runner.isolated_filesystem(): os.mkdir("test")
result = runner.invoke(write_to_dir, ["-O", "test"]) assert not result.exception
with open("test/foo.txt", "rb") as f: assert f.read() == b"meh\n"
result = runner.invoke(write_to_dir, ["-O", "test/foo.txt"]) assert "is a file" in result.output
@click.command() @click.option("-f", type=click.Path(exists=True)) def showtype(f): click.echo(f"is_file={os.path.isfile(f)}") click.echo(f"is_dir={os.path.isdir(f)}")
with runner.isolated_filesystem(): result = runner.invoke(showtype, ["-f", "xxx"]) assert "does not exist" in result.output
result = runner.invoke(showtype, ["-f", "."]) assert "is_file=False" in result.output assert "is_dir=True" in result.output
@click.command() @click.option("-f", type=click.Path()) def exists(f): click.echo(f"exists={os.path.exists(f)}")
with runner.isolated_filesystem(): result = runner.invoke(exists, ["-f", "xxx"]) assert "exists=False" in result.output
result = runner.invoke(exists, ["-f", "."]) assert "exists=True" in result.output
def test_choice_option(runner): @click.command() @click.option("--method", type=click.Choice(["foo", "bar", "baz"])) def cli(method): click.echo(method)
result = runner.invoke(cli, ["--method=foo"]) assert not result.exception assert result.output == "foo\n"
result = runner.invoke(cli, ["--method=meh"]) assert result.exit_code == 2 assert ( "Invalid value for '--method': 'meh' is not one of 'foo', 'bar', 'baz'." in result.output )
result = runner.invoke(cli, ["--help"]) assert "--method [foo|bar|baz]" in result.output
def test_choice_argument(runner): @click.command() @click.argument("method", type=click.Choice(["foo", "bar", "baz"])) def cli(method): click.echo(method)
result = runner.invoke(cli, ["foo"]) assert not result.exception assert result.output == "foo\n"
result = runner.invoke(cli, ["meh"]) assert result.exit_code == 2 assert ( "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo'," " 'bar', 'baz'." in result.output )
result = runner.invoke(cli, ["--help"]) assert "{foo|bar|baz}" in result.output
def test_datetime_option_default(runner): @click.command() @click.option("--start_date", type=click.DateTime()) def cli(start_date): click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S"))
result = runner.invoke(cli, ["--start_date=2015-09-29"]) assert not result.exception assert result.output == "2015-09-29T00:00:00\n"
result = runner.invoke(cli, ["--start_date=2015-09-29T09:11:22"]) assert not result.exception assert result.output == "2015-09-29T09:11:22\n"
result = runner.invoke(cli, ["--start_date=2015-09"]) assert result.exit_code == 2 assert ( "Invalid value for '--start_date': '2015-09' does not match the formats" " '%Y-%m-%d', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S'." ) in result.output
result = runner.invoke(cli, ["--help"]) assert ( "--start_date [%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]" in result.output )
def test_datetime_option_custom(runner): @click.command() @click.option("--start_date", type=click.DateTime(formats=["%A %B %d, %Y"])) def cli(start_date): click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S"))
result = runner.invoke(cli, ["--start_date=Wednesday June 05, 2010"]) assert not result.exception assert result.output == "2010-06-05T00:00:00\n"
def test_required_option(runner): @click.command() @click.option("--foo", required=True) def cli(foo): click.echo(foo)
result = runner.invoke(cli, []) assert result.exit_code == 2 assert "Missing option '--foo'" in result.output
def test_evaluation_order(runner): called = []
def memo(ctx, param, value): called.append(value) return value
@click.command() @click.option("--missing", default="missing", is_eager=False, callback=memo) @click.option("--eager-flag1", flag_value="eager1", is_eager=True, callback=memo) @click.option("--eager-flag2", flag_value="eager2", is_eager=True, callback=memo) @click.option("--eager-flag3", flag_value="eager3", is_eager=True, callback=memo) @click.option("--normal-flag1", flag_value="normal1", is_eager=False, callback=memo) @click.option("--normal-flag2", flag_value="normal2", is_eager=False, callback=memo) @click.option("--normal-flag3", flag_value="normal3", is_eager=False, callback=memo) def cli(**x): pass
result = runner.invoke( cli, [ "--eager-flag2", "--eager-flag1", "--normal-flag2", "--eager-flag3", "--normal-flag3", "--normal-flag3", "--normal-flag1", "--normal-flag1", ], ) assert not result.exception assert called == [ "eager2", "eager1", "eager3", "normal2", "normal3", "normal1", "missing", ]
def test_hidden_option(runner): @click.command() @click.option("--nope", hidden=True) def cli(nope): click.echo(nope)
result = runner.invoke(cli, ["--help"]) assert result.exit_code == 0 assert "--nope" not in result.output
def test_hidden_command(runner): @click.group() def cli(): pass
@cli.command(hidden=True) def nope(): pass
result = runner.invoke(cli, ["--help"]) assert result.exit_code == 0 assert "nope" not in result.output
def test_hidden_group(runner): @click.group() def cli(): pass
@cli.group(hidden=True) def subgroup(): pass
@subgroup.command() def nope(): pass
result = runner.invoke(cli, ["--help"]) assert result.exit_code == 0 assert "subgroup" not in result.output assert "nope" not in result.output
def test_summary_line(runner): @click.group() def cli(): pass
@cli.command() def cmd(): """ Summary line without period
Here is a sentence. And here too. """ pass
result = runner.invoke(cli, ["--help"]) assert "Summary line without period" in result.output assert "Here is a sentence." not in result.output
def test_help_invalid_default(runner): cli = click.Command( "cli", params=[ click.Option( ["-a"], type=click.Path(exists=True), default="not found", show_default=True, ), ], ) result = runner.invoke(cli, ["--help"]) assert result.exit_code == 0 assert "default: not found" in result.output123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245import sys
import pytest
import click
def debug(): click.echo( f"{sys._getframe(1).f_code.co_name}" f"={'|'.join(click.get_current_context().args)}" )
def test_basic_chaining(runner): @click.group(chain=True) def cli(): pass
@cli.command("sdist") def sdist(): click.echo("sdist called")
@cli.command("bdist") def bdist(): click.echo("bdist called")
result = runner.invoke(cli, ["bdist", "sdist", "bdist"]) assert not result.exception assert result.output.splitlines() == [ "bdist called", "sdist called", "bdist called", ]
@pytest.mark.parametrize( ("args", "expect"), [ (["--help"], "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."), (["--help"], "ROOT HELP"), (["sdist", "--help"], "SDIST HELP"), (["bdist", "--help"], "BDIST HELP"), (["bdist", "sdist", "--help"], "SDIST HELP"), ],)def test_chaining_help(runner, args, expect): @click.group(chain=True) def cli(): """ROOT HELP""" pass
@cli.command("sdist") def sdist(): """SDIST HELP""" click.echo("sdist called")
@cli.command("bdist") def bdist(): """BDIST HELP""" click.echo("bdist called")
result = runner.invoke(cli, args) assert not result.exception assert expect in result.output
def test_chaining_with_options(runner): @click.group(chain=True) def cli(): pass
@cli.command("sdist") @click.option("--format") def sdist(format): click.echo(f"sdist called {format}")
@cli.command("bdist") @click.option("--format") def bdist(format): click.echo(f"bdist called {format}")
result = runner.invoke(cli, ["bdist", "--format=1", "sdist", "--format=2"]) assert not result.exception assert result.output.splitlines() == ["bdist called 1", "sdist called 2"]
@pytest.mark.parametrize(("chain", "expect"), [(False, "1"), (True, "[]")])def test_no_command_result_callback(runner, chain, expect): """When a group has ``invoke_without_command=True``, the result callback is always invoked. A regular group invokes it with its return value, a chained group with ``[]``. """
@click.group(invoke_without_command=True, chain=chain) def cli(): return 1
@cli.result_callback() def process_result(result): click.echo(result, nl=False)
result = runner.invoke(cli, []) assert result.output == expect
def test_chaining_with_arguments(runner): @click.group(chain=True) def cli(): pass
@cli.command("sdist") @click.argument("format") def sdist(format): click.echo(f"sdist called {format}")
@cli.command("bdist") @click.argument("format") def bdist(format): click.echo(f"bdist called {format}")
result = runner.invoke(cli, ["bdist", "1", "sdist", "2"]) assert not result.exception assert result.output.splitlines() == ["bdist called 1", "sdist called 2"]
@pytest.mark.parametrize( ("args", "input", "expect"), [ (["-f", "-"], "foo\nbar", ["foo", "bar"]), (["-f", "-", "strip"], "foo \n bar", ["foo", "bar"]), (["-f", "-", "strip", "uppercase"], "foo \n bar", ["FOO", "BAR"]), ],)def test_pipeline(runner, args, input, expect): @click.group(chain=True, invoke_without_command=True) @click.option("-f", type=click.File("r")) def cli(f): pass
@cli.result_callback() def process_pipeline(processors, f): iterator = (x.rstrip("\r\n") for x in f) for processor in processors: iterator = processor(iterator) for item in iterator: click.echo(item)
@cli.command("uppercase") def make_uppercase(): def processor(iterator): for line in iterator: yield line.upper()
return processor
@cli.command("strip") def make_strip(): def processor(iterator): for line in iterator: yield line.strip()
return processor
result = runner.invoke(cli, args, input=input) assert not result.exception assert result.output.splitlines() == expect
def test_args_and_chain(runner): @click.group(chain=True) def cli(): debug()
@cli.command() def a(): debug()
@cli.command() def b(): debug()
@cli.command() def c(): debug()
result = runner.invoke(cli, ["a", "b", "c"]) assert not result.exception assert result.output.splitlines() == ["cli=", "a=", "b=", "c="]
def test_group_arg_behavior(runner): with pytest.raises(RuntimeError):
@click.group(chain=True) @click.argument("forbidden", required=False) def bad_cli(): pass
with pytest.raises(RuntimeError):
@click.group(chain=True) @click.argument("forbidden", nargs=-1) def bad_cli2(): pass
@click.group(chain=True) @click.argument("arg") def cli(arg): click.echo(f"cli:{arg}")
@cli.command() def a(): click.echo("a")
result = runner.invoke(cli, ["foo", "a"]) assert not result.exception assert result.output.splitlines() == ["cli:foo", "a"]
@pytest.mark.xfaildef test_group_chaining(runner): @click.group(chain=True) def cli(): debug()
@cli.group() def l1a(): debug()
@l1a.command() def l2a(): debug()
@l1a.command() def l2b(): debug()
@cli.command() def l1b(): debug()
result = runner.invoke(cli, ["l1a", "l2a", "l1b"]) assert not result.exception assert result.output.splitlines() == ["cli=", "l1a=", "l2a=", "l1b="]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192import pytest
import click
def test_command_no_parens(runner): @click.command def cli(): click.echo("hello")
result = runner.invoke(cli) assert result.exception is None assert result.output == "hello\n"
def test_custom_command_no_parens(runner): class CustomCommand(click.Command): pass
class CustomGroup(click.Group): command_class = CustomCommand
@click.group(cls=CustomGroup) def grp(): pass
@grp.command def cli(): click.echo("hello custom command class")
result = runner.invoke(cli) assert result.exception is None assert result.output == "hello custom command class\n"
def test_group_no_parens(runner): @click.group def grp(): click.echo("grp1")
@grp.command def cmd1(): click.echo("cmd1")
@grp.group def grp2(): click.echo("grp2")
@grp2.command def cmd2(): click.echo("cmd2")
result = runner.invoke(grp, ["cmd1"]) assert result.exception is None assert result.output == "grp1\ncmd1\n"
result = runner.invoke(grp, ["grp2", "cmd2"]) assert result.exception is None assert result.output == "grp1\ngrp2\ncmd2\n"
def test_params_argument(runner): opt = click.Argument(["a"])
@click.command(params=[opt]) @click.argument("b") def cli(a, b): click.echo(f"{a} {b}")
assert cli.params[0].name == "a" assert cli.params[1].name == "b" result = runner.invoke(cli, ["1", "2"]) assert result.output == "1 2\n"
@pytest.mark.parametrize( "name", [ "init_data", "init_data_command", "init_data_cmd", "init_data_group", "init_data_grp", ],)def test_generate_name(name: str) -> None: def f(): pass
f.__name__ = name f = click.command(f) assert f.name == "init-data"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407import re
import pytest
import click
def test_other_command_invoke(runner): @click.command() @click.pass_context def cli(ctx): return ctx.invoke(other_cmd, arg=42)
@click.command() @click.argument("arg", type=click.INT) def other_cmd(arg): click.echo(arg)
result = runner.invoke(cli, []) assert not result.exception assert result.output == "42\n"
def test_other_command_forward(runner): cli = click.Group()
@cli.command() @click.option("--count", default=1) def test(count): click.echo(f"Count: {count:d}")
@cli.command() @click.option("--count", default=1) @click.pass_context def dist(ctx, count): ctx.forward(test) ctx.invoke(test, count=42)
result = runner.invoke(cli, ["dist"]) assert not result.exception assert result.output == "Count: 1\nCount: 42\n"
def test_forwarded_params_consistency(runner): cli = click.Group()
@cli.command() @click.option("-a") @click.pass_context def first(ctx, **kwargs): click.echo(f"{ctx.params}")
@cli.command() @click.option("-a") @click.option("-b") @click.pass_context def second(ctx, **kwargs): click.echo(f"{ctx.params}") ctx.forward(first)
result = runner.invoke(cli, ["second", "-a", "foo", "-b", "bar"]) assert not result.exception assert result.output == "{'a': 'foo', 'b': 'bar'}\n{'a': 'foo', 'b': 'bar'}\n"
def test_auto_shorthelp(runner): @click.group() def cli(): pass
@cli.command() def short(): """This is a short text."""
@cli.command() def special_chars(): """Login and store the token in ~/.netrc."""
@cli.command() def long(): """This is a long text that is too long to show as short help and will be truncated instead."""
result = runner.invoke(cli, ["--help"]) assert ( re.search( r"Commands:\n\s+" r"long\s+This is a long text that is too long to show as short help" r"\.\.\.\n\s+" r"short\s+This is a short text\.\n\s+" r"special-chars\s+Login and store the token in ~/.netrc\.\s*", result.output, ) is not None )
def test_command_no_args_is_help(runner): result = runner.invoke(click.Command("test", no_args_is_help=True)) assert result.exit_code == 2 assert "Show this message and exit." in result.output
def test_default_maps(runner): @click.group() def cli(): pass
@cli.command() @click.option("--name", default="normal") def foo(name): click.echo(name)
result = runner.invoke(cli, ["foo"], default_map={"foo": {"name": "changed"}})
assert not result.exception assert result.output == "changed\n"
@pytest.mark.parametrize( ("args", "exit_code", "expect"), [ (["obj1"], 2, "Error: Missing command."), (["obj1", "--help"], 0, "Show this message and exit."), (["obj1", "move"], 0, "obj=obj1\nmove\n"), ([], 2, "Show this message and exit."), ],)def test_group_with_args(runner, args, exit_code, expect): @click.group() @click.argument("obj") def cli(obj): click.echo(f"obj={obj}")
@cli.command() def move(): click.echo("move")
result = runner.invoke(cli, args) assert result.exit_code == exit_code assert expect in result.output
def test_custom_parser(runner): import optparse
@click.group() def cli(): pass
class OptParseCommand(click.Command): def __init__(self, name, parser, callback): super().__init__(name) self.parser = parser self.callback = callback
def parse_args(self, ctx, args): try: opts, args = parser.parse_args(args) except Exception as e: ctx.fail(str(e)) ctx.args = args ctx.params = vars(opts)
def get_usage(self, ctx): return self.parser.get_usage()
def get_help(self, ctx): return self.parser.format_help()
def invoke(self, ctx): ctx.invoke(self.callback, ctx.args, **ctx.params)
parser = optparse.OptionParser(usage="Usage: foo test [OPTIONS]") parser.add_option( "-f", "--file", dest="filename", help="write report to FILE", metavar="FILE" ) parser.add_option( "-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout", )
def test_callback(args, filename, verbose): click.echo(" ".join(args)) click.echo(filename) click.echo(verbose)
cli.add_command(OptParseCommand("test", parser, test_callback))
result = runner.invoke(cli, ["test", "-f", "f.txt", "-q", "q1.txt", "q2.txt"]) assert result.exception is None assert result.output.splitlines() == ["q1.txt q2.txt", "f.txt", "False"]
result = runner.invoke(cli, ["test", "--help"]) assert result.exception is None assert result.output.splitlines() == [ "Usage: foo test [OPTIONS]", "", "Options:", " -h, --help show this help message and exit", " -f FILE, --file=FILE write report to FILE", " -q, --quiet don't print status messages to stdout", ]
def test_object_propagation(runner): for chain in False, True:
@click.group(chain=chain) @click.option("--debug/--no-debug", default=False) @click.pass_context def cli(ctx, debug): if ctx.obj is None: ctx.obj = {} ctx.obj["DEBUG"] = debug
@cli.command() @click.pass_context def sync(ctx): click.echo(f"Debug is {'on' if ctx.obj['DEBUG'] else 'off'}")
result = runner.invoke(cli, ["sync"]) assert result.exception is None assert result.output == "Debug is off\n"
def test_other_command_invoke_with_defaults(runner): @click.command() @click.pass_context def cli(ctx): return ctx.invoke(other_cmd)
@click.command() @click.option("-a", type=click.INT, default=42) @click.option("-b", type=click.INT, default="15") @click.option("-c", multiple=True) @click.pass_context def other_cmd(ctx, a, b, c): return ctx.info_name, a, b, c
result = runner.invoke(cli, standalone_mode=False) # invoke should type cast default values, str becomes int, empty # multiple should be empty tuple instead of None assert result.return_value == ("other", 42, 15, ())
def test_invoked_subcommand(runner): @click.group(invoke_without_command=True) @click.pass_context def cli(ctx): if ctx.invoked_subcommand is None: click.echo("no subcommand, use default") ctx.invoke(sync) else: click.echo("invoke subcommand")
@cli.command() def sync(): click.echo("in subcommand")
result = runner.invoke(cli, ["sync"]) assert not result.exception assert result.output == "invoke subcommand\nin subcommand\n"
result = runner.invoke(cli) assert not result.exception assert result.output == "no subcommand, use default\nin subcommand\n"
def test_aliased_command_canonical_name(runner): class AliasedGroup(click.Group): def get_command(self, ctx, cmd_name): return push
def resolve_command(self, ctx, args): _, command, args = super().resolve_command(ctx, args) return command.name, command, args
cli = AliasedGroup()
@cli.command() def push(): click.echo("push command")
result = runner.invoke(cli, ["pu", "--help"]) assert not result.exception assert result.output.startswith("Usage: root push [OPTIONS]")
def test_group_add_command_name(runner): cli = click.Group("cli") cmd = click.Command("a", params=[click.Option(["-x"], required=True)]) cli.add_command(cmd, "b") # Check that the command is accessed through the registered name, # not the original name. result = runner.invoke(cli, ["b"], default_map={"b": {"x": 3}}) assert result.exit_code == 0
def test_unprocessed_options(runner): @click.command(context_settings=dict(ignore_unknown_options=True)) @click.argument("args", nargs=-1, type=click.UNPROCESSED) @click.option("--verbose", "-v", count=True) def cli(verbose, args): click.echo(f"Verbosity: {verbose}") click.echo(f"Args: {'|'.join(args)}")
result = runner.invoke(cli, ["-foo", "-vvvvx", "--muhaha", "x", "y", "-x"]) assert not result.exception assert result.output.splitlines() == [ "Verbosity: 4", "Args: -foo|-x|--muhaha|x|y|-x", ]
@pytest.mark.parametrize("doc", ["CLI HELP", None])def test_deprecated_in_help_messages(runner, doc): @click.command(deprecated=True, help=doc) def cli(): pass
result = runner.invoke(cli, ["--help"]) assert "(Deprecated)" in result.output
def test_deprecated_in_invocation(runner): @click.command(deprecated=True) def deprecated_cmd(): pass
result = runner.invoke(deprecated_cmd) assert "DeprecationWarning:" in result.output
def test_command_parse_args_collects_option_prefixes(): @click.command() @click.option("+p", is_flag=True) @click.option("!e", is_flag=True) def test(p, e): pass
ctx = click.Context(test) test.parse_args(ctx, [])
assert ctx._opt_prefixes == {"-", "--", "+", "!"}
def test_group_parse_args_collects_base_option_prefixes(): @click.group() @click.option("~t", is_flag=True) def group(t): pass
@group.command() @click.option("+p", is_flag=True) def command1(p): pass
@group.command() @click.option("!e", is_flag=True) def command2(e): pass
ctx = click.Context(group) group.parse_args(ctx, ["command1", "+p"])
assert ctx._opt_prefixes == {"-", "--", "~"}
def test_group_invoke_collects_used_option_prefixes(runner): opt_prefixes = set()
@click.group() @click.option("~t", is_flag=True) def group(t): pass
@group.command() @click.option("+p", is_flag=True) @click.pass_context def command1(ctx, p): nonlocal opt_prefixes opt_prefixes = ctx._opt_prefixes
@group.command() @click.option("!e", is_flag=True) def command2(e): pass
runner.invoke(group, ["command1"]) assert opt_prefixes == {"-", "--", "~", "+"}
@pytest.mark.parametrize("exc", (EOFError, KeyboardInterrupt))def test_abort_exceptions_with_disabled_standalone_mode(runner, exc): @click.command() def cli(): raise exc("catch me!")
rv = runner.invoke(cli, standalone_mode=False) assert rv.exit_code == 1 assert isinstance(rv.exception.__cause__, exc) assert rv.exception.__cause__.args == ("catch me!",)12345678910from click._compat import should_strip_ansi
def test_is_jupyter_kernel_output(): class JupyterKernelFakeStream: pass
# implementation detail, aka cheapskate test JupyterKernelFakeStream.__module__ = "ipykernel.faked" assert not should_strip_ansi(stream=JupyterKernelFakeStream())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545import loggingfrom contextlib import contextmanager
import pytest
import clickfrom click import Contextfrom click import Optionfrom click import Parameterfrom click.core import ParameterSourcefrom click.decorators import help_optionfrom click.decorators import pass_meta_key
def test_ensure_context_objects(runner): class Foo: def __init__(self): self.title = "default"
pass_foo = click.make_pass_decorator(Foo, ensure=True)
@click.group() @pass_foo def cli(foo): pass
@cli.command() @pass_foo def test(foo): click.echo(foo.title)
result = runner.invoke(cli, ["test"]) assert not result.exception assert result.output == "default\n"
def test_get_context_objects(runner): class Foo: def __init__(self): self.title = "default"
pass_foo = click.make_pass_decorator(Foo, ensure=True)
@click.group() @click.pass_context def cli(ctx): ctx.obj = Foo() ctx.obj.title = "test"
@cli.command() @pass_foo def test(foo): click.echo(foo.title)
result = runner.invoke(cli, ["test"]) assert not result.exception assert result.output == "test\n"
def test_get_context_objects_no_ensuring(runner): class Foo: def __init__(self): self.title = "default"
pass_foo = click.make_pass_decorator(Foo)
@click.group() @click.pass_context def cli(ctx): ctx.obj = Foo() ctx.obj.title = "test"
@cli.command() @pass_foo def test(foo): click.echo(foo.title)
result = runner.invoke(cli, ["test"]) assert not result.exception assert result.output == "test\n"
def test_get_context_objects_missing(runner): class Foo: pass
pass_foo = click.make_pass_decorator(Foo)
@click.group() @click.pass_context def cli(ctx): pass
@cli.command() @pass_foo def test(foo): click.echo(foo.title)
result = runner.invoke(cli, ["test"]) assert result.exception is not None assert isinstance(result.exception, RuntimeError) assert ( "Managed to invoke callback without a context object of type" " 'Foo' existing" in str(result.exception) )
def test_multi_enter(runner): called = []
@click.command() @click.pass_context def cli(ctx): def callback(): called.append(True)
ctx.call_on_close(callback)
with ctx: pass assert not called
result = runner.invoke(cli, []) assert result.exception is None assert called == [True]
def test_global_context_object(runner): @click.command() @click.pass_context def cli(ctx): assert click.get_current_context() is ctx ctx.obj = "FOOBAR" assert click.get_current_context().obj == "FOOBAR"
assert click.get_current_context(silent=True) is None runner.invoke(cli, [], catch_exceptions=False) assert click.get_current_context(silent=True) is None
def test_context_meta(runner): LANG_KEY = f"{__name__}.lang"
def set_language(value): click.get_current_context().meta[LANG_KEY] = value
def get_language(): return click.get_current_context().meta.get(LANG_KEY, "en_US")
@click.command() @click.pass_context def cli(ctx): assert get_language() == "en_US" set_language("de_DE") assert get_language() == "de_DE"
runner.invoke(cli, [], catch_exceptions=False)
def test_make_pass_meta_decorator(runner): @click.group() @click.pass_context def cli(ctx): ctx.meta["value"] = "good"
@cli.command() @pass_meta_key("value") def show(value): return value
result = runner.invoke(cli, ["show"], standalone_mode=False) assert result.return_value == "good"
def test_make_pass_meta_decorator_doc(): pass_value = pass_meta_key("value") assert "the 'value' key from :attr:`click.Context.meta`" in pass_value.__doc__ pass_value = pass_meta_key("value", doc_description="the test value") assert "passes the test value" in pass_value.__doc__
def test_context_pushing(): rv = []
@click.command() def cli(): pass
ctx = click.Context(cli)
@ctx.call_on_close def test_callback(): rv.append(42)
with ctx.scope(cleanup=False): # Internal assert ctx._depth == 2
assert rv == []
with ctx.scope(): # Internal assert ctx._depth == 1
assert rv == [42]
def test_pass_obj(runner): @click.group() @click.pass_context def cli(ctx): ctx.obj = "test"
@cli.command() @click.pass_obj def test(obj): click.echo(obj)
result = runner.invoke(cli, ["test"]) assert not result.exception assert result.output == "test\n"
def test_close_before_pop(runner): called = []
@click.command() @click.pass_context def cli(ctx): ctx.obj = "test"
@ctx.call_on_close def foo(): assert click.get_current_context().obj == "test" called.append(True)
click.echo("aha!")
result = runner.invoke(cli, []) assert not result.exception assert result.output == "aha!\n" assert called == [True]
def test_close_before_exit(runner): called = []
@click.command() @click.pass_context def cli(ctx): ctx.obj = "test"
@ctx.call_on_close def foo(): assert click.get_current_context().obj == "test" called.append(True)
ctx.exit()
click.echo("aha!")
result = runner.invoke(cli, []) assert not result.exception assert not result.output assert called == [True]
@pytest.mark.parametrize( ("cli_args", "expect"), [ pytest.param( ("--option-with-callback", "--force-exit"), ["ExitingOption", "NonExitingOption"], id="natural_order", ), pytest.param( ("--force-exit", "--option-with-callback"), ["ExitingOption"], id="eagerness_precedence", ), ],)def test_multiple_eager_callbacks(runner, cli_args, expect): """Checks all callbacks are called on exit, even the nasty ones hidden within callbacks.
Also checks the order in which they're called. """ # Keeps track of callback calls. called = []
class NonExitingOption(Option): def reset_state(self): called.append(self.__class__.__name__)
def set_state(self, ctx: Context, param: Parameter, value: str) -> str: ctx.call_on_close(self.reset_state) return value
def __init__(self, *args, **kwargs) -> None: kwargs.setdefault("expose_value", False) kwargs.setdefault("callback", self.set_state) super().__init__(*args, **kwargs)
class ExitingOption(NonExitingOption): def set_state(self, ctx: Context, param: Parameter, value: str) -> str: value = super().set_state(ctx, param, value) ctx.exit() return value
@click.command() @click.option("--option-with-callback", is_eager=True, cls=NonExitingOption) @click.option("--force-exit", is_eager=True, cls=ExitingOption) def cli(): click.echo("This will never be printed as we forced exit via --force-exit")
result = runner.invoke(cli, cli_args) assert not result.exception assert not result.output
assert called == expect
def test_no_state_leaks(runner): """Demonstrate state leaks with a specific case of the generic test above.
Use a logger as a real-world example of a common fixture which, due to its global nature, can leak state if not clean-up properly in a callback. """ # Keeps track of callback calls. called = []
class DebugLoggerOption(Option): """A custom option to set the name of the debug logger."""
logger_name: str """The ID of the logger to use."""
def reset_loggers(self): """Forces logger managed by the option to be reset to the default level.""" logger = logging.getLogger(self.logger_name) logger.setLevel(logging.NOTSET)
# Logger has been properly reset to its initial state. assert logger.level == logging.NOTSET assert logger.getEffectiveLevel() == logging.WARNING
called.append(True)
def set_level(self, ctx: Context, param: Parameter, value: str) -> None: """Set the logger to DEBUG level.""" # Keep the logger name around so we can reset it later when winding down # the option. self.logger_name = value
# Get the global logger object. logger = logging.getLogger(self.logger_name)
# Check pre-conditions: new logger is not set, but inherits its level from # default <root> logger. That's the exact same state we are expecting our # logger to be in after being messed with by the CLI. assert logger.level == logging.NOTSET assert logger.getEffectiveLevel() == logging.WARNING
logger.setLevel(logging.DEBUG) ctx.call_on_close(self.reset_loggers) return value
def __init__(self, *args, **kwargs) -> None: kwargs.setdefault("callback", self.set_level) super().__init__(*args, **kwargs)
@click.command() @click.option("--debug-logger-name", is_eager=True, cls=DebugLoggerOption) @help_option() @click.pass_context def messing_with_logger(ctx, debug_logger_name): # Introspect context to make sure logger name are aligned. assert debug_logger_name == ctx.command.params[0].logger_name
logger = logging.getLogger(debug_logger_name)
# Logger's level has been properly set to DEBUG by DebugLoggerOption. assert logger.level == logging.DEBUG assert logger.getEffectiveLevel() == logging.DEBUG
logger.debug("Blah blah blah")
ctx.exit()
click.echo("This will never be printed as we exited early")
# Call the CLI to mess with the custom logger. result = runner.invoke( messing_with_logger, ["--debug-logger-name", "my_logger", "--help"] )
assert called == [True]
# Check the custom logger has been reverted to it initial state by the option # callback after being messed with by the CLI. logger = logging.getLogger("my_logger") assert logger.level == logging.NOTSET assert logger.getEffectiveLevel() == logging.WARNING
assert not result.exception assert result.output.startswith("Usage: messing-with-logger [OPTIONS]")
def test_with_resource(): @contextmanager def manager(): val = [1] yield val val[0] = 0
ctx = click.Context(click.Command("test"))
with ctx.scope(): rv = ctx.with_resource(manager()) assert rv[0] == 1
assert rv == [0]
def test_make_pass_decorator_args(runner): """ Test to check that make_pass_decorator doesn't consume arguments based on invocation order. """
class Foo: title = "foocmd"
pass_foo = click.make_pass_decorator(Foo)
@click.group() @click.pass_context def cli(ctx): ctx.obj = Foo()
@cli.command() @click.pass_context @pass_foo def test1(foo, ctx): click.echo(foo.title)
@cli.command() @pass_foo @click.pass_context def test2(ctx, foo): click.echo(foo.title)
result = runner.invoke(cli, ["test1"]) assert not result.exception assert result.output == "foocmd\n"
result = runner.invoke(cli, ["test2"]) assert not result.exception assert result.output == "foocmd\n"
def test_propagate_show_default_setting(runner): """A context's ``show_default`` setting defaults to the value from the parent context. """ group = click.Group( commands={ "sub": click.Command("sub", params=[click.Option(["-a"], default="a")]), }, context_settings={"show_default": True}, ) result = runner.invoke(group, ["sub", "--help"]) assert "[default: a]" in result.output
def test_exit_not_standalone(): @click.command() @click.pass_context def cli(ctx): ctx.exit(1)
assert cli.main([], "test_exit_not_standalone", standalone_mode=False) == 1
@click.command() @click.pass_context def cli(ctx): ctx.exit(0)
assert cli.main([], "test_exit_not_standalone", standalone_mode=False) == 0
@pytest.mark.parametrize( ("option_args", "invoke_args", "expect"), [ pytest.param({}, {}, ParameterSource.DEFAULT, id="default"), pytest.param( {}, {"default_map": {"option": 1}}, ParameterSource.DEFAULT_MAP, id="default_map", ), pytest.param( {}, {"args": ["-o", "1"]}, ParameterSource.COMMANDLINE, id="commandline short", ), pytest.param( {}, {"args": ["--option", "1"]}, ParameterSource.COMMANDLINE, id="commandline long", ), pytest.param( {}, {"auto_envvar_prefix": "TEST", "env": {"TEST_OPTION": "1"}}, ParameterSource.ENVIRONMENT, id="environment auto", ), pytest.param( {"envvar": "NAME"}, {"env": {"NAME": "1"}}, ParameterSource.ENVIRONMENT, id="environment manual", ), ],)def test_parameter_source(runner, option_args, invoke_args, expect): @click.command() @click.pass_context @click.option("-o", "--option", default=1, **option_args) def cli(ctx, option): return ctx.get_parameter_source("option")
rv = runner.invoke(cli, standalone_mode=False, **invoke_args) assert rv.return_value == expect
def test_propagate_opt_prefixes(): parent = click.Context(click.Command("test")) parent._opt_prefixes = {"-", "--", "!"} ctx = click.Context(click.Command("test2"), parent=parent)
assert ctx._opt_prefixes == {"-", "--", "!"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112import click
def test_command_context_class(): """A command with a custom ``context_class`` should produce a context using that type. """
class CustomContext(click.Context): pass
class CustomCommand(click.Command): context_class = CustomContext
command = CustomCommand("test") context = command.make_context("test", []) assert isinstance(context, CustomContext)
def test_context_invoke_type(runner): """A command invoked from a custom context should have a new context with the same type. """
class CustomContext(click.Context): pass
class CustomCommand(click.Command): context_class = CustomContext
@click.command() @click.argument("first_id", type=int) @click.pass_context def second(ctx, first_id): assert isinstance(ctx, CustomContext) assert id(ctx) != first_id
@click.command(cls=CustomCommand) @click.pass_context def first(ctx): assert isinstance(ctx, CustomContext) ctx.invoke(second, first_id=id(ctx))
assert not runner.invoke(first).exception
def test_context_formatter_class(): """A context with a custom ``formatter_class`` should format help using that type. """
class CustomFormatter(click.HelpFormatter): def write_heading(self, heading): heading = click.style(heading, fg="yellow") return super().write_heading(heading)
class CustomContext(click.Context): formatter_class = CustomFormatter
context = CustomContext( click.Command("test", params=[click.Option(["--value"])]), color=True ) assert "\x1b[33mOptions\x1b[0m:" in context.get_help()
def test_group_command_class(runner): """A group with a custom ``command_class`` should create subcommands of that type by default. """
class CustomCommand(click.Command): pass
class CustomGroup(click.Group): command_class = CustomCommand
group = CustomGroup() subcommand = group.command()(lambda: None) assert type(subcommand) is CustomCommand subcommand = group.command(cls=click.Command)(lambda: None) assert type(subcommand) is click.Command
def test_group_group_class(runner): """A group with a custom ``group_class`` should create subgroups of that type by default. """
class CustomSubGroup(click.Group): pass
class CustomGroup(click.Group): group_class = CustomSubGroup
group = CustomGroup() subgroup = group.group()(lambda: None) assert type(subgroup) is CustomSubGroup subgroup = group.command(cls=click.Group)(lambda: None) assert type(subgroup) is click.Group
def test_group_group_class_self(runner): """A group with ``group_class = type`` should create subgroups of the same type as itself. """
class CustomGroup(click.Group): group_class = type
group = CustomGroup() subgroup = group.group()(lambda: None) assert type(subgroup) is CustomGroup1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586import click
def test_basic_defaults(runner): @click.command() @click.option("--foo", default=42, type=click.FLOAT) def cli(foo): assert isinstance(foo, float) click.echo(f"FOO:[{foo}]")
result = runner.invoke(cli, []) assert not result.exception assert "FOO:[42.0]" in result.output
def test_multiple_defaults(runner): @click.command() @click.option("--foo", default=[23, 42], type=click.FLOAT, multiple=True) def cli(foo): for item in foo: assert isinstance(item, float) click.echo(item)
result = runner.invoke(cli, []) assert not result.exception assert result.output.splitlines() == ["23.0", "42.0"]
def test_nargs_plus_multiple(runner): @click.command() @click.option( "--arg", default=((1, 2), (3, 4)), nargs=2, multiple=True, type=click.INT ) def cli(arg): for a, b in arg: click.echo(f"<{a:d}|{b:d}>")
result = runner.invoke(cli, []) assert not result.exception assert result.output.splitlines() == ["<1|2>", "<3|4>"]
def test_multiple_flag_default(runner): """Default default for flags when multiple=True should be empty tuple."""
@click.command # flag due to secondary token @click.option("-y/-n", multiple=True) # flag due to is_flag @click.option("-f", is_flag=True, multiple=True) # flag due to flag_value @click.option("-v", "v", flag_value=1, multiple=True) @click.option("-q", "v", flag_value=-1, multiple=True) def cli(y, f, v): return y, f, v
result = runner.invoke(cli, standalone_mode=False) assert result.return_value == ((), (), ())
result = runner.invoke(cli, ["-y", "-n", "-f", "-v", "-q"], standalone_mode=False) assert result.return_value == ((True, False), (True,), (1, -1))
def test_flag_default_map(runner): """test flag with default map"""
@click.group() def cli(): pass
@cli.command() @click.option("--name/--no-name", is_flag=True, show_default=True, help="name flag") def foo(name): click.echo(name)
result = runner.invoke(cli, ["foo"]) assert "False" in result.output
result = runner.invoke(cli, ["foo", "--help"]) assert "default: no-name" in result.output
result = runner.invoke(cli, ["foo"], default_map={"foo": {"name": True}}) assert "True" in result.output
result = runner.invoke(cli, ["foo", "--help"], default_map={"foo": {"name": True}}) assert "default: name" in result.output123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368import click
def test_basic_functionality(runner): @click.command() def cli(): """First paragraph.
This is a very long second paragraph and not correctly wrapped but it will be rewrapped.
\b This is a paragraph without rewrapping.
\b 1 2 3
And this is a paragraph that will be rewrapped again. """
result = runner.invoke(cli, ["--help"], terminal_width=60) assert not result.exception assert result.output.splitlines() == [ "Usage: cli [OPTIONS]", "", " First paragraph.", "", " This is a very long second paragraph and not correctly", " wrapped but it will be rewrapped.", "", " This is", " a paragraph", " without rewrapping.", "", " 1", " 2", " 3", "", " And this is a paragraph that will be rewrapped again.", "", "Options:", " --help Show this message and exit.", ]
def test_wrapping_long_options_strings(runner): @click.group() def cli(): """Top level command"""
@cli.group() def a_very_long(): """Second level"""
@a_very_long.command() @click.argument("first") @click.argument("second") @click.argument("third") @click.argument("fourth") @click.argument("fifth") @click.argument("sixth") def command(): """A command."""
# 54 is chosen as a length where the second line is one character # longer than the maximum length. result = runner.invoke(cli, ["a-very-long", "command", "--help"], terminal_width=54) assert not result.exception assert result.output.splitlines() == [ "Usage: cli a-very-long command [OPTIONS] FIRST SECOND", " THIRD FOURTH FIFTH", " SIXTH", "", " A command.", "", "Options:", " --help Show this message and exit.", ]
def test_wrapping_long_command_name(runner): @click.group() def cli(): """Top level command"""
@cli.group() def a_very_very_very_long(): """Second level"""
@a_very_very_very_long.command() @click.argument("first") @click.argument("second") @click.argument("third") @click.argument("fourth") @click.argument("fifth") @click.argument("sixth") def command(): """A command."""
result = runner.invoke( cli, ["a-very-very-very-long", "command", "--help"], terminal_width=54 ) assert not result.exception assert result.output.splitlines() == [ "Usage: cli a-very-very-very-long command ", " [OPTIONS] FIRST SECOND THIRD FOURTH FIFTH", " SIXTH", "", " A command.", "", "Options:", " --help Show this message and exit.", ]
def test_formatting_empty_help_lines(runner): @click.command() def cli(): # fmt: off """Top level command
""" # fmt: on
result = runner.invoke(cli, ["--help"]) assert not result.exception assert result.output.splitlines() == [ "Usage: cli [OPTIONS]", "", " Top level command", "", "", "", "Options:", " --help Show this message and exit.", ]
def test_formatting_usage_error(runner): @click.command() @click.argument("arg") def cmd(arg): click.echo(f"arg:{arg}")
result = runner.invoke(cmd, []) assert result.exit_code == 2 assert result.output.splitlines() == [ "Usage: cmd [OPTIONS] ARG", "Try 'cmd --help' for help.", "", "Error: Missing argument 'ARG'.", ]
def test_formatting_usage_error_metavar_missing_arg(runner): """ :author: @r-m-n Including attribution to #612 """
@click.command() @click.argument("arg", metavar="metavar") def cmd(arg): pass
result = runner.invoke(cmd, []) assert result.exit_code == 2 assert result.output.splitlines() == [ "Usage: cmd [OPTIONS] metavar", "Try 'cmd --help' for help.", "", "Error: Missing argument 'metavar'.", ]
def test_formatting_usage_error_metavar_bad_arg(runner): @click.command() @click.argument("arg", type=click.INT, metavar="metavar") def cmd(arg): pass
result = runner.invoke(cmd, ["3.14"]) assert result.exit_code == 2 assert result.output.splitlines() == [ "Usage: cmd [OPTIONS] metavar", "Try 'cmd --help' for help.", "", "Error: Invalid value for 'metavar': '3.14' is not a valid integer.", ]
def test_formatting_usage_error_nested(runner): @click.group() def cmd(): pass
@cmd.command() @click.argument("bar") def foo(bar): click.echo(f"foo:{bar}")
result = runner.invoke(cmd, ["foo"]) assert result.exit_code == 2 assert result.output.splitlines() == [ "Usage: cmd foo [OPTIONS] BAR", "Try 'cmd foo --help' for help.", "", "Error: Missing argument 'BAR'.", ]
def test_formatting_usage_error_no_help(runner): @click.command(add_help_option=False) @click.argument("arg") def cmd(arg): click.echo(f"arg:{arg}")
result = runner.invoke(cmd, []) assert result.exit_code == 2 assert result.output.splitlines() == [ "Usage: cmd [OPTIONS] ARG", "", "Error: Missing argument 'ARG'.", ]
def test_formatting_usage_custom_help(runner): @click.command(context_settings=dict(help_option_names=["--man"])) @click.argument("arg") def cmd(arg): click.echo(f"arg:{arg}")
result = runner.invoke(cmd, []) assert result.exit_code == 2 assert result.output.splitlines() == [ "Usage: cmd [OPTIONS] ARG", "Try 'cmd --man' for help.", "", "Error: Missing argument 'ARG'.", ]
def test_formatting_custom_type_metavar(runner): class MyType(click.ParamType): def get_metavar(self, param): return "MY_TYPE"
@click.command("foo") @click.help_option() @click.argument("param", type=MyType()) def cmd(param): pass
result = runner.invoke(cmd, "--help") assert not result.exception assert result.output.splitlines() == [ "Usage: foo [OPTIONS] MY_TYPE", "", "Options:", " --help Show this message and exit.", ]
def test_truncating_docstring(runner): @click.command() @click.pass_context def cli(ctx): """First paragraph.
This is a very long second paragraph and not correctly wrapped but it will be rewrapped. \f
:param click.core.Context ctx: Click context. """
result = runner.invoke(cli, ["--help"], terminal_width=60) assert not result.exception assert result.output.splitlines() == [ "Usage: cli [OPTIONS]", "", " First paragraph.", "", " This is a very long second paragraph and not correctly", " wrapped but it will be rewrapped.", "", "Options:", " --help Show this message and exit.", ]
def test_truncating_docstring_no_help(runner): @click.command() @click.pass_context def cli(ctx): """ \f
This text should be truncated. """
result = runner.invoke(cli, ["--help"], terminal_width=60) assert not result.exception assert result.output.splitlines() == [ "Usage: cli [OPTIONS]", "", "Options:", " --help Show this message and exit.", ]
def test_removing_multiline_marker(runner): @click.group() def cli(): pass
@cli.command() def cmd1(): """\b This is command with a multiline help text which should not be rewrapped. The output of the short help text should not contain the multiline marker. """ pass
result = runner.invoke(cli, ["--help"]) assert "\b" not in result.output
def test_global_show_default(runner): @click.command(context_settings=dict(show_default=True)) @click.option("-f", "in_file", default="out.txt", help="Output file name") def cli(): pass
result = runner.invoke(cli, ["--help"]) # the default to "--help" is not shown because it is False assert result.output.splitlines() == [ "Usage: cli [OPTIONS]", "", "Options:", " -f TEXT Output file name [default: out.txt]", " --help Show this message and exit.", ]
def test_formatting_with_options_metavar_empty(runner): cli = click.Command("cli", options_metavar="", params=[click.Argument(["var"])]) result = runner.invoke(cli, ["--help"]) assert "Usage: cli VAR\n" in result.output
def test_help_formatter_write_text(): text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit" formatter = click.HelpFormatter(width=len(" Lorem ipsum dolor sit amet,")) formatter.current_indent = 2 formatter.write_text(text) actual = formatter.getvalue() expected = " Lorem ipsum dolor sit amet,\n consectetur adipiscing elit\n" assert actual == expected123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869import jsonimport subprocessimport sys
from click._compat import WIN
IMPORT_TEST = b"""\import builtins
found_imports = set()real_import = builtins.__import__import sys
def tracking_import(module, locals=None, globals=None, fromlist=None, level=0): rv = real_import(module, locals, globals, fromlist, level) if globals and globals['__name__'].startswith('click') and level == 0: found_imports.add(module) return rvbuiltins.__import__ = tracking_import
import clickrv = list(found_imports)import jsonclick.echo(json.dumps(rv))"""
ALLOWED_IMPORTS = { "__future__", "weakref", "os", "struct", "collections", "collections.abc", "sys", "contextlib", "functools", "stat", "re", "codecs", "inspect", "itertools", "io", "threading", "errno", "fcntl", "datetime", "enum", "typing", "types", "gettext",}
if WIN: ALLOWED_IMPORTS.update(["ctypes", "ctypes.wintypes", "msvcrt", "time"])
def test_light_imports(): c = subprocess.Popen( [sys.executable, "-"], stdin=subprocess.PIPE, stdout=subprocess.PIPE ) rv = c.communicate(IMPORT_TEST)[0] rv = rv.decode("utf-8") imported = json.loads(rv)
for module in imported: if module == "click" or module.startswith("click."): continue assert module in ALLOWED_IMPORTS123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275import pytest
import click.types
# Common (obj, expect) pairs used to construct multiple tests.STRING_PARAM_TYPE = (click.STRING, {"param_type": "String", "name": "text"})INT_PARAM_TYPE = (click.INT, {"param_type": "Int", "name": "integer"})BOOL_PARAM_TYPE = (click.BOOL, {"param_type": "Bool", "name": "boolean"})HELP_OPTION = ( None, { "name": "help", "param_type_name": "option", "opts": ["--help"], "secondary_opts": [], "type": BOOL_PARAM_TYPE[1], "required": False, "nargs": 1, "multiple": False, "default": False, "envvar": None, "help": "Show this message and exit.", "prompt": None, "is_flag": True, "flag_value": True, "count": False, "hidden": False, },)NAME_ARGUMENT = ( click.Argument(["name"]), { "name": "name", "param_type_name": "argument", "opts": ["name"], "secondary_opts": [], "type": STRING_PARAM_TYPE[1], "required": True, "nargs": 1, "multiple": False, "default": None, "envvar": None, },)NUMBER_OPTION = ( click.Option(["-c", "--count", "number"], default=1), { "name": "number", "param_type_name": "option", "opts": ["-c", "--count"], "secondary_opts": [], "type": INT_PARAM_TYPE[1], "required": False, "nargs": 1, "multiple": False, "default": 1, "envvar": None, "help": None, "prompt": None, "is_flag": False, "flag_value": False, "count": False, "hidden": False, },)HELLO_COMMAND = ( click.Command("hello", params=[NUMBER_OPTION[0]]), { "name": "hello", "params": [NUMBER_OPTION[1], HELP_OPTION[1]], "help": None, "epilog": None, "short_help": None, "hidden": False, "deprecated": False, },)HELLO_GROUP = ( click.Group("cli", [HELLO_COMMAND[0]]), { "name": "cli", "params": [HELP_OPTION[1]], "help": None, "epilog": None, "short_help": None, "hidden": False, "deprecated": False, "commands": {"hello": HELLO_COMMAND[1]}, "chain": False, },)
@pytest.mark.parametrize( ("obj", "expect"), [ pytest.param( click.types.FuncParamType(range), {"param_type": "Func", "name": "range", "func": range}, id="Func ParamType", ), pytest.param( click.UNPROCESSED, {"param_type": "Unprocessed", "name": "text"}, id="UNPROCESSED ParamType", ), pytest.param(*STRING_PARAM_TYPE, id="STRING ParamType"), pytest.param( click.Choice(["a", "b"]), { "param_type": "Choice", "name": "choice", "choices": ["a", "b"], "case_sensitive": True, }, id="Choice ParamType", ), pytest.param( click.DateTime(["%Y-%m-%d"]), {"param_type": "DateTime", "name": "datetime", "formats": ["%Y-%m-%d"]}, id="DateTime ParamType", ), pytest.param(*INT_PARAM_TYPE, id="INT ParamType"), pytest.param( click.IntRange(0, 10, clamp=True), { "param_type": "IntRange", "name": "integer range", "min": 0, "max": 10, "min_open": False, "max_open": False, "clamp": True, }, id="IntRange ParamType", ), pytest.param( click.FLOAT, {"param_type": "Float", "name": "float"}, id="FLOAT ParamType" ), pytest.param( click.FloatRange(-0.5, 0.5), { "param_type": "FloatRange", "name": "float range", "min": -0.5, "max": 0.5, "min_open": False, "max_open": False, "clamp": False, }, id="FloatRange ParamType", ), pytest.param(*BOOL_PARAM_TYPE, id="Bool ParamType"), pytest.param( click.UUID, {"param_type": "UUID", "name": "uuid"}, id="UUID ParamType" ), pytest.param( click.File(), {"param_type": "File", "name": "filename", "mode": "r", "encoding": None}, id="File ParamType", ), pytest.param( click.Path(), { "param_type": "Path", "name": "path", "exists": False, "file_okay": True, "dir_okay": True, "writable": False, "readable": True, "allow_dash": False, }, id="Path ParamType", ), pytest.param( click.Tuple((click.STRING, click.INT)), { "param_type": "Tuple", "name": "<text integer>", "types": [STRING_PARAM_TYPE[1], INT_PARAM_TYPE[1]], }, id="Tuple ParamType", ), pytest.param(*NUMBER_OPTION, id="Option"), pytest.param( click.Option(["--cache/--no-cache", "-c/-u"]), { "name": "cache", "param_type_name": "option", "opts": ["--cache", "-c"], "secondary_opts": ["--no-cache", "-u"], "type": BOOL_PARAM_TYPE[1], "required": False, "nargs": 1, "multiple": False, "default": False, "envvar": None, "help": None, "prompt": None, "is_flag": True, "flag_value": True, "count": False, "hidden": False, }, id="Flag Option", ), pytest.param(*NAME_ARGUMENT, id="Argument"), ],)def test_parameter(obj, expect): out = obj.to_info_dict() assert out == expect
@pytest.mark.parametrize( ("obj", "expect"), [ pytest.param(*HELLO_COMMAND, id="Command"), pytest.param(*HELLO_GROUP, id="Group"), pytest.param( click.Group( "base", [click.Command("test", params=[NAME_ARGUMENT[0]]), HELLO_GROUP[0]], ), { "name": "base", "params": [HELP_OPTION[1]], "help": None, "epilog": None, "short_help": None, "hidden": False, "deprecated": False, "commands": { "cli": HELLO_GROUP[1], "test": { "name": "test", "params": [NAME_ARGUMENT[1], HELP_OPTION[1]], "help": None, "epilog": None, "short_help": None, "hidden": False, "deprecated": False, }, }, "chain": False, }, id="Nested Group", ), ],)def test_command(obj, expect): ctx = click.Context(obj) out = obj.to_info_dict(ctx) assert out == expect
def test_context(): ctx = click.Context(HELLO_COMMAND[0]) out = ctx.to_info_dict() assert out == { "command": HELLO_COMMAND[1], "info_name": None, "allow_extra_args": False, "allow_interspersed_args": True, "ignore_unknown_options": False, "auto_envvar_prefix": None, }
def test_paramtype_no_name(): class TestType(click.ParamType): pass
assert TestType().to_info_dict()["name"] == "TestType"1234567891011121314151617181920212223242526272829303132333435363738import click
CONTEXT_SETTINGS = dict(token_normalize_func=lambda x: x.lower())
def test_option_normalization(runner): @click.command(context_settings=CONTEXT_SETTINGS) @click.option("--foo") @click.option("-x") def cli(foo, x): click.echo(foo) click.echo(x)
result = runner.invoke(cli, ["--FOO", "42", "-X", 23]) assert result.output == "42\n23\n"
def test_choice_normalization(runner): @click.command(context_settings=CONTEXT_SETTINGS) @click.option("--choice", type=click.Choice(["Foo", "Bar"])) def cli(choice): click.echo(choice)
result = runner.invoke(cli, ["--CHOICE", "FOO"]) assert result.output == "Foo\n"
def test_command_normalization(runner): @click.group(context_settings=CONTEXT_SETTINGS) def cli(): pass
@cli.command() def foo(): click.echo("here!")
result = runner.invoke(cli, ["FOO"]) assert result.output == "here!\n"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017import osimport re
import pytest
import clickfrom click import Option
def test_prefixes(runner): @click.command() @click.option("++foo", is_flag=True, help="das foo") @click.option("--bar", is_flag=True, help="das bar") def cli(foo, bar): click.echo(f"foo={foo} bar={bar}")
result = runner.invoke(cli, ["++foo", "--bar"]) assert not result.exception assert result.output == "foo=True bar=True\n"
result = runner.invoke(cli, ["--help"]) assert re.search(r"\+\+foo\s+das foo", result.output) is not None assert re.search(r"--bar\s+das bar", result.output) is not None
def test_invalid_option(runner): with pytest.raises(TypeError, match="name was passed") as exc_info: click.Option(["foo"])
message = str(exc_info.value) assert "name was passed (foo)" in message assert "declare an argument" in message assert "'--foo'" in message
def test_invalid_nargs(runner): with pytest.raises(TypeError, match="nargs=-1"):
@click.command() @click.option("--foo", nargs=-1) def cli(foo): pass
def test_nargs_tup_composite_mult(runner): @click.command() @click.option("--item", type=(str, int), multiple=True) def copy(item): for name, id in item: click.echo(f"name={name} id={id:d}")
result = runner.invoke(copy, ["--item", "peter", "1", "--item", "max", "2"]) assert not result.exception assert result.output.splitlines() == ["name=peter id=1", "name=max id=2"]
def test_counting(runner): @click.command() @click.option("-v", count=True, help="Verbosity", type=click.IntRange(0, 3)) def cli(v): click.echo(f"verbosity={v:d}")
result = runner.invoke(cli, ["-vvv"]) assert not result.exception assert result.output == "verbosity=3\n"
result = runner.invoke(cli, ["-vvvv"]) assert result.exception assert "Invalid value for '-v': 4 is not in the range 0<=x<=3." in result.output
result = runner.invoke(cli, []) assert not result.exception assert result.output == "verbosity=0\n"
result = runner.invoke(cli, ["--help"]) assert re.search(r"-v\s+Verbosity", result.output) is not None
@pytest.mark.parametrize("unknown_flag", ["--foo", "-f"])def test_unknown_options(runner, unknown_flag): @click.command() def cli(): pass
result = runner.invoke(cli, [unknown_flag]) assert result.exception assert f"No such option: {unknown_flag}" in result.output
@pytest.mark.parametrize( ("value", "expect"), [ ("--cat", "Did you mean --count?"), ("--bounds", "(Possible options: --bound, --count)"), ("--bount", "(Possible options: --bound, --count)"), ],)def test_suggest_possible_options(runner, value, expect): cli = click.Command( "cli", params=[click.Option(["--bound"]), click.Option(["--count"])] ) result = runner.invoke(cli, [value]) assert expect in result.output
def test_multiple_required(runner): @click.command() @click.option("-m", "--message", multiple=True, required=True) def cli(message): click.echo("\n".join(message))
result = runner.invoke(cli, ["-m", "foo", "-mbar"]) assert not result.exception assert result.output == "foo\nbar\n"
result = runner.invoke(cli, []) assert result.exception assert "Error: Missing option '-m' / '--message'." in result.output
@pytest.mark.parametrize( ("multiple", "nargs", "default"), [ (True, 1, []), (True, 1, [1]), # (False, -1, []), # (False, -1, [1]), (False, 2, [1, 2]), # (True, -1, [[]]), # (True, -1, []), # (True, -1, [[1]]), (True, 2, []), (True, 2, [[1, 2]]), ],)def test_init_good_default_list(runner, multiple, nargs, default): click.Option(["-a"], multiple=multiple, nargs=nargs, default=default)
@pytest.mark.parametrize( ("multiple", "nargs", "default"), [ (True, 1, 1), # (False, -1, 1), (False, 2, [1]), (True, 2, [[1]]), ],)def test_init_bad_default_list(runner, multiple, nargs, default): type = (str, str) if nargs == 2 else None
with pytest.raises(ValueError, match="default"): click.Option(["-a"], type=type, multiple=multiple, nargs=nargs, default=default)
@pytest.mark.parametrize("env_key", ["MYPATH", "AUTO_MYPATH"])def test_empty_envvar(runner, env_key): @click.command() @click.option("--mypath", type=click.Path(exists=True), envvar="MYPATH") def cli(mypath): click.echo(f"mypath: {mypath}")
result = runner.invoke(cli, env={env_key: ""}, auto_envvar_prefix="AUTO") assert result.exception is None assert result.output == "mypath: None\n"
def test_multiple_envvar(runner): @click.command() @click.option("--arg", multiple=True) def cmd(arg): click.echo("|".join(arg))
result = runner.invoke( cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar baz"} ) assert not result.exception assert result.output == "foo|bar|baz\n"
@click.command() @click.option("--arg", multiple=True, envvar="X") def cmd(arg): click.echo("|".join(arg))
result = runner.invoke(cmd, [], env={"X": "foo bar baz"}) assert not result.exception assert result.output == "foo|bar|baz\n"
@click.command() @click.option("--arg", multiple=True, type=click.Path()) def cmd(arg): click.echo("|".join(arg))
result = runner.invoke( cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": f"foo{os.path.pathsep}bar"}, ) assert not result.exception assert result.output == "foo|bar\n"
def test_trailing_blanks_boolean_envvar(runner): @click.command() @click.option("--shout/--no-shout", envvar="SHOUT") def cli(shout): click.echo(f"shout: {shout!r}")
result = runner.invoke(cli, [], env={"SHOUT": " true "}) assert result.exit_code == 0 assert result.output == "shout: True\n"
def test_multiple_default_help(runner): @click.command() @click.option("--arg1", multiple=True, default=("foo", "bar"), show_default=True) @click.option("--arg2", multiple=True, default=(1, 2), type=int, show_default=True) def cmd(arg, arg2): pass
result = runner.invoke(cmd, ["--help"]) assert not result.exception assert "foo, bar" in result.output assert "1, 2" in result.output
def test_show_default_default_map(runner): @click.command() @click.option("--arg", default="a", show_default=True) def cmd(arg): click.echo(arg)
result = runner.invoke(cmd, ["--help"], default_map={"arg": "b"})
assert not result.exception assert "[default: b]" in result.output
def test_multiple_default_type(): opt = click.Option(["-a"], multiple=True, default=(1, 2)) assert opt.nargs == 1 assert opt.multiple assert opt.type is click.INT ctx = click.Context(click.Command("test")) assert opt.get_default(ctx) == (1, 2)
def test_multiple_default_composite_type(): opt = click.Option(["-a"], multiple=True, default=[(1, "a")]) assert opt.nargs == 2 assert opt.multiple assert isinstance(opt.type, click.Tuple) assert opt.type.types == [click.INT, click.STRING] ctx = click.Context(click.Command("test")) assert opt.type_cast_value(ctx, opt.get_default(ctx)) == ((1, "a"),)
def test_parse_multiple_default_composite_type(runner): @click.command() @click.option("-a", multiple=True, default=("a", "b")) @click.option("-b", multiple=True, default=[(1, "a")]) def cmd(a, b): click.echo(a) click.echo(b)
# result = runner.invoke(cmd, "-a c -a 1 -a d -b 2 two -b 4 four".split()) # assert result.output == "('c', '1', 'd')\n((2, 'two'), (4, 'four'))\n" result = runner.invoke(cmd) assert result.output == "('a', 'b')\n((1, 'a'),)\n"
def test_dynamic_default_help_unset(runner): @click.command() @click.option( "--username", prompt=True, default=lambda: os.environ.get("USER", ""), show_default=True, ) def cmd(username): print("Hello,", username)
result = runner.invoke(cmd, ["--help"]) assert result.exit_code == 0 assert "--username" in result.output assert "lambda" not in result.output assert "(dynamic)" in result.output
def test_dynamic_default_help_text(runner): @click.command() @click.option( "--username", prompt=True, default=lambda: os.environ.get("USER", ""), show_default="current user", ) def cmd(username): print("Hello,", username)
result = runner.invoke(cmd, ["--help"]) assert result.exit_code == 0 assert "--username" in result.output assert "lambda" not in result.output assert "(current user)" in result.output
def test_dynamic_default_help_special_method(runner): class Value: def __call__(self): return 42
def __str__(self): return "special value"
opt = click.Option(["-a"], default=Value(), show_default=True) ctx = click.Context(click.Command("cli")) assert opt.get_help_extra(ctx) == {"default": "special value"} assert "special value" in opt.get_help_record(ctx)[1]
@pytest.mark.parametrize( ("type", "expect"), [ (click.IntRange(1, 32), "1<=x<=32"), (click.IntRange(1, 32, min_open=True, max_open=True), "1<x<32"), (click.IntRange(1), "x>=1"), (click.IntRange(max=32), "x<=32"), ],)def test_intrange_default_help_text(type, expect): option = click.Option(["--num"], type=type, show_default=True, default=2) context = click.Context(click.Command("test")) assert option.get_help_extra(context) == {"default": "2", "range": expect} result = option.get_help_record(context)[1] assert expect in result
def test_count_default_type_help(): """A count option with the default type should not show >=0 in help.""" option = click.Option(["--count"], count=True, help="some words") context = click.Context(click.Command("test")) assert option.get_help_extra(context) == {} result = option.get_help_record(context)[1] assert result == "some words"
def test_file_type_help_default(): """The default for a File type is a filename string. The string should be displayed in help, not an open file object.
Type casting is only applied to defaults in processing, not when getting the default value. """ option = click.Option( ["--in"], type=click.File(), default=__file__, show_default=True ) context = click.Context(click.Command("test")) assert option.get_help_extra(context) == {"default": __file__} result = option.get_help_record(context)[1] assert __file__ in result
def test_toupper_envvar_prefix(runner): @click.command() @click.option("--arg") def cmd(arg): click.echo(arg)
result = runner.invoke(cmd, [], auto_envvar_prefix="test", env={"TEST_ARG": "foo"}) assert not result.exception assert result.output == "foo\n"
def test_nargs_envvar(runner): @click.command() @click.option("--arg", nargs=2) def cmd(arg): click.echo("|".join(arg))
result = runner.invoke( cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar"} ) assert not result.exception assert result.output == "foo|bar\n"
@click.command() @click.option("--arg", nargs=2, multiple=True) def cmd(arg): for item in arg: click.echo("|".join(item))
result = runner.invoke( cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "x 1 y 2"} ) assert not result.exception assert result.output == "x|1\ny|2\n"
def test_show_envvar(runner): @click.command() @click.option("--arg1", envvar="ARG1", show_envvar=True) def cmd(arg): pass
result = runner.invoke(cmd, ["--help"]) assert not result.exception assert "ARG1" in result.output
def test_show_envvar_auto_prefix(runner): @click.command() @click.option("--arg1", show_envvar=True) def cmd(arg): pass
result = runner.invoke(cmd, ["--help"], auto_envvar_prefix="TEST") assert not result.exception assert "TEST_ARG1" in result.output
def test_show_envvar_auto_prefix_dash_in_command(runner): @click.group() def cli(): pass
@cli.command() @click.option("--baz", show_envvar=True) def foo_bar(baz): pass
result = runner.invoke(cli, ["foo-bar", "--help"], auto_envvar_prefix="TEST") assert not result.exception assert "TEST_FOO_BAR_BAZ" in result.output
def test_custom_validation(runner): def validate_pos_int(ctx, param, value): if value < 0: raise click.BadParameter("Value needs to be positive") return value
@click.command() @click.option("--foo", callback=validate_pos_int, default=1) def cmd(foo): click.echo(foo)
result = runner.invoke(cmd, ["--foo", "-1"]) assert "Invalid value for '--foo': Value needs to be positive" in result.output
result = runner.invoke(cmd, ["--foo", "42"]) assert result.output == "42\n"
def test_callback_validates_prompt(runner, monkeypatch): def validate(ctx, param, value): if value < 0: raise click.BadParameter("should be positive")
return value
@click.command() @click.option("-a", type=int, callback=validate, prompt=True) def cli(a): click.echo(a)
result = runner.invoke(cli, input="-12\n60\n") assert result.output == "A: -12\nError: should be positive\nA: 60\n60\n"
def test_winstyle_options(runner): @click.command() @click.option("/debug;/no-debug", help="Enables or disables debug mode.") def cmd(debug): click.echo(debug)
result = runner.invoke(cmd, ["/debug"], help_option_names=["/?"]) assert result.output == "True\n" result = runner.invoke(cmd, ["/no-debug"], help_option_names=["/?"]) assert result.output == "False\n" result = runner.invoke(cmd, [], help_option_names=["/?"]) assert result.output == "False\n" result = runner.invoke(cmd, ["/?"], help_option_names=["/?"]) assert "/debug; /no-debug Enables or disables debug mode." in result.output assert "/? Show this message and exit." in result.output
def test_legacy_options(runner): @click.command() @click.option("-whatever") def cmd(whatever): click.echo(whatever)
result = runner.invoke(cmd, ["-whatever", "42"]) assert result.output == "42\n" result = runner.invoke(cmd, ["-whatever=23"]) assert result.output == "23\n"
def test_missing_option_string_cast(): ctx = click.Context(click.Command(""))
with pytest.raises(click.MissingParameter) as excinfo: click.Option(["-a"], required=True).process_value(ctx, None)
assert str(excinfo.value) == "Missing parameter: a"
def test_missing_required_flag(runner): cli = click.Command( "cli", params=[click.Option(["--on/--off"], is_flag=True, required=True)] ) result = runner.invoke(cli) assert result.exit_code == 2 assert "Error: Missing option '--on'." in result.output
def test_missing_choice(runner): @click.command() @click.option("--foo", type=click.Choice(["foo", "bar"]), required=True) def cmd(foo): click.echo(foo)
result = runner.invoke(cmd) assert result.exit_code == 2 error, separator, choices = result.output.partition("Choose from") assert "Error: Missing option '--foo'. " in error assert "Choose from" in separator assert "foo" in choices assert "bar" in choices
def test_missing_envvar(runner): cli = click.Command( "cli", params=[click.Option(["--foo"], envvar="bar", required=True)] ) result = runner.invoke(cli) assert result.exit_code == 2 assert "Error: Missing option '--foo'." in result.output cli = click.Command( "cli", params=[click.Option(["--foo"], envvar="bar", show_envvar=True, required=True)], ) result = runner.invoke(cli) assert result.exit_code == 2 assert "Error: Missing option '--foo' (env var: 'bar')." in result.output
def test_case_insensitive_choice(runner): @click.command() @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False)) def cmd(foo): click.echo(foo)
result = runner.invoke(cmd, ["--foo", "apple"]) assert result.exit_code == 0 assert result.output == "Apple\n"
result = runner.invoke(cmd, ["--foo", "oRANGe"]) assert result.exit_code == 0 assert result.output == "Orange\n"
result = runner.invoke(cmd, ["--foo", "Apple"]) assert result.exit_code == 0 assert result.output == "Apple\n"
@click.command() @click.option("--foo", type=click.Choice(["Orange", "Apple"])) def cmd2(foo): click.echo(foo)
result = runner.invoke(cmd2, ["--foo", "apple"]) assert result.exit_code == 2
result = runner.invoke(cmd2, ["--foo", "oRANGe"]) assert result.exit_code == 2
result = runner.invoke(cmd2, ["--foo", "Apple"]) assert result.exit_code == 0
def test_case_insensitive_choice_returned_exactly(runner): @click.command() @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False)) def cmd(foo): click.echo(foo)
result = runner.invoke(cmd, ["--foo", "apple"]) assert result.exit_code == 0 assert result.output == "Apple\n"
def test_option_help_preserve_paragraphs(runner): @click.command() @click.option( "-C", "--config", type=click.Path(), help="""Configuration file to use.
If not given, the environment variable CONFIG_FILE is consulted and used if set. If neither are given, a default configuration file is loaded.""", ) def cmd(config): pass
result = runner.invoke(cmd, ["--help"]) assert result.exit_code == 0 i = " " * 21 assert ( " -C, --config PATH Configuration file to use.\n" f"{i}\n" f"{i}If not given, the environment variable CONFIG_FILE is\n" f"{i}consulted and used if set. If neither are given, a default\n" f"{i}configuration file is loaded." ) in result.output
def test_argument_custom_class(runner): class CustomArgument(click.Argument): def get_default(self, ctx, call=True): """a dumb override of a default value for testing""" return "I am a default"
@click.command() @click.argument("testarg", cls=CustomArgument, default="you wont see me") def cmd(testarg): click.echo(testarg)
result = runner.invoke(cmd) assert "I am a default" in result.output assert "you wont see me" not in result.output
def test_option_custom_class(runner): class CustomOption(click.Option): def get_help_record(self, ctx): """a dumb override of a help text for testing""" return ("--help", "I am a help text")
@click.command() @click.option("--testoption", cls=CustomOption, help="you wont see me") def cmd(testoption): click.echo(testoption)
result = runner.invoke(cmd, ["--help"]) assert "I am a help text" in result.output assert "you wont see me" not in result.output
def test_option_custom_class_reusable(runner): """Ensure we can reuse a custom class option. See Issue #926"""
class CustomOption(click.Option): def get_help_record(self, ctx): """a dumb override of a help text for testing""" return ("--help", "I am a help text")
# Assign to a variable to re-use the decorator. testoption = click.option("--testoption", cls=CustomOption, help="you wont see me")
@click.command() @testoption def cmd1(testoption): click.echo(testoption)
@click.command() @testoption def cmd2(testoption): click.echo(testoption)
# Both of the commands should have the --help option now. for cmd in (cmd1, cmd2): result = runner.invoke(cmd, ["--help"]) assert "I am a help text" in result.output assert "you wont see me" not in result.output
def test_bool_flag_with_type(runner): @click.command() @click.option("--shout/--no-shout", default=False, type=bool) def cmd(shout): pass
result = runner.invoke(cmd) assert not result.exception
def test_aliases_for_flags(runner): @click.command() @click.option("--warnings/--no-warnings", " /-W", default=True) def cli(warnings): click.echo(warnings)
result = runner.invoke(cli, ["--warnings"]) assert result.output == "True\n" result = runner.invoke(cli, ["--no-warnings"]) assert result.output == "False\n" result = runner.invoke(cli, ["-W"]) assert result.output == "False\n"
@click.command() @click.option("--warnings/--no-warnings", "-w", default=True) def cli_alt(warnings): click.echo(warnings)
result = runner.invoke(cli_alt, ["--warnings"]) assert result.output == "True\n" result = runner.invoke(cli_alt, ["--no-warnings"]) assert result.output == "False\n" result = runner.invoke(cli_alt, ["-w"]) assert result.output == "True\n"
@pytest.mark.parametrize( "option_args,expected", [ (["--aggressive", "--all", "-a"], "aggressive"), (["--first", "--second", "--third", "-a", "-b", "-c"], "first"), (["--apple", "--banana", "--cantaloupe", "-a", "-b", "-c"], "apple"), (["--cantaloupe", "--banana", "--apple", "-c", "-b", "-a"], "cantaloupe"), (["-a", "-b", "-c"], "a"), (["-c", "-b", "-a"], "c"), (["-a", "--apple", "-b", "--banana", "-c", "--cantaloupe"], "apple"), (["-c", "-a", "--cantaloupe", "-b", "--banana", "--apple"], "cantaloupe"), (["--from", "-f", "_from"], "_from"), (["--return", "-r", "_ret"], "_ret"), ],)def test_option_names(runner, option_args, expected): @click.command() @click.option(*option_args, is_flag=True) def cmd(**kwargs): click.echo(str(kwargs[expected]))
assert cmd.params[0].name == expected
for form in option_args: if form.startswith("-"): result = runner.invoke(cmd, [form]) assert result.output == "True\n"
def test_flag_duplicate_names(runner): with pytest.raises(ValueError, match="cannot use the same flag for true/false"): click.Option(["--foo/--foo"], default=False)
@pytest.mark.parametrize(("default", "expect"), [(False, "no-cache"), (True, "cache")])def test_show_default_boolean_flag_name(runner, default, expect): """When a boolean flag has distinct True/False opts, it should show the default opt name instead of the default value. It should only show one name even if multiple are declared. """ opt = click.Option( ("--cache/--no-cache", "--c/--nc"), default=default, show_default=True, help="Enable/Disable the cache.", ) ctx = click.Context(click.Command("test")) assert opt.get_help_extra(ctx) == {"default": expect} message = opt.get_help_record(ctx)[1] assert f"[default: {expect}]" in message
def test_show_true_default_boolean_flag_value(runner): """When a boolean flag only has one opt and its default is True, it will show the default value, not the opt name. """ opt = click.Option( ("--cache",), is_flag=True, show_default=True, default=True, help="Enable the cache.", ) ctx = click.Context(click.Command("test")) assert opt.get_help_extra(ctx) == {"default": "True"} message = opt.get_help_record(ctx)[1] assert "[default: True]" in message
@pytest.mark.parametrize("default", [False, None])def test_hide_false_default_boolean_flag_value(runner, default): """When a boolean flag only has one opt and its default is False or None, it will not show the default """ opt = click.Option( ("--cache",), is_flag=True, show_default=True, default=default, help="Enable the cache.", ) ctx = click.Context(click.Command("test")) assert opt.get_help_extra(ctx) == {} message = opt.get_help_record(ctx)[1] assert "[default: " not in message
def test_show_default_string(runner): """When show_default is a string show that value as default.""" opt = click.Option(["--limit"], show_default="unlimited") ctx = click.Context(click.Command("cli")) assert opt.get_help_extra(ctx) == {"default": "(unlimited)"} message = opt.get_help_record(ctx)[1] assert "[default: (unlimited)]" in message
def test_show_default_with_empty_string(runner): """When show_default is True and default is set to an empty string.""" opt = click.Option(["--limit"], default="", show_default=True) ctx = click.Context(click.Command("cli")) message = opt.get_help_record(ctx)[1] assert '[default: ""]' in message
def test_do_not_show_no_default(runner): """When show_default is True and no default is set do not show None.""" opt = click.Option(["--limit"], show_default=True) ctx = click.Context(click.Command("cli")) assert opt.get_help_extra(ctx) == {} message = opt.get_help_record(ctx)[1] assert "[default: None]" not in message
def test_do_not_show_default_empty_multiple(): """When show_default is True and multiple=True is set, it should not print empty default value in --help output. """ opt = click.Option(["-a"], multiple=True, help="values", show_default=True) ctx = click.Context(click.Command("cli")) assert opt.get_help_extra(ctx) == {} message = opt.get_help_record(ctx)[1] assert message == "values"
@pytest.mark.parametrize( ("ctx_value", "opt_value", "extra_value", "expect"), [ (None, None, {}, False), (None, False, {}, False), (None, True, {"default": "1"}, True), (False, None, {}, False), (False, False, {}, False), (False, True, {"default": "1"}, True), (True, None, {"default": "1"}, True), (True, False, {}, False), (True, True, {"default": "1"}, True), (False, "one", {"default": "(one)"}, True), ],)def test_show_default_precedence(ctx_value, opt_value, extra_value, expect): ctx = click.Context(click.Command("test"), show_default=ctx_value) opt = click.Option("-a", default=1, help="value", show_default=opt_value) assert opt.get_help_extra(ctx) == extra_value help = opt.get_help_record(ctx)[1] assert ("default:" in help) is expect
@pytest.mark.parametrize( ("args", "expect"), [ (None, (None, None, ())), (["--opt"], ("flag", None, ())), (["--opt", "-a", 42], ("flag", "42", ())), (["--opt", "test", "-a", 42], ("test", "42", ())), (["--opt=test", "-a", 42], ("test", "42", ())), (["-o"], ("flag", None, ())), (["-o", "-a", 42], ("flag", "42", ())), (["-o", "test", "-a", 42], ("test", "42", ())), (["-otest", "-a", 42], ("test", "42", ())), (["a", "b", "c"], (None, None, ("a", "b", "c"))), (["--opt", "a", "b", "c"], ("a", None, ("b", "c"))), (["--opt", "test"], ("test", None, ())), (["-otest", "a", "b", "c"], ("test", None, ("a", "b", "c"))), (["--opt=test", "a", "b", "c"], ("test", None, ("a", "b", "c"))), ],)def test_option_with_optional_value(runner, args, expect): @click.command() @click.option("-o", "--opt", is_flag=False, flag_value="flag") @click.option("-a") @click.argument("b", nargs=-1) def cli(opt, a, b): return opt, a, b
result = runner.invoke(cli, args, standalone_mode=False, catch_exceptions=False) assert result.return_value == expect
def test_multiple_option_with_optional_value(runner): cli = click.Command( "cli", params=[ click.Option(["-f"], is_flag=False, flag_value="flag", multiple=True), click.Option(["-a"]), click.Argument(["b"], nargs=-1), ], callback=lambda **kwargs: kwargs, ) result = runner.invoke( cli, ["-f", "-f", "other", "-f", "-a", "1", "a", "b"], standalone_mode=False, catch_exceptions=False, ) assert result.return_value == { "f": ("flag", "other", "flag"), "a": "1", "b": ("a", "b"), }
def test_type_from_flag_value(): param = click.Option(["-a", "x"], default=True, flag_value=4) assert param.type is click.INT param = click.Option(["-b", "x"], flag_value=8) assert param.type is click.INT
@pytest.mark.parametrize( ("option", "expected"), [ # Not boolean flags pytest.param(Option(["-a"], type=int), False, id="int option"), pytest.param(Option(["-a"], type=bool), False, id="bool non-flag [None]"), pytest.param(Option(["-a"], default=True), False, id="bool non-flag [True]"), pytest.param(Option(["-a"], default=False), False, id="bool non-flag [False]"), pytest.param(Option(["-a"], flag_value=1), False, id="non-bool flag_value"), # Boolean flags pytest.param(Option(["-a"], is_flag=True), True, id="is_flag=True"), pytest.param(Option(["-a/-A"]), True, id="secondary option [implicit flag]"), pytest.param(Option(["-a"], flag_value=True), True, id="bool flag_value"), ],)def test_is_bool_flag_is_correctly_set(option, expected): assert option.is_bool_flag is expected
@pytest.mark.parametrize( ("kwargs", "message"), [ ({"count": True, "multiple": True}, "'count' is not valid with 'multiple'."), ({"count": True, "is_flag": True}, "'count' is not valid with 'is_flag'."), ],)def test_invalid_flag_combinations(runner, kwargs, message): with pytest.raises(TypeError) as e: click.Option(["-a"], **kwargs)
assert message in str(e.value)
@pytest.mark.parametrize( ("choices", "metavars"), [ pytest.param(["foo", "bar"], "[TEXT]", id="text choices"), pytest.param([1, 2], "[INTEGER]", id="int choices"), pytest.param([1.0, 2.0], "[FLOAT]", id="float choices"), pytest.param([True, False], "[BOOLEAN]", id="bool choices"), pytest.param(["foo", 1], "[TEXT|INTEGER]", id="text/int choices"), ],)def test_usage_show_choices(runner, choices, metavars): """When show_choices=False is set, the --help output should print choice metavars instead of values. """
@click.command() @click.option("-g", type=click.Choice(choices)) def cli_with_choices(g): pass
@click.command() @click.option( "-g", type=click.Choice(choices), show_choices=False, ) def cli_without_choices(g): pass
result = runner.invoke(cli_with_choices, ["--help"]) assert f"[{'|'.join([str(i) for i in choices])}]" in result.output
result = runner.invoke(cli_without_choices, ["--help"]) assert metavars in result.output
@pytest.mark.parametrize( "opts_one,opts_two", [ # No duplicate shortnames ( ("-a", "--aardvark"), ("-a", "--avocado"), ), # No duplicate long names ( ("-a", "--aardvark"), ("-b", "--aardvark"), ), ],)def test_duplicate_names_warning(runner, opts_one, opts_two): @click.command() @click.option(*opts_one) @click.option(*opts_two) def cli(one, two): pass
with pytest.warns(UserWarning): runner.invoke(cli, [])1234567891011121314151617181920212223242526272829303132import pytest
import clickfrom click.parser import _OptionParserfrom click.shell_completion import split_arg_string
@pytest.mark.parametrize( ("value", "expect"), [ ("cli a b c", ["cli", "a", "b", "c"]), ("cli 'my file", ["cli", "my file"]), ("cli 'my file'", ["cli", "my file"]), ("cli my\\", ["cli", "my"]), ("cli my\\ file", ["cli", "my file"]), ],)def test_split_arg_string(value, expect): assert split_arg_string(value) == expect
def test_parser_default_prefixes(): parser = _OptionParser() assert parser._opt_prefixes == {"-", "--"}
def test_parser_collects_prefixes(): ctx = click.Context(click.Command("test")) parser = _OptionParser(ctx) click.Option("+p", is_flag=True).add_to_parser(parser, ctx) click.Option("!e", is_flag=True).add_to_parser(parser, ctx) assert parser._opt_prefixes == {"-", "--", "+", "!"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442import warnings
import pytest
import click.shell_completionfrom click.core import Argumentfrom click.core import Commandfrom click.core import Groupfrom click.core import Optionfrom click.shell_completion import add_completion_classfrom click.shell_completion import CompletionItemfrom click.shell_completion import ShellCompletefrom click.types import Choicefrom click.types import Filefrom click.types import Path
def _get_completions(cli, args, incomplete): comp = ShellComplete(cli, {}, cli.name, "_CLICK_COMPLETE") return comp.get_completions(args, incomplete)
def _get_words(cli, args, incomplete): return [c.value for c in _get_completions(cli, args, incomplete)]
def test_command(): cli = Command("cli", params=[Option(["-t", "--test"])]) assert _get_words(cli, [], "") == [] assert _get_words(cli, [], "-") == ["-t", "--test", "--help"] assert _get_words(cli, [], "--") == ["--test", "--help"] assert _get_words(cli, [], "--t") == ["--test"] # -t has been seen, so --test isn't suggested assert _get_words(cli, ["-t", "a"], "-") == ["--help"]
def test_group(): cli = Group("cli", params=[Option(["-a"])], commands=[Command("x"), Command("y")]) assert _get_words(cli, [], "") == ["x", "y"] assert _get_words(cli, [], "-") == ["-a", "--help"]
def test_group_command_same_option(): cli = Group( "cli", params=[Option(["-a"])], commands=[Command("x", params=[Option(["-a"])])] ) assert _get_words(cli, [], "-") == ["-a", "--help"] assert _get_words(cli, ["-a", "a"], "-") == ["--help"] assert _get_words(cli, ["-a", "a", "x"], "-") == ["-a", "--help"] assert _get_words(cli, ["-a", "a", "x", "-a", "a"], "-") == ["--help"]
def test_chained(): cli = Group( "cli", chain=True, commands=[ Command("set", params=[Option(["-y"])]), Command("start"), Group("get", commands=[Command("full")]), ], ) assert _get_words(cli, [], "") == ["get", "set", "start"] assert _get_words(cli, [], "s") == ["set", "start"] assert _get_words(cli, ["set", "start"], "") == ["get"] # subcommands and parent subcommands assert _get_words(cli, ["get"], "") == ["full", "set", "start"] assert _get_words(cli, ["get", "full"], "") == ["set", "start"] assert _get_words(cli, ["get"], "s") == ["set", "start"]
def test_help_option(): cli = Group("cli", commands=[Command("with"), Command("no", add_help_option=False)]) assert _get_words(cli, ["with"], "--") == ["--help"] assert _get_words(cli, ["no"], "--") == []
def test_argument_order(): cli = Command( "cli", params=[ Argument(["plain"]), Argument(["c1"], type=Choice(["a1", "a2", "b"])), Argument(["c2"], type=Choice(["c1", "c2", "d"])), ], ) # first argument has no completions assert _get_words(cli, [], "") == [] assert _get_words(cli, [], "a") == [] # first argument filled, now completion can happen assert _get_words(cli, ["x"], "a") == ["a1", "a2"] assert _get_words(cli, ["x", "b"], "d") == ["d"]
def test_argument_default(): cli = Command( "cli", add_help_option=False, params=[ Argument(["a"], type=Choice(["a"]), default="a"), Argument(["b"], type=Choice(["b"]), default="b"), ], ) assert _get_words(cli, [], "") == ["a"] assert _get_words(cli, ["a"], "b") == ["b"] # ignore type validation assert _get_words(cli, ["x"], "b") == ["b"]
def test_type_choice(): cli = Command("cli", params=[Option(["-c"], type=Choice(["a1", "a2", "b"]))]) assert _get_words(cli, ["-c"], "") == ["a1", "a2", "b"] assert _get_words(cli, ["-c"], "a") == ["a1", "a2"] assert _get_words(cli, ["-c"], "a2") == ["a2"]
def test_choice_special_characters(): cli = Command("cli", params=[Option(["-c"], type=Choice(["!1", "!2", "+3"]))]) assert _get_words(cli, ["-c"], "") == ["!1", "!2", "+3"] assert _get_words(cli, ["-c"], "!") == ["!1", "!2"] assert _get_words(cli, ["-c"], "!2") == ["!2"]
def test_choice_conflicting_prefix(): cli = Command( "cli", params=[ Option(["-c"], type=Choice(["!1", "!2", "+3"])), Option(["+p"], is_flag=True), ], ) assert _get_words(cli, ["-c"], "") == ["!1", "!2", "+3"] assert _get_words(cli, ["-c"], "+") == ["+p"]
def test_option_count(): cli = Command("cli", params=[Option(["-c"], count=True)]) assert _get_words(cli, ["-c"], "") == [] assert _get_words(cli, ["-c"], "-") == ["--help"]
def test_option_optional(): cli = Command( "cli", add_help_option=False, params=[ Option(["--name"], is_flag=False, flag_value="value"), Option(["--flag"], is_flag=True), ], ) assert _get_words(cli, ["--name"], "") == [] assert _get_words(cli, ["--name"], "-") == ["--flag"] assert _get_words(cli, ["--name", "--flag"], "-") == []
@pytest.mark.parametrize( ("type", "expect"), [(File(), "file"), (Path(), "file"), (Path(file_okay=False), "dir")],)def test_path_types(type, expect): cli = Command("cli", params=[Option(["-f"], type=type)]) out = _get_completions(cli, ["-f"], "ab") assert len(out) == 1 c = out[0] assert c.value == "ab" assert c.type == expect
def test_absolute_path(): cli = Command("cli", params=[Option(["-f"], type=Path())]) out = _get_completions(cli, ["-f"], "/ab") assert len(out) == 1 c = out[0] assert c.value == "/ab"
def test_option_flag(): cli = Command( "cli", add_help_option=False, params=[ Option(["--on/--off"]), Argument(["a"], type=Choice(["a1", "a2", "b"])), ], ) assert _get_words(cli, [], "--") == ["--on", "--off"] # flag option doesn't take value, use choice argument assert _get_words(cli, ["--on"], "a") == ["a1", "a2"]
def test_option_custom(): def custom(ctx, param, incomplete): return [incomplete.upper()]
cli = Command( "cli", params=[ Argument(["x"]), Argument(["y"]), Argument(["z"], shell_complete=custom), ], ) assert _get_words(cli, ["a", "b"], "") == [""] assert _get_words(cli, ["a", "b"], "c") == ["C"]
def test_option_multiple(): cli = Command( "type", params=[Option(["-m"], type=Choice(["a", "b"]), multiple=True), Option(["-f"])], ) assert _get_words(cli, ["-m"], "") == ["a", "b"] assert "-m" in _get_words(cli, ["-m", "a"], "-") assert _get_words(cli, ["-m", "a", "-m"], "") == ["a", "b"] # used single options aren't suggested again assert "-c" not in _get_words(cli, ["-c", "f"], "-")
def test_option_nargs(): cli = Command("cli", params=[Option(["-c"], type=Choice(["a", "b"]), nargs=2)]) assert _get_words(cli, ["-c"], "") == ["a", "b"] assert _get_words(cli, ["-c", "a"], "") == ["a", "b"] assert _get_words(cli, ["-c", "a", "b"], "") == []
def test_argument_nargs(): cli = Command( "cli", params=[ Argument(["x"], type=Choice(["a", "b"]), nargs=2), Argument(["y"], type=Choice(["c", "d"]), nargs=-1), Option(["-z"]), ], ) assert _get_words(cli, [], "") == ["a", "b"] assert _get_words(cli, ["a"], "") == ["a", "b"] assert _get_words(cli, ["a", "b"], "") == ["c", "d"] assert _get_words(cli, ["a", "b", "c"], "") == ["c", "d"] assert _get_words(cli, ["a", "b", "c", "d"], "") == ["c", "d"] assert _get_words(cli, ["a", "-z", "1"], "") == ["a", "b"] assert _get_words(cli, ["a", "-z", "1", "b"], "") == ["c", "d"]
def test_double_dash(): cli = Command( "cli", add_help_option=False, params=[ Option(["--opt"]), Argument(["name"], type=Choice(["name", "--", "-o", "--opt"])), ], ) assert _get_words(cli, [], "-") == ["--opt"] assert _get_words(cli, ["value"], "-") == ["--opt"] assert _get_words(cli, [], "") == ["name", "--", "-o", "--opt"] assert _get_words(cli, ["--"], "") == ["name", "--", "-o", "--opt"]
def test_hidden(): cli = Group( "cli", commands=[ Command( "hidden", add_help_option=False, hidden=True, params=[ Option(["-a"]), Option(["-b"], type=Choice(["a", "b"]), hidden=True), ], ) ], ) assert "hidden" not in _get_words(cli, [], "") assert "hidden" not in _get_words(cli, [], "hidden") assert _get_words(cli, ["hidden"], "-") == ["-a"] assert _get_words(cli, ["hidden", "-b"], "") == ["a", "b"]
def test_add_different_name(): cli = Group("cli", commands={"renamed": Command("original")}) words = _get_words(cli, [], "") assert "renamed" in words assert "original" not in words
def test_completion_item_data(): c = CompletionItem("test", a=1) assert c.a == 1 assert c.b is None
@pytest.fixture()def _patch_for_completion(monkeypatch): monkeypatch.setattr( "click.shell_completion.BashComplete._check_version", lambda self: True )
@pytest.mark.parametrize("shell", ["bash", "zsh", "fish"])@pytest.mark.usefixtures("_patch_for_completion")def test_full_source(runner, shell): cli = Group("cli", commands=[Command("a"), Command("b")]) result = runner.invoke(cli, env={"_CLI_COMPLETE": f"{shell}_source"}) assert f"_CLI_COMPLETE={shell}_complete" in result.output
@pytest.mark.parametrize( ("shell", "env", "expect"), [ ("bash", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain,a\nplain,b\n"), ("bash", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain,b\n"), ("zsh", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain\na\n_\nplain\nb\nbee\n"), ("zsh", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain\nb\nbee\n"), ("fish", {"COMP_WORDS": "", "COMP_CWORD": ""}, "plain,a\nplain,b\tbee\n"), ("fish", {"COMP_WORDS": "a b", "COMP_CWORD": "b"}, "plain,b\tbee\n"), ],)@pytest.mark.usefixtures("_patch_for_completion")def test_full_complete(runner, shell, env, expect): cli = Group("cli", commands=[Command("a"), Command("b", help="bee")]) env["_CLI_COMPLETE"] = f"{shell}_complete" result = runner.invoke(cli, env=env) assert result.output == expect
@pytest.mark.usefixtures("_patch_for_completion")def test_context_settings(runner): def complete(ctx, param, incomplete): return ctx.obj["choices"]
cli = Command("cli", params=[Argument("x", shell_complete=complete)]) result = runner.invoke( cli, obj={"choices": ["a", "b"]}, env={"COMP_WORDS": "", "COMP_CWORD": "0", "_CLI_COMPLETE": "bash_complete"}, ) assert result.output == "plain,a\nplain,b\n"
@pytest.mark.parametrize(("value", "expect"), [(False, ["Au", "al"]), (True, ["al"])])def test_choice_case_sensitive(value, expect): cli = Command( "cli", params=[Option(["-a"], type=Choice(["Au", "al", "Bc"], case_sensitive=value))], ) completions = _get_words(cli, ["-a"], "a") assert completions == expect
@pytest.fixture()def _restore_available_shells(tmpdir): prev_available_shells = click.shell_completion._available_shells.copy() click.shell_completion._available_shells.clear() yield click.shell_completion._available_shells.clear() click.shell_completion._available_shells.update(prev_available_shells)
@pytest.mark.usefixtures("_restore_available_shells")def test_add_completion_class(): # At first, "mysh" is not in available shells assert "mysh" not in click.shell_completion._available_shells
class MyshComplete(ShellComplete): name = "mysh" source_template = "dummy source"
# "mysh" still not in available shells because it is not registered assert "mysh" not in click.shell_completion._available_shells
# Adding a completion class should return that class assert add_completion_class(MyshComplete) is MyshComplete
# Now, "mysh" is finally in available shells assert "mysh" in click.shell_completion._available_shells assert click.shell_completion._available_shells["mysh"] is MyshComplete
@pytest.mark.usefixtures("_restore_available_shells")def test_add_completion_class_with_name(): # At first, "mysh" is not in available shells assert "mysh" not in click.shell_completion._available_shells assert "not_mysh" not in click.shell_completion._available_shells
class MyshComplete(ShellComplete): name = "not_mysh" source_template = "dummy source"
# "mysh" and "not_mysh" are still not in available shells because # it is not registered yet assert "mysh" not in click.shell_completion._available_shells assert "not_mysh" not in click.shell_completion._available_shells
# Adding a completion class should return that class. # Because we are using the "name" parameter, the name isn't taken # from the class. assert add_completion_class(MyshComplete, name="mysh") is MyshComplete
# Now, "mysh" is finally in available shells assert "mysh" in click.shell_completion._available_shells assert "not_mysh" not in click.shell_completion._available_shells assert click.shell_completion._available_shells["mysh"] is MyshComplete
@pytest.mark.usefixtures("_restore_available_shells")def test_add_completion_class_decorator(): # At first, "mysh" is not in available shells assert "mysh" not in click.shell_completion._available_shells
@add_completion_class class MyshComplete(ShellComplete): name = "mysh" source_template = "dummy source"
# Using `add_completion_class` as a decorator adds the new shell immediately assert "mysh" in click.shell_completion._available_shells assert click.shell_completion._available_shells["mysh"] is MyshComplete
# Don't make the ResourceWarning give an error@pytest.mark.filterwarnings("default")def test_files_closed(runner) -> None: with runner.isolated_filesystem(): config_file = "foo.txt" with open(config_file, "w") as f: f.write("bar")
@click.group() @click.option( "--config-file", default=config_file, type=click.File(mode="r"), ) @click.pass_context def cli(ctx, config_file): pass
with warnings.catch_warnings(record=True) as current_warnings: assert not current_warnings, "There should be no warnings to start" _get_completions(cli, args=[], incomplete="") assert not current_warnings, "There should be no warnings after either"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487import platformimport tempfileimport time
import pytest
import click._termui_implfrom click._compat import WIN
class FakeClock: def __init__(self): self.now = time.time()
def advance_time(self, seconds=1): self.now += seconds
def time(self): return self.now
def _create_progress(length=10, **kwargs): progress = click.progressbar(tuple(range(length))) for key, value in kwargs.items(): setattr(progress, key, value) return progress
def test_progressbar_strip_regression(runner, monkeypatch): label = " padded line"
@click.command() def cli(): with _create_progress(label=label) as progress: for _ in progress: pass
monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True) assert ( label in runner.invoke(cli, [], standalone_mode=False, catch_exceptions=False).output )
def test_progressbar_length_hint(runner, monkeypatch): class Hinted: def __init__(self, n): self.items = list(range(n))
def __length_hint__(self): return len(self.items)
def __iter__(self): return self
def __next__(self): if self.items: return self.items.pop() else: raise StopIteration
next = __next__
@click.command() def cli(): with click.progressbar(Hinted(10), label="test") as progress: for _ in progress: pass
monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True) result = runner.invoke(cli, []) assert result.exception is None
def test_progressbar_no_tty(runner, monkeypatch): @click.command() def cli(): with _create_progress(label="working") as progress: for _ in progress: pass
monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False) assert runner.invoke(cli, []).output == "working\n"
def test_progressbar_hidden_manual(runner, monkeypatch): @click.command() def cli(): with _create_progress(label="see nothing", hidden=True) as progress: for _ in progress: pass
monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True) assert runner.invoke(cli, []).output == ""
@pytest.mark.parametrize("avg, expected", [([], 0.0), ([1, 4], 2.5)])def test_progressbar_time_per_iteration(runner, avg, expected): with _create_progress(2, avg=avg) as progress: assert progress.time_per_iteration == expected
@pytest.mark.parametrize("finished, expected", [(False, 5), (True, 0)])def test_progressbar_eta(runner, finished, expected): with _create_progress(2, finished=finished, avg=[1, 4]) as progress: assert progress.eta == expected
@pytest.mark.parametrize( "eta, expected", [ (0, "00:00:00"), (30, "00:00:30"), (90, "00:01:30"), (900, "00:15:00"), (9000, "02:30:00"), (99999999999, "1157407d 09:46:39"), (None, ""), ],)def test_progressbar_format_eta(runner, eta, expected): with _create_progress(1, eta_known=eta is not None, avg=[eta]) as progress: assert progress.format_eta() == expected
@pytest.mark.parametrize("pos, length", [(0, 5), (-1, 1), (5, 5), (6, 5), (4, 0)])def test_progressbar_format_pos(runner, pos, length): with _create_progress(length, pos=pos) as progress: result = progress.format_pos() assert result == f"{pos}/{length}"
@pytest.mark.parametrize( "length, finished, pos, avg, expected", [ (8, False, 7, 0, "#######-"), (0, True, 8, 0, "########"), ],)def test_progressbar_format_bar(runner, length, finished, pos, avg, expected): with _create_progress( length, width=8, pos=pos, finished=finished, avg=[avg] ) as progress: assert progress.format_bar() == expected
@pytest.mark.parametrize( "length, show_percent, show_pos, pos, expected", [ (0, True, True, 0, " [--------] 0/0 0%"), (0, False, True, 0, " [--------] 0/0"), (0, False, False, 0, " [--------]"), (0, False, False, 0, " [--------]"), (8, True, True, 8, " [########] 8/8 100%"), ],)def test_progressbar_format_progress_line( runner, length, show_percent, show_pos, pos, expected): with _create_progress( length, width=8, show_percent=show_percent, pos=pos, show_pos=show_pos, ) as progress: assert progress.format_progress_line() == expected
@pytest.mark.parametrize("test_item", ["test", None])def test_progressbar_format_progress_line_with_show_func(runner, test_item): def item_show_func(item): return item
with _create_progress( item_show_func=item_show_func, current_item=test_item ) as progress: if test_item: assert progress.format_progress_line().endswith(test_item) else: assert progress.format_progress_line().endswith(progress.format_pct())
def test_progressbar_init_exceptions(runner): with pytest.raises(TypeError, match="iterable or length is required"): click.progressbar()
def test_progressbar_iter_outside_with_exceptions(runner): progress = click.progressbar(length=2)
with pytest.raises(RuntimeError, match="with block"): iter(progress)
def test_progressbar_is_iterator(runner, monkeypatch): @click.command() def cli(): with click.progressbar(range(10), label="test") as progress: while True: try: next(progress) except StopIteration: break
monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True) result = runner.invoke(cli, []) assert result.exception is None
def test_choices_list_in_prompt(runner, monkeypatch): @click.command() @click.option( "-g", type=click.Choice(["none", "day", "week", "month"]), prompt=True ) def cli_with_choices(g): pass
@click.command() @click.option( "-g", type=click.Choice(["none", "day", "week", "month"]), prompt=True, show_choices=False, ) def cli_without_choices(g): pass
result = runner.invoke(cli_with_choices, [], input="none") assert "(none, day, week, month)" in result.output
result = runner.invoke(cli_without_choices, [], input="none") assert "(none, day, week, month)" not in result.output
@pytest.mark.parametrize( "file_kwargs", [{"mode": "rt"}, {"mode": "rb"}, {"lazy": True}])def test_file_prompt_default_format(runner, file_kwargs): @click.command() @click.option("-f", default=__file__, prompt="file", type=click.File(**file_kwargs)) def cli(f): click.echo(f.name)
result = runner.invoke(cli) assert result.output == f"file [{__file__}]: \n{__file__}\n"
def test_secho(runner): with runner.isolation() as outstreams: click.secho(None, nl=False) bytes = outstreams[0].getvalue() assert bytes == b""
@pytest.mark.skipif(platform.system() == "Windows", reason="No style on Windows.")@pytest.mark.parametrize( ("value", "expect"), [(123, b"\x1b[45m123\x1b[0m"), (b"test", b"test")])def test_secho_non_text(runner, value, expect): with runner.isolation() as (out, _, _): click.secho(value, nl=False, color=True, bg="magenta") result = out.getvalue() assert result == expect
def test_progressbar_yields_all_items(runner): with click.progressbar(range(3)) as progress: assert len(list(progress)) == 3
def test_progressbar_update(runner, monkeypatch): fake_clock = FakeClock()
@click.command() def cli(): with click.progressbar(range(4)) as progress: for _ in progress: fake_clock.advance_time() print("")
monkeypatch.setattr(time, "time", fake_clock.time) monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True) output = runner.invoke(cli, []).output
lines = [line for line in output.split("\n") if "[" in line]
assert " 0%" in lines[0] assert " 25% 00:00:03" in lines[1] assert " 50% 00:00:02" in lines[2] assert " 75% 00:00:01" in lines[3] assert "100% " in lines[4]
def test_progressbar_item_show_func(runner, monkeypatch): """item_show_func should show the current item being yielded."""
@click.command() def cli(): with click.progressbar(range(3), item_show_func=lambda x: str(x)) as progress: for item in progress: click.echo(f" item {item}")
monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True) lines = runner.invoke(cli).output.splitlines()
for i, line in enumerate(x for x in lines if "item" in x): assert f"{i} item {i}" in line
def test_progressbar_update_with_item_show_func(runner, monkeypatch): @click.command() def cli(): with click.progressbar( length=6, item_show_func=lambda x: f"Custom {x}" ) as progress: while not progress.finished: progress.update(2, progress.pos) click.echo()
monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True) output = runner.invoke(cli, []).output
lines = [line for line in output.split("\n") if "[" in line]
assert "Custom 0" in lines[0] assert "Custom 2" in lines[1] assert "Custom 4" in lines[2]
def test_progress_bar_update_min_steps(runner): bar = _create_progress(update_min_steps=5) bar.update(3) assert bar._completed_intervals == 3 assert bar.pos == 0 bar.update(2) assert bar._completed_intervals == 0 assert bar.pos == 5
@pytest.mark.parametrize("key_char", ("h", "H", "é", "À", " ", "字", "àH", "àR"))@pytest.mark.parametrize("echo", [True, False])@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")def test_getchar_windows(runner, monkeypatch, key_char, echo): monkeypatch.setattr(click._termui_impl.msvcrt, "getwche", lambda: key_char) monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char) monkeypatch.setattr(click.termui, "_getchar", None) assert click.getchar(echo) == key_char
@pytest.mark.parametrize( "special_key_char, key_char", [("\x00", "a"), ("\x00", "b"), ("\xe0", "c")])@pytest.mark.skipif( not WIN, reason="Tests special character inputs using the msvcrt module.")def test_getchar_special_key_windows(runner, monkeypatch, special_key_char, key_char): ordered_inputs = [key_char, special_key_char] monkeypatch.setattr( click._termui_impl.msvcrt, "getwch", lambda: ordered_inputs.pop() ) monkeypatch.setattr(click.termui, "_getchar", None) assert click.getchar() == f"{special_key_char}{key_char}"
@pytest.mark.parametrize( ("key_char", "exc"), [("\x03", KeyboardInterrupt), ("\x1a", EOFError)])@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")def test_getchar_windows_exceptions(runner, monkeypatch, key_char, exc): monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char) monkeypatch.setattr(click.termui, "_getchar", None)
with pytest.raises(exc): click.getchar()
@pytest.mark.skipif(platform.system() == "Windows", reason="No sed on Windows.")def test_fast_edit(runner): result = click.edit("a\nb", editor="sed -i~ 's/$/Test/'") assert result == "aTest\nbTest\n"
@pytest.mark.skipif(platform.system() == "Windows", reason="No sed on Windows.")def test_edit(runner): with tempfile.NamedTemporaryFile(mode="w") as named_tempfile: named_tempfile.write("a\nb") named_tempfile.flush()
result = click.edit(filename=named_tempfile.name, editor="sed -i~ 's/$/Test/'") assert result is None
# We need ot reopen the file as it becomes unreadable after the edit. with open(named_tempfile.name) as reopened_file: assert reopened_file.read() == "aTest\nbTest"
@pytest.mark.parametrize( ("prompt_required", "required", "args", "expect"), [ (True, False, None, "prompt"), (True, False, ["-v"], "Option '-v' requires an argument."), (False, True, None, "prompt"), (False, True, ["-v"], "prompt"), ],)def test_prompt_required_with_required(runner, prompt_required, required, args, expect): @click.command() @click.option("-v", prompt=True, prompt_required=prompt_required, required=required) def cli(v): click.echo(str(v))
result = runner.invoke(cli, args, input="prompt") assert expect in result.output
@pytest.mark.parametrize( ("args", "expect"), [ # Flag not passed, don't prompt. pytest.param(None, None, id="no flag"), # Flag and value passed, don't prompt. pytest.param(["-v", "value"], "value", id="short sep value"), pytest.param(["--value", "value"], "value", id="long sep value"), pytest.param(["-vvalue"], "value", id="short join value"), pytest.param(["--value=value"], "value", id="long join value"), # Flag without value passed, prompt. pytest.param(["-v"], "prompt", id="short no value"), pytest.param(["--value"], "prompt", id="long no value"), # Don't use next option flag as value. pytest.param(["-v", "-o", "42"], ("prompt", "42"), id="no value opt"), ],)def test_prompt_required_false(runner, args, expect): @click.command() @click.option("-v", "--value", prompt=True, prompt_required=False) @click.option("-o") def cli(value, o): if o is not None: return value, o
return value
result = runner.invoke(cli, args=args, input="prompt", standalone_mode=False) assert result.exception is None assert result.return_value == expect
@pytest.mark.parametrize( ("prompt", "input", "default", "expect"), [ (True, "password\npassword", None, "password"), ("Confirm Password", "password\npassword\n", None, "password"), (True, "", "", ""), (False, None, None, None), ],)def test_confirmation_prompt(runner, prompt, input, default, expect): @click.command() @click.option( "--password", prompt=prompt, hide_input=True, default=default, confirmation_prompt=prompt, ) def cli(password): return password
result = runner.invoke(cli, input=input, standalone_mode=False) assert result.exception is None assert result.return_value == expect
if prompt == "Confirm Password": assert "Confirm Password: " in result.output
def test_false_show_default_cause_no_default_display_in_prompt(runner): @click.command() @click.option("--arg1", show_default=False, prompt=True, default="my-default-value") def cmd(arg1): pass
# Confirm that the default value is not included in the output when `show_default` # is False result = runner.invoke(cmd, input="my-input", standalone_mode=False) assert "my-default-value" not in result.output123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430import osimport sysfrom io import BytesIO
import pytest
import clickfrom click.exceptions import ClickExceptionfrom click.testing import CliRunner
def test_runner(): @click.command() def test(): i = click.get_binary_stream("stdin") o = click.get_binary_stream("stdout") while True: chunk = i.read(4096) if not chunk: break o.write(chunk) o.flush()
runner = CliRunner() result = runner.invoke(test, input="Hello World!\n") assert not result.exception assert result.output == "Hello World!\n"
def test_echo_stdin_stream(): @click.command() def test(): i = click.get_binary_stream("stdin") o = click.get_binary_stream("stdout") while True: chunk = i.read(4096) if not chunk: break o.write(chunk) o.flush()
runner = CliRunner(echo_stdin=True) result = runner.invoke(test, input="Hello World!\n") assert not result.exception assert result.output == "Hello World!\nHello World!\n"
def test_echo_stdin_prompts(): @click.command() def test_python_input(): foo = input("Foo: ") click.echo(f"foo={foo}")
runner = CliRunner(echo_stdin=True) result = runner.invoke(test_python_input, input="bar bar\n") assert not result.exception assert result.output == "Foo: bar bar\nfoo=bar bar\n"
@click.command() @click.option("--foo", prompt=True) def test_prompt(foo): click.echo(f"foo={foo}")
result = runner.invoke(test_prompt, input="bar bar\n") assert not result.exception assert result.output == "Foo: bar bar\nfoo=bar bar\n"
@click.command() @click.option("--foo", prompt=True, hide_input=True) def test_hidden_prompt(foo): click.echo(f"foo={foo}")
result = runner.invoke(test_hidden_prompt, input="bar bar\n") assert not result.exception assert result.output == "Foo: \nfoo=bar bar\n"
@click.command() @click.option("--foo", prompt=True) @click.option("--bar", prompt=True) def test_multiple_prompts(foo, bar): click.echo(f"foo={foo}, bar={bar}")
result = runner.invoke(test_multiple_prompts, input="one\ntwo\n") assert not result.exception assert result.output == "Foo: one\nBar: two\nfoo=one, bar=two\n"
def test_runner_with_stream(): @click.command() def test(): i = click.get_binary_stream("stdin") o = click.get_binary_stream("stdout") while True: chunk = i.read(4096) if not chunk: break o.write(chunk) o.flush()
runner = CliRunner() result = runner.invoke(test, input=BytesIO(b"Hello World!\n")) assert not result.exception assert result.output == "Hello World!\n"
runner = CliRunner(echo_stdin=True) result = runner.invoke(test, input=BytesIO(b"Hello World!\n")) assert not result.exception assert result.output == "Hello World!\nHello World!\n"
def test_prompts(): @click.command() @click.option("--foo", prompt=True) def test(foo): click.echo(f"foo={foo}")
runner = CliRunner() result = runner.invoke(test, input="wau wau\n") assert not result.exception assert result.output == "Foo: wau wau\nfoo=wau wau\n"
@click.command() @click.option("--foo", prompt=True, hide_input=True) def test(foo): click.echo(f"foo={foo}")
runner = CliRunner() result = runner.invoke(test, input="wau wau\n") assert not result.exception assert result.output == "Foo: \nfoo=wau wau\n"
def test_getchar(): @click.command() def continue_it(): click.echo(click.getchar())
runner = CliRunner() result = runner.invoke(continue_it, input="y") assert not result.exception assert result.output == "y\n"
runner = CliRunner(echo_stdin=True) result = runner.invoke(continue_it, input="y") assert not result.exception assert result.output == "y\n"
@click.command() def getchar_echo(): click.echo(click.getchar(echo=True))
runner = CliRunner() result = runner.invoke(getchar_echo, input="y") assert not result.exception assert result.output == "yy\n"
runner = CliRunner(echo_stdin=True) result = runner.invoke(getchar_echo, input="y") assert not result.exception assert result.output == "yy\n"
def test_catch_exceptions(): class CustomError(Exception): pass
@click.command() def cli(): raise CustomError(1)
runner = CliRunner()
result = runner.invoke(cli) assert isinstance(result.exception, CustomError) assert type(result.exc_info) is tuple assert len(result.exc_info) == 3
with pytest.raises(CustomError): runner.invoke(cli, catch_exceptions=False)
CustomError = SystemExit
result = runner.invoke(cli) assert result.exit_code == 1
def test_with_color(): @click.command() def cli(): click.secho("hello world", fg="blue")
runner = CliRunner()
result = runner.invoke(cli) assert result.output == "hello world\n" assert not result.exception
result = runner.invoke(cli, color=True) assert result.output == f"{click.style('hello world', fg='blue')}\n" assert not result.exception
def test_with_color_errors(): class CLIError(ClickException): def format_message(self) -> str: return click.style(self.message, fg="red")
@click.command() def cli(): raise CLIError("Red error")
runner = CliRunner()
result = runner.invoke(cli) assert result.output == "Error: Red error\n" assert result.exception
result = runner.invoke(cli, color=True) assert result.output == f"Error: {click.style('Red error', fg='red')}\n" assert result.exception
def test_with_color_but_pause_not_blocking(): @click.command() def cli(): click.pause()
runner = CliRunner() result = runner.invoke(cli, color=True) assert not result.exception assert result.output == ""
def test_exit_code_and_output_from_sys_exit(): # See issue #362 @click.command() def cli_string(): click.echo("hello world") sys.exit("error")
@click.command() @click.pass_context def cli_string_ctx_exit(ctx): click.echo("hello world") ctx.exit("error")
@click.command() def cli_int(): click.echo("hello world") sys.exit(1)
@click.command() @click.pass_context def cli_int_ctx_exit(ctx): click.echo("hello world") ctx.exit(1)
@click.command() def cli_float(): click.echo("hello world") sys.exit(1.0)
@click.command() @click.pass_context def cli_float_ctx_exit(ctx): click.echo("hello world") ctx.exit(1.0)
@click.command() def cli_no_error(): click.echo("hello world")
runner = CliRunner()
result = runner.invoke(cli_string) assert result.exit_code == 1 assert result.output == "hello world\nerror\n"
result = runner.invoke(cli_string_ctx_exit) assert result.exit_code == 1 assert result.output == "hello world\nerror\n"
result = runner.invoke(cli_int) assert result.exit_code == 1 assert result.output == "hello world\n"
result = runner.invoke(cli_int_ctx_exit) assert result.exit_code == 1 assert result.output == "hello world\n"
result = runner.invoke(cli_float) assert result.exit_code == 1 assert result.output == "hello world\n1.0\n"
result = runner.invoke(cli_float_ctx_exit) assert result.exit_code == 1 assert result.output == "hello world\n1.0\n"
result = runner.invoke(cli_no_error) assert result.exit_code == 0 assert result.output == "hello world\n"
def test_env(): @click.command() def cli_env(): click.echo(f"ENV={os.environ['TEST_CLICK_ENV']}")
runner = CliRunner()
env_orig = dict(os.environ) env = dict(env_orig) assert "TEST_CLICK_ENV" not in env env["TEST_CLICK_ENV"] = "some_value" result = runner.invoke(cli_env, env=env) assert result.exit_code == 0 assert result.output == "ENV=some_value\n"
assert os.environ == env_orig
def test_stderr(): @click.command() def cli_stderr(): click.echo("1 - stdout") click.echo("2 - stderr", err=True) click.echo("3 - stdout") click.echo("4 - stderr", err=True)
runner_mix = CliRunner() result_mix = runner_mix.invoke(cli_stderr)
assert result_mix.output == "1 - stdout\n2 - stderr\n3 - stdout\n4 - stderr\n" assert result_mix.stdout == "1 - stdout\n3 - stdout\n" assert result_mix.stderr == "2 - stderr\n4 - stderr\n"
@click.command() def cli_empty_stderr(): click.echo("stdout")
runner = CliRunner() result = runner.invoke(cli_empty_stderr)
assert result.output == "stdout\n" assert result.stdout == "stdout\n" assert result.stderr == ""
@pytest.mark.parametrize( "args, expected_output", [ (None, "bar\n"), ([], "bar\n"), ("", "bar\n"), (["--foo", "one two"], "one two\n"), ('--foo "one two"', "one two\n"), ],)def test_args(args, expected_output): @click.command() @click.option("--foo", default="bar") def cli_args(foo): click.echo(foo)
runner = CliRunner() result = runner.invoke(cli_args, args=args) assert result.exit_code == 0 assert result.output == expected_output
def test_setting_prog_name_in_extra(): @click.command() def cli(): click.echo("ok")
runner = CliRunner() result = runner.invoke(cli, prog_name="foobar") assert not result.exception assert result.output == "ok\n"
def test_command_standalone_mode_returns_value(): @click.command() def cli(): click.echo("ok") return "Hello, World!"
runner = CliRunner() result = runner.invoke(cli, standalone_mode=False) assert result.output == "ok\n" assert result.return_value == "Hello, World!" assert result.exit_code == 0
def test_file_stdin_attrs(runner): @click.command() @click.argument("f", type=click.File()) def cli(f): click.echo(f.name) click.echo(f.mode, nl=False)
result = runner.invoke(cli, ["-"]) assert result.output == "<stdin>\nr"
def test_isolated_runner(runner): with runner.isolated_filesystem() as d: assert os.path.exists(d)
assert not os.path.exists(d)
def test_isolated_runner_custom_tempdir(runner, tmp_path): with runner.isolated_filesystem(temp_dir=tmp_path) as d: assert os.path.exists(d)
assert os.path.exists(d) os.rmdir(d)
def test_isolation_stderr_errors(): """Writing to stderr should escape invalid characters instead of raising a UnicodeEncodeError. """ runner = CliRunner()
with runner.isolation() as (_, err, _): click.echo("\udce2", err=True, nl=False)
assert err.getvalue() == b"\\udce2"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252import os.pathimport pathlibimport platformimport tempfile
import pytest
import clickfrom click import FileError
@pytest.mark.parametrize( ("type", "value", "expect"), [ (click.IntRange(0, 5), "3", 3), (click.IntRange(5), "5", 5), (click.IntRange(5), "100", 100), (click.IntRange(max=5), "5", 5), (click.IntRange(max=5), "-100", -100), (click.IntRange(0, clamp=True), "-1", 0), (click.IntRange(max=5, clamp=True), "6", 5), (click.IntRange(0, min_open=True, clamp=True), "0", 1), (click.IntRange(max=5, max_open=True, clamp=True), "5", 4), (click.FloatRange(0.5, 1.5), "1.2", 1.2), (click.FloatRange(0.5, min_open=True), "0.51", 0.51), (click.FloatRange(max=1.5, max_open=True), "1.49", 1.49), (click.FloatRange(0.5, clamp=True), "-0.0", 0.5), (click.FloatRange(max=1.5, clamp=True), "inf", 1.5), ],)def test_range(type, value, expect): assert type.convert(value, None, None) == expect
@pytest.mark.parametrize( ("type", "value", "expect"), [ (click.IntRange(0, 5), "6", "6 is not in the range 0<=x<=5."), (click.IntRange(5), "4", "4 is not in the range x>=5."), (click.IntRange(max=5), "6", "6 is not in the range x<=5."), (click.IntRange(0, 5, min_open=True), 0, "0<x<=5"), (click.IntRange(0, 5, max_open=True), 5, "0<=x<5"), (click.FloatRange(0.5, min_open=True), 0.5, "x>0.5"), (click.FloatRange(max=1.5, max_open=True), 1.5, "x<1.5"), ],)def test_range_fail(type, value, expect): with pytest.raises(click.BadParameter) as exc_info: type.convert(value, None, None)
assert expect in exc_info.value.message
def test_float_range_no_clamp_open(): with pytest.raises(TypeError): click.FloatRange(0, 1, max_open=True, clamp=True)
sneaky = click.FloatRange(0, 1, max_open=True) sneaky.clamp = True
with pytest.raises(RuntimeError): sneaky.convert("1.5", None, None)
@pytest.mark.parametrize( ("nargs", "multiple", "default", "expect"), [ (2, False, None, None), (2, False, (None, None), (None, None)), (None, True, None, ()), (None, True, (None, None), (None, None)), (2, True, None, ()), (2, True, [(None, None)], ((None, None),)), (-1, None, None, ()), ],)def test_cast_multi_default(runner, nargs, multiple, default, expect): if nargs == -1: param = click.Argument(["a"], nargs=nargs, default=default) else: param = click.Option(["-a"], nargs=nargs, multiple=multiple, default=default)
cli = click.Command("cli", params=[param], callback=lambda a: a) result = runner.invoke(cli, standalone_mode=False) assert result.exception is None assert result.return_value == expect
@pytest.mark.parametrize( ("cls", "expect"), [ (None, "a/b/c.txt"), (str, "a/b/c.txt"), (bytes, b"a/b/c.txt"), (pathlib.Path, pathlib.Path("a", "b", "c.txt")), ],)def test_path_type(runner, cls, expect): cli = click.Command( "cli", params=[click.Argument(["p"], type=click.Path(path_type=cls))], callback=lambda p: p, ) result = runner.invoke(cli, ["a/b/c.txt"], standalone_mode=False) assert result.exception is None assert result.return_value == expect
def _symlinks_supported(): with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir: target = os.path.join(tempdir, "target") open(target, "w").close() link = os.path.join(tempdir, "link")
try: os.symlink(target, link) return True except OSError: return False
@pytest.mark.skipif( not _symlinks_supported(), reason="The current OS or FS doesn't support symlinks.")def test_path_resolve_symlink(tmp_path, runner): test_file = tmp_path / "file" test_file_str = os.fspath(test_file) test_file.write_text("")
path_type = click.Path(resolve_path=True) param = click.Argument(["a"], type=path_type) ctx = click.Context(click.Command("cli", params=[param]))
test_dir = tmp_path / "dir" test_dir.mkdir()
abs_link = test_dir / "abs" abs_link.symlink_to(test_file) abs_rv = path_type.convert(os.fspath(abs_link), param, ctx) assert abs_rv == test_file_str
rel_link = test_dir / "rel" rel_link.symlink_to(pathlib.Path("..") / "file") rel_rv = path_type.convert(os.fspath(rel_link), param, ctx) assert rel_rv == test_file_str
def _non_utf8_filenames_supported(): with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir: try: f = open(os.path.join(tempdir, "\udcff"), "w") except OSError: return False
f.close() return True
@pytest.mark.skipif( not _non_utf8_filenames_supported(), reason="The current OS or FS doesn't support non-UTF-8 filenames.",)def test_path_surrogates(tmp_path, monkeypatch): monkeypatch.chdir(tmp_path) type = click.Path(exists=True) path = pathlib.Path("\udcff")
with pytest.raises(click.BadParameter, match="'�' does not exist"): type.convert(path, None, None)
type = click.Path(file_okay=False) path.touch()
with pytest.raises(click.BadParameter, match="'�' is a file"): type.convert(path, None, None)
path.unlink() type = click.Path(dir_okay=False) path.mkdir()
with pytest.raises(click.BadParameter, match="'�' is a directory"): type.convert(path, None, None)
path.rmdir()
def no_access(*args, **kwargs): """Test environments may be running as root, so we have to fake the result of the access tests that use os.access """ p = args[0] assert p == path, f"unexpected os.access call on file not under test: {p!r}" return False
path.touch() type = click.Path(readable=True)
with pytest.raises(click.BadParameter, match="'�' is not readable"): with monkeypatch.context() as m: m.setattr(os, "access", no_access) type.convert(path, None, None)
type = click.Path(readable=False, writable=True)
with pytest.raises(click.BadParameter, match="'�' is not writable"): with monkeypatch.context() as m: m.setattr(os, "access", no_access) type.convert(path, None, None)
type = click.Path(readable=False, executable=True)
with pytest.raises(click.BadParameter, match="'�' is not executable"): with monkeypatch.context() as m: m.setattr(os, "access", no_access) type.convert(path, None, None)
path.unlink()
@pytest.mark.parametrize( "type", [ click.File(mode="r"), click.File(mode="r", lazy=True), ],)def test_file_surrogates(type, tmp_path): path = tmp_path / "\udcff"
with pytest.raises(click.BadParameter, match="�': No such file or directory"): type.convert(path, None, None)
def test_file_error_surrogates(): message = FileError(filename="\udcff").format_message() assert message == "Could not open file '�': unknown error"
@pytest.mark.skipif( platform.system() == "Windows", reason="Filepath syntax differences.")def test_invalid_path_with_esc_sequence(): with pytest.raises(click.BadParameter) as exc_info: with tempfile.TemporaryDirectory(prefix="my\ndir") as tempdir: click.Path(dir_okay=False).convert(tempdir, None, None)
assert "my\\ndir" in exc_info.value.message
def test_choice_get_invalid_choice_message(): choice = click.Choice(["a", "b", "c"]) message = choice.get_invalid_choice_message("d") assert message == "'d' is not one of 'a', 'b', 'c'."123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653import osimport pathlibimport statimport sysfrom collections import namedtuplefrom io import StringIOfrom tempfile import tempdir
import pytest
import click._termui_implimport click.utilsfrom click._compat import WIN
def test_echo(runner): with runner.isolation() as outstreams: click.echo("\N{SNOWMAN}") click.echo(b"\x44\x44") click.echo(42, nl=False) click.echo(b"a", nl=False) click.echo("\x1b[31mx\x1b[39m", nl=False) bytes = outstreams[0].getvalue().replace(b"\r\n", b"\n") assert bytes == b"\xe2\x98\x83\nDD\n42ax"
# if wrapped, we expect bytes to survive. @click.command() def cli(): click.echo(b"\xf6")
result = runner.invoke(cli, []) assert result.stdout_bytes == b"\xf6\n"
# Ensure we do not strip for bytes. with runner.isolation() as outstreams: click.echo(bytearray(b"\x1b[31mx\x1b[39m"), nl=False) assert outstreams[0].getvalue() == b"\x1b[31mx\x1b[39m"
def test_echo_custom_file(): f = StringIO() click.echo("hello", file=f) assert f.getvalue() == "hello\n"
def test_echo_no_streams(monkeypatch, runner): """echo should not fail when stdout and stderr are None with pythonw on Windows.""" with runner.isolation(): sys.stdout = None sys.stderr = None click.echo("test") click.echo("test", err=True)
@pytest.mark.parametrize( ("styles", "ref"), [ ({"fg": "black"}, "\x1b[30mx y\x1b[0m"), ({"fg": "red"}, "\x1b[31mx y\x1b[0m"), ({"fg": "green"}, "\x1b[32mx y\x1b[0m"), ({"fg": "yellow"}, "\x1b[33mx y\x1b[0m"), ({"fg": "blue"}, "\x1b[34mx y\x1b[0m"), ({"fg": "magenta"}, "\x1b[35mx y\x1b[0m"), ({"fg": "cyan"}, "\x1b[36mx y\x1b[0m"), ({"fg": "white"}, "\x1b[37mx y\x1b[0m"), ({"bg": "black"}, "\x1b[40mx y\x1b[0m"), ({"bg": "red"}, "\x1b[41mx y\x1b[0m"), ({"bg": "green"}, "\x1b[42mx y\x1b[0m"), ({"bg": "yellow"}, "\x1b[43mx y\x1b[0m"), ({"bg": "blue"}, "\x1b[44mx y\x1b[0m"), ({"bg": "magenta"}, "\x1b[45mx y\x1b[0m"), ({"bg": "cyan"}, "\x1b[46mx y\x1b[0m"), ({"bg": "white"}, "\x1b[47mx y\x1b[0m"), ({"bg": 91}, "\x1b[48;5;91mx y\x1b[0m"), ({"bg": (135, 0, 175)}, "\x1b[48;2;135;0;175mx y\x1b[0m"), ({"bold": True}, "\x1b[1mx y\x1b[0m"), ({"dim": True}, "\x1b[2mx y\x1b[0m"), ({"underline": True}, "\x1b[4mx y\x1b[0m"), ({"overline": True}, "\x1b[53mx y\x1b[0m"), ({"italic": True}, "\x1b[3mx y\x1b[0m"), ({"blink": True}, "\x1b[5mx y\x1b[0m"), ({"reverse": True}, "\x1b[7mx y\x1b[0m"), ({"strikethrough": True}, "\x1b[9mx y\x1b[0m"), ({"bold": False}, "\x1b[22mx y\x1b[0m"), ({"dim": False}, "\x1b[22mx y\x1b[0m"), ({"underline": False}, "\x1b[24mx y\x1b[0m"), ({"overline": False}, "\x1b[55mx y\x1b[0m"), ({"italic": False}, "\x1b[23mx y\x1b[0m"), ({"blink": False}, "\x1b[25mx y\x1b[0m"), ({"reverse": False}, "\x1b[27mx y\x1b[0m"), ({"strikethrough": False}, "\x1b[29mx y\x1b[0m"), ({"fg": "black", "reset": False}, "\x1b[30mx y"), ],)def test_styling(styles, ref): assert click.style("x y", **styles) == ref assert click.unstyle(ref) == "x y"
@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")])def test_unstyle_other_ansi(text, expect): assert click.unstyle(text) == expect
def test_filename_formatting(): assert click.format_filename(b"foo.txt") == "foo.txt" assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt" assert click.format_filename("/x/foo.txt") == "/x/foo.txt" assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt" assert click.format_filename(b"/x/\xff.txt", shorten=True) == "�.txt"
def test_prompts(runner): @click.command() def test(): if click.confirm("Foo"): click.echo("yes!") else: click.echo("no :(")
result = runner.invoke(test, input="y\n") assert not result.exception assert result.output == "Foo [y/N]: y\nyes!\n"
result = runner.invoke(test, input="\n") assert not result.exception assert result.output == "Foo [y/N]: \nno :(\n"
result = runner.invoke(test, input="n\n") assert not result.exception assert result.output == "Foo [y/N]: n\nno :(\n"
@click.command() def test_no(): if click.confirm("Foo", default=True): click.echo("yes!") else: click.echo("no :(")
result = runner.invoke(test_no, input="y\n") assert not result.exception assert result.output == "Foo [Y/n]: y\nyes!\n"
result = runner.invoke(test_no, input="\n") assert not result.exception assert result.output == "Foo [Y/n]: \nyes!\n"
result = runner.invoke(test_no, input="n\n") assert not result.exception assert result.output == "Foo [Y/n]: n\nno :(\n"
def test_confirm_repeat(runner): cli = click.Command( "cli", params=[click.Option(["--a/--no-a"], default=None, prompt=True)] ) result = runner.invoke(cli, input="\ny\n") assert result.output == "A [y/n]: \nError: invalid input\nA [y/n]: y\n"
@pytest.mark.skipif(WIN, reason="Different behavior on windows.")def test_prompts_abort(monkeypatch, capsys): def f(_): raise KeyboardInterrupt()
monkeypatch.setattr("click.termui.hidden_prompt_func", f)
try: click.prompt("Password", hide_input=True) except click.Abort: click.echo("interrupted")
out, err = capsys.readouterr() assert out == "Password:\ninterrupted\n"
def _test_gen_func(): yield "a" yield "b" yield "c" yield "abc"
def _test_gen_func_fails(): yield "test" raise RuntimeError("This is a test.")
def _test_gen_func_echo(file=None): yield "test" click.echo("hello", file=file) yield "test"
def _test_simulate_keyboard_interrupt(file=None): yield "output_before_keyboard_interrupt" raise KeyboardInterrupt()
EchoViaPagerTest = namedtuple( "EchoViaPagerTest", ( "description", "test_input", "expected_pager", "expected_stdout", "expected_stderr", "expected_error", ),)
@pytest.mark.skipif(WIN, reason="Different behavior on windows.")@pytest.mark.parametrize( "test", [ # We need to pass a parameter function instead of a plain param # as pytest.mark.parametrize will reuse the parameters causing the # generators to be used up so they will not yield anymore EchoViaPagerTest( description="Plain string argument", test_input=lambda: "just text", expected_pager="just text\n", expected_stdout="", expected_stderr="", expected_error=None, ), EchoViaPagerTest( description="Iterable argument", test_input=lambda: ["itera", "ble"], expected_pager="iterable\n", expected_stdout="", expected_stderr="", expected_error=None, ), EchoViaPagerTest( description="Generator function argument", test_input=lambda: _test_gen_func, expected_pager="abcabc\n", expected_stdout="", expected_stderr="", expected_error=None, ), EchoViaPagerTest( description="String generator argument", test_input=lambda: _test_gen_func(), expected_pager="abcabc\n", expected_stdout="", expected_stderr="", expected_error=None, ), EchoViaPagerTest( description="Number generator expression argument", test_input=lambda: (c for c in range(6)), expected_pager="012345\n", expected_stdout="", expected_stderr="", expected_error=None, ), EchoViaPagerTest( description="Exception in generator function argument", test_input=lambda: _test_gen_func_fails, # Because generator throws early on, the pager did not have # a chance yet to write the file. expected_pager=None, expected_stdout="", expected_stderr="", expected_error=RuntimeError, ), EchoViaPagerTest( description="Exception in generator argument", test_input=lambda: _test_gen_func_fails, # Because generator throws early on, the pager did not have a # chance yet to write the file. expected_pager=None, expected_stdout="", expected_stderr="", expected_error=RuntimeError, ), EchoViaPagerTest( description="Keyboard interrupt should not terminate the pager", test_input=lambda: _test_simulate_keyboard_interrupt(), # Due to the keyboard interrupt during pager execution, click program # should abort, but the pager should stay open. # This allows users to cancel the program and search in the pager # output, before they decide to terminate the pager. expected_pager="output_before_keyboard_interrupt", expected_stdout="", expected_stderr="", expected_error=KeyboardInterrupt, ), EchoViaPagerTest( description="Writing to stdout during generator execution", test_input=lambda: _test_gen_func_echo(), expected_pager="testtest\n", expected_stdout="hello\n", expected_stderr="", expected_error=None, ), EchoViaPagerTest( description="Writing to stderr during generator execution", test_input=lambda: _test_gen_func_echo(file=sys.stderr), expected_pager="testtest\n", expected_stdout="", expected_stderr="hello\n", expected_error=None, ), ],)def test_echo_via_pager(monkeypatch, capfd, test): pager_out_tmp = f"{tempdir}/pager_out.txt"
if os.path.exists(pager_out_tmp): os.remove(pager_out_tmp)
monkeypatch.setitem(os.environ, "PAGER", f"cat > {pager_out_tmp}") monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)
test_input = test.test_input() expected_pager = test.expected_pager expected_stdout = test.expected_stdout expected_stderr = test.expected_stderr expected_error = test.expected_error
if expected_error: with pytest.raises(expected_error): click.echo_via_pager(test_input) else: click.echo_via_pager(test_input)
out, err = capfd.readouterr()
if os.path.exists(pager_out_tmp): with open(pager_out_tmp) as f: pager = f.read() else: # The pager process was not started or has been # terminated before it could finish writing pager = None
assert ( pager == expected_pager ), f"Unexpected pager output in test case '{test.description}'" assert ( out == expected_stdout ), f"Unexpected stdout in test case '{test.description}'" assert ( err == expected_stderr ), f"Unexpected stderr in test case '{test.description}'"
def test_echo_color_flag(monkeypatch, capfd): isatty = True monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)
text = "foo" styled_text = click.style(text, fg="red") assert styled_text == "\x1b[31mfoo\x1b[0m"
click.echo(styled_text, color=False) out, err = capfd.readouterr() assert out == f"{text}\n"
click.echo(styled_text, color=True) out, err = capfd.readouterr() assert out == f"{styled_text}\n"
isatty = True click.echo(styled_text) out, err = capfd.readouterr() assert out == f"{styled_text}\n"
isatty = False # Faking isatty() is not enough on Windows; # the implementation caches the colorama wrapped stream # so we have to use a new stream for each test stream = StringIO() click.echo(styled_text, file=stream) assert stream.getvalue() == f"{text}\n"
stream = StringIO() click.echo(styled_text, file=stream, color=True) assert stream.getvalue() == f"{styled_text}\n"
def test_prompt_cast_default(capfd, monkeypatch): monkeypatch.setattr(sys, "stdin", StringIO("\n")) value = click.prompt("value", default="100", type=int) capfd.readouterr() assert isinstance(value, int)
@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")def test_echo_writing_to_standard_error(capfd, monkeypatch): def emulate_input(text): """Emulate keyboard input.""" monkeypatch.setattr(sys, "stdin", StringIO(text))
click.echo("Echo to standard output") out, err = capfd.readouterr() assert out == "Echo to standard output\n" assert err == ""
click.echo("Echo to standard error", err=True) out, err = capfd.readouterr() assert out == "" assert err == "Echo to standard error\n"
emulate_input("asdlkj\n") click.prompt("Prompt to stdin") out, err = capfd.readouterr() assert out == "Prompt to stdin: " assert err == ""
emulate_input("asdlkj\n") click.prompt("Prompt to stderr", err=True) out, err = capfd.readouterr() assert out == " " assert err == "Prompt to stderr:"
emulate_input("y\n") click.confirm("Prompt to stdin") out, err = capfd.readouterr() assert out == "Prompt to stdin [y/N]: " assert err == ""
emulate_input("y\n") click.confirm("Prompt to stderr", err=True) out, err = capfd.readouterr() assert out == " " assert err == "Prompt to stderr [y/N]:"
monkeypatch.setattr(click.termui, "isatty", lambda x: True) monkeypatch.setattr(click.termui, "getchar", lambda: " ")
click.pause("Pause to stdout") out, err = capfd.readouterr() assert out == "Pause to stdout\n" assert err == ""
click.pause("Pause to stderr", err=True) out, err = capfd.readouterr() assert out == "" assert err == "Pause to stderr\n"
def test_echo_with_capsys(capsys): click.echo("Capture me.") out, err = capsys.readouterr() assert out == "Capture me.\n"
def test_open_file(runner): @click.command() @click.argument("filename") def cli(filename): with click.open_file(filename) as f: click.echo(f.read())
click.echo("meep")
with runner.isolated_filesystem(): with open("hello.txt", "w") as f: f.write("Cool stuff")
result = runner.invoke(cli, ["hello.txt"]) assert result.exception is None assert result.output == "Cool stuff\nmeep\n"
result = runner.invoke(cli, ["-"], input="foobar") assert result.exception is None assert result.output == "foobar\nmeep\n"
def test_open_file_pathlib_dash(runner): @click.command() @click.argument( "filename", type=click.Path(allow_dash=True, path_type=pathlib.Path) ) def cli(filename): click.echo(str(type(filename)))
with click.open_file(filename) as f: click.echo(f.read())
result = runner.invoke(cli, ["-"], input="value") assert result.exception is None assert result.output == "pathlib.Path\nvalue\n"
def test_open_file_ignore_errors_stdin(runner): @click.command() @click.argument("filename") def cli(filename): with click.open_file(filename, errors="ignore") as f: click.echo(f.read())
result = runner.invoke(cli, ["-"], input=os.urandom(16)) assert result.exception is None
def test_open_file_respects_ignore(runner): with runner.isolated_filesystem(): with open("test.txt", "w") as f: f.write("Hello world!")
with click.open_file("test.txt", encoding="utf8", errors="ignore") as f: assert f.errors == "ignore"
def test_open_file_ignore_invalid_utf8(runner): with runner.isolated_filesystem(): with open("test.txt", "wb") as f: f.write(b"\xe2\x28\xa1")
with click.open_file("test.txt", encoding="utf8", errors="ignore") as f: f.read()
def test_open_file_ignore_no_encoding(runner): with runner.isolated_filesystem(): with open("test.bin", "wb") as f: f.write(os.urandom(16))
with click.open_file("test.bin", errors="ignore") as f: f.read()
@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])def test_open_file_atomic_permissions_existing_file(runner, permissions): with runner.isolated_filesystem(): with open("existing.txt", "w") as f: f.write("content") os.chmod("existing.txt", permissions)
@click.command() @click.argument("filename") def cli(filename): click.open_file(filename, "w", atomic=True).close()
result = runner.invoke(cli, ["existing.txt"]) assert result.exception is None assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions
@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")def test_open_file_atomic_permissions_new_file(runner): with runner.isolated_filesystem():
@click.command() @click.argument("filename") def cli(filename): click.open_file(filename, "w", atomic=True).close()
# Create a test file to get the expected permissions for new files # according to the current umask. with open("test.txt", "w"): pass permissions = stat.S_IMODE(os.stat("test.txt").st_mode)
result = runner.invoke(cli, ["new.txt"]) assert result.exception is None assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions
def test_iter_keepopenfile(tmpdir): expected = list(map(str, range(10))) p = tmpdir.mkdir("testdir").join("testfile") p.write("\n".join(expected)) with p.open() as f: for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)): assert e_line == a_line.strip()
def test_iter_lazyfile(tmpdir): expected = list(map(str, range(10))) p = tmpdir.mkdir("testdir").join("testfile") p.write("\n".join(expected)) with p.open() as f: with click.utils.LazyFile(f.name) as lf: for e_line, a_line in zip(expected, lf): assert e_line == a_line.strip()
class MockMain: __slots__ = "__package__"
def __init__(self, package_name): self.__package__ = package_name
@pytest.mark.parametrize( ("path", "main", "expected"), [ ("example.py", None, "example.py"), (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"), ("example", None, "example"), (str(pathlib.Path("example/__main__.py")), "example", "python -m example"), (str(pathlib.Path("example/cli.py")), "example", "python -m example.cli"), (str(pathlib.Path("./example")), "", "example"), ],)def test_detect_program_name(path, main, expected): assert click.utils._detect_program_name(path, _main=MockMain(main)) == expected
def test_expand_args(monkeypatch): user = os.path.expanduser("~") assert user in click.utils._expand_args(["~"]) monkeypatch.setenv("CLICK_TEST", "hello") assert "hello" in click.utils._expand_args(["$CLICK_TEST"]) assert "pyproject.toml" in click.utils._expand_args(["*.toml"]) assert os.path.join("docs", "conf.py") in click.utils._expand_args(["**/conf.py"]) assert "*.not-found" in click.utils._expand_args(["*.not-found"]) # a bad glob pattern, such as a pytest identifier, should return itself assert click.utils._expand_args(["test.py::test_bad"])[0] == "test.py::test_bad"
@pytest.mark.parametrize( ("value", "max_length", "expect"), [ pytest.param("", 10, "", id="empty"), pytest.param("123 567 90", 10, "123 567 90", id="equal length, no dot"), pytest.param("123 567 9. aaaa bbb", 10, "123 567 9.", id="sentence < max"), pytest.param("123 567\n\n 9. aaaa bbb", 10, "123 567", id="paragraph < max"), pytest.param("123 567 90123.", 10, "123 567...", id="truncate"), pytest.param("123 5678 xxxxxx", 10, "123...", id="length includes suffix"), pytest.param( "token in ~/.netrc ciao ciao", 20, "token in ~/.netrc...", id="ignore dot in word", ), ],)@pytest.mark.parametrize( "alter", [ pytest.param(None, id=""), pytest.param( lambda text: "\n\b\n" + " ".join(text.split(" ")) + "\n", id="no-wrap mark" ), ],)def test_make_default_short_help(value, max_length, alter, expect): assert len(expect) <= max_length
if alter: value = alter(value)
out = click.utils.make_default_short_help(value, max_length) assert out == expect12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""Example from https://click.palletsprojects.com/en/8.1.x/advanced/#command-aliases"""
from __future__ import annotations
from typing_extensions import assert_type
import click
class AliasedGroup(click.Group): def get_command(self, ctx: click.Context, cmd_name: str) -> click.Command | None: rv = click.Group.get_command(self, ctx, cmd_name) if rv is not None: return rv matches = [x for x in self.list_commands(ctx) if x.startswith(cmd_name)] if not matches: return None elif len(matches) == 1: return click.Group.get_command(self, ctx, matches[0]) ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")
def resolve_command( self, ctx: click.Context, args: list[str] ) -> tuple[str | None, click.Command, list[str]]: # always return the full command name _, cmd, args = super().resolve_command(ctx, args) assert cmd is not None return cmd.name, cmd, args
@click.command(cls=AliasedGroup)def cli() -> None: pass
assert_type(cli, AliasedGroup)
@cli.command()def push() -> None: pass
@cli.command()def pop() -> None: pass1234567891011121314"""From https://click.palletsprojects.com/en/8.1.x/options/#yes-parameters"""
from typing_extensions import assert_type
import click
@click.command()@click.confirmation_option(prompt="Are you sure you want to drop the db?")def dropdb() -> None: click.echo("Dropped all tables!")
assert_type(dropdb, click.Command)1234567891011from typing_extensions import assert_type
import click
@click.group(context_settings={})def hello() -> None: pass
assert_type(hello, click.Group)12345678910111213from typing_extensions import assert_type
import click
@click.command()@click.help_option("-h", "--help")def hello() -> None: """Simple program that greets NAME for a total of COUNT times.""" click.echo("Hello!")
assert_type(hello, click.Command)tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/tests/trusted-inventory.jsonAdded+167
tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/tests/trusted/tests/typing/typing_progressbar.pyAdded+24
tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/tests/trusted/tests/typing/typing_simple_example.pyAdded+17
tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/tests/trusted/tests/typing/typing_version_option.pyAdded+16
tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/tests/trusted/tox.iniAdded+55
tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/validation/canaries/first-hunk-only.shAdded+35
tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/validation/canaries/original-bug.shAdded+3
tasks/pallets__click.fde47b4b.combine_file__1dmpgrck/validation/openenv.jsonAdded+27
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/LICENSE.sourceAdded+28
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/adapter.jsonAdded+127
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/dependency-setup.shAdded+8
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/environment/DockerfileAdded+3
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/instruction.mdAdded+46
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/metadata.jsonAdded+744
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/provenance.jsonAdded+88
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/provided-gold.diffAdded+95
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/solution/solve.shAdded+101
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/task.tomlAdded+23
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/check_pytest.pyAdded+91
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/expected-panels.jsonAdded+485
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/grade.pyAdded+128
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/panel-config.jsonAdded+23
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/test.shAdded+6
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted-inventory.jsonAdded+167
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/pyproject.tomlAdded+102
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/conftest.pyAdded+8
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_arguments.pyAdded+436
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_basic.pyAdded+575
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_chain.pyAdded+245
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_command_decorators.pyAdded+92
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_commands.pyAdded+407
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_compat.pyAdded+10
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_context.pyAdded+545
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_custom_classes.pyAdded+112
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_defaults.pyAdded+86
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_formatting.pyAdded+368
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_imports.pyAdded+69
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_info_dict.pyAdded+275
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_normalization.pyAdded+38
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_options.pyAdded+1017
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_parser.pyAdded+32
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_shell_completion.pyAdded+442
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_termui.pyAdded+487
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_testing.pyAdded+430
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_types.pyAdded+252
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/test_utils.pyAdded+653
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_aliased_group.pyAdded+46
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_confirmation_option.pyAdded+14
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_group_kw_options.pyAdded+11
tasks/pallets__click.fde47b4b.combine_file__3hfoaaic/tests/trusted/tests/typing/typing_help_option.pyAdded+13